file_path
stringlengths
21
224
content
stringlengths
0
80.8M
NVIDIA-Omniverse/iot-samples/source/ingest_app_mqtt/run_app.py
# Copyright (c) 2023, NVIDIA CORPORATION. All rights reserved. # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. import os import argparse import platform import subprocess from pathlib import Path PLATFORM_SYSTEM = platform.system().lower() PLATFORM_MACHINE = platform.machine() if PLATFORM_MACHINE == "i686" or PLATFORM_MACHINE == "AMD64": PLATFORM_MACHINE = "x86_64" CURRENT_PLATFORM = f"{PLATFORM_SYSTEM}-{PLATFORM_MACHINE}" default_username = os.environ.get("OMNI_USER") default_password = os.environ.get("OMNI_PASS") default_server = os.environ.get("OMNI_HOST", "localhost") parser = argparse.ArgumentParser() parser.add_argument("--server", "-s", default=default_server) parser.add_argument("--username", "-u", default=default_username) parser.add_argument("--password", "-p", default=default_password) parser.add_argument("--config", "-c", choices=["debug", "release"], default="release") parser.add_argument("--platform", default=CURRENT_PLATFORM) args = parser.parse_args() SCRIPT_DIR = os.path.dirname(os.path.realpath(__file__)) ROOT_DIR = Path(SCRIPT_DIR).resolve().parents[1] BUILD_DIR = ROOT_DIR.joinpath("_build", args.platform, args.config) DEPS_DIR = ROOT_DIR.joinpath("_build", "target-deps") USD_BIN_DIR = DEPS_DIR.joinpath("usd", args.config, "bin") USD_LIB_DIR = DEPS_DIR.joinpath("usd", args.config, "lib") CLIENT_LIB_DIR = DEPS_DIR.joinpath("omni_client_library", args.config) RESOLVER_DIR = DEPS_DIR.joinpath("omni_usd_resolver", args.config) EXTRA_PATHS = [str(CLIENT_LIB_DIR), str(USD_BIN_DIR), str(USD_LIB_DIR), str(BUILD_DIR), str(RESOLVER_DIR)] EXTRA_PYTHON_PATHS = [ str(Path(SCRIPT_DIR).resolve().parents[0]), str(USD_LIB_DIR.joinpath("python")), str(CLIENT_LIB_DIR.joinpath("bindings-python")), str(BUILD_DIR.joinpath("bindings-python")), ] if PLATFORM_SYSTEM == "windows": os.environ["PATH"] += os.pathsep + os.pathsep.join(EXTRA_PATHS) ot_bin = "carb.omnitrace.plugin.dll" else: p = os.environ.get("LD_LIBRARY_PATH", "") p += os.pathsep + os.pathsep.join(EXTRA_PATHS) os.environ["LD_LIBRARY_PATH"] = p ot_bin = "libcarb.omnitrace.plugin.so" os.environ["OMNI_TRACE_LIB"] = os.path.join(str(DEPS_DIR), "omni-trace", "bin", ot_bin) os.environ["PYTHONPATH"] = os.pathsep + os.pathsep.join(EXTRA_PYTHON_PATHS) os.environ["OMNI_USER"] = args.username os.environ["OMNI_PASS"] = args.password os.environ["OMNI_HOST"] = args.server if PLATFORM_SYSTEM == "windows": PYTHON_EXE = DEPS_DIR.joinpath("python", "python") else: PYTHON_EXE = DEPS_DIR.joinpath("python", "bin", "python3") plugin_paths = DEPS_DIR.joinpath("omni_usd_resolver", args.config, "usd", "omniverse", "resources") os.environ["PXR_PLUGINPATH_NAME"] = str(plugin_paths) REQ_FILE = ROOT_DIR.joinpath("requirements.txt") subprocess.run(f"{PYTHON_EXE} -m pip install -r {REQ_FILE}", shell=True) result = subprocess.run( [PYTHON_EXE, os.path.join(SCRIPT_DIR, "app.py")], stderr=subprocess.STDOUT, )
NVIDIA-Omniverse/iot-samples/source/transform_geometry/app.py
# SPDX-FileCopyrightText: Copyright (c) 2023 NVIDIA CORPORATION & AFFILIATES. All rights reserved. # SPDX-License-Identifier: MIT # # Permission is hereby granted, free of charge, to any person obtaining a # copy of this software and associated documentation files (the "Software"), # to deal in the Software without restriction, including without limitation # the rights to use, copy, modify, merge, publish, distribute, sublicense, # and/or sell copies of the Software, and to permit persons to whom the # Software is furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in # all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL # THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING # FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER # DEALINGS IN THE SOFTWARE. # pip install openpyxl # pip install pandas import asyncio import os import omni.client from pxr import Usd, Sdf from pathlib import Path import time from omni.live import LiveEditSession, LiveCube, getUserNameFromToken OMNI_HOST = os.environ.get("OMNI_HOST", "localhost") OMNI_USER = os.environ.get("OMNI_USER", "ov") if OMNI_USER.lower() == "omniverse": OMNI_USER = "ov" elif OMNI_USER.lower() == "$omni-api-token": OMNI_USER = getUserNameFromToken(os.environ.get("OMNI_PASS")) BASE_FOLDER = "omniverse://" + OMNI_HOST + "/Users/" + OMNI_USER + "/iot-samples" SCRIPT_DIR = os.path.dirname(os.path.realpath(__file__)) CONTENT_DIR = Path(SCRIPT_DIR).resolve().parents[1].joinpath("content") messages = [] def log_handler(thread, component, level, message): # print(message) messages.append((thread, component, level, message)) async def initialize_async(): # copy a the Conveyor Belt to the target nucleus server stage_name = "Dancing_Cubes" stage_folder = f"{BASE_FOLDER}/{stage_name}" stage_url = f"{stage_folder}/{stage_name}.usd" try: stage = Usd.Stage.Open(stage_url) except: stage = Usd.Stage.CreateNew(stage_url) if not stage: raise Exception(f"Could load the stage {stage_url}.") live_session = LiveEditSession(stage_url) live_layer = await live_session.ensure_exists() session_layer = stage.GetSessionLayer() session_layer.subLayerPaths.append(live_layer.identifier) # set the live layer as the edit target stage.SetEditTarget(live_layer) stage.DefinePrim("/World", "Xform") omni.client.live_process() return stage, live_layer def run(stage, live_layer): # we assume that the file contains the data for single device # play back the data in at 30fps for 20 seconds delay = 0.033 iterations = 600 live_cube = LiveCube(stage) omni.client.live_process() for x in range(iterations): with Sdf.ChangeBlock(): live_cube.rotate() omni.client.live_process() time.sleep(delay) if __name__ == "__main__": omni.client.initialize() omni.client.set_log_level(omni.client.LogLevel.DEBUG) omni.client.set_log_callback(log_handler) try: stage, live_layer = asyncio.run(initialize_async()) run(stage, live_layer) except: print("---- LOG MESSAGES ---") print(*messages, sep="\n") print("----") finally: omni.client.shutdown()
NVIDIA-Omniverse/iot-samples/source/transform_geometry/run_app.py
# Copyright (c) 2023, NVIDIA CORPORATION. All rights reserved. # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. import os import argparse import platform import subprocess from pathlib import Path PLATFORM_SYSTEM = platform.system().lower() PLATFORM_MACHINE = platform.machine() if PLATFORM_MACHINE == "i686" or PLATFORM_MACHINE == "AMD64": PLATFORM_MACHINE = "x86_64" CURRENT_PLATFORM = f"{PLATFORM_SYSTEM}-{PLATFORM_MACHINE}" default_username = os.environ.get("OMNI_USER") default_password = os.environ.get("OMNI_PASS") default_server = os.environ.get("OMNI_HOST", "localhost") parser = argparse.ArgumentParser() parser.add_argument("--server", "-s", default=default_server) parser.add_argument("--username", "-u", default=default_username) parser.add_argument("--password", "-p", default=default_password) parser.add_argument("--config", "-c", choices=["debug", "release"], default="release") parser.add_argument("--platform", default=CURRENT_PLATFORM) args = parser.parse_args() SCRIPT_DIR = os.path.dirname(os.path.realpath(__file__)) ROOT_DIR = Path(SCRIPT_DIR).resolve().parents[1] BUILD_DIR = ROOT_DIR.joinpath("_build", args.platform, args.config) DEPS_DIR = ROOT_DIR.joinpath("_build", "target-deps") USD_BIN_DIR = DEPS_DIR.joinpath("usd", args.config, "bin") USD_LIB_DIR = DEPS_DIR.joinpath("usd", args.config, "lib") CLIENT_LIB_DIR = DEPS_DIR.joinpath("omni_client_library", args.config) RESOLVER_DIR = DEPS_DIR.joinpath("omni_usd_resolver", args.config) EXTRA_PATHS = [str(CLIENT_LIB_DIR), str(USD_BIN_DIR), str(USD_LIB_DIR), str(BUILD_DIR), str(RESOLVER_DIR)] EXTRA_PYTHON_PATHS = [ str(Path(SCRIPT_DIR).resolve().parents[0]), str(USD_LIB_DIR.joinpath("python")), str(CLIENT_LIB_DIR.joinpath("bindings-python")), str(BUILD_DIR.joinpath("bindings-python")), ] if PLATFORM_SYSTEM == "windows": os.environ["PATH"] += os.pathsep + os.pathsep.join(EXTRA_PATHS) ot_bin = "carb.omnitrace.plugin.dll" else: p = os.environ.get("LD_LIBRARY_PATH", "") p += os.pathsep + os.pathsep.join(EXTRA_PATHS) os.environ["LD_LIBRARY_PATH"] = p ot_bin = "libcarb.omnitrace.plugin.so" os.environ["OMNI_TRACE_LIB"] = os.path.join(str(DEPS_DIR), "omni-trace", "bin", ot_bin) os.environ["PYTHONPATH"] = os.pathsep + os.pathsep.join(EXTRA_PYTHON_PATHS) os.environ["OMNI_USER"] = args.username os.environ["OMNI_PASS"] = args.password os.environ["OMNI_HOST"] = args.server if PLATFORM_SYSTEM == "windows": PYTHON_EXE = DEPS_DIR.joinpath("python", "python") else: PYTHON_EXE = DEPS_DIR.joinpath("python", "bin", "python3") plugin_paths = DEPS_DIR.joinpath("omni_usd_resolver", args.config, "usd", "omniverse", "resources") os.environ["PXR_PLUGINPATH_NAME"] = str(plugin_paths) REQ_FILE = ROOT_DIR.joinpath("requirements.txt") subprocess.run(f"{PYTHON_EXE} -m pip install -r {REQ_FILE}", shell=True) result = subprocess.run( [PYTHON_EXE, os.path.join(SCRIPT_DIR, "app.py")], stderr=subprocess.STDOUT, )
NVIDIA-Omniverse/iot-samples/source/omni/live/live_cube.py
import random from pxr import Usd, Gf, UsdGeom, Sdf, UsdShade class LiveCube: def __init__(self, stage: Usd.Stage): points = [ (50, 50, 50), (-50, 50, 50), (-50, -50, 50), (50, -50, 50), (-50, -50, -50), (-50, 50, -50), (50, 50, -50), (50, -50, -50), ] faceVertexIndices = [0, 1, 2, 3, 4, 5, 6, 7, 0, 6, 5, 1, 4, 7, 3, 2, 0, 3, 7, 6, 4, 2, 1, 5] faceVertexCounts = [4, 4, 4, 4, 4, 4] cube = stage.GetPrimAtPath("/World/cube") if not cube: cube = stage.DefinePrim("/World/cube", "Cube") if not cube: raise Exception("Could load the cube: /World/cube.") self.mesh = stage.GetPrimAtPath("/World/cube/mesh") if not self.mesh: self.mesh = UsdGeom.Mesh.Define(stage, "/World/cube/mesh") self.mesh.CreatePointsAttr().Set(points) self.mesh.CreateFaceVertexIndicesAttr().Set(faceVertexIndices) self.mesh.CreateFaceVertexCountsAttr().Set(faceVertexCounts) self.mesh.CreateDoubleSidedAttr().Set(False) self.mesh.CreateSubdivisionSchemeAttr("bilinear") self.mesh.CreateDisplayColorAttr().Set([(0.463, 0.725, 0.0)]) self.mesh.AddTranslateOp().Set(Gf.Vec3d(0.0)) self.mesh.AddScaleOp().Set(Gf.Vec3f(0.8535)) self.mesh.AddTransformOp().Set(Gf.Matrix4d(1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1)) texCoords = UsdGeom.PrimvarsAPI(self.mesh).CreatePrimvar( "st", Sdf.ValueTypeNames.TexCoord2fArray, UsdGeom.Tokens.varying ) texCoords.Set([(0, 0), (1, 0), (1, 1), (0, 1)]) self._rotationIncrement = Gf.Vec3f( random.uniform(-1.0, 1.0) * 10.0, random.uniform(-1.0, 1.0) * 10.0, random.uniform(-1.0, 1.0) * 10.0 ) material = UsdShade.Material.Define(stage, '/World/Looks/Plastic_Yellow_A') if material: self.mesh.GetPrim().ApplyAPI(UsdShade.MaterialBindingAPI) UsdShade.MaterialBindingAPI(self.mesh).Bind(material) self._rotateXYZOp = None self._scale = None self._translate = None self.cube = UsdGeom.Xformable(cube) for op in self.cube.GetOrderedXformOps(): if op.GetOpType() == UsdGeom.XformOp.TypeRotateXYZ: self._rotateXYZOp = op if op.GetOpType() == UsdGeom.XformOp.TypeScale: self._scale = op if op.GetOpType() == UsdGeom.XformOp.TypeTranslate: self._translate = op if self._rotateXYZOp is None: self._rotateXYZOp = self.cube.AddRotateXYZOp() self._rotation = Gf.Vec3f(0.0, 0.0, 0.0) self._rotateXYZOp.Set(self._rotation) def translate(self, value: Gf.Vec3f): if self._translate is None: self._translate = self.cube.AddTranslateOp() self._translate.Set(value) def scale(self, value: Gf.Vec3f): if self._scale is None: self._scale = self.cube.AddScaleOp() self._scale.Set(value) def rotate(self): if abs(self._rotation[0] + self._rotationIncrement[0]) > 360.0: self._rotationIncrement[0] *= -1.0 if abs(self._rotation[1] + self._rotationIncrement[1]) > 360.0: self._rotationIncrement[1] *= -1.0 if abs(self._rotation[2] + self._rotationIncrement[2]) > 360.0: self._rotationIncrement[2] *= -1.0 self._rotation[0] += self._rotationIncrement[0] self._rotation[1] += self._rotationIncrement[1] self._rotation[2] += self._rotationIncrement[2] self._rotateXYZOp.Set(self._rotation)
NVIDIA-Omniverse/iot-samples/source/omni/live/__init__.py
import jwt from .live_edit_session import LiveEditSession from .nucleus_client_error import NucleusClientError from .live_cube import LiveCube def getUserNameFromToken(token: str): unvalidated = jwt.decode(token, options={"verify_signature": False}) email = unvalidated["profile"]["email"] if email is None or email == '': return "$omni-api-token" return email
NVIDIA-Omniverse/iot-samples/source/omni/live/nucleus_client_error.py
from fastapi import HTTPException class NucleusClientError(HTTPException): def __init__(self, message, original_exception=None): self.message = f"Error connecting to Nucleus - {message}" if original_exception: self.message = f"{self.message}: {original_exception}" super().__init__(detail=self.message, status_code=502)
NVIDIA-Omniverse/iot-samples/source/omni/live/nucleus_server_config.py
import omni.client def nucleus_server_config(live_edit_session): _, server_info = omni.client.get_server_info(live_edit_session.stage_url) return { "user_name": server_info.username, "stage_url": live_edit_session.stage_url, "mode": "default", "name": live_edit_session.session_name, "version": "1.0", }
NVIDIA-Omniverse/iot-samples/source/omni/live/live_edit_session.py
import os from .nucleus_client_error import NucleusClientError from .nucleus_server_config import nucleus_server_config import omni.client from pxr import Sdf class LiveEditSession: """ Class used to create a live edit session (unless already exists) on the Nucleus server, by writing a session toml file and creating a .live stage Session name: {org_id}_{simulation_id}_iot_session Root folder: .live/{usd-file-name}.live/{session-name}/root.live session_folder_url: {root_folder}/.live/{usd-file-name}.live live_session_url: {session_folder_url}/{session-name}/root.live toml_url: {session_folder_url}/{session-name}/__session__.toml """ def __init__(self, stage_url): self.session_name = "iot_session" self.stage_url = stage_url self.omni_url = omni.client.break_url(self.stage_url) root_folder = self._make_root_folder_path() self.session_folder_url = self._make_url(root_folder) live_session_folder = f"{root_folder}/{self.session_name}.live" self.live_session_url = self._make_url(f"{live_session_folder}/root.live") self.toml_url = self._make_url(f"{live_session_folder}/__session__.toml") async def ensure_exists(self): """Either find an existing live edit session or create a new one""" # get the folder contains the sessions and list the available sessions _result, sessions = await omni.client.list_async(self.session_folder_url) for entry in sessions: session_name = os.path.splitext(entry.relative_path)[0] if session_name == self.session_name: # session exists so exit return self._ensure_live_layer() # create new session # first create the toml file self._write_session_toml() return self._ensure_live_layer() def _ensure_live_layer(self): # create a new root.live session file live_layer = Sdf.Layer.FindOrOpen(self.live_session_url) if not live_layer: live_layer = Sdf.Layer.CreateNew(self.live_session_url) if not live_layer: raise Exception(f"Could load the live layer {self.live_session_url}.") Sdf.PrimSpec(live_layer, "iot", Sdf.SpecifierDef, "IoT Root") live_layer.Save() return live_layer def _make_url(self, path): return omni.client.make_url( self.omni_url.scheme, self.omni_url.user, self.omni_url.host, self.omni_url.port, path, ) def _make_root_folder_path(self): """ construct the folder that would contain sessions: {.live}/{usd-file-name.live}/{session_name}/root.live """ stage_file_name = os.path.splitext(os.path.basename(self.omni_url.path))[0] return f"{os.path.dirname(self.omni_url.path)}/.live/{stage_file_name}.live" def _write_session_toml(self): """ writes the session toml to Nucleus OWNER_KEY = "user_name" STAGE_URL_KEY = "stage_url" MODE_KEY = "mode" (possible modes - "default" = "root_authoring", "auto_authoring", "project_authoring") SESSION_NAME_KEY = "session_name" """ session_config = nucleus_server_config(self) toml_string = "".join([f'{key} = "{value}"\n' for (key, value) in session_config.items()]) result = omni.client.write_file(self.toml_url, self._toml_bytes(toml_string)) if result != omni.client.Result.OK: raise NucleusClientError( f"Error writing live session toml file {self.toml_url}, " f"with configuration {session_config}" ) @staticmethod def _toml_bytes(toml_string): return bytes(toml_string, "utf-8")
NVIDIA-Omniverse/iot-samples/source/ingest_app_csv/app.py
# SPDX-FileCopyrightText: Copyright (c) 2023 NVIDIA CORPORATION & AFFILIATES. All rights reserved. # SPDX-License-Identifier: MIT # # Permission is hereby granted, free of charge, to any person obtaining a # copy of this software and associated documentation files (the "Software"), # to deal in the Software without restriction, including without limitation # the rights to use, copy, modify, merge, publish, distribute, sublicense, # and/or sell copies of the Software, and to permit persons to whom the # Software is furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in # all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL # THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING # FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER # DEALINGS IN THE SOFTWARE. # pip install pandas import asyncio import os import omni.client from pxr import Usd, Sdf, Gf from pathlib import Path import pandas as pd import time from omni.live import LiveEditSession, LiveCube, getUserNameFromToken OMNI_HOST = os.environ.get("OMNI_HOST", "localhost") OMNI_USER = os.environ.get("OMNI_USER", "ov") if OMNI_USER.lower() == "omniverse": OMNI_USER = "ov" elif OMNI_USER.lower() == "$omni-api-token": OMNI_USER = getUserNameFromToken(os.environ.get("OMNI_PASS")) BASE_FOLDER = "omniverse://" + OMNI_HOST + "/Users/" + OMNI_USER + "/iot-samples" SCRIPT_DIR = os.path.dirname(os.path.realpath(__file__)) CONTENT_DIR = Path(SCRIPT_DIR).resolve().parents[1].joinpath("content") messages = [] def log_handler(thread, component, level, message): # print(message) messages.append((thread, component, level, message)) def initialize_device_prim(live_layer, iot_topic): iot_root = live_layer.GetPrimAtPath("/iot") if not iot_root: iot_root = Sdf.PrimSpec(live_layer, "iot", Sdf.SpecifierDef, "IoT Root") iot_spec = live_layer.GetPrimAtPath(f"/iot/{iot_topic}") if not iot_spec: iot_spec = Sdf.PrimSpec(iot_root, iot_topic, Sdf.SpecifierDef, "ConveyorBelt Type") if not iot_spec: raise Exception("Failed to create the IoT Spec.") # clear out any attrubutes that may be on the spec for attrib in iot_spec.attributes: iot_spec.RemoveProperty(attrib) IOT_TOPIC_DATA = f"{CONTENT_DIR}/{iot_topic}_iot_data.csv" data = pd.read_csv(IOT_TOPIC_DATA) data.head() # create all the IoT attributes that will be written attr = Sdf.AttributeSpec(iot_spec, "_ts", Sdf.ValueTypeNames.Double) if not attr: raise Exception(f"Could not define the attribute: {attrName}") # infer the unique data points in the CSV. # The values may be known in advance and can be hard coded grouped = data.groupby("Id") for attrName, group in grouped: attr = Sdf.AttributeSpec(iot_spec, attrName, Sdf.ValueTypeNames.Double) if not attr: raise Exception(f"Could not define the attribute: {attrName}") async def initialize_async(iot_topic): # copy a the Conveyor Belt to the target nucleus server stage_name = f"ConveyorBelt_{iot_topic}" local_folder = f"file:{CONTENT_DIR}/{stage_name}" stage_folder = f"{BASE_FOLDER}/{stage_name}" stage_url = f"{stage_folder}/{stage_name}.usd" result = await omni.client.copy_async( local_folder, stage_folder, behavior=omni.client.CopyBehavior.ERROR_IF_EXISTS, message="Copy Conveyor Belt", ) stage = Usd.Stage.Open(stage_url) if not stage: raise Exception(f"Could load the stage {stage_url}.") live_session = LiveEditSession(stage_url) live_layer = await live_session.ensure_exists() session_layer = stage.GetSessionLayer() session_layer.subLayerPaths.append(live_layer.identifier) # set the live layer as the edit target stage.SetEditTarget(live_layer) initialize_device_prim(live_layer, iot_topic) # place the cube on the conveyor live_cube = LiveCube(stage) live_cube.scale(Gf.Vec3f(0.5)) live_cube.translate(Gf.Vec3f(100.0, -30.0, 195.0)) omni.client.live_process() return stage, live_layer def write_to_live(live_layer, iot_topic, group, ts): # write the iot values to the usd prim attributes print(group.iloc[0]["TimeStamp"]) ts_attribute = live_layer.GetAttributeAtPath(f"/iot/{iot_topic}._ts") ts_attribute.default = ts with Sdf.ChangeBlock(): for index, row in group.iterrows(): id = row["Id"] value = row["Value"] attr = live_layer.GetAttributeAtPath(f"/iot/{iot_topic}.{id}") if not attr: raise Exception(f"Could not find attribute /iot/{iot_topic}.{id}.") attr.default = value omni.client.live_process() def run(stage, live_layer, iot_topic): # we assume that the file contains the data for single device IOT_TOPIC_DATA = f"{CONTENT_DIR}/{iot_topic}_iot_data.csv" data = pd.read_csv(IOT_TOPIC_DATA) data.head() # Converting to DateTime Format and drop ms data["TimeStamp"] = pd.to_datetime(data["TimeStamp"]) data["TimeStamp"] = data["TimeStamp"].dt.floor("s") data.set_index("TimeStamp") start_time = data.min()["TimeStamp"] last_time = start_time grouped = data.groupby("TimeStamp") # play back the data in real-time for next_time, group in grouped: diff = (next_time - last_time).total_seconds() if diff > 0: time.sleep(diff) write_to_live(live_layer, iot_topic, group, (next_time - start_time).total_seconds()) last_time = next_time if __name__ == "__main__": IOT_TOPIC = "A08_PR_NVD_01" omni.client.initialize() omni.client.set_log_level(omni.client.LogLevel.DEBUG) omni.client.set_log_callback(log_handler) try: stage, live_layer = asyncio.run(initialize_async(IOT_TOPIC)) run(stage, live_layer, IOT_TOPIC) except: print("---- LOG MESSAGES ---") print(*messages, sep="\n") print("----") finally: omni.client.shutdown()
NVIDIA-Omniverse/iot-samples/source/ingest_app_csv/run_app.py
# Copyright (c) 2023, NVIDIA CORPORATION. All rights reserved. # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. import os import argparse import platform import subprocess from pathlib import Path PLATFORM_SYSTEM = platform.system().lower() PLATFORM_MACHINE = platform.machine() if PLATFORM_MACHINE == "i686" or PLATFORM_MACHINE == "AMD64": PLATFORM_MACHINE = "x86_64" CURRENT_PLATFORM = f"{PLATFORM_SYSTEM}-{PLATFORM_MACHINE}" default_username = os.environ.get("OMNI_USER") default_password = os.environ.get("OMNI_PASS") default_server = os.environ.get("OMNI_HOST", "localhost") parser = argparse.ArgumentParser() parser.add_argument("--server", "-s", default=default_server) parser.add_argument("--username", "-u", default=default_username) parser.add_argument("--password", "-p", default=default_password) parser.add_argument("--config", "-c", choices=["debug", "release"], default="release") parser.add_argument("--platform", default=CURRENT_PLATFORM) args = parser.parse_args() SCRIPT_DIR = os.path.dirname(os.path.realpath(__file__)) ROOT_DIR = Path(SCRIPT_DIR).resolve().parents[1] BUILD_DIR = ROOT_DIR.joinpath("_build", args.platform, args.config) DEPS_DIR = ROOT_DIR.joinpath("_build", "target-deps") USD_BIN_DIR = DEPS_DIR.joinpath("usd", args.config, "bin") USD_LIB_DIR = DEPS_DIR.joinpath("usd", args.config, "lib") CLIENT_LIB_DIR = DEPS_DIR.joinpath("omni_client_library", args.config) RESOLVER_DIR = DEPS_DIR.joinpath("omni_usd_resolver", args.config) EXTRA_PATHS = [str(CLIENT_LIB_DIR), str(USD_BIN_DIR), str(USD_LIB_DIR), str(BUILD_DIR), str(RESOLVER_DIR)] EXTRA_PYTHON_PATHS = [ str(Path(SCRIPT_DIR).resolve().parents[0]), str(USD_LIB_DIR.joinpath("python")), str(CLIENT_LIB_DIR.joinpath("bindings-python")), str(BUILD_DIR.joinpath("bindings-python")), ] if PLATFORM_SYSTEM == "windows": os.environ["PATH"] += os.pathsep + os.pathsep.join(EXTRA_PATHS) ot_bin = "carb.omnitrace.plugin.dll" else: p = os.environ.get("LD_LIBRARY_PATH", "") p += os.pathsep + os.pathsep.join(EXTRA_PATHS) os.environ["LD_LIBRARY_PATH"] = p ot_bin = "libcarb.omnitrace.plugin.so" os.environ["OMNI_TRACE_LIB"] = os.path.join(str(DEPS_DIR), "omni-trace", "bin", ot_bin) os.environ["PYTHONPATH"] = os.pathsep + os.pathsep.join(EXTRA_PYTHON_PATHS) os.environ["OMNI_USER"] = args.username os.environ["OMNI_PASS"] = args.password os.environ["OMNI_HOST"] = args.server if PLATFORM_SYSTEM == "windows": PYTHON_EXE = DEPS_DIR.joinpath("python", "python") else: PYTHON_EXE = DEPS_DIR.joinpath("python", "bin", "python3") plugin_paths = DEPS_DIR.joinpath("omni_usd_resolver", args.config, "usd", "omniverse", "resources") os.environ["PXR_PLUGINPATH_NAME"] = str(plugin_paths) REQ_FILE = ROOT_DIR.joinpath("requirements.txt") subprocess.run(f"{PYTHON_EXE} -m pip install -r {REQ_FILE}", shell=True) result = subprocess.run( [PYTHON_EXE, os.path.join(SCRIPT_DIR, "app.py")], stderr=subprocess.STDOUT, )
NVIDIA-Omniverse/ext-openvdb/MAINTAINERS.md
<!-- SPDX-License-Identifier: CC-BY-4.0 --> <!-- Copyright Contributors to the OpenVDB project. --> # OpenVDB Committers The current OpenVDB maintainers are: | Name | Email | | -------------- | ----------------- | Jeff Lait | [email protected] | Dan Bailey | [email protected] | Nick Avramoussis | [email protected] | Ken Museth | [email protected] | Peter Cucka | [email protected]
NVIDIA-Omniverse/ext-openvdb/CODE_OF_CONDUCT.md
All participants agree to abide by LF Projects Code of Conduct (as defined in the [charter](tsc/charter.md)) available at https://lfprojects.org/policies/code-of-conduct/
NVIDIA-Omniverse/ext-openvdb/CONTRIBUTING.md
# Overview This project aims to be governed in a transparent, accessible way for the benefit of the community. All participation in this project is open and not bound to corporate affiliation. Participants are all bound to the [Code of Conduct](CODE_OF_CONDUCT.md). # Project roles ## Contributor The contributor role is the starting role for anyone participating in the project and wishing to contribute code. ### Process for becoming a contributor * Review the [coding standards](http://www.openvdb.org/documentation/doxygen/codingStyle.html) to ensure your contribution is in line with the project's coding and styling guidelines. * Have a signed CLA on file ( see [below](#contributor-license-agreements) ) * Submit your code as a PR with the appropriate [DCO sign-off](#commit-sign-off). * Have your submission approved by the [committer(s)](#committer) and merged into the codebase. ### Legal Requirements OpenVDB is a project of the Academy Software Foundation and follows the open source software best practice policies of the Linux Foundation. #### License OpenVDB is licensed under the [Mozilla Public License, version 2.0](LICENSE.md) license. Contributions to OpenVDB should abide by that standard license. #### Contributor License Agreements Developers who wish to contribute code to be considered for inclusion in OpenVDB must first complete a **Contributor License Agreement**. OpenVDB uses [EasyCLA](https://lfcla.com/) for managing CLAs, which automatically checks to ensure CLAs are signed by a contributor before a commit can be merged. * If you are an individual writing the code on your own time and you're SURE you are the sole owner of any intellectual property you contribute, you can [sign the CLA as an individual contributor](https://docs.linuxfoundation.org/lfx/easycla/contributors/individual-contributor). * If you are writing the code as part of your job, or if there is any possibility that your employers might think they own any intellectual property you create, then you should use the [Corporate Contributor Licence Agreement](https://docs.linuxfoundation.org/lfx/easycla/contributors/corporate-contributor). The OpenVDB CLAs are the standard forms used by Linux Foundation projects and [recommended by the ASWF TAC](https://github.com/AcademySoftwareFoundation/tac/blob/master/process/contributing.md#contributor-license-agreement-cla). You can review the text of the CLAs in the [TSC directory](tsc/). #### Commit Sign-Off Every commit must be signed off. That is, every commit log message must include a “`Signed-off-by`” line (generated, for example, with “`git commit --signoff`”), indicating that the committer wrote the code and has the right to release it under the [Mozilla Public License, version 2.0](LICENSE.md) license. See the [TAC documentation on contribution sign off](https://github.com/AcademySoftwareFoundation/tac/blob/master/process/contributing.md#contribution-sign-off) for more information on this requirement. ## Committer The committer role enables the participant to commit code directly to the repository, but also comes with the obligation to be a responsible leader in the community. ### Process for becoming a committer * Show your experience with the codebase through contributions and engagement on the community channels. * Request to become a committer. * Have the majority of committers approve you becoming a committer. * Your name and email is added to the MAINTAINERS.md file for the project. ### Committer responsibilities * Monitor email aliases. * Monitor Slack (delayed response is perfectly acceptable). * Triage GitHub issues and perform pull request reviews for other committers and the community. * Make sure that ongoing PRs are moving forward at the right pace or close them. * Remain an active contributor to the project in general and the code base in particular. ### When does a committer lose committer status? If a committer is no longer interested or cannot perform the committer duties listed above, they should volunteer to be moved to emeritus status. In extreme cases this can also occur by a vote of the committers per the voting process below. ## Technical Steering Committee (TSC) member The Technical Steering Committee (TSC) oversees the overall technical direction of OpenVDB, as defined in the [charter](charter.md). TSC voting members consist of committers that have been nominated by the committers, with a supermajority of voting members required to have a committer elected to be a TSC voting member. TSC voting members term and succession is defined in the [charter](charter.md). All meetings of the TSC are open to participation by any member of the OpenVDB community. Meeting times are listed in the [ASWF technical community calendar](https://lists.aswf.io/g/tac/calendar). ## Current TSC members * Ken Museth, Chair / Weta * Peter Cucka, DreamWorks * Jeff Lait, SideFX * Nick Avramoussis, DNEG * Dan Bailey, ILM # Release Process Project releases will occur on a scheduled basis as agreed to by the TSC. # Conflict resolution and voting In general, we prefer that technical issues and committer status/TSC membership are amicably worked out between the persons involved. If a dispute cannot be decided independently, the TSC can be called in to decide an issue. If the TSC themselves cannot decide an issue, the issue will be resolved by voting. The voting process is a simple majority in which each TSC receives one vote. # Communication This project, just like all of open source, is a global community. In addition to the [Code of Conduct](CODE_OF_CONDUCT.md), this project will: * Keep all communication on open channels ( mailing list, forums, chat ). * Be respectful of time and language differences between community members ( such as scheduling meetings, email/issue responsiveness, etc ). * Ensure tools are able to be used by community members regardless of their region. If you have concerns about communication challenges for this project, please contact the [TSC](mailto:[email protected]).
NVIDIA-Omniverse/ext-openvdb/CMakeLists.txt
# Copyright Contributors to the OpenVDB Project # SPDX-License-Identifier: MPL-2.0 # #[=======================================================================[ CMake Configuration for OpenVDB The OpenVDB CMake build system generates targets depending on the enabled components. It is designed for out of source CMake generation (a build location for CMake to write to will be required). For example, from the root of the repository: mkdir build cd build cmake ../ Depending on the components you choose to build, a number of optional and required dependencies are expected. See the dependency documentation for more information: https://www.openvdb.org/documentation/doxygen/dependencies.html And the documentation on building OpenVDB for more in depth installation instructions: https://www.openvdb.org/documentation/doxygen/build.html This CMakeLists file provides most available options for configuring the build and installation of all OpenVDB components. By default the core library and the vdb_print binary are enabled. Note that various packages have inbuilt CMake module support. See the CMake documentation for more ZLib, Doxygen, OpenGL, Boost and Python controls: https://cmake.org/cmake/help/latest/manual/cmake-modules.7.html OpenVDB's CMake supports building the various components of against a prior installation of OpenVDB. #]=======================================================================] # note: cmake_minimum_required must be called before project commands to # ensure policy scope is set up correctly cmake_minimum_required(VERSION 3.12) # CMP0091 allows for MSVC ABI targetting via CMAKE_MSVC_RUNTIME_LIBRARY # from CMake 3.15 and above. Must come before project(). if(POLICY CMP0091) cmake_policy(SET CMP0091 NEW) endif() project(OpenVDB LANGUAGES CXX) ###### OpenVDB Build/Component Options include(CMakeDependentOption) include(GNUInstallDirs) # todo epydoc and pdflatex option(OPENVDB_BUILD_CORE "Enable the core OpenVDB library. Both static and shared versions are enabled by default" ON) option(OPENVDB_BUILD_BINARIES "Enable the vdb binaries. Only vdb_print is enabled by default" ON) option(OPENVDB_BUILD_PYTHON_MODULE "Build the pyopenvdb Python module" OFF) option(OPENVDB_BUILD_UNITTESTS "Build the OpenVDB unit tests" OFF) option(OPENVDB_BUILD_DOCS "Build the OpenVDB documentation" OFF) option(OPENVDB_BUILD_HOUDINI_PLUGIN "Build the Houdini plugin" OFF) option(OPENVDB_BUILD_HOUDINI_ABITESTS "Build the Houdini ABI tests" OFF) option(OPENVDB_BUILD_AX "Build the OpenVDB AX library" OFF) option(OPENVDB_BUILD_AX_BINARIES "Build the OpenVDB AX command line binary" OFF) option(OPENVDB_BUILD_AX_UNITTESTS "Build the OpenVDB AX unit tests" OFF) option(OPENVDB_INSTALL_HOUDINI_PYTHONRC [=[Install a Houdini startup script that sets the visibilty of OpenVDB nodes and their native equivalents.]=] OFF) option(OPENVDB_BUILD_MAYA_PLUGIN "Build the Maya plugin" OFF) option(OPENVDB_ENABLE_RPATH "Build with RPATH information" ON) option(OPENVDB_CXX_STRICT "Enable or disable pre-defined compiler warnings" OFF) option(OPENVDB_CODE_COVERAGE "Enable code coverage. This also overrides CMAKE_BUILD_TYPE to Debug" OFF) cmake_dependent_option(OPENVDB_INSTALL_CMAKE_MODULES "Install the provided OpenVDB CMake modules when building the core library" ON "OPENVDB_BUILD_CORE" OFF) option(USE_HOUDINI [=[ Build the library against a Houdini installation. Turns on automatically if OPENVDB_BUILD_HOUDINI_PLUGIN is enabled. When enabled, you do not need to provide dependency locations for TBB, Blosc, IlmBase and OpenEXR. Boost must be provided. IlmBase/OpenEXR can optionally be provided if Houdini Version >= 17.5.]=] OFF) option(USE_MAYA [=[ Build the library against a Maya installation. Turns on automatically if OPENVDB_BUILD_MAYA_PLUGIN is enabled. When enabled, you do not need to provide dependency locations for TBB. All other dependencies must be provided.]=] OFF) option(USE_BLOSC [=[ Use blosc while building openvdb components. If OPENVDB_BUILD_CORE is OFF, CMake attempts to query the located openvdb build configuration to decide on blosc support. You may set this to on to force blosc to be used if you know it to be required.]=] ON) option(USE_ZLIB [=[ Use zlib while building openvdb components. If OPENVDB_BUILD_CORE is OFF, CMake attempts to query the located openvdb build configuration to decide on zlib support. ZLib can only be disabled if Blosc is also disabled. ]=] ON) option(USE_LOG4CPLUS [=[ Use log4cplus while building openvdb components. If OPENVDB_BUILD_CORE is OFF, CMake attempts to query the located openvdb build configuration to decide on log4cplus support. You may set this to on to force log4cplus to be used if you know it to be required.]=] OFF) option(USE_EXR [=[ Use OpenEXR while building the core openvdb library. If OPENVDB_BUILD_CORE is OFF, CMake attempts to query the located openvdb build configuration to decide on OpenEXR support. You may set this to on to force OpenEXR to be used if you know it to be required.]=] OFF) cmake_dependent_option(OPENVDB_DISABLE_BOOST_IMPLICIT_LINKING "Disable the implicit linking of Boost libraries on Windows" ON "WIN32" OFF) option(USE_CCACHE "Build using Ccache if found on the path" ON) option(USE_STATIC_DEPENDENCIES [=[ Only search for and use static libraries. If OFF the shared versions of requried libraries are prioritised, falling back to static libraries. Forcing individual static dependencies can be enabled by setting XXX_USE_STATIC_LIBS to ON, where XXX is the package name. On Windows this behaviour is less strict, with any located libraries assumed to be static. ]=] OFF) option(DISABLE_DEPENDENCY_VERSION_CHECKS [=[ Disable minimum version checks for OpenVDB dependencies. It is strongly recommended that this remains disabled. Consider updating your dependencies where possible if encountering minimum requirement CMake errors.]=] OFF) option(DISABLE_CMAKE_SEARCH_PATHS [=[ Disable CMakes default system search paths when locating dependencies. When enabled, CMake will fall back to its default system search routine if it cannot find a dependency with the provided settings. When disabled, only paths provided through the Xxx_ROOT, supported XXX_INCLUDEDIR/XXX_LIBRARYDIR variables or the SYSTEM_LIBRARY_PATHS list will be searched.]=] OFF) option(OPENVDB_USE_DEPRECATED_ABI_5 "Bypass minimum ABI requirement checks" OFF) option(OPENVDB_USE_DEPRECATED_ABI_6 "Bypass minimum ABI requirement checks" OFF) option(OPENVDB_FUTURE_DEPRECATION "Generate messages for upcoming deprecation" OFF) option(USE_COLORED_OUTPUT "Always produce ANSI-colored output (GNU/Clang only)." OFF) option(USE_PKGCONFIG "Use pkg-config to search for dependent libraries." ON) set(SYSTEM_LIBRARY_PATHS "" CACHE STRING [=[ A global list of library paths to additionally use into when searching for dependencies.]=]) set(_CONCURRENT_MALLOC_OPTIONS None Auto Jemalloc Tbbmalloc) if(NOT CONCURRENT_MALLOC) set(CONCURRENT_MALLOC Auto CACHE STRING "Explicitly link the OpenVDB executables against a particular concurrent malloc library. Options are: None Auto Jemalloc Tbbmalloc. Although not required, it is strongly recommended to use a concurrent memory allocator. Has no effect if OPENVDB_BUILD_BINARIES and OPENVDB_BUILD_UNITTESTS are false. Auto is the default and implies Jemalloc, unless USE_MAYA is ON or Jemalloc is unavailable, in which case Tbbmalloc is used. Note that this is not linked into library builds and defers this choice to downstream applications via explicit CMake targets." FORCE ) elseif(NOT ${CONCURRENT_MALLOC} IN_LIST _CONCURRENT_MALLOC_OPTIONS) message(WARNING "Unrecognized value for CONCURRENT_MALLOC, using Auto instead.") set(CONCURRENT_MALLOC Auto CACHE STRING FORCE) endif() set(_OPENVDB_SIMD_OPTIONS None SSE42 AVX) if(NOT OPENVDB_SIMD) set(OPENVDB_SIMD None CACHE STRING "Choose whether to enable SIMD compiler flags or not, options are: None SSE42 AVX. Although not required, it is strongly recommended to enable SIMD. AVX implies SSE42. None is the default." FORCE ) elseif(NOT ${OPENVDB_SIMD} IN_LIST _OPENVDB_SIMD_OPTIONS) message(WARNING "Unrecognized or unsupported value for OPENVDB_SIMD, " "using None instead.") set(OPENVDB_SIMD None CACHE STRING FORCE) endif() if(USE_BLOSC AND NOT USE_ZLIB) message(WARNING "ZLib can only be disabled if Blosc is also disabled. Enabling ZLib.") endif() # Top-level location for all openvdb headers set(OPENVDB_INSTALL_INCLUDEDIR "${CMAKE_INSTALL_INCLUDEDIR}/openvdb") ###### Deprecated options if(OPENVDB_BUILD_HOUDINI_SOPS) message(FATAL_ERROR "The OPENVDB_BUILD_HOUDINI_SOPS option has been removed. Use OPENVDB_BUILD_HOUDINI_PLUGIN.") endif() if(DEFINED USE_SYSTEM_LIBRARY_PATHS) message(FATAL_ERROR "The USE_SYSTEM_LIBRARY_PATHS option has been removed. Use DISABLE_CMAKE_SEARCH_PATHS.") endif() # Various root level CMake options which are marked as advanced mark_as_advanced( OPENVDB_CXX_STRICT OPENVDB_ENABLE_RPATH USE_HOUDINI USE_MAYA USE_LOG4CPLUS USE_CCACHE OPENVDB_BUILD_HOUDINI_ABITESTS DISABLE_DEPENDENCY_VERSION_CHECKS DISABLE_CMAKE_SEARCH_PATHS OPENVDB_USE_DEPRECATED_ABI_5 OPENVDB_USE_DEPRECATED_ABI_6 OPENVDB_FUTURE_DEPRECATION CONCURRENT_MALLOC OPENVDB_CODE_COVERAGE USE_COLORED_OUTPUT SYSTEM_LIBRARY_PATHS OPENVDB_SIMD ) # Configure minimum version requirements - some are treated specially and fall # outside of the DISABLE_DEPENDENCY_VERSION_CHECKS catch # @note Blosc version is currently treated as exception which must be adhered # to. The minimum version must be at least 1.5.0. Previous versions are incompatible. # Later versions (including 1.5.4), can be buggy on certain platforms. set(MINIMUM_BLOSC_VERSION 1.5.0) # @note ABI always enforced so the correct deprecation messages are available. # OPENVDB_USE_DEPRECATED_ABI_<VERSION> should be used to circumvent this set(MINIMUM_OPENVDB_ABI_VERSION 6) set(MINIMUM_CXX_STANDARD 14) set(FUTURE_MINIMUM_OPENVDB_ABI_VERSION 7) if(NOT DISABLE_DEPENDENCY_VERSION_CHECKS) # @note Currently tracking CY2019 of the VFX platform where available set(MINIMUM_GCC_VERSION 6.3.1) set(MINIMUM_CLANG_VERSION 3.8) set(MINIMUM_ICC_VERSION 17) set(MINIMUM_MSVC_VERSION 19.10) set(MINIMUM_BOOST_VERSION 1.61) # @warning should be 1.66, but H18 ships with 1.61 set(MINIMUM_ILMBASE_VERSION 2.2) # @warning should be 2.3, but H18 ships with 2.2 set(MINIMUM_OPENEXR_VERSION 2.2) # @warning should be 2.3, but H18 ships with 2.2 set(MINIMUM_ZLIB_VERSION 1.2.7) set(MINIMUM_TBB_VERSION 2018.0) set(MINIMUM_LLVM_VERSION 6.0.0) set(MINIMUM_PYTHON_VERSION 2.7) set(MINIMUM_NUMPY_VERSION 1.14.0) set(MINIMUM_GOOGLETEST_VERSION 1.8) set(MINIMUM_GLFW_VERSION 3.1) set(MINIMUM_LOG4CPLUS_VERSION 1.1.2) set(MINIMUM_HOUDINI_VERSION 18.0) # These always promote warnings rather than errors set(MINIMUM_MAYA_VERSION 2017) set(MINIMUM_DOXYGEN_VERSION 1.8.8) endif() # VFX 20 deprecations to transition to MINIMUM_* variables in OpenVDB 9.0.0 # Note: CMake 3.15 chosen as possible next version due to Windows support # with CMAKE_MSVC_RUNTIME_LIBRARY, numpy modules with CMake 3.14 and simplified # python linkage on macOS (Python::Module target in 3.15) set(FUTURE_MINIMUM_CMAKE_VERSION 3.15) # No compiler upgrades planned #set(FUTURE_MINIMUM_GCC_VERSION 6.3.1) #set(FUTURE_MINIMUM_ICC_VERSION 17) #set(FUTURE_MINIMUM_MSVC_VERSION 19.10) set(FUTURE_MINIMUM_ILMBASE_VERSION 2.4) set(FUTURE_MINIMUM_OPENEXR_VERSION 2.4) set(FUTURE_MINIMUM_BOOST_VERSION 1.70) set(FUTURE_MINIMUM_TBB_VERSION 2019.0) set(FUTURE_MINIMUM_PYTHON_VERSION 3.7) set(FUTURE_MINIMUM_NUMPY_VERSION 1.17.0) set(FUTURE_MINIMUM_HOUDINI_VERSION 18.5) ######################################################################### # General CMake and CXX settings if(FUTURE_MINIMUM_CMAKE_VERSION) if(${CMAKE_VERSION} VERSION_LESS ${FUTURE_MINIMUM_CMAKE_VERSION}) message(DEPRECATION "Support for CMake versions < ${FUTURE_MINIMUM_CMAKE_VERSION} " "is deprecated and will be removed.") endif() endif() if(NOT CMAKE_CXX_STANDARD) set(CMAKE_CXX_STANDARD ${MINIMUM_CXX_STANDARD} CACHE STRING "The C++ standard whose features are requested to build OpenVDB components." FORCE) elseif(CMAKE_CXX_STANDARD LESS ${MINIMUM_CXX_STANDARD}) message(FATAL_ERROR "Provided C++ Standard is less than the supported minimum." "Required is at least \"${MINIMUM_CXX_STANDARD}\" (found ${CMAKE_CXX_STANDARD})") endif() # Configure MS Runtime if(CMAKE_MSVC_RUNTIME_LIBRARY AND CMAKE_VERSION VERSION_LESS 3.15) message(FATAL_ERROR "CMAKE_MSVC_RUNTIME_LIBRARY support is only available from CMake 3.15") elseif(NOT CMAKE_MSVC_RUNTIME_LIBRARY) set(CMAKE_MSVC_RUNTIME_LIBRARY "" CACHE STRING "Select the MSVC runtime library for use by compilers targeting the MSVC ABI. Options are: MultiThreaded MultiThreadedDLL MultiThreadedDebug MultiThreadedDebugDLL. If empty, CMake defaults to MultiThreaded$<$<CONFIG:Debug>:Debug>DLL." FORCE) endif() if(WIN32 AND CMAKE_MSVC_RUNTIME_LIBRARY) message(STATUS "CMAKE_MSVC_RUNTIME_LIBRARY set to target ${CMAKE_MSVC_RUNTIME_LIBRARY}") # Configure Boost library varient on Windows if(NOT Boost_USE_STATIC_RUNTIME) set(Boost_USE_STATIC_RUNTIME OFF) if(CMAKE_MSVC_RUNTIME_LIBRARY STREQUAL MultiThreaded OR CMAKE_MSVC_RUNTIME_LIBRARY STREQUAL MultiThreadedDebug) set(Boost_USE_STATIC_RUNTIME ON) endif() endif() if(NOT Boost_USE_DEBUG_RUNTIME) set(Boost_USE_DEBUG_RUNTIME OFF) if(CMAKE_MSVC_RUNTIME_LIBRARY STREQUAL MultiThreadedDebugDLL OR CMAKE_MSVC_RUNTIME_LIBRARY STREQUAL MultiThreadedDebug) set(Boost_USE_DEBUG_RUNTIME ON) endif() endif() endif() set(CMAKE_CXX_STANDARD_REQUIRED ON) set(CMAKE_CXX_EXTENSIONS OFF) set(CMAKE_DISABLE_SOURCE_CHANGES ON) set(CMAKE_DISABLE_IN_SOURCE_BUILD ON) if(OPENVDB_ENABLE_RPATH) # Configure rpath for installation base on the following: # https://gitlab.kitware.com/cmake/community/wikis/doc/cmake/RPATH-handling set(CMAKE_SKIP_BUILD_RPATH FALSE) set(CMAKE_BUILD_WITH_INSTALL_RPATH FALSE) set(CMAKE_INSTALL_RPATH_USE_LINK_PATH TRUE) endif() # For CMake's find Threads module which brings in pthread - This flag # forces the compiler -pthread flag vs -lpthread set(THREADS_PREFER_PTHREAD_FLAG TRUE) enable_testing() # Add our cmake modules list(APPEND CMAKE_MODULE_PATH "${CMAKE_CURRENT_LIST_DIR}/cmake") # Add backports to support older versions of CMake # FindNumPy.cmake is needed if CMake < 3.14 if(${CMAKE_VERSION} VERSION_LESS 3.14) list(APPEND CMAKE_MODULE_PATH "${CMAKE_CURRENT_LIST_DIR}/cmake/backports") endif() # Add cmake modules to installation command # @todo fix our glew cmake module if(OPENVDB_INSTALL_CMAKE_MODULES) set(OPENVDB_CMAKE_MODULES cmake/FindBlosc.cmake cmake/FindJemalloc.cmake cmake/FindIlmBase.cmake cmake/FindLog4cplus.cmake cmake/FindOpenEXR.cmake cmake/FindOpenVDB.cmake cmake/FindTBB.cmake cmake/OpenVDBGLFW3Setup.cmake cmake/OpenVDBHoudiniSetup.cmake cmake/OpenVDBMayaSetup.cmake cmake/OpenVDBUtils.cmake ) install(FILES ${OPENVDB_CMAKE_MODULES} DESTINATION ${CMAKE_INSTALL_LIBDIR}/cmake/OpenVDB) endif() # Configure DCC installation if necessary if(OPENVDB_BUILD_HOUDINI_PLUGIN OR OPENVDB_BUILD_HOUDINI_ABITESTS) set(USE_HOUDINI ON) endif() if(OPENVDB_BUILD_MAYA_PLUGIN) set(USE_MAYA ON) endif() # Configure component dependencies by loading the Houdini/Maya setup # scripts. These also find the Houdini/Maya installations if(USE_HOUDINI) include(OpenVDBHoudiniSetup) endif() if(USE_MAYA) include(OpenVDBMayaSetup) endif() if(OPENVDB_BUILD_DOCS) add_subdirectory(doc) endif() # Early exit if there's nothing to build if(NOT ( OPENVDB_BUILD_CORE OR OPENVDB_BUILD_BINARIES OR OPENVDB_BUILD_AX OR OPENVDB_BUILD_AX_BINARIES OR OPENVDB_BUILD_AX_UNITTESTS OR OPENVDB_BUILD_PYTHON_MODULE OR OPENVDB_BUILD_UNITTESTS OR OPENVDB_BUILD_HOUDINI_PLUGIN OR OPENVDB_BUILD_HOUDINI_ABITESTS OR OPENVDB_BUILD_MAYA_PLUGIN) ) return() endif() if(USE_MAYA AND USE_HOUDINI) # @todo technically this is possible so long as library versions match # exactly but it's difficult to validate and dangerous message(FATAL_ERROR "Cannot build both Houdini and Maya plugins against " "the same core dependencies. Plugins must be compiled separately to " "ensure the required DCC dependencies are met." ) endif() ######################################################################### # ccache setup if(USE_CCACHE) find_program(CCACHE_PATH ccache) if(CCACHE_PATH) set_property(GLOBAL PROPERTY RULE_LAUNCH_COMPILE ccache) set_property(GLOBAL PROPERTY RULE_LAUNCH_LINK ccache) message(STATUS "Using ccache: ${CCACHE_PATH}") endif() endif() # Build type configuration - default to Release if none is set unless # code coverage is in use, in which case override to Debug if(OPENVDB_CODE_COVERAGE) message(WARNING "Code coverage requires debug mode, setting CMAKE_BUILD_TYPE " "to Debug.") set(CMAKE_BUILD_TYPE Debug CACHE STRING "Code coverage requires debug mode." FORCE ) elseif(NOT CMAKE_BUILD_TYPE) set(CMAKE_BUILD_TYPE Release CACHE STRING "Choose the type of build, options are: None Debug Release RelWithDebInfo MinSizeRel." FORCE ) endif() message(STATUS "CMake Build Type: ${CMAKE_BUILD_TYPE}") # Code coverage configuration if(OPENVDB_CODE_COVERAGE) # set gcov compile and link flags set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} --coverage") set(CMAKE_SHARED_LINKER_FLAGS "${CMAKE_SHARED_LINKER_FLAGS} --coverage") set(CMAKE_EXE_LINKER_FLAGS "${CMAKE_EXE_LINKER_FLAGS} --coverage") # use .gcno extension instead of .cc.gcno set(CMAKE_CXX_OUTPUT_EXTENSION_REPLACE 1) endif() ######################################################################### # Compiler configuration. Add definitions for a number of compiler warnings # for sub projects and verify version requirements # @todo add definitions for Intel. set(HAS_AVAILABLE_WARNINGS FALSE) if(CMAKE_CXX_COMPILER_ID STREQUAL "Clang" OR CMAKE_CXX_COMPILER_ID STREQUAL "AppleClang") if(CMAKE_CXX_COMPILER_VERSION VERSION_LESS MINIMUM_CLANG_VERSION) message(FATAL_ERROR "Insufficient clang++ version. Minimum required is " "\"${MINIMUM_CLANG_VERSION}\". Found version \"${CMAKE_CXX_COMPILER_VERSION}\"" ) endif() if(OPENVDB_CXX_STRICT) message(STATUS "Configuring Clang CXX warnings") set(HAS_AVAILABLE_WARNINGS TRUE) add_compile_options( -Werror -Wall -Wextra -Wconversion -Wno-sign-conversion ) endif() if(USE_COLORED_OUTPUT) message(STATUS "Enabling colored compiler output") add_compile_options(-fcolor-diagnostics) endif() elseif(CMAKE_CXX_COMPILER_ID STREQUAL "GNU") if(CMAKE_CXX_COMPILER_VERSION VERSION_LESS MINIMUM_GCC_VERSION) message(FATAL_ERROR "Insufficient g++ version. Minimum required is " "\"${MINIMUM_GCC_VERSION}\". Found version \"${CMAKE_CXX_COMPILER_VERSION}\"" ) endif() if(OPENVDB_FUTURE_DEPRECATION AND FUTURE_MINIMUM_GCC_VERSION) if(CMAKE_CXX_COMPILER_VERSION VERSION_LESS FUTURE_MINIMUM_GCC_VERSION) message(DEPRECATION "Support for GCC versions < ${FUTURE_MINIMUM_GCC_VERSION} " "is deprecated and will be removed.") endif() endif() if(OPENVDB_CXX_STRICT) message(STATUS "Configuring GCC CXX warnings") set(HAS_AVAILABLE_WARNINGS TRUE) add_compile_options( -Werror -Wall -Wextra -pedantic -Wcast-align -Wcast-qual -Wconversion -Wdisabled-optimization -Woverloaded-virtual ) endif() if(USE_COLORED_OUTPUT) message(STATUS "Enabling colored compiler output") add_compile_options(-fdiagnostics-color=always) endif() elseif(CMAKE_CXX_COMPILER_ID STREQUAL "Intel") if(CMAKE_CXX_COMPILER_VERSION VERSION_LESS MINIMUM_ICC_VERSION) message(FATAL_ERROR "Insufficient ICC version. Minimum required is " "\"${MINIMUM_ICC_VERSION}\". Found version \"${CMAKE_CXX_COMPILER_VERSION}\"" ) endif() if(OPENVDB_FUTURE_DEPRECATION AND FUTURE_MINIMUM_ICC_VERSION) if(CMAKE_CXX_COMPILER_VERSION VERSION_LESS FUTURE_MINIMUM_ICC_VERSION) message(DEPRECATION "Support for ICC versions < ${FUTURE_MINIMUM_ICC_VERSION} " "is deprecated and will be removed.") endif() endif() elseif(CMAKE_CXX_COMPILER_ID STREQUAL "MSVC") if(CMAKE_CXX_COMPILER_VERSION VERSION_LESS MINIMUM_MSVC_VERSION) message(FATAL_ERROR "Insufficient MSVC version. Minimum required is " "\"${MINIMUM_MSVC_VERSION}\". Found version \"${CMAKE_CXX_COMPILER_VERSION}\"" ) endif() if(OPENVDB_FUTURE_DEPRECATION AND FUTURE_MINIMUM_MSVC_VERSION) if(CMAKE_CXX_COMPILER_VERSION VERSION_LESS FUTURE_MINIMUM_MSVC_VERSION) message(DEPRECATION "Support for MSVC versions < ${FUTURE_MINIMUM_MSVC_VERSION} " "is deprecated and will be removed.") endif() endif() # Increase the number of sections that an object file can contain add_compile_options(/bigobj) # Math constants are not included in <cmath> unless _USE_MATH_DEFINES is # defined on MSVC # https://msdn.microsoft.com/en-us/library/4hwaceh6.aspx add_definitions(-D_USE_MATH_DEFINES) # Disable the non-portable Windows definitions of min() and max() macros add_definitions(-DNOMINMAX) # Excludes APIs such as Cryptography, DDE, RPC, Shell, and Windows Sockets add_definitions(-DWIN32_LEAN_AND_MEAN) # Disable non-secure CRT library function warnings # https://docs.microsoft.com/en-us/cpp/error-messages/compiler-warnings/ # compiler-warning-level-3-c4996?view=vs-2019#unsafe-crt-library-functions add_definitions(-D_CRT_SECURE_NO_WARNINGS) # Disable POSIX function name warnings # https://docs.microsoft.com/en-us/cpp/error-messages/compiler-warnings/ # compiler-warning-level-3-c4996?view=vs-2019#posix-function-names add_definitions(-D_CRT_NONSTDC_NO_WARNINGS) if(NOT OPENVDB_CXX_STRICT) message(STATUS "Suppressing some noisy MSVC CXX warnings, " "set OPENVDB_CXX_STRICT=ON to re-enable them.") # Conversion from int64_t to long add_compile_options(/wd4244) # It's not possible to use STL types in DLL interfaces in a portable and # reliable way so disable this warning add_compile_options(/wd4251) # Conversion from size_t to uLong add_compile_options(/wd4267) # Non dll-interface class used as base for dll-interface class add_compile_options(/wd4275) # Truncation from 'int' to 'bool' add_compile_options(/wd4305) endif() endif() if(OPENVDB_CXX_STRICT AND NOT HAS_AVAILABLE_WARNINGS) message(WARNING "No available CXX warnings for compiler ${CMAKE_CXX_COMPILER_ID}") endif() unset(HAS_AVAILABLE_WARNINGS) # Configure malloc library. Use Jemalloc for Linux and non-Maya, otherwise Tbbmalloc. # * On Mac OSX, linking against Jemalloc < 4.3.0 seg-faults with this error: # malloc: *** malloc_zone_unregister() failed for 0xaddress # Houdini 17.5 and older ships with Jemalloc 3.6.0, so we make Tbbmalloc the default # on Mac OSX (https://github.com/jemalloc/jemalloc/issues/420). Later versions of # Jemalloc are thought to work, but haven't been tested. # * On Windows, we follow SideFX's example in using Tbbmalloc due to the challenges # of injecting into the Windows runtime to replace the system allocator. if((OPENVDB_BUILD_BINARIES OR OPENVDB_BUILD_UNITTESTS) AND CONCURRENT_MALLOC STREQUAL "Auto") if(WIN32 OR APPLE OR USE_MAYA) set(CONCURRENT_MALLOC "Tbbmalloc") else() find_package(Jemalloc QUIET) if(NOT TARGET Jemalloc::jemalloc) message(WARNING "Unable to find Jemalloc, attempting to fall back to TBB malloc. It is recommended to use Jemalloc for optimum performance.") set(CONCURRENT_MALLOC "Tbbmalloc") else() set(CONCURRENT_MALLOC "Jemalloc") endif() endif() endif() # Configure SIMD. AVX implies SSE 4.2. if(OPENVDB_SIMD STREQUAL "AVX") add_compile_options(-mavx -msse4.2) add_definitions(-DOPENVDB_USE_AVX) add_definitions(-DOPENVDB_USE_SSE42) elseif(OPENVDB_SIMD STREQUAL "SSE42") add_compile_options(-msse4.2) add_definitions(-DOPENVDB_USE_SSE42) endif() ######################################################################### # Configure our cmake modules to only search for static libraries if(USE_STATIC_DEPENDENCIES) set(BLOSC_USE_STATIC_LIBS ON) set(OPENEXR_USE_STATIC_LIBS ON) set(ILMBASE_USE_STATIC_LIBS ON) set(TBB_USE_STATIC_LIBS ON) set(LOG4CPLUS_USE_STATIC_LIBS ON) set(JEMALLOC_USE_STATIC_LIBS ON) set(GTEST_USE_STATIC_LIBS ON) set(Boost_USE_STATIC_LIBS ON) # @todo glfw needs custom support. # set(GLFW_USE_STATIC_LIBS ON) endif() # Configure OpenVDB Library and ABI versions if(NOT OPENVDB_BUILD_CORE) # Find VDB installation and determine lib/abi versions find_package(OpenVDB REQUIRED) # Check ABI version was found and explicitly error if attempting to build against # an incompatible Houdini version if(OpenVDB_ABI AND OPENVDB_HOUDINI_ABI) if(NOT ${OpenVDB_ABI} EQUAL ${OPENVDB_HOUDINI_ABI}) message(FATAL_ERROR "Located OpenVDB installation is not ABI compatible with " "Houdini Version ${Houdini_VERSION}. Requires ABI ${OPENVDB_HOUDINI_ABI}, found " "ABI ${OpenVDB_ABI}.") endif() endif() else() include("${CMAKE_CURRENT_LIST_DIR}/cmake/OpenVDBUtils.cmake") set(OPENVDB_VERSION_HEADER "${CMAKE_CURRENT_SOURCE_DIR}/openvdb/openvdb/version.h") if(NOT EXISTS "${OPENVDB_VERSION_HEADER}") message(FATAL_ERROR "Unable to read ${OPENVDB_VERSION_HEADER}. File does not exist.") endif() OPENVDB_VERSION_FROM_HEADER("${OPENVDB_VERSION_HEADER}" VERSION OpenVDB_VERSION MAJOR OpenVDB_MAJOR_VERSION MINOR OpenVDB_MINOR_VERSION PATCH OpenVDB_PATCH_VERSION ) message(STATUS "Configuring for OpenVDB Version ${OpenVDB_VERSION}") endif() # Locate openvdb_ax if necessary if(WIN32) if(OPENVDB_BUILD_AX OR OPENVDB_BUILD_AX_BINARIES OR OPENVDB_BUILD_AX_UNITTESTS) message(FATAL_ERROR "Currently no support for building OpenVDB AX on Windows.") endif() endif() if(NOT OPENVDB_BUILD_AX AND (OPENVDB_BUILD_AX_BINARIES OR OPENVDB_BUILD_AX_UNITTESTS)) find_package(OpenVDB REQUIRED COMPONENTS openvdb_ax) endif() # Validate the OpenVDB ABI Version. If OpenVDB_ABI is not set, we're either building # the core library OR the ABI hasn't been deduced from a VDB installation. Use the # value from OPENVDB_ABI_VERSION_NUMBER, falling back to the lib major version number if(NOT OpenVDB_ABI) if(OPENVDB_ABI_VERSION_NUMBER) set(OpenVDB_ABI ${OPENVDB_ABI_VERSION_NUMBER}) else() set(OpenVDB_ABI ${OpenVDB_MAJOR_VERSION}) endif() endif() # From the deduced ABI, check against the required ABI for Houdini (if set). # Forcefully set the ABI to the required value if necessary - do this after to # explicitly warn the user if their chosen value is different. if(OPENVDB_HOUDINI_ABI AND (NOT "${OpenVDB_ABI}" EQUAL "${OPENVDB_HOUDINI_ABI}")) message(WARNING "CMake will explicitly set the value of OPENVDB_ABI_VERSION_NUMBER to " "${OPENVDB_HOUDINI_ABI} to match the ABI of the target Houdini Version.") set(OpenVDB_ABI ${OPENVDB_HOUDINI_ABI}) endif() if(OpenVDB_ABI LESS MINIMUM_OPENVDB_ABI_VERSION) message(FATAL_ERROR "OpenVDB ABI versions earlier than ${MINIMUM_OPENVDB_ABI_VERSION} are " "no longer supported.") endif() if(FUTURE_MINIMUM_OPENVDB_ABI_VERSION AND OpenVDB_ABI LESS FUTURE_MINIMUM_OPENVDB_ABI_VERSION) if((OpenVDB_ABI EQUAL 5 AND OPENVDB_USE_DEPRECATED_ABI_5) OR (OpenVDB_ABI EQUAL 6 AND OPENVDB_USE_DEPRECATED_ABI_6)) message(DEPRECATION "OpenVDB ABI versions earlier than ${FUTURE_MINIMUM_OPENVDB_ABI_VERSION} " "are deprecated and will soon be removed.") else() message(FATAL_ERROR "OpenVDB ABI versions earlier than ${FUTURE_MINIMUM_OPENVDB_ABI_VERSION} " "are deprecated. Set CMake option OPENVDB_USE_DEPRECATED_ABI_5 or OPENVDB_USE_DEPRECATED_ABI_6 to ON to suppress this error.") endif() # global target definition add_definitions(-DOPENVDB_USE_DEPRECATED_ABI_5) add_definitions(-DOPENVDB_USE_DEPRECATED_ABI_6) endif() # The ABI is a global target definition, applicable to all components, so just add it # via add_definitions() add_definitions(-DOPENVDB_ABI_VERSION_NUMBER=${OpenVDB_ABI}) message(STATUS "Configuring for OpenVDB ABI Version ${OpenVDB_ABI}") # Always force set as we may need to change it if it's incompatible with Houdini set(OPENVDB_ABI_VERSION_NUMBER ${OpenVDB_ABI} CACHE STRING [=[ Build for compatibility with version N of the OpenVDB Grid ABI, where N is 3, 4, 5 etc. (some newer features will be disabled). If OPENVDB_BUILD_CORE is OFF, CMake attempts to query the installed vdb_print binary to determine the ABI number. You may set this to force a given ABI number.]=] FORCE) ########################################################################## if(OPENVDB_BUILD_CORE) add_subdirectory(openvdb/openvdb) endif() if(OPENVDB_BUILD_AX) add_subdirectory(openvdb_ax/openvdb_ax) endif() if(OPENVDB_BUILD_AX_BINARIES) add_subdirectory(openvdb_ax/openvdb_ax/cmd) endif() if(OPENVDB_BUILD_AX_UNITTESTS) add_subdirectory(openvdb_ax/openvdb_ax/test) endif() if(OPENVDB_BUILD_PYTHON_MODULE) add_subdirectory(openvdb/openvdb/python) endif() if(OPENVDB_BUILD_BINARIES) add_subdirectory(openvdb/openvdb/cmd) endif() if(OPENVDB_BUILD_UNITTESTS) add_subdirectory(openvdb/openvdb/unittest) endif() if(OPENVDB_BUILD_HOUDINI_PLUGIN) add_subdirectory(openvdb_houdini/openvdb_houdini) endif() if(OPENVDB_BUILD_HOUDINI_ABITESTS) add_subdirectory(openvdb_houdini/openvdb_houdini/abitest) endif() if(OPENVDB_BUILD_MAYA_PLUGIN) add_subdirectory(openvdb_maya/openvdb_maya) endif() ########################################################################## add_custom_target(uninstall COMMAND ${CMAKE_COMMAND} -P ${PROJECT_SOURCE_DIR}/cmake/Uninstall.cmake )
NVIDIA-Omniverse/ext-openvdb/README.md
![OpenVDB](https://www.openvdb.org/images/openvdb_logo.png) [![License](https://img.shields.io/github/license/AcademySoftwareFoundation/openvdb)](LICENSE.md) [![CII Best Practices](https://bestpractices.coreinfrastructure.org/projects/2774/badge)](https://bestpractices.coreinfrastructure.org/projects/2774) | Build | Status | | --------------- | ------ | | OpenVDB | [![Build](https://github.com/AcademySoftwareFoundation/openvdb/workflows/Build/badge.svg)](https://github.com/AcademySoftwareFoundation/openvdb/actions?query=workflow%3ABuild) | | OpenVDB AX | [![ax](https://github.com/AcademySoftwareFoundation/openvdb/workflows/ax/badge.svg)](https://github.com/AcademySoftwareFoundation/openvdb/actions?query=workflow%3Aax) | [Website](https://www.openvdb.org) | [Discussion Forum](https://www.openvdb.org/forum) | [Documentation](https://www.openvdb.org/documentation/) OpenVDB is an open source C++ library comprising a novel hierarchical data structure and a large suite of tools for the efficient storage and manipulation of sparse volumetric data discretized on three-dimensional grids. It was developed by DreamWorks Animation for use in volumetric applications typically encountered in feature film production. ### Development Repository This GitHub repository hosts the trunk of the OpenVDB development. This implies that it is the newest public version with the latest features and bug fixes. However, it also means that it has not undergone a lot of testing and is generally less stable than the [production releases](https://github.com/AcademySoftwareFoundation/openvdb/releases). ### License OpenVDB is released under the [Mozilla Public License Version 2.0](https://www.mozilla.org/MPL/2.0/), which is a free, open source software license developed and maintained by the Mozilla Foundation. The trademarks of any contributor to this project may not be used in association with the project without the contributor's express permission. ### Contributing OpenVDB welcomes contributions to the OpenVDB project. Please refer to the [contribution guidelines](CONTRIBUTING.md) for details on how to make a contribution. ### Developer Quick Start See the [build documentation](https://www.openvdb.org/documentation/doxygen/build.html) for help with installations. #### Linux ##### Installing Dependencies (Boost, TBB, OpenEXR, Blosc) ``` apt-get install -y libboost-iostreams-dev apt-get install -y libboost-system-dev apt-get install -y libtbb-dev apt-get install -y libilmbase-dev apt-get install -y libopenexr-dev ``` ``` git clone [email protected]:Blosc/c-blosc.git cd c-blosc git checkout tags/v1.5.0 -b v1.5.0 mkdir build cd build cmake .. make -j4 make install cd ../.. ``` ##### Building OpenVDB ``` git clone [email protected]:AcademySoftwareFoundation/openvdb.git cd openvdb mkdir build cd build cmake .. make -j4 make install ``` #### macOS ##### Installing Dependencies (Boost, TBB, OpenEXR, Blosc) ``` brew install boost brew install tbb brew install ilmbase brew install openexr ``` ``` git clone [email protected]:Blosc/c-blosc.git cd c-blosc git checkout tags/v1.5.0 -b v1.5.0 mkdir build cd build cmake .. make -j4 make install cd ../.. ``` ##### Building OpenVDB ``` git clone [email protected]:AcademySoftwareFoundation/openvdb.git cd openvdb mkdir build cd build cmake .. make -j4 make install ``` #### Windows ##### Installing Dependencies (Boost, TBB, OpenEXR, Blosc) Note that the following commands have only been tested for 64bit systems/libraries. It is recommended to set the `VCPKG_DEFAULT_TRIPLET` environment variable to `x64-windows` to use 64-bit libraries by default. You will also require [Git](https://git-scm.com/downloads), [vcpkg](https://github.com/microsoft/vcpkg) and [CMake](https://cmake.org/download/) to be installed. ``` vcpkg install zlib:x64-windows vcpkg install blosc:x64-windows vcpkg install openexr:x64-windows vcpkg install tbb:x64-windows vcpkg install boost-iostreams:x64-windows vcpkg install boost-system:x64-windows vcpkg install boost-any:x64-windows vcpkg install boost-algorithm:x64-windows vcpkg install boost-uuid:x64-windows vcpkg install boost-interprocess:x64-windows ``` ##### Building OpenVDB ``` git clone [email protected]:AcademySoftwareFoundation/openvdb.git cd openvdb mkdir build cd build cmake -DCMAKE_TOOLCHAIN_FILE=<PATH_TO_VCPKG>\scripts\buildsystems\vcpkg.cmake -DVCPKG_TARGET_TRIPLET=x64-windows -A x64 .. cmake --build . --parallel 4 --config Release --target install ```
NVIDIA-Omniverse/ext-openvdb/ci/build_sonar.sh
#!/usr/bin/env bash set -ex wget -q https://sonarcloud.io/static/cpp/build-wrapper-linux-x86.zip unzip build-wrapper-linux-x86.zip mkdir build cd build cmake \ -DCMAKE_CXX_COMPILER=g++ \ -DOPENVDB_ABI_VERSION_NUMBER=6 \ -DUSE_BLOSC=ON \ -DOPENVDB_CXX_STRICT=ON \ -DOPENVDB_BUILD_UNITTESTS=ON \ -DOPENVDB_BUILD_BINARIES=OFF \ -DOPENVDB_CORE_STATIC=OFF \ -DOPENVDB_BUILD_PYTHON_MODULE=OFF \ -DOPENVDB_CODE_COVERAGE=ON \ .. ../build-wrapper-linux-x86/build-wrapper-linux-x86-64 --out-dir bw_output make -j2
NVIDIA-Omniverse/ext-openvdb/ci/test_install.sh
#!/usr/bin/env bash set -e # Various tests to test the FindOpenVDB CMake modules and # general VDB installation # 1) Test basic CMakeLists is able to build vdb_print with # the expected VDB installation cmakelists=" cmake_minimum_required(VERSION 3.12) project(TestInstall LANGUAGES CXX) find_package(OpenVDB REQUIRED COMPONENTS openvdb) add_executable(test_vdb_print \"../openvdb/openvdb/cmd/openvdb_print.cc\") target_link_libraries(test_vdb_print OpenVDB::openvdb) " mkdir tmp cd tmp echo -e "$cmakelists" > CMakeLists.txt cmake -DCMAKE_MODULE_PATH=/usr/local/lib64/cmake/OpenVDB/ . cmake --build . --config Release --target test_vdb_print
NVIDIA-Omniverse/ext-openvdb/ci/install_macos.sh
#!/usr/bin/env bash set -x brew update brew install bash brew install cmake brew install ilmbase brew install openexr brew install boost brew install boost-python3 # also installs the dependent python version brew install gtest brew install tbb brew install zlib brew install glfw brew install jq # for trivial parsing of brew json # Alias python version installed by boost-python3 to path py_version=$(brew info boost-python3 --json | \ jq -cr '.[].dependencies[] | select(. | startswith("python"))') echo "Using python $py_version" # export for subsequent action steps (note, not exported for this env) echo "Python_ROOT_DIR=/usr/local/opt/$py_version" >> $GITHUB_ENV echo "/usr/local/opt/$py_version/bin" >> $GITHUB_PATH
NVIDIA-Omniverse/ext-openvdb/ci/install_cmake.sh
#!/usr/bin/env bash set -ex CMAKE_VERSION="$1" git clone https://github.com/Kitware/CMake.git cd CMake if [ "$CMAKE_VERSION" != "latest" ]; then git checkout tags/v${CMAKE_VERSION} -b v${CMAKE_VERSION} fi mkdir build cd build cmake ../. make -j4 make install
NVIDIA-Omniverse/ext-openvdb/ci/install_macos_ax.sh
#!/usr/bin/env bash # Download and install deps from homebrew on macos LLVM_VERSION=$1 if [ -z $LLVM_VERSION ]; then echo "No LLVM version provided for LLVM installation" exit -1 fi brew update brew install bash brew install ilmbase brew install openexr brew install cmake brew install boost brew install cppunit brew install c-blosc brew install tbb brew install llvm@$LLVM_VERSION brew install zlib
NVIDIA-Omniverse/ext-openvdb/ci/install_blosc.sh
#!/usr/bin/env bash set -ex BLOSC_VERSION="$1" git clone https://github.com/Blosc/c-blosc.git cd c-blosc if [ "$BLOSC_VERSION" != "latest" ]; then git checkout tags/v${BLOSC_VERSION} -b v${BLOSC_VERSION} fi mkdir build cd build cmake ../. make -j4 make install
NVIDIA-Omniverse/ext-openvdb/ci/test.sh
#!/usr/bin/env bash set -ex if [ -d "build" ]; then cd build ctest -V fi
NVIDIA-Omniverse/ext-openvdb/ci/install_doxygen.sh
#!/usr/bin/env bash set -ex DOXYGEN_VERSION="$1" git clone https://github.com/doxygen/doxygen.git cd doxygen if [ "$DOXYGEN_VERSION" != "latest" ]; then git checkout Release_${DOXYGEN_VERSION} -b v${DOXYGEN_VERSION} fi mkdir build cd build cmake ../. make -j4 make install
NVIDIA-Omniverse/ext-openvdb/ci/test_sonar.sh
#!/usr/bin/env bash set -ex SONAR_VERSION=3.3.0.1492 wget -q https://binaries.sonarsource.com/Distribution/sonar-scanner-cli/sonar-scanner-cli-${SONAR_VERSION}-linux.zip unzip sonar-scanner-cli-${SONAR_VERSION}-linux.zip mkdir coverage cd coverage for g in $(find ../build -name "*.gcno" -type f); do gcov -p -l -o $(dirname "$g") $(echo "$g" | sed -e 's/\/build\//\//' -e 's/\.gcno/\.cc/' -e 's/\/CMakeFiles.*\.dir\//\//') done cd .. sonar-scanner-${SONAR_VERSION}-linux/bin/sonar-scanner -X \ -Dsonar.projectKey=openvdb \ -Dsonar.links.homepage=https://www.openvdb.org/ \ -Dsonar.links.scm=https://github.com/AcademySoftwareFoundation/openvdb \ -Dsonar.links.issue=https://jira.aswf.io/projects/OVDB \ -Dsonar.sources=openvdb \ -Dsonar.exclusions=openvdb/cmd/**,openvdb/unittest/**,openvdb/viewer/**,openvdb/python/** \ -Dsonar.binaries=build/openvdb/unittest/vdb_test \ -Dsonar.tests=openvdb/unittest \ -Dsonar.sourceEncoding=UTF-8 \ -Dsonar.organization=danrbailey-github \ -Dsonar.cfamily.build-wrapper-output=build/bw_output \ -Dsonar.cfamily.gcov.reportsPath=coverage \ -Dsonar.host.url=https://sonarcloud.io \ -Dsonar.login=$SONAR_TOKEN
NVIDIA-Omniverse/ext-openvdb/ci/build.sh
#!/usr/bin/env bash set -ex # print versions bash --version if [ ! -z "$CXX" ]; then $CXX -v; fi cmake --version ################################################ BUILD_TYPE="$1"; shift ABI="$1"; shift BLOSC="$1"; shift SIMD="$1"; shift # Command seperated list of components i.e. "core,ax,bin" IN_COMPONENTS="$1"; shift CMAKE_EXTRA="$@" ################################################ # # Select components to build # Available components. If a component is not provided it is # explicitly set to OFF. declare -A COMPONENTS COMPONENTS['core']='OPENVDB_BUILD_CORE' COMPONENTS['python']='OPENVDB_BUILD_PYTHON_MODULE' COMPONENTS['test']='OPENVDB_BUILD_UNITTESTS' COMPONENTS['bin']='OPENVDB_BUILD_BINARIES' COMPONENTS['doc']='OPENVDB_BUILD_DOCS' COMPONENTS['axcore']='OPENVDB_BUILD_AX' COMPONENTS['axgr']='OPENVDB_BUILD_AX_GRAMMAR' COMPONENTS['axbin']='OPENVDB_BUILD_AX_BINARIES' COMPONENTS['axtest']='OPENVDB_BUILD_AX_UNITTESTS' # Check inputs IFS=', ' read -r -a IN_COMPONENTS <<< "$IN_COMPONENTS" for comp in "${IN_COMPONENTS[@]}"; do if [ -z ${COMPONENTS[$comp]} ]; then echo "Invalid component passed to build \"$comp\""; exit -1 fi done # Build CMake command for comp in "${!COMPONENTS[@]}"; do found=false for in in "${IN_COMPONENTS[@]}"; do if [[ $comp == "$in" ]]; then found=true; break fi done if $found; then CMAKE_EXTRA+=" -D${COMPONENTS[$comp]}=ON " else CMAKE_EXTRA+=" -D${COMPONENTS[$comp]}=OFF " fi done if [ "$ABI" != "None" ]; then CMAKE_EXTRA+=" -DOPENVDB_ABI_VERSION_NUMBER=${ABI} " fi # ################################################ # github actions runners have 2 threads # https://help.github.com/en/actions/reference/virtual-environments-for-github-hosted-runners export CMAKE_BUILD_PARALLEL_LEVEL=2 # DebugNoInfo is a custom CMAKE_BUILD_TYPE - no optimizations, no symbols, asserts enabled mkdir -p build cd build # Note: all sub binary options are always on and can be toggles with # OPENVDB_BUILD_BINARIES=ON/OFF cmake \ -DCMAKE_CXX_FLAGS_DebugNoInfo="" \ -DCMAKE_BUILD_TYPE=${BUILD_TYPE} \ -DOPENVDB_USE_DEPRECATED_ABI_6=ON \ -DUSE_BLOSC=${BLOSC} \ -DOPENVDB_SIMD=${SIMD} \ -DOPENVDB_BUILD_VDB_PRINT=ON \ -DOPENVDB_BUILD_VDB_LOD=ON \ -DOPENVDB_BUILD_VDB_RENDER=ON \ -DOPENVDB_BUILD_VDB_VIEW=ON \ ${CMAKE_EXTRA} \ .. cmake --build . --config $BUILD_TYPE --target install
NVIDIA-Omniverse/ext-openvdb/ci/build_houdini.sh
#!/usr/bin/env bash set -ex RELEASE="$1"; shift EXTRAS="$1"; shift CMAKE_EXTRA="$@" # print versions bash --version $CXX -v cmake --version # DebugNoInfo is a custom CMAKE_BUILD_TYPE - no optimizations, no symbols, asserts enabled if [ -d "hou" ]; then cd hou source houdini_setup_bash cd - mkdir build cd build cmake \ -DCMAKE_CXX_FLAGS_DebugNoInfo="" \ -DCMAKE_BUILD_TYPE=${RELEASE} \ -DOPENVDB_CXX_STRICT=ON \ -DOPENVDB_USE_DEPRECATED_ABI_6=ON \ -DOPENVDB_BUILD_HOUDINI_PLUGIN=ON \ -DOPENVDB_BUILD_HOUDINI_ABITESTS=ON \ -DOPENVDB_BUILD_BINARIES=${EXTRAS} \ -DOPENVDB_BUILD_PYTHON_MODULE=${EXTRAS} \ -DOPENVDB_BUILD_UNITTESTS=${EXTRAS} \ -DOPENVDB_HOUDINI_INSTALL_PREFIX=/tmp \ ${CMAKE_EXTRA} \ .. # Can only build using one thread with GCC due to memory constraints if [ "$CXX" = "clang++" ]; then make -j2 else make fi fi
NVIDIA-Omniverse/ext-openvdb/ci/build_windows.sh
#!/usr/bin/env bash set -ex VCPKG_ROOT="$1"; shift CMAKE_EXTRA="$@" mkdir build cd build # See the following regarding boost installation: # https://github.com/actions/virtual-environments/issues/687 # https://github.com/actions/virtual-environments/blob/master/images/win/Windows2019-Readme.md # print version cmake --version cmake \ -G "Visual Studio 16 2019" -A x64 \ -DVCPKG_TARGET_TRIPLET="${VCPKG_DEFAULT_TRIPLET}" \ -DCMAKE_BUILD_TYPE=Release \ -DCMAKE_TOOLCHAIN_FILE="${VCPKG_ROOT}\scripts\buildsystems\vcpkg.cmake" \ -DOPENVDB_BUILD_BINARIES=ON \ -DOPENVDB_BUILD_VDB_PRINT=ON \ -DOPENVDB_BUILD_VDB_LOD=ON \ -DOPENVDB_BUILD_VDB_RENDER=ON \ -DOPENVDB_BUILD_VDB_VIEW=ON \ -DOPENVDB_BUILD_UNITTESTS=ON \ -DBOOST_ROOT="${BOOST_ROOT_1_72_0}" \ -DBOOST_INCLUDEDIR="${BOOST_ROOT_1_72_0}\boost\include" \ -DBOOST_LIBRARYDIR="${BOOST_ROOT_1_72_0}\lib" \ ${CMAKE_EXTRA} \ .. cmake --build . --parallel 4 --config Release --target install
NVIDIA-Omniverse/ext-openvdb/ci/install_windows.sh
#!/usr/bin/env bash set -ex vcpkg update vcpkg install zlib openexr tbb gtest blosc glfw3 glew
NVIDIA-Omniverse/ext-openvdb/ci/extract_test_examples.sh
#!/usr/bin/env bash set -e ROOT="$( cd "$( dirname "${BASH_SOURCE[0]}" )" >/dev/null 2>&1 && pwd )/../" VDB_AX=$ROOT/build/openvdb_ax/openvdb_ax/cmd/vdb_ax DOCS=() DOCS+=($ROOT/doc/ax/ax.txt) DOCS+=($ROOT/doc/ax/axcplusplus.txt) DOCS+=($ROOT/doc/ax/axexamples.txt) # DOCS+=($ROOT/doc/ax/axfunctionlist.txt) do not test this file DOCS+=($ROOT/doc/ax/doc.txt) for DOC in "${DOCS[@]}"; do echo "Checking doxygen code in '$DOC...'" # Make sure the file exists if [ ! -f $DOC ]; then echo "Could not find '$DOC.'" exit -1 fi # Extract all code segments from doxygen documentation in between @code and @endcode data=$(sed -n '/^ *@code.* *$/,/^ *@endcode *$/p' $DOC) str="" skip=false count=0 # For each extracted line, rebuild each code segment from @code and @endcode and # run it through a vdb_ax binary if necessary while IFS= read -r line; do # If the code is marked as unparsed, c++ or shell, skip if [[ "$line" == "@code{.unparsed}" ]]; then skip=true elif [[ "$line" == "@code{.cpp}" ]]; then skip=true elif [[ "$line" == "@code{.sh}" ]]; then skip=true elif [[ $line == @code* ]]; then str="" elif [[ $line == @endcode ]]; then echo -e "\nTesting [$count]:" if [ "$skip" = true ]; then echo "Skipping the following unparsed/c++/shell code:" echo -e "$str" | sed 's/^/ /' else # parse $VDB_AX analyze -s "$str" -v fi skip=false count=$((count+1)) str="" else str+="$line"$'\n' fi done <<< "$data" done
NVIDIA-Omniverse/ext-openvdb/ci/download_houdini.py
#!/usr/local/bin/python # # Copyright Contributors to the OpenVDB Project # SPDX-License-Identifier: MPL-2.0 # # Python script to download the latest Houdini builds # using the SideFX download API: # # https://www.sidefx.com/docs/api/download/index.html # # Authors: Dan Bailey, SideFX import time import sys import re import shutil import json import base64 import requests import hashlib # this argument is for the major.minor version of Houdini to download (such as 15.0, 15.5, 16.0) version = sys.argv[1] only_production = True if sys.argv[2] == 'ON' else False user_client_id = sys.argv[3] user_client_secret_key = sys.argv[4] if not re.match('[0-9][0-9]\.[0-9]$', version): raise IOError('Invalid Houdini Version "%s", expecting in the form "major.minor" such as "16.0"' % version) # Code that provides convenient Python wrappers to call into the API: def service( access_token_url, client_id, client_secret_key, endpoint_url, access_token=None, access_token_expiry_time=None): if (access_token is None or access_token_expiry_time is None or access_token_expiry_time < time.time()): access_token, access_token_expiry_time = ( get_access_token_and_expiry_time( access_token_url, client_id, client_secret_key)) return _Service( endpoint_url, access_token, access_token_expiry_time) class _Service(object): def __init__( self, endpoint_url, access_token, access_token_expiry_time): self.endpoint_url = endpoint_url self.access_token = access_token self.access_token_expiry_time = access_token_expiry_time def __getattr__(self, attr_name): return _APIFunction(attr_name, self) class _APIFunction(object): def __init__(self, function_name, service): self.function_name = function_name self.service = service def __getattr__(self, attr_name): # This isn't actually an API function, but a family of them. Append # the requested function name to our name. return _APIFunction( "{0}.{1}".format(self.function_name, attr_name), self.service) def __call__(self, *args, **kwargs): return call_api_with_access_token( self.service.endpoint_url, self.service.access_token, self.function_name, args, kwargs) #--------------------------------------------------------------------------- # Code that implements authentication and raw calls into the API: def get_access_token_and_expiry_time( access_token_url, client_id, client_secret_key): """Given an API client (id and secret key) that is allowed to make API calls, return an access token that can be used to make calls. """ response = requests.post( access_token_url, headers={ "Authorization": u"Basic {0}".format( base64.b64encode( "{0}:{1}".format( client_id, client_secret_key ).encode() ).decode('utf-8') ), }) if response.status_code != 200: raise AuthorizationError(response.status_code, reponse.text) response_json = response.json() access_token_expiry_time = time.time() - 2 + response_json["expires_in"] return response_json["access_token"], access_token_expiry_time class AuthorizationError(Exception): """Raised from the client if the server generated an error while generating an access token. """ def __init__(self, http_code, message): super(AuthorizationError, self).__init__(message) self.http_code = http_code def call_api_with_access_token( endpoint_url, access_token, function_name, args, kwargs): """Call into the API using an access token that was returned by get_access_token. """ response = requests.post( endpoint_url, headers={ "Authorization": "Bearer " + access_token, }, data=dict( json=json.dumps([function_name, args, kwargs]), )) if response.status_code == 200: return response.json() raise APIError(response.status_code, response.text) class APIError(Exception): """Raised from the client if the server generated an error while calling into the API. """ def __init__(self, http_code, message): super(APIError, self).__init__(message) self.http_code = http_code service = service( access_token_url="https://www.sidefx.com/oauth2/application_token", client_id=user_client_id, client_secret_key=user_client_secret_key, endpoint_url="https://www.sidefx.com/api/", ) releases_list = service.download.get_daily_builds_list( product='houdini', version=version, platform='linux', only_production=only_production) latest_release = service.download.get_daily_build_download( product='houdini', version=version, platform='linux', build=releases_list[0]['build']) # Download the file as hou.tar.gz local_filename = 'hou.tar.gz' response = requests.get(latest_release['download_url'], stream=True) if response.status_code == 200: with open(local_filename, 'wb') as f: response.raw.decode_content = True shutil.copyfileobj(response.raw, f) else: raise Exception('Error downloading file!') # Verify the file checksum is matching file_hash = hashlib.md5() with open(local_filename, 'rb') as f: for chunk in iter(lambda: f.read(4096), b''): file_hash.update(chunk) if file_hash.hexdigest() != latest_release['hash']: raise Exception('Checksum does not match!')
NVIDIA-Omniverse/ext-openvdb/ci/install_houdini.sh
#!/usr/bin/env bash set -e if [ -d "hou" ]; then # move hou tarball into top-level and untar cp hou/hou.tar.gz . tar -xzf hou.tar.gz fi
NVIDIA-Omniverse/ext-openvdb/ci/download_houdini.sh
#!/usr/bin/env bash set -e HOUDINI_MAJOR="$1" GOLD="$2" HOUDINI_CLIENT_ID="$4" HOUDINI_SECRET_KEY="$5" if [ "$HOUDINI_CLIENT_ID" == "" ]; then echo "HOUDINI_CLIENT_ID GitHub Action Secret needs to be set to install Houdini builds" exit 0 fi if [ "$HOUDINI_SECRET_KEY" == "" ]; then echo "HOUDINI_SECRET_KEY GitHub Action Secret needs to be set to install Houdini builds" exit 0 fi pip install --user requests python ci/download_houdini.py $HOUDINI_MAJOR $GOLD $HOUDINI_CLIENT_ID $HOUDINI_SECRET_KEY # create dir hierarchy mkdir -p hou/bin mkdir -p hou/houdini mkdir -p hou/toolkit mkdir -p hou/dsolib # unpack hou.tar.gz and cleanup tar -xzf hou.tar.gz rm -rf hou.tar.gz cd houdini* tar -xzf houdini.tar.gz # copy required files into hou dir cp houdini_setup* ../hou/. cp -r toolkit/cmake ../hou/toolkit/. cp -r toolkit/include ../hou/toolkit/. cp -r dsolib/libHoudini* ../hou/dsolib/. cp -r dsolib/libopenvdb_sesi* ../hou/dsolib/. cp -r dsolib/libblosc* ../hou/dsolib/. cp -r dsolib/libhboost* ../hou/dsolib/. cp -r dsolib/libz* ../hou/dsolib/. cp -r dsolib/libbz2* ../hou/dsolib/. cp -r dsolib/libtbb* ../hou/dsolib/. cp -r dsolib/libHalf* ../hou/dsolib/. cp -r dsolib/libjemalloc* ../hou/dsolib/. cp -r dsolib/liblzma* ../hou/dsolib/. # needed for < H18.0 (due to sesitag) if [ "$HOUDINI_MAJOR" == "17.0" ] || [ "$HOUDINI_MAJOR" == "17.5" ]; then cp -r bin/app_init* ../hou/bin/. cp -r bin/sesitag* ../hou/bin/. cp -r dsolib/lib* ../hou/dsolib/. fi # write hou into hou.tar.gz and cleanup cd .. tar -czvf hou.tar.gz hou # move hou.tar.gz into hou subdirectory rm -rf hou/* mv hou.tar.gz hou # inspect size of tarball ls -lart hou/hou.tar.gz
NVIDIA-Omniverse/ext-openvdb/ci/install_gtest.sh
#!/usr/bin/env bash set -ex GTEST_VERSION="$1" git clone https://github.com/google/googletest.git cd googletest if [ "$GTEST_VERSION" != "latest" ]; then git checkout release-${GTEST_VERSION} -b v${GTEST_VERSION} fi mkdir build cd build cmake ../. make -j4 make install
NVIDIA-Omniverse/ext-openvdb/openvdb_ax/openvdb_ax/ax.h
// Copyright Contributors to the OpenVDB Project // SPDX-License-Identifier: MPL-2.0 /// @file ax.h /// /// @author Nick Avramoussis /// /// @brief Single header include which provides methods for initializing AX and /// running a full AX pipeline (pasrsing, compiling and executing) across /// standard OpenVDB Grid types. /// /// @details These methods wrap the internal components of OpenVDB AX to /// provide easier and quick access to running AX code. Users who wish to /// further optimise and customise the process may interface with these /// components directly. See the body of the methods provided in this file for /// example implementations. #ifndef OPENVDB_AX_AX_HAS_BEEN_INCLUDED #define OPENVDB_AX_AX_HAS_BEEN_INCLUDED #include <openvdb/openvdb.h> #include <openvdb/version.h> namespace openvdb { OPENVDB_USE_VERSION_NAMESPACE namespace OPENVDB_VERSION_NAME { namespace ax { /// @brief Initializes OpenVDB AX and subsequent LLVM components. /// @details Must be called before any AX compilation or execution is performed. /// Can be safely called from multiple threads. Cannot be called after /// uninitialize has been called. void initialize(); /// @brief Check to see if OpenVDB AX components have been initialized. /// @note Can be safely called from multiple threads. bool isInitialized(); /// @brief Uninitialize and deregister OpenVDB AX. /// @details This has the important function of shutting down LLVM and /// correctly freeing statically allocated LLVM types. Should be /// called on application termination. Can be safely called from /// multiple threads. void uninitialize(); //////////////////////////////////////// //////////////////////////////////////// /// @brief Run a full AX pipeline (parse, compile and execute) on a single /// OpenVDB Grid. /// @details This method wraps the parsing, compilation and execution of AX /// code for a single OpenVDB grid of any standard grid type /// (including OpenVDB Points Grids). Provided AX code is expected to /// only refer to the provided single grid. On success, the grid will /// have its voxels or point data modified as dictated by the provided /// AX code. /// @note Various defaults are applied to this pipeline to provide a simple /// run signature. For OpenVDB Numerical grids, only active voxels are /// processed. For OpenVDB Points grids, all points are processed. Any /// warnings generated by the parser, compiler or executable will be /// ignored. /// @note Various runtime errors may be thrown from the different AX pipeline /// stages. See Exceptions.h for the possible different errors. /// @param ax The null terminated AX code string to parse and compile /// @param grid The grid to which to apply the compiled AX function void run(const char* ax, openvdb::GridBase& grid); /// @brief Run a full AX pipeline (parse, compile and execute) on a vector of /// OpenVDB numerical grids OR a vector of OpenVDB Point Data grids. /// @details This method wraps the parsing, compilation and execution of AX /// code for a vector of OpenVDB grids. The vector must contain either /// a set of any numerical grids supported by the default AX types OR /// a set of OpenVDB Points grids. On success, grids in the provided /// grid vector will be iterated over and updated if they are written /// to. /// @warning The type of grids provided changes the type of AX compilation. If /// the vector is empty, this function immediately returns with no /// other effect. /// @note Various defaults are applied to this pipeline to provide a simple /// run signature. For numerical grids, only active voxels are processed /// and missing grid creation is disabled. For OpenVDB Points grids, all /// points are processed. Any warnings generated by the parser, compiler /// or executable will be ignored. /// @note Various runtime errors may be thrown from the different AX pipeline /// stages. See Exceptions.h for the possible different errors. /// @param ax The null terminated AX code string to parse and compile /// @param grids The grids to which to apply the compiled AX function void run(const char* ax, openvdb::GridPtrVec& grids); } // namespace ax } // namespace OPENVDB_VERSION_NAME } // namespace openvdb #endif // OPENVDB_AX_AX_HAS_BEEN_INCLUDED
NVIDIA-Omniverse/ext-openvdb/openvdb_ax/openvdb_ax/ax.cc
// Copyright Contributors to the OpenVDB Project // SPDX-License-Identifier: MPL-2.0 #include "ax.h" #include "ast/AST.h" #include "compiler/Logger.h" #include "compiler/Compiler.h" #include "compiler/PointExecutable.h" #include "compiler/VolumeExecutable.h" #include <llvm/InitializePasses.h> #include <llvm/PassRegistry.h> #include <llvm/Config/llvm-config.h> // version numbers #include <llvm/Support/TargetSelect.h> // InitializeNativeTarget #include <llvm/Support/ManagedStatic.h> // llvm_shutdown #include <llvm/ExecutionEngine/MCJIT.h> // LLVMLinkInMCJIT #include <tbb/mutex.h> namespace openvdb { OPENVDB_USE_VERSION_NAMESPACE namespace OPENVDB_VERSION_NAME { namespace ax { /// @note Implementation for initialize, isInitialized and unitialized /// reamins in compiler/Compiler.cc void run(const char* ax, openvdb::GridBase& grid) { // Construct a logger that will output errors to cerr and suppress warnings openvdb::ax::Logger logger; // Construct a generic compiler openvdb::ax::Compiler compiler; // Parse the provided code and produce an abstract syntax tree // @note Throws with parser errors if invalid. Parsable code does not // necessarily equate to compilable code const openvdb::ax::ast::Tree::ConstPtr ast = openvdb::ax::ast::parse(ax, logger); if (grid.isType<points::PointDataGrid>()) { // Compile for Point support and produce an executable // @note Throws compiler errors on invalid code. On success, returns // the executable which can be used multiple times on any inputs const openvdb::ax::PointExecutable::Ptr exe = compiler.compile<openvdb::ax::PointExecutable>(*ast, logger); // Execute on the provided points // @note Throws on invalid point inputs such as mismatching types exe->execute(static_cast<points::PointDataGrid&>(grid)); } else { // Compile for numerical grid support and produce an executable // @note Throws compiler errors on invalid code. On success, returns // the executable which can be used multiple times on any inputs const openvdb::ax::VolumeExecutable::Ptr exe = compiler.compile<openvdb::ax::VolumeExecutable>(*ast, logger); // Execute on the provided numerical grid // @note Throws on invalid grid inputs such as mismatching types exe->execute(grid); } } void run(const char* ax, openvdb::GridPtrVec& grids) { if (grids.empty()) return; // Check the type of all grids. If they are all points, run for point data. // Otherwise, run for numerical volumes. Throw if the container has both. const bool points = grids.front()->isType<points::PointDataGrid>(); for (auto& grid : grids) { if (points ^ grid->isType<points::PointDataGrid>()) { OPENVDB_THROW(AXCompilerError, "Unable to process both OpenVDB Points and OpenVDB Volumes in " "a single invocation of ax::run()"); } } // Construct a logger that will output errors to cerr and suppress warnings openvdb::ax::Logger logger; // Construct a generic compiler openvdb::ax::Compiler compiler; // Parse the provided code and produce an abstract syntax tree // @note Throws with parser errors if invalid. Parsable code does not // necessarily equate to compilable code const openvdb::ax::ast::Tree::ConstPtr ast = openvdb::ax::ast::parse(ax, logger); if (points) { // Compile for Point support and produce an executable // @note Throws compiler errors on invalid code. On success, returns // the executable which can be used multiple times on any inputs const openvdb::ax::PointExecutable::Ptr exe = compiler.compile<openvdb::ax::PointExecutable>(*ast, logger); // Execute on the provided points individually // @note Throws on invalid point inputs such as mismatching types for (auto& grid : grids) { exe->execute(static_cast<points::PointDataGrid&>(*grid)); } } else { // Compile for Volume support and produce an executable // @note Throws compiler errors on invalid code. On success, returns // the executable which can be used multiple times on any inputs const openvdb::ax::VolumeExecutable::Ptr exe = compiler.compile<openvdb::ax::VolumeExecutable>(*ast, logger); // Execute on the provided volumes // @note Throws on invalid grid inputs such as mismatching types exe->execute(grids); } } namespace { // Declare this at file scope to ensure thread-safe initialization. tbb::mutex sInitMutex; bool sIsInitialized = false; bool sShutdown = false; } bool isInitialized() { tbb::mutex::scoped_lock lock(sInitMutex); return sIsInitialized; } void initialize() { tbb::mutex::scoped_lock lock(sInitMutex); if (sIsInitialized) return; if (sShutdown) { OPENVDB_THROW(AXCompilerError, "Unable to re-initialize LLVM target after uninitialize has been called."); } // Init JIT if (llvm::InitializeNativeTarget() || llvm::InitializeNativeTargetAsmPrinter() || llvm::InitializeNativeTargetAsmParser()) { OPENVDB_THROW(AXCompilerError, "Failed to initialize LLVM target for JIT"); } // required on some systems LLVMLinkInMCJIT(); // Initialize passes llvm::PassRegistry& registry = *llvm::PassRegistry::getPassRegistry(); llvm::initializeCore(registry); llvm::initializeScalarOpts(registry); llvm::initializeObjCARCOpts(registry); llvm::initializeVectorization(registry); llvm::initializeIPO(registry); llvm::initializeAnalysis(registry); llvm::initializeTransformUtils(registry); llvm::initializeInstCombine(registry); #if LLVM_VERSION_MAJOR > 6 llvm::initializeAggressiveInstCombine(registry); #endif llvm::initializeInstrumentation(registry); llvm::initializeTarget(registry); // For codegen passes, only passes that do IR to IR transformation are // supported. llvm::initializeExpandMemCmpPassPass(registry); llvm::initializeScalarizeMaskedMemIntrinPass(registry); llvm::initializeCodeGenPreparePass(registry); llvm::initializeAtomicExpandPass(registry); llvm::initializeRewriteSymbolsLegacyPassPass(registry); llvm::initializeWinEHPreparePass(registry); llvm::initializeDwarfEHPreparePass(registry); llvm::initializeSafeStackLegacyPassPass(registry); llvm::initializeSjLjEHPreparePass(registry); llvm::initializePreISelIntrinsicLoweringLegacyPassPass(registry); llvm::initializeGlobalMergePass(registry); #if LLVM_VERSION_MAJOR > 6 llvm::initializeIndirectBrExpandPassPass(registry); #endif #if LLVM_VERSION_MAJOR > 7 llvm::initializeInterleavedLoadCombinePass(registry); #endif llvm::initializeInterleavedAccessPass(registry); llvm::initializeEntryExitInstrumenterPass(registry); llvm::initializePostInlineEntryExitInstrumenterPass(registry); llvm::initializeUnreachableBlockElimLegacyPassPass(registry); llvm::initializeExpandReductionsPass(registry); #if LLVM_VERSION_MAJOR > 6 llvm::initializeWasmEHPreparePass(registry); #endif llvm::initializeWriteBitcodePassPass(registry); sIsInitialized = true; } void uninitialize() { tbb::mutex::scoped_lock lock(sInitMutex); if (!sIsInitialized) return; // @todo consider replacing with storage to Support/InitLLVM llvm::llvm_shutdown(); sIsInitialized = false; sShutdown = true; } } // namespace ax } // namespace OPENVDB_VERSION_NAME } // namespace openvdb
NVIDIA-Omniverse/ext-openvdb/openvdb_ax/openvdb_ax/Exceptions.h
// Copyright Contributors to the OpenVDB Project // SPDX-License-Identifier: MPL-2.0 /// @file openvdb_ax/Exceptions.h /// /// @authors Nick Avramoussis, Richard Jones /// /// @brief OpenVDB AX Exceptions /// #ifndef OPENVDB_AX_EXCEPTIONS_HAS_BEEN_INCLUDED #define OPENVDB_AX_EXCEPTIONS_HAS_BEEN_INCLUDED #include <openvdb/version.h> #include <openvdb/Exceptions.h> #include <sstream> #include <string> namespace openvdb { OPENVDB_USE_VERSION_NAMESPACE namespace OPENVDB_VERSION_NAME { #define OPENVDB_AX_EXCEPTION(_classname) \ class OPENVDB_API _classname: public Exception \ { \ public: \ _classname() noexcept: Exception( #_classname ) {} \ explicit _classname(const std::string& msg) noexcept: Exception( #_classname , &msg) {} \ } // @note: Compilation errors due to invalid AX code should be collected using a separate logging system. // These errors are only thrown upon encountering fatal errors within the compiler/executables themselves OPENVDB_AX_EXCEPTION(AXTokenError); OPENVDB_AX_EXCEPTION(AXSyntaxError); OPENVDB_AX_EXCEPTION(AXCodeGenError); OPENVDB_AX_EXCEPTION(AXCompilerError); OPENVDB_AX_EXCEPTION(AXExecutionError); #undef OPENVDB_AX_EXCEPTION } // namespace OPENVDB_VERSION_NAME } // namespace openvdb #endif // OPENVDB_AX_EXCEPTIONS_HAS_BEEN_INCLUDED
NVIDIA-Omniverse/ext-openvdb/openvdb_ax/openvdb_ax/CMakeLists.txt
# Copyright Contributors to the OpenVDB Project # SPDX-License-Identifier: MPL-2.0 # #[=======================================================================[ CMake Configuration for OpenVDB AX #]=======================================================================] cmake_minimum_required(VERSION 3.12) project(OpenVDBAXCore LANGUAGES CXX) include(GNUInstallDirs) option(OPENVDB_AX_SHARED "Build dynamically linked version of the ax library." ON) option(OPENVDB_AX_STATIC "Build statically linked version of the ax library." ON) option(USE_NEW_PASS_MANAGER [=[ Enable the new Optimization Pass Manager. This is a developer option.]=] OFF) if(NOT OPENVDB_AX_SHARED AND NOT OPENVDB_AX_STATIC) message(FATAL_ERROR "Both static and shared ax OpenVDB libraries have been disabled. " "At least one must be enabled when building the ax library." ) endif() mark_as_advanced(USE_NEW_PASS_MANAGER) ######################################################################### message(STATUS "----------------------------------------------------") message(STATUS "-------------- Configuring OpenVDBAX ---------------") message(STATUS "----------------------------------------------------") ########################################################################## if(NOT OPENVDB_BUILD_CORE) set(OPENVDB_LIB OpenVDB::openvdb) else() set(OPENVDB_LIB openvdb) endif() # Configure grammar target set(OPENVDB_AX_GRAMMAR_DIR ${CMAKE_CURRENT_BINARY_DIR}/openvdb_ax/grammar) file(MAKE_DIRECTORY ${OPENVDB_AX_GRAMMAR_DIR}) if(OPENVDB_BUILD_AX_GRAMMAR) find_package(FLEX REQUIRED) find_package(BISON 3.0 REQUIRED) set(BISON_COMPILE_FLAGS "${BISON_COMPILE_FLAGS} -Werror") if(OPENVDB_AX_GRAMMAR_NO_LINES) # Suppress #line directives set(FLEX_COMPILE_FLAGS "${FLEX_COMPILE_FLAGS} -L") set(BISON_COMPILE_FLAGS "${BISON_COMPILE_FLAGS} -l") endif() FLEX_TARGET(openvdb_ax_lexer grammar/axlexer.l ${OPENVDB_AX_GRAMMAR_DIR}/axlexer.cc COMPILE_FLAGS ${FLEX_COMPILE_FLAGS} ) BISON_TARGET(openvdb_ax_parser grammar/axparser.y ${OPENVDB_AX_GRAMMAR_DIR}/axparser.cc DEFINES_FILE ${OPENVDB_AX_GRAMMAR_DIR}/axparser.h COMPILE_FLAGS ${BISON_COMPILE_FLAGS} ) ADD_FLEX_BISON_DEPENDENCY(openvdb_ax_lexer openvdb_ax_parser) # Add a custom target so the language is only ever generated once add_custom_target(openvdb_ax_grammar COMMENT "Re-generate the AX language files." DEPENDS ${OPENVDB_AX_GRAMMAR_DIR}/axlexer.cc ${OPENVDB_AX_GRAMMAR_DIR}/axparser.cc) endif() ######################################################################### # Configure LLVM find_package(LLVM REQUIRED) find_library(found_LLVM LLVM HINTS ${LLVM_LIBRARY_DIRS}) if(found_LLVM) set(LLVM_LIBS "LLVM") else() llvm_map_components_to_libnames(_llvm_libs native core executionengine support mcjit passes objcarcopts) set(LLVM_LIBS "${_llvm_libs}") endif() if(MINIMUM_LLVM_VERSION) if(LLVM_PACKAGE_VERSION VERSION_LESS MINIMUM_LLVM_VERSION) message(FATAL_ERROR "Could NOT find LLVM: Found unsuitable version \"${LLVM_PACKAGE_VERSION}\", " "but required is at least \"${MINIMUM_LLVM_VERSION}\" (found ${LLVM_DIR})") endif() endif() message(STATUS "Found LLVM: ${LLVM_DIR} (found suitable version \"${LLVM_PACKAGE_VERSION}\", " "minimum required is \"${MINIMUM_LLVM_VERSION}\")") ######################################################################### set(OPENVDB_AX_LIBRARY_SOURCE_FILES ast/Parse.cc ast/PrintTree.cc ast/Scanners.cc ax.cc codegen/ComputeGenerator.cc codegen/FunctionRegistry.cc codegen/FunctionTypes.cc codegen/PointComputeGenerator.cc codegen/PointFunctions.cc codegen/StandardFunctions.cc codegen/Types.cc codegen/VolumeComputeGenerator.cc codegen/VolumeFunctions.cc compiler/Compiler.cc compiler/Logger.cc compiler/PointExecutable.cc compiler/VolumeExecutable.cc math/OpenSimplexNoise.cc ) if(OPENVDB_BUILD_AX_GRAMMAR) list(APPEND OPENVDB_AX_LIBRARY_SOURCE_FILES ${OPENVDB_AX_GRAMMAR_DIR}/axlexer.cc ${OPENVDB_AX_GRAMMAR_DIR}/axparser.cc) else() list(APPEND OPENVDB_AX_LIBRARY_SOURCE_FILES grammar/generated/axlexer.cc grammar/generated/axparser.cc) endif() set(OPENVDB_AX_AST_INCLUDE_FILES ast/AST.h ast/Parse.h ast/PrintTree.h ast/Scanners.h ast/Tokens.h ast/Visitor.h ) set(OPENVDB_AX_CODEGEN_INCLUDE_FILES codegen/ComputeGenerator.h codegen/ConstantFolding.h codegen/FunctionRegistry.h codegen/Functions.h codegen/FunctionTypes.h codegen/PointComputeGenerator.h codegen/PointLeafLocalData.h codegen/SymbolTable.h codegen/Types.h codegen/Utils.h codegen/VolumeComputeGenerator.h math/OpenSimplexNoise.h ) set(OPENVDB_AX_COMPILER_INCLUDE_FILES compiler/AttributeRegistry.h compiler/Compiler.h compiler/CompilerOptions.h compiler/CustomData.h compiler/Logger.h compiler/PointExecutable.h compiler/VolumeExecutable.h ) # @todo CMake >= 3.12, use an object library to consolidate shared/static # builds. There are limitations with earlier versions of CMake when used with # imported targets. if(OPENVDB_AX_SHARED) add_library(openvdb_ax_shared SHARED ${OPENVDB_AX_LIBRARY_SOURCE_FILES}) if(OPENVDB_BUILD_AX_GRAMMAR) add_dependencies(openvdb_ax_shared openvdb_ax_grammar) endif() endif() if(OPENVDB_AX_STATIC) add_library(openvdb_ax_static STATIC ${OPENVDB_AX_LIBRARY_SOURCE_FILES}) if(OPENVDB_BUILD_AX_GRAMMAR) add_dependencies(openvdb_ax_static openvdb_ax_grammar) endif() endif() # Alias either the shared or static library to the generic OpenVDB # target. Dependent components should use this target to build against # such that they are always able to find a valid build of OpenVDB if(OPENVDB_AX_SHARED) add_library(openvdb_ax ALIAS openvdb_ax_shared) else() add_library(openvdb_ax ALIAS openvdb_ax_static) endif() set(OPENVDB_AX_CORE_DEPENDENT_LIBS ${OPENVDB_LIB} ${LLVM_LIBS} ) ########################################################################## # Configure static build if(OPENVDB_AX_STATIC) target_compile_definitions(openvdb_ax_static PUBLIC ${LLVM_DEFINITIONS}) target_include_directories(openvdb_ax_static PUBLIC ../) target_include_directories(openvdb_ax_static SYSTEM PUBLIC ${LLVM_INCLUDE_DIRS} ) if(OPENVDB_BUILD_AX_GRAMMAR) target_include_directories(openvdb_ax_static PRIVATE ${OPENVDB_AX_GRAMMAR_DIR} ) target_compile_definitions(openvdb_ax_static PRIVATE -DOPENVDB_AX_REGENERATE_GRAMMAR ) endif() set_target_properties(openvdb_ax_static PROPERTIES OUTPUT_NAME openvdb_ax ) target_link_libraries(openvdb_ax_static PUBLIC ${OPENVDB_AX_CORE_DEPENDENT_LIBS} ) if(USE_NEW_PASS_MANAGER) target_compile_definitions(openvdb_ax_static PRIVATE -DUSE_NEW_PASS_MANAGER) endif() endif() if(OPENVDB_AX_SHARED) target_compile_definitions(openvdb_ax_shared PUBLIC ${LLVM_DEFINITIONS}) target_include_directories(openvdb_ax_shared PUBLIC ../) target_include_directories(openvdb_ax_shared SYSTEM PUBLIC ${LLVM_INCLUDE_DIRS} ) if(OPENVDB_BUILD_AX_GRAMMAR) target_include_directories(openvdb_ax_shared PRIVATE ${OPENVDB_AX_GRAMMAR_DIR} ) target_compile_definitions(openvdb_ax_shared PRIVATE -DOPENVDB_AX_REGENERATE_GRAMMAR ) endif() set_target_properties( openvdb_ax_shared PROPERTIES OUTPUT_NAME openvdb_ax SOVERSION ${OpenVDB_MAJOR_VERSION}.${OpenVDB_MINOR_VERSION} VERSION ${OpenVDB_MAJOR_VERSION}.${OpenVDB_MINOR_VERSION}.${OpenVDB_PATCH_VERSION} ) if(OPENVDB_ENABLE_RPATH) # @todo There is probably a better way to do this for imported targets list(APPEND RPATHS ${Boost_LIBRARY_DIRS} ${IlmBase_LIBRARY_DIRS} ${OpenEXR_LIBRARY_DIRS} ${Log4cplus_LIBRARY_DIRS} ${Blosc_LIBRARY_DIRS} ${Tbb_LIBRARY_DIRS} ${LLVM_LIBRARY_DIRS} ) list(REMOVE_DUPLICATES RPATHS) set_target_properties(openvdb_ax_shared PROPERTIES INSTALL_RPATH "${RPATHS}" ) endif() target_link_libraries(openvdb_ax_shared PUBLIC ${OPENVDB_AX_CORE_DEPENDENT_LIBS} ) if(USE_NEW_PASS_MANAGER) target_compile_definitions(openvdb_ax_shared PRIVATE -DUSE_NEW_PASS_MANAGER) endif() endif() install(FILES ax.h Exceptions.h DESTINATION ${CMAKE_INSTALL_INCLUDEDIR}/openvdb_ax/) install(FILES ${OPENVDB_AX_AST_INCLUDE_FILES} DESTINATION ${CMAKE_INSTALL_INCLUDEDIR}/openvdb_ax/ast) install(FILES ${OPENVDB_AX_CODEGEN_INCLUDE_FILES} DESTINATION ${CMAKE_INSTALL_INCLUDEDIR}/openvdb_ax/codegen) install(FILES ${OPENVDB_AX_COMPILER_INCLUDE_FILES} DESTINATION ${CMAKE_INSTALL_INCLUDEDIR}/openvdb_ax/compiler) if(OPENVDB_AX_STATIC) install(TARGETS openvdb_ax_static RUNTIME DESTINATION ${CMAKE_INSTALL_BINDIR} LIBRARY DESTINATION ${CMAKE_INSTALL_LIBDIR} ARCHIVE DESTINATION ${CMAKE_INSTALL_LIBDIR} ) endif() if(OPENVDB_AX_SHARED) install(TARGETS openvdb_ax_shared RUNTIME DESTINATION ${CMAKE_INSTALL_BINDIR} LIBRARY DESTINATION ${CMAKE_INSTALL_LIBDIR} ARCHIVE DESTINATION ${CMAKE_INSTALL_LIBDIR} ) endif()
NVIDIA-Omniverse/ext-openvdb/openvdb_ax/openvdb_ax/math/OpenSimplexNoise.h
// Copyright Contributors to the OpenVDB Project // SPDX-License-Identifier: MPL-2.0 /// @file math/OpenSimplexNoise.h /// /// @authors Francisco Gochez /// /// @brief Methods for generating OpenSimplexNoise (n-dimensional gradient noise) /// /// @details This code is based on https://gist.github.com/tombsar/716134ec71d1b8c1b530 /// (accessed on 22/05/2019). We have simplified that code in a number of ways, /// most notably by removing the template on dimension (this only generates 3 /// dimensional noise) and removing the base class as it's unnecessary for our /// uses. We also assume C++ 2011 or above and have thus removed a number of /// ifdef blocks. /// /// The OSN namespace contains the original copyright. /// #ifndef OPENVDB_AX_MATH_OPEN_SIMPLEX_NOISE_HAS_BEEN_INCLUDED #define OPENVDB_AX_MATH_OPEN_SIMPLEX_NOISE_HAS_BEEN_INCLUDED #include <openvdb/version.h> #include <cstdint> namespace openvdb { OPENVDB_USE_VERSION_NAMESPACE namespace OPENVDB_VERSION_NAME { namespace ax { namespace math { template <typename NoiseT> void curlnoise(double (*out)[3], const double (*in)[3]) { float delta = 0.0001f; float a, b; // noise coordinates for vector potential components. float p[3][3] = { { static_cast<float>((*in)[0]) + 000.0f, static_cast<float>((*in)[1]) + 000.0f, static_cast<float>((*in)[2]) + 000.0f }, // x { static_cast<float>((*in)[0]) + 256.0f, static_cast<float>((*in)[1]) - 256.0f, static_cast<float>((*in)[2]) + 256.0f }, // y { static_cast<float>((*in)[0]) - 512.0f, static_cast<float>((*in)[1]) + 512.0f, static_cast<float>((*in)[2]) - 512.0f }, // z }; OPENVDB_NO_TYPE_CONVERSION_WARNING_BEGIN // Compute curl.x a = (NoiseT::noise(p[2][0], p[2][1] + delta, p[2][2]) - NoiseT::noise(p[2][0], p[2][1] - delta, p[2][2])) / (2.0f * delta); b = (NoiseT::noise(p[1][0], p[1][1], p[1][2] + delta) - NoiseT::noise(p[1][0], p[1][1], p[1][2] - delta)) / (2.0f * delta); (*out)[0] = a - b; // Compute curl.y a = (NoiseT::noise(p[0][0], p[0][1], p[0][2] + delta) - NoiseT::noise(p[0][0], p[0][1], p[0][2] - delta)) / (2.0f * delta); b = (NoiseT::noise(p[2][0] + delta, p[2][1], p[2][2]) - NoiseT::noise(p[2][0] - delta, p[2][1], p[2][2])) / (2.0f * delta); (*out)[1] = a - b; // Compute curl.z a = (NoiseT::noise(p[1][0] + delta, p[1][1], p[1][2]) - NoiseT::noise(p[1][0] - delta, p[1][1], p[1][2])) / (2.0f * delta); b = (NoiseT::noise(p[0][0], p[0][1] + delta, p[0][2]) - NoiseT::noise(p[0][0], p[0][1] - delta, p[0][2])) / (2.0f * delta); (*out)[2] = a - b; OPENVDB_NO_TYPE_CONVERSION_WARNING_END } template <typename NoiseT> void curlnoise(double (*out)[3], double x, double y, double z) { const double in[3] = {x, y, z}; curlnoise<NoiseT>(out, &in); } } } } } namespace OSN { // The following is the original copyright notice: /* * * * OpenSimplex (Simplectic) Noise in C++ * by Arthur Tombs * * Modified 2015-01-08 * * This is a derivative work based on OpenSimplex by Kurt Spencer: * https://gist.github.com/KdotJPG/b1270127455a94ac5d19 * * Anyone is free to make use of this software in whatever way they want. * Attribution is appreciated, but not required. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. * IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR * OTHER DEALINGS IN THE SOFTWARE. */ // 3D Implementation of the OpenSimplexNoise generator. class OSNoise { public: using inttype = int64_t; // Initializes the class using a permutation array generated from a 64-bit seed. // Generates a proper permutation (i.e. doesn't merely perform N successive // pair swaps on a base array). // Uses a simple 64-bit LCG. OSNoise(inttype seed = 0LL); OSNoise(const int * p); template <typename T> T eval(const T x, const T y, const T z) const; private: template <typename T> inline T extrapolate(const inttype xsb, const inttype ysb, const inttype zsb, const T dx, const T dy, const T dz) const; template <typename T> inline T extrapolate(const inttype xsb, const inttype ysb, const inttype zsb, const T dx, const T dy, const T dz, T (&de) [3]) const; int mPerm [256]; // Array of gradient values for 3D. Values are defined below the class definition. static const int sGradients [72]; // Because 72 is not a power of two, extrapolate cannot use a bitmask to index // into the perm array. Pre-calculate and store the indices instead. int mPermGradIndex [256]; }; } #endif // OPENVDB_AX_MATH_OPEN_SIMPLEX_NOISE_HAS_BEEN_INCLUDED
NVIDIA-Omniverse/ext-openvdb/openvdb_ax/openvdb_ax/math/OpenSimplexNoise.cc
// Copyright Contributors to the OpenVDB Project // SPDX-License-Identifier: MPL-2.0 /// @file math/OpenSimplexNoise.cc #include "OpenSimplexNoise.h" #include <algorithm> #include <cmath> #include <type_traits> // see OpenSimplexNoise.h for details about the origin on this code namespace OSN { namespace { template <typename T> inline T pow4 (T x) { x *= x; return x*x; } template <typename T> inline T pow2 (T x) { return x*x; } template <typename T> inline OSNoise::inttype fastFloori (T x) { OSNoise::inttype ip = (OSNoise::inttype)x; if (x < 0.0) --ip; return ip; } inline void LCG_STEP (int64_t & x) { // Magic constants are attributed to Donald Knuth's MMIX implementation. static const int64_t MULTIPLIER = 6364136223846793005LL; static const int64_t INCREMENT = 1442695040888963407LL; x = ((x * MULTIPLIER) + INCREMENT); } } // anonymous namespace // Array of gradient values for 3D. They approximate the directions to the // vertices of a rhombicuboctahedron from its center, skewed so that the // triangular and square facets can be inscribed in circles of the same radius. // New gradient set 2014-10-06. const int OSNoise::sGradients [] = { -11, 4, 4, -4, 11, 4, -4, 4, 11, 11, 4, 4, 4, 11, 4, 4, 4, 11, -11,-4, 4, -4,-11, 4, -4,-4, 11, 11,-4, 4, 4,-11, 4, 4,-4, 11, -11, 4,-4, -4, 11,-4, -4, 4,-11, 11, 4,-4, 4, 11,-4, 4, 4,-11, -11,-4,-4, -4,-11,-4, -4,-4,-11, 11,-4,-4, 4,-11,-4, 4,-4,-11 }; template <typename T> inline T OSNoise::extrapolate(const OSNoise::inttype xsb, const OSNoise::inttype ysb, const OSNoise::inttype zsb, const T dx, const T dy, const T dz) const { unsigned int index = mPermGradIndex[(mPerm[(mPerm[xsb & 0xFF] + ysb) & 0xFF] + zsb) & 0xFF]; return sGradients[index] * dx + sGradients[index + 1] * dy + sGradients[index + 2] * dz; } template <typename T> inline T OSNoise::extrapolate(const OSNoise::inttype xsb, const OSNoise::inttype ysb, const OSNoise::inttype zsb, const T dx, const T dy, const T dz, T (&de) [3]) const { unsigned int index = mPermGradIndex[(mPerm[(mPerm[xsb & 0xFF] + ysb) & 0xFF] + zsb) & 0xFF]; return (de[0] = sGradients[index]) * dx + (de[1] = sGradients[index + 1]) * dy + (de[2] = sGradients[index + 2]) * dz; } OSNoise::OSNoise(OSNoise::inttype seed) { int source [256]; for (int i = 0; i < 256; ++i) { source[i] = i; } LCG_STEP(seed); LCG_STEP(seed); LCG_STEP(seed); for (int i = 255; i >= 0; --i) { LCG_STEP(seed); int r = (int)((seed + 31) % (i + 1)); if (r < 0) { r += (i + 1); } mPerm[i] = source[r]; mPermGradIndex[i] = (int)((mPerm[i] % (72 / 3)) * 3); source[r] = source[i]; } } OSNoise::OSNoise(const int * p) { // Copy the supplied permutation array into this instance. for (int i = 0; i < 256; ++i) { mPerm[i] = p[i]; mPermGradIndex[i] = (int)((mPerm[i] % (72 / 3)) * 3); } } template <typename T> T OSNoise::eval(const T x, const T y, const T z) const { static_assert(std::is_floating_point<T>::value, "OpenSimplexNoise can only be used with floating-point types"); static const T STRETCH_CONSTANT = (T)(-1.0 / 6.0); // (1 / sqrt(3 + 1) - 1) / 3 static const T SQUISH_CONSTANT = (T)(1.0 / 3.0); // (sqrt(3 + 1) - 1) / 3 static const T NORM_CONSTANT = (T)(1.0 / 103.0); OSNoise::inttype xsb, ysb, zsb; T dx0, dy0, dz0; T xins, yins, zins; // Parameters for the individual contributions T contr_m [9], contr_ext [9]; { // Place input coordinates on simplectic lattice. T stretchOffset = (x + y + z) * STRETCH_CONSTANT; T xs = x + stretchOffset; T ys = y + stretchOffset; T zs = z + stretchOffset; // Floor to get simplectic lattice coordinates of rhombohedron // (stretched cube) super-cell. #ifdef __FAST_MATH__ T xsbd = std::floor(xs); T ysbd = std::floor(ys); T zsbd = std::floor(zs); xsb = (OSNoise::inttype)xsbd; ysb = (OSNoise::inttype)ysbd; zsb = (OSNoise::inttype)zsbd; #else xsb = fastFloori(xs); ysb = fastFloori(ys); zsb = fastFloori(zs); T xsbd = (T)xsb; T ysbd = (T)ysb; T zsbd = (T)zsb; #endif // Skew out to get actual coordinates of rhombohedron origin. T squishOffset = (xsbd + ysbd + zsbd) * SQUISH_CONSTANT; T xb = xsbd + squishOffset; T yb = ysbd + squishOffset; T zb = zsbd + squishOffset; // Positions relative to origin point. dx0 = x - xb; dy0 = y - yb; dz0 = z - zb; // Compute simplectic lattice coordinates relative to rhombohedral origin. xins = xs - xsbd; yins = ys - ysbd; zins = zs - zsbd; } // These are given values inside the next block, and used afterwards. OSNoise::inttype xsv_ext0, ysv_ext0, zsv_ext0; OSNoise::inttype xsv_ext1, ysv_ext1, zsv_ext1; T dx_ext0, dy_ext0, dz_ext0; T dx_ext1, dy_ext1, dz_ext1; // Sum together to get a value that determines which cell we are in. T inSum = xins + yins + zins; if (inSum > (T)1.0 && inSum < (T)2.0) { // The point is inside the octahedron (rectified 3-Simplex) inbetween. T aScore; uint_fast8_t aPoint; bool aIsFurtherSide; T bScore; uint_fast8_t bPoint; bool bIsFurtherSide; // Decide between point (1,0,0) and (0,1,1) as closest. T p1 = xins + yins; if (p1 <= (T)1.0) { aScore = (T)1.0 - p1; aPoint = 4; aIsFurtherSide = false; } else { aScore = p1 - (T)1.0; aPoint = 3; aIsFurtherSide = true; } // Decide between point (0,1,0) and (1,0,1) as closest. T p2 = xins + zins; if (p2 <= (T)1.0) { bScore = (T)1.0 - p2; bPoint = 2; bIsFurtherSide = false; } else { bScore = p2 - (T)1.0; bPoint = 5; bIsFurtherSide = true; } // The closest out of the two (0,0,1) and (1,1,0) will replace the // furthest out of the two decided above if closer. T p3 = yins + zins; if (p3 > (T)1.0) { T score = p3 - (T)1.0; if (aScore > bScore && bScore < score) { bScore = score; bPoint = 6; bIsFurtherSide = true; } else if (aScore <= bScore && aScore < score) { aScore = score; aPoint = 6; aIsFurtherSide = true; } } else { T score = (T)1.0 - p3; if (aScore > bScore && bScore < score) { bScore = score; bPoint = 1; bIsFurtherSide = false; } else if (aScore <= bScore && aScore < score) { aScore = score; aPoint = 1; aIsFurtherSide = false; } } // Where each of the two closest points are determines how the // extra two vertices are calculated. if (aIsFurtherSide == bIsFurtherSide) { if (aIsFurtherSide) { // Both closest points on (1,1,1) side. // One of the two extra points is (1,1,1) xsv_ext0 = xsb + 1; ysv_ext0 = ysb + 1; zsv_ext0 = zsb + 1; dx_ext0 = dx0 - (T)1.0 - (SQUISH_CONSTANT * (T)3.0); dy_ext0 = dy0 - (T)1.0 - (SQUISH_CONSTANT * (T)3.0); dz_ext0 = dz0 - (T)1.0 - (SQUISH_CONSTANT * (T)3.0); // Other extra point is based on the shared axis. uint_fast8_t c = aPoint & bPoint; if (c & 0x01) { xsv_ext1 = xsb + 2; ysv_ext1 = ysb; zsv_ext1 = zsb; dx_ext1 = dx0 - (T)2.0 - (SQUISH_CONSTANT * (T)2.0); dy_ext1 = dy0 - (SQUISH_CONSTANT * (T)2.0); dz_ext1 = dz0 - (SQUISH_CONSTANT * (T)2.0); } else if (c & 0x02) { xsv_ext1 = xsb; ysv_ext1 = ysb + 2; zsv_ext1 = zsb; dx_ext1 = dx0 - (SQUISH_CONSTANT * (T)2.0); dy_ext1 = dy0 - (T)2.0 - (SQUISH_CONSTANT * (T)2.0); dz_ext1 = dz0 - (SQUISH_CONSTANT * (T)2.0); } else { xsv_ext1 = xsb; ysv_ext1 = ysb; zsv_ext1 = zsb + 2; dx_ext1 = dx0 - (SQUISH_CONSTANT * (T)2.0); dy_ext1 = dy0 - (SQUISH_CONSTANT * (T)2.0); dz_ext1 = dz0 - (T)2.0 - (SQUISH_CONSTANT * (T)2.0); } } else { // Both closest points are on the (0,0,0) side. // One of the two extra points is (0,0,0). xsv_ext0 = xsb; ysv_ext0 = ysb; zsv_ext0 = zsb; dx_ext0 = dx0; dy_ext0 = dy0; dz_ext0 = dz0; // The other extra point is based on the omitted axis. uint_fast8_t c = aPoint | bPoint; if (!(c & 0x01)) { xsv_ext1 = xsb - 1; ysv_ext1 = ysb + 1; zsv_ext1 = zsb + 1; dx_ext1 = dx0 + (T)1.0 - SQUISH_CONSTANT; dy_ext1 = dy0 - (T)1.0 - SQUISH_CONSTANT; dz_ext1 = dz0 - (T)1.0 - SQUISH_CONSTANT; } else if (!(c & 0x02)) { xsv_ext1 = xsb + 1; ysv_ext1 = ysb - 1; zsv_ext1 = zsb + 1; dx_ext1 = dx0 - (T)1.0 - SQUISH_CONSTANT; dy_ext1 = dy0 + (T)1.0 - SQUISH_CONSTANT; dz_ext1 = dz0 - (T)1.0 - SQUISH_CONSTANT; } else { xsv_ext1 = xsb + 1; ysv_ext1 = ysb + 1; zsv_ext1 = zsb - 1; dx_ext1 = dx0 - (T)1.0 - SQUISH_CONSTANT; dy_ext1 = dy0 - (T)1.0 - SQUISH_CONSTANT; dz_ext1 = dz0 + (T)1.0 - SQUISH_CONSTANT; } } } else { // One point is on the (0,0,0) side, one point is on the (1,1,1) side. uint_fast8_t c1, c2; if (aIsFurtherSide) { c1 = aPoint; c2 = bPoint; } else { c1 = bPoint; c2 = aPoint; } // One contribution is a permutation of (1,1,-1). if (!(c1 & 0x01)) { xsv_ext0 = xsb - 1; ysv_ext0 = ysb + 1; zsv_ext0 = zsb + 1; dx_ext0 = dx0 + (T)1.0 - SQUISH_CONSTANT; dy_ext0 = dy0 - (T)1.0 - SQUISH_CONSTANT; dz_ext0 = dz0 - (T)1.0 - SQUISH_CONSTANT; } else if (!(c1 & 0x02)) { xsv_ext0 = xsb + 1; ysv_ext0 = ysb - 1; zsv_ext0 = zsb + 1; dx_ext0 = dx0 - (T)1.0 - SQUISH_CONSTANT; dy_ext0 = dy0 + (T)1.0 - SQUISH_CONSTANT; dz_ext0 = dz0 - (T)1.0 - SQUISH_CONSTANT; } else { xsv_ext0 = xsb + 1; ysv_ext0 = ysb + 1; zsv_ext0 = zsb - 1; dx_ext0 = dx0 - (T)1.0 - SQUISH_CONSTANT; dy_ext0 = dy0 - (T)1.0 - SQUISH_CONSTANT; dz_ext0 = dz0 + (T)1.0 - SQUISH_CONSTANT; } // One contribution is a permutation of (0,0,2). if (c2 & 0x01) { xsv_ext1 = xsb + 2; ysv_ext1 = ysb; zsv_ext1 = zsb; dx_ext1 = dx0 - (T)2.0 - (SQUISH_CONSTANT * (T)2.0); dy_ext1 = dy0 - (SQUISH_CONSTANT * (T)2.0); dz_ext1 = dz0 - (SQUISH_CONSTANT * (T)2.0); } else if (c2 & 0x02) { xsv_ext1 = xsb; ysv_ext1 = ysb + 2; zsv_ext1 = zsb; dx_ext1 = dx0 - (SQUISH_CONSTANT * (T)2.0); dy_ext1 = dy0 - (T)2.0 - (SQUISH_CONSTANT * (T)2.0); dz_ext1 = dz0 - (SQUISH_CONSTANT * (T)2.0); } else { xsv_ext1 = xsb; ysv_ext1 = ysb; zsv_ext1 = zsb + 2; dx_ext1 = dx0 - (SQUISH_CONSTANT * (T)2.0); dy_ext1 = dy0 - (SQUISH_CONSTANT * (T)2.0); dz_ext1 = dz0 - (T)2.0 - (SQUISH_CONSTANT * (T)2.0); } } contr_m[0] = contr_ext[0] = 0.0; // Contribution (0,0,1). T dx1 = dx0 - (T)1.0 - SQUISH_CONSTANT; T dy1 = dy0 - SQUISH_CONSTANT; T dz1 = dz0 - SQUISH_CONSTANT; contr_m[1] = pow2(dx1) + pow2(dy1) + pow2(dz1); contr_ext[1] = extrapolate(xsb + 1, ysb, zsb, dx1, dy1, dz1); // Contribution (0,1,0). T dx2 = dx0 - SQUISH_CONSTANT; T dy2 = dy0 - (T)1.0 - SQUISH_CONSTANT; T dz2 = dz1; contr_m[2] = pow2(dx2) + pow2(dy2) + pow2(dz2); contr_ext[2] = extrapolate(xsb, ysb + 1, zsb, dx2, dy2, dz2); // Contribution (1,0,0). T dx3 = dx2; T dy3 = dy1; T dz3 = dz0 - (T)1.0 - SQUISH_CONSTANT; contr_m[3] = pow2(dx3) + pow2(dy3) + pow2(dz3); contr_ext[3] = extrapolate(xsb, ysb, zsb + 1, dx3, dy3, dz3); // Contribution (1,1,0). T dx4 = dx0 - (T)1.0 - (SQUISH_CONSTANT * (T)2.0); T dy4 = dy0 - (T)1.0 - (SQUISH_CONSTANT * (T)2.0); T dz4 = dz0 - (SQUISH_CONSTANT * (T)2.0); contr_m[4] = pow2(dx4) + pow2(dy4) + pow2(dz4); contr_ext[4] = extrapolate(xsb + 1, ysb + 1, zsb, dx4, dy4, dz4); // Contribution (1,0,1). T dx5 = dx4; T dy5 = dy0 - (SQUISH_CONSTANT * (T)2.0); T dz5 = dz0 - (T)1.0 - (SQUISH_CONSTANT * (T)2.0); contr_m[5] = pow2(dx5) + pow2(dy5) + pow2(dz5); contr_ext[5] = extrapolate(xsb + 1, ysb, zsb + 1, dx5, dy5, dz5); // Contribution (0,1,1). T dx6 = dx0 - (SQUISH_CONSTANT * (T)2.0); T dy6 = dy4; T dz6 = dz5; contr_m[6] = pow2(dx6) + pow2(dy6) + pow2(dz6); contr_ext[6] = extrapolate(xsb, ysb + 1, zsb + 1, dx6, dy6, dz6); } else if (inSum <= (T)1.0) { // The point is inside the tetrahedron (3-Simplex) at (0,0,0) // Determine which of (0,0,1), (0,1,0), (1,0,0) are closest. uint_fast8_t aPoint = 1; T aScore = xins; uint_fast8_t bPoint = 2; T bScore = yins; if (aScore < bScore && zins > aScore) { aScore = zins; aPoint = 4; } else if (aScore >= bScore && zins > bScore) { bScore = zins; bPoint = 4; } // Determine the two lattice points not part of the tetrahedron that may contribute. // This depends on the closest two tetrahedral vertices, including (0,0,0). T wins = (T)1.0 - inSum; if (wins > aScore || wins > bScore) { // (0,0,0) is one of the closest two tetrahedral vertices. // The other closest vertex is the closer of a and b. uint_fast8_t c = ((bScore > aScore) ? bPoint : aPoint); if (c != 1) { xsv_ext0 = xsb - 1; xsv_ext1 = xsb; dx_ext0 = dx0 + (T)1.0; dx_ext1 = dx0; } else { xsv_ext0 = xsv_ext1 = xsb + 1; dx_ext0 = dx_ext1 = dx0 - (T)1.0; } if (c != 2) { ysv_ext0 = ysv_ext1 = ysb; dy_ext0 = dy_ext1 = dy0; if (c == 1) { ysv_ext0 -= 1; dy_ext0 += (T)1.0; } else { ysv_ext1 -= 1; dy_ext1 += (T)1.0; } } else { ysv_ext0 = ysv_ext1 = ysb + 1; dy_ext0 = dy_ext1 = dy0 - (T)1.0; } if (c != 4) { zsv_ext0 = zsb; zsv_ext1 = zsb - 1; dz_ext0 = dz0; dz_ext1 = dz0 + (T)1.0; } else { zsv_ext0 = zsv_ext1 = zsb + 1; dz_ext0 = dz_ext1 = dz0 - (T)1.0; } } else { // (0,0,0) is not one of the closest two tetrahedral vertices. // The two extra vertices are determined by the closest two. uint_fast8_t c = (aPoint | bPoint); if (c & 0x01) { xsv_ext0 = xsv_ext1 = xsb + 1; dx_ext0 = dx0 - (T)1.0 - (SQUISH_CONSTANT * (T)2.0); dx_ext1 = dx0 - (T)1.0 - SQUISH_CONSTANT; } else { xsv_ext0 = xsb; xsv_ext1 = xsb - 1; dx_ext0 = dx0 - (SQUISH_CONSTANT * (T)2.0); dx_ext1 = dx0 + (T)1.0 - SQUISH_CONSTANT; } if (c & 0x02) { ysv_ext0 = ysv_ext1 = ysb + 1; dy_ext0 = dy0 - (T)1.0 - (SQUISH_CONSTANT * (T)2.0); dy_ext1 = dy0 - (T)1.0 - SQUISH_CONSTANT; } else { ysv_ext0 = ysb; ysv_ext1 = ysb - 1; dy_ext0 = dy0 - (SQUISH_CONSTANT * (T)2.0); dy_ext1 = dy0 + (T)1.0 - SQUISH_CONSTANT; } if (c & 0x04) { zsv_ext0 = zsv_ext1 = zsb + 1; dz_ext0 = dz0 - (T)1.0 - (SQUISH_CONSTANT * (T)2.0); dz_ext1 = dz0 - (T)1.0 - SQUISH_CONSTANT; } else { zsv_ext0 = zsb; zsv_ext1 = zsb - 1; dz_ext0 = dz0 - (SQUISH_CONSTANT * (T)2.0); dz_ext1 = dz0 + (T)1.0 - SQUISH_CONSTANT; } } // Contribution (0,0,0) { contr_m[0] = pow2(dx0) + pow2(dy0) + pow2(dz0); contr_ext[0] = extrapolate(xsb, ysb, zsb, dx0, dy0, dz0); } // Contribution (0,0,1) T dx1 = dx0 - (T)1.0 - SQUISH_CONSTANT; T dy1 = dy0 - SQUISH_CONSTANT; T dz1 = dz0 - SQUISH_CONSTANT; contr_m[1] = pow2(dx1) + pow2(dy1) + pow2(dz1); contr_ext[1] = extrapolate(xsb + 1, ysb, zsb, dx1, dy1, dz1); // Contribution (0,1,0) T dx2 = dx0 - SQUISH_CONSTANT; T dy2 = dy0 - (T)1.0 - SQUISH_CONSTANT; T dz2 = dz1; contr_m[2] = pow2(dx2) + pow2(dy2) + pow2(dz2); contr_ext[2] = extrapolate(xsb, ysb + 1, zsb, dx2, dy2, dz2); // Contribution (1,0,0) T dx3 = dx2; T dy3 = dy1; T dz3 = dz0 - (T)1.0 - SQUISH_CONSTANT; contr_m[3] = pow2(dx3) + pow2(dy3) + pow2(dz3); contr_ext[3] = extrapolate(xsb, ysb, zsb + 1, dx3, dy3, dz3); contr_m[4] = contr_m[5] = contr_m[6] = 0.0; contr_ext[4] = contr_ext[5] = contr_ext[6] = 0.0; } else { // The point is inside the tetrahedron (3-Simplex) at (1,1,1) // Determine which two tetrahedral vertices are the closest // out of (1,1,0), (1,0,1), and (0,1,1), but not (1,1,1). uint_fast8_t aPoint = 6; T aScore = xins; uint_fast8_t bPoint = 5; T bScore = yins; if (aScore <= bScore && zins < bScore) { bScore = zins; bPoint = 3; } else if (aScore > bScore && zins < aScore) { aScore = zins; aPoint = 3; } // Determine the two lattice points not part of the tetrahedron that may contribute. // This depends on the closest two tetrahedral vertices, including (1,1,1). T wins = 3.0 - inSum; if (wins < aScore || wins < bScore) { // (1,1,1) is one of the closest two tetrahedral vertices. // The other closest vertex is the closest of a and b. uint_fast8_t c = ((bScore < aScore) ? bPoint : aPoint); if (c & 0x01) { xsv_ext0 = xsb + 2; xsv_ext1 = xsb + 1; dx_ext0 = dx0 - (T)2.0 - (SQUISH_CONSTANT * (T)3.0); dx_ext1 = dx0 - (T)1.0 - (SQUISH_CONSTANT * (T)3.0); } else { xsv_ext0 = xsv_ext1 = xsb; dx_ext0 = dx_ext1 = dx0 - (SQUISH_CONSTANT * (T)3.0); } if (c & 0x02) { ysv_ext0 = ysv_ext1 = ysb + 1; dy_ext0 = dy_ext1 = dy0 - (T)1.0 - (SQUISH_CONSTANT * (T)3.0); if (c & 0x01) { ysv_ext1 += 1; dy_ext1 -= (T)1.0; } else { ysv_ext0 += 1; dy_ext0 -= (T)1.0; } } else { ysv_ext0 = ysv_ext1 = ysb; dy_ext0 = dy_ext1 = dy0 - (SQUISH_CONSTANT * (T)3.0); } if (c & 0x04) { zsv_ext0 = zsb + 1; zsv_ext1 = zsb + 2; dz_ext0 = dz0 - (T)1.0 - (SQUISH_CONSTANT * (T)3.0); dz_ext1 = dz0 - (T)2.0 - (SQUISH_CONSTANT * (T)3.0); } else { zsv_ext0 = zsv_ext1 = zsb; dz_ext0 = dz_ext1 = dz0 - (SQUISH_CONSTANT * (T)3.0); } } else { // (1,1,1) is not one of the closest two tetrahedral vertices. // The two extra vertices are determined by the closest two. uint_fast8_t c = aPoint & bPoint; if (c & 0x01) { xsv_ext0 = xsb + 1; xsv_ext1 = xsb + 2; dx_ext0 = dx0 - (T)1.0 - SQUISH_CONSTANT; dx_ext1 = dx0 - (T)2.0 - (SQUISH_CONSTANT * (T)2.0); } else { xsv_ext0 = xsv_ext1 = xsb; dx_ext0 = dx0 - SQUISH_CONSTANT; dx_ext1 = dx0 - (SQUISH_CONSTANT * (T)2.0); } if (c & 0x02) { ysv_ext0 = ysb + 1; ysv_ext1 = ysb + 2; dy_ext0 = dy0 - (T)1.0 - SQUISH_CONSTANT; dy_ext1 = dy0 - (T)2.0 - (SQUISH_CONSTANT * (T)2.0); } else { ysv_ext0 = ysv_ext1 = ysb; dy_ext0 = dy0 - SQUISH_CONSTANT; dy_ext1 = dy0 - (SQUISH_CONSTANT * (T)2.0); } if (c & 0x04) { zsv_ext0 = zsb + 1; zsv_ext1 = zsb + 2; dz_ext0 = dz0 - (T)1.0 - SQUISH_CONSTANT; dz_ext1 = dz0 - (T)2.0 - (SQUISH_CONSTANT * (T)2.0); } else { zsv_ext0 = zsv_ext1 = zsb; dz_ext0 = dz0 - SQUISH_CONSTANT; dz_ext1 = dz0 - (SQUISH_CONSTANT * (T)2.0); } } // Contribution (1,1,0) T dx3 = dx0 - (T)1.0 - (SQUISH_CONSTANT * (T)2.0); T dy3 = dy0 - (T)1.0 - (SQUISH_CONSTANT * (T)2.0); T dz3 = dz0 - (SQUISH_CONSTANT * (T)2.0); contr_m[3] = pow2(dx3) + pow2(dy3) + pow2(dz3); contr_ext[3] = extrapolate(xsb + 1, ysb + 1, zsb, dx3, dy3, dz3); // Contribution (1,0,1) T dx2 = dx3; T dy2 = dy0 - (SQUISH_CONSTANT * (T)2.0); T dz2 = dz0 - (T)1.0 - (SQUISH_CONSTANT * (T)2.0); contr_m[2] = pow2(dx2) + pow2(dy2) + pow2(dz2); contr_ext[2] = extrapolate(xsb + 1, ysb, zsb + 1, dx2, dy2, dz2); // Contribution (0,1,1) { T dx1 = dx0 - (SQUISH_CONSTANT * (T)2.0); T dy1 = dy3; T dz1 = dz2; contr_m[1] = pow2(dx1) + pow2(dy1) + pow2(dz1); contr_ext[1] = extrapolate(xsb, ysb + 1, zsb + 1, dx1, dy1, dz1); } // Contribution (1,1,1) { dx0 = dx0 - (T)1.0 - (SQUISH_CONSTANT * (T)3.0); dy0 = dy0 - (T)1.0 - (SQUISH_CONSTANT * (T)3.0); dz0 = dz0 - (T)1.0 - (SQUISH_CONSTANT * (T)3.0); contr_m[0] = pow2(dx0) + pow2(dy0) + pow2(dz0); contr_ext[0] = extrapolate(xsb + 1, ysb + 1, zsb + 1, dx0, dy0, dz0); } contr_m[4] = contr_m[5] = contr_m[6] = 0.0; contr_ext[4] = contr_ext[5] = contr_ext[6] = 0.0; } // First extra vertex. contr_m[7] = pow2(dx_ext0) + pow2(dy_ext0) + pow2(dz_ext0); contr_ext[7] = extrapolate(xsv_ext0, ysv_ext0, zsv_ext0, dx_ext0, dy_ext0, dz_ext0); // Second extra vertex. contr_m[8] = pow2(dx_ext1) + pow2(dy_ext1) + pow2(dz_ext1); contr_ext[8] = extrapolate(xsv_ext1, ysv_ext1, zsv_ext1, dx_ext1, dy_ext1, dz_ext1); T value = 0.0; for (int i=0; i<9; ++i) { value += pow4(std::max((T)2.0 - contr_m[i], (T)0.0)) * contr_ext[i]; } return (value * NORM_CONSTANT); } template double OSNoise::extrapolate(const OSNoise::inttype xsb, const OSNoise::inttype ysb, const OSNoise::inttype zsb, const double dx, const double dy, const double dz) const; template double OSNoise::extrapolate(const OSNoise::inttype xsb, const OSNoise::inttype ysb, const OSNoise::inttype zsb, const double dx, const double dy, const double dz, double (&de) [3]) const; template double OSNoise::eval(const double x, const double y, const double z) const; } // namespace OSN
NVIDIA-Omniverse/ext-openvdb/openvdb_ax/openvdb_ax/test/main.cc
// Copyright Contributors to the OpenVDB Project // SPDX-License-Identifier: MPL-2.0 #include <openvdb_ax/compiler/Compiler.h> #include <openvdb/openvdb.h> #include <openvdb/points/PointDataGrid.h> #include <openvdb/util/CpuTimer.h> #include <openvdb/util/logging.h> #include <cppunit/CompilerOutputter.h> #include <cppunit/TestFailure.h> #include <cppunit/TestListener.h> #include <cppunit/TestResult.h> #include <cppunit/TestResultCollector.h> #include <cppunit/TextTestProgressListener.h> #include <cppunit/extensions/TestFactoryRegistry.h> #include <cppunit/ui/text/TestRunner.h> #include <algorithm> // for std::shuffle() #include <cmath> // for std::round() #include <cstdlib> // for EXIT_SUCCESS #include <cstring> // for strrchr() #include <exception> #include <fstream> #include <iostream> #include <random> #include <string> #include <vector> /// @note Global unit test flag enabled with -g which symbolises the integration /// tests to auto-generate their AX tests. Any previous tests will be /// overwritten. int sGenerateAX = false; namespace { using StringVec = std::vector<std::string>; void usage(const char* progName, std::ostream& ostrm) { ostrm << "Usage: " << progName << " [options]\n" << "Which: runs OpenVDB AX library unit tests\n" << "Options:\n" << " -f file read whitespace-separated names of tests to be run\n" << " from the given file (\"#\" comments are supported)\n" << " -l list all available tests\n" << " -shuffle run tests in random order\n" << " -t test specific suite or test to run, e.g., \"-t TestGrid\"\n" << " or \"-t TestGrid::testGetGrid\" (default: run all tests)\n" << " -v verbose output\n" << " -g As well as testing, auto-generate any integration tests\n"; #ifdef OPENVDB_USE_LOG4CPLUS ostrm << "\n" << " -error log fatal and non-fatal errors (default: log only fatal errors)\n" << " -warn log warnings and errors\n" << " -info log info messages, warnings and errors\n" << " -debug log debugging messages, info messages, warnings and errors\n"; #endif } void getTestNames(StringVec& nameVec, const CppUnit::Test* test) { if (test) { const int numChildren = test->getChildTestCount(); if (numChildren == 0) { nameVec.push_back(test->getName()); } else { for (int i = 0; i < test->getChildTestCount(); ++i) { getTestNames(nameVec, test->getChildTestAt(i)); } } } } /// Listener that prints the name, elapsed time, and error status of each test class TimedTestProgressListener: public CppUnit::TestListener { public: void startTest(CppUnit::Test* test) override { mFailed = false; std::cout << test->getName() << std::flush; mTimer.start(); } void addFailure(const CppUnit::TestFailure& failure) override { std::cout << " : " << (failure.isError() ? "error" : "assertion"); mFailed = true; } void endTest(CppUnit::Test*) override { if (!mFailed) { // Print elapsed time only for successful tests. const double msec = std::round(mTimer.milliseconds()); if (msec > 1.0) { openvdb::util::printTime(std::cout, msec, " : OK (", ")", /*width=*/0, /*precision=*/(msec > 1000.0 ? 1 : 0), /*verbose=*/0); } else { std::cout << " : OK (<1ms)"; } } std::cout << std::endl; } private: openvdb::util::CpuTimer mTimer; bool mFailed = false; }; int run(int argc, char* argv[]) { const char* progName = argv[0]; if (const char* ptr = ::strrchr(progName, '/')) progName = ptr + 1; bool shuffle = false, verbose = false; StringVec tests; for (int i = 1; i < argc; ++i) { const std::string arg = argv[i]; if (arg == "-l") { StringVec allTests; getTestNames(allTests, CppUnit::TestFactoryRegistry::getRegistry().makeTest()); for (const auto& name: allTests) { std::cout << name << "\n"; } return EXIT_SUCCESS; } else if (arg == "-shuffle") { shuffle = true; } else if (arg == "-v") { verbose = true; } else if (arg == "-g") { sGenerateAX = true; } else if (arg == "-t") { if (i + 1 < argc) { ++i; tests.push_back(argv[i]); } else { OPENVDB_LOG_FATAL("missing test name after \"-t\""); usage(progName, std::cerr); return EXIT_FAILURE; } } else if (arg == "-f") { if (i + 1 < argc) { ++i; std::ifstream file{argv[i]}; if (file.fail()) { OPENVDB_LOG_FATAL("unable to read file " << argv[i]); return EXIT_FAILURE; } while (file) { // Read a whitespace-separated string from the file. std::string test; file >> test; if (!test.empty()) { if (test[0] != '#') { tests.push_back(test); } else { // If the string starts with a comment symbol ("#"), // skip it and jump to the end of the line. while (file) { if (file.get() == '\n') break; } } } } } else { OPENVDB_LOG_FATAL("missing filename after \"-f\""); usage(progName, std::cerr); return EXIT_FAILURE; } } else if (arg == "-h" || arg == "-help" || arg == "--help") { usage(progName, std::cout); return EXIT_SUCCESS; } else { OPENVDB_LOG_FATAL("unrecognized option \"" << arg << "\""); usage(progName, std::cerr); return EXIT_FAILURE; } } try { CppUnit::TestFactoryRegistry& registry = CppUnit::TestFactoryRegistry::getRegistry(); auto* root = registry.makeTest(); if (!root) { throw std::runtime_error( "CppUnit test registry was not initialized properly"); } if (!shuffle) { if (tests.empty()) tests.push_back(""); } else { // Get the names of all selected tests and their children. StringVec allTests; if (tests.empty()) { getTestNames(allTests, root); } else { for (const auto& name: tests) { getTestNames(allTests, root->findTest(name)); } } // Randomly shuffle the list of names. std::random_device randDev; std::mt19937 generator(randDev()); std::shuffle(allTests.begin(), allTests.end(), generator); tests.swap(allTests); } CppUnit::TestRunner runner; runner.addTest(root); CppUnit::TestResult controller; CppUnit::TestResultCollector result; controller.addListener(&result); CppUnit::TextTestProgressListener progress; TimedTestProgressListener vProgress; if (verbose) { controller.addListener(&vProgress); } else { controller.addListener(&progress); } for (size_t i = 0; i < tests.size(); ++i) { runner.run(controller, tests[i]); } CppUnit::CompilerOutputter outputter(&result, std::cerr); outputter.write(); return result.wasSuccessful() ? EXIT_SUCCESS : EXIT_FAILURE; } catch (std::exception& e) { OPENVDB_LOG_FATAL(e.what()); return EXIT_FAILURE; } } } // anonymous namespace template <typename T> static inline void registerType() { if (!openvdb::points::TypedAttributeArray<T>::isRegistered()) openvdb::points::TypedAttributeArray<T>::registerType(); } int main(int argc, char *argv[]) { openvdb::initialize(); openvdb::ax::initialize(); openvdb::logging::initialize(argc, argv); // Also intialize Vec2/4 point attributes registerType<openvdb::math::Vec2<int32_t>>(); registerType<openvdb::math::Vec2<float>>(); registerType<openvdb::math::Vec2<double>>(); registerType<openvdb::math::Vec4<int32_t>>(); registerType<openvdb::math::Vec4<float>>(); registerType<openvdb::math::Vec4<double>>(); auto value = run(argc, argv); openvdb::ax::uninitialize(); openvdb::uninitialize(); return value; }
NVIDIA-Omniverse/ext-openvdb/openvdb_ax/openvdb_ax/test/CMakeLists.txt
# Copyright Contributors to the OpenVDB Project # SPDX-License-Identifier: MPL-2.0 # #[=======================================================================[ CMake Configuration for OpenVDB Unit Tests #]=======================================================================] cmake_minimum_required(VERSION 3.12) project(OpenVDBAXUnitTests LANGUAGES CXX) option(OPENVDB_AX_TEST_PROFILE "Switch on profiling for some of the unit tests." OFF) ########################################################################## message(STATUS "----------------------------------------------------") message(STATUS "---------- Configuring OpenVDBAXUnitTests ----------") message(STATUS "----------------------------------------------------") ########################################################################## if(NOT OPENVDB_BUILD_AX) set(OPENVDBAX_LIB OpenVDB::openvdb_ax) else() set(OPENVDBAX_LIB openvdb_ax) endif() find_package(CppUnit ${MINIMUM_CPPUNIT_VERSION} REQUIRED) set(TEST_SOURCE_FILES ast/TestScanners.cc ast/TestPrinters.cc backend/TestComputeGeneratorFailures.cc backend/TestFunctionGroup.cc backend/TestFunctionRegistry.cc backend/TestFunctionTypes.cc backend/TestLogger.cc backend/TestSymbolTable.cc backend/TestTypes.cc compiler/TestAXRun.cc compiler/TestPointExecutable.cc compiler/TestVolumeExecutable.cc frontend/TestArrayPack.cc frontend/TestArrayUnpackNode.cc frontend/TestAssignExpressionNode.cc frontend/TestAttributeNode.cc frontend/TestBinaryOperatorNode.cc frontend/TestCastNode.cc frontend/TestCommaOperator.cc frontend/TestConditionalStatementNode.cc frontend/TestCrementNode.cc frontend/TestDeclareLocalNode.cc frontend/TestExternalVariableNode.cc frontend/TestFunctionCallNode.cc frontend/TestKeywordNode.cc frontend/TestLocalNode.cc frontend/TestLoopNode.cc frontend/TestStatementListNode.cc frontend/TestSyntaxFailures.cc frontend/TestTernaryOperatorNode.cc frontend/TestUnaryOperatorNode.cc frontend/TestValueNode.cc integration/CompareGrids.cc integration/TestArrayUnpack.cc integration/TestAssign.cc integration/TestBinary.cc integration/TestCast.cc integration/TestConditional.cc integration/TestCrement.cc integration/TestDeclare.cc integration/TestEmpty.cc integration/TestExternals.cc integration/TestHarness.cc integration/TestKeyword.cc integration/TestLoop.cc integration/TestStandardFunctions.cc integration/TestString.cc integration/TestTernary.cc integration/TestUnary.cc integration/TestVDBFunctions.cc integration/TestWorldSpaceAccessors.cc main.cc ) add_executable(vdb_ax_test ${TEST_SOURCE_FILES} ) target_link_libraries(vdb_ax_test ${OPENVDBAX_LIB} CppUnit::cppunit ) target_include_directories(vdb_ax_test PRIVATE ../ . ) if(OPENVDB_AX_TEST_PROFILE) target_compile_definitions(vdb_ax_test PRIVATE "-DPROFILE") endif() add_test(NAME vdb_ax_unit_test COMMAND vdb_ax_test -v WORKING_DIRECTORY ${CMAKE_CURRENT_LIST_DIR}/../)
NVIDIA-Omniverse/ext-openvdb/openvdb_ax/openvdb_ax/test/util.h
// Copyright Contributors to the OpenVDB Project // SPDX-License-Identifier: MPL-2.0 /// @file test/util.h /// /// @author Nick Avramoussis /// /// @brief Test utilities #ifndef OPENVDB_AX_UNITTEST_UTIL_HAS_BEEN_INCLUDED #define OPENVDB_AX_UNITTEST_UTIL_HAS_BEEN_INCLUDED #include <openvdb_ax/ast/AST.h> #include <openvdb_ax/ast/Parse.h> #include <openvdb_ax/ast/Tokens.h> #include <openvdb_ax/compiler/Logger.h> #include <openvdb/Types.h> #include <memory> #include <vector> #include <utility> #include <string> #include <type_traits> #define ERROR_MSG(Msg, Code) Msg + std::string(": \"") + Code + std::string("\"") #define TEST_SYNTAX_PASSES(Tests) \ { \ openvdb::ax::Logger logger;\ for (const auto& test : Tests) { \ logger.clear();\ const std::string& code = test.first; \ openvdb::ax::ast::Tree::ConstPtr tree = openvdb::ax::ast::parse(code.c_str(), logger);\ std::stringstream str; \ CPPUNIT_ASSERT_MESSAGE(ERROR_MSG("Unexpected parsing error(s)\n", str.str()), tree); \ } \ } \ #define TEST_SYNTAX_FAILS(Tests) \ { \ openvdb::ax::Logger logger([](const std::string&) {});\ for (const auto& test : Tests) { \ logger.clear();\ const std::string& code = test.first; \ openvdb::ax::ast::Tree::ConstPtr tree = openvdb::ax::ast::parse(code.c_str(), logger);\ CPPUNIT_ASSERT_MESSAGE(ERROR_MSG("Expected parsing error", code), logger.hasError()); \ } \ } \ namespace unittest_util { // Use shared pointers rather than unique pointers so initializer lists can easily // be used. Could easily introduce some move semantics to work around this if // necessary. using CodeTests = std::vector<std::pair<std::string, openvdb::ax::ast::Node::Ptr>>; // // Find + Replace all string helper inline void replace(std::string& str, const std::string& oldStr, const std::string& newStr) { std::string::size_type pos = 0u; while ((pos = str.find(oldStr, pos)) != std::string::npos) { str.replace(pos, oldStr.length(), newStr); pos += newStr.length(); } } // inline bool compareLinearTrees(const std::vector<const openvdb::ax::ast::Node*>& a, const std::vector<const openvdb::ax::ast::Node*>& b, const bool allowEmpty = false) { if (!allowEmpty && (a.empty() || b.empty())) return false; if (a.size() != b.size()) return false; const size_t size = a.size(); for (size_t i = 0; i < size; ++i) { if ((a[i] == nullptr) ^ (b[i] == nullptr)) return false; if (a[i] == nullptr) continue; if (a[i]->nodetype() != b[i]->nodetype()) return false; // Specific handling of various node types to compare child data // @todo generalize this // @note Value methods does not compare child text data if (a[i]->nodetype() == openvdb::ax::ast::Node::AssignExpressionNode) { if (static_cast<const openvdb::ax::ast::AssignExpression*>(a[i])->operation() != static_cast<const openvdb::ax::ast::AssignExpression*>(b[i])->operation()) { return false; } } else if (a[i]->nodetype() == openvdb::ax::ast::Node::BinaryOperatorNode) { if (static_cast<const openvdb::ax::ast::BinaryOperator*>(a[i])->operation() != static_cast<const openvdb::ax::ast::BinaryOperator*>(b[i])->operation()) { return false; } } else if (a[i]->nodetype() == openvdb::ax::ast::Node::CrementNode) { if (static_cast<const openvdb::ax::ast::Crement*>(a[i])->operation() != static_cast<const openvdb::ax::ast::Crement*>(b[i])->operation()) { return false; } if (static_cast<const openvdb::ax::ast::Crement*>(a[i])->post() != static_cast<const openvdb::ax::ast::Crement*>(b[i])->post()) { return false; } } else if (a[i]->nodetype() == openvdb::ax::ast::Node::CastNode) { if (static_cast<const openvdb::ax::ast::Cast*>(a[i])->type() != static_cast<const openvdb::ax::ast::Cast*>(b[i])->type()) { return false; } } else if (a[i]->nodetype() == openvdb::ax::ast::Node::FunctionCallNode) { if (static_cast<const openvdb::ax::ast::FunctionCall*>(a[i])->name() != static_cast<const openvdb::ax::ast::FunctionCall*>(b[i])->name()) { return false; } } else if (a[i]->nodetype() == openvdb::ax::ast::Node::LoopNode) { if (static_cast<const openvdb::ax::ast::Loop*>(a[i])->loopType() != static_cast<const openvdb::ax::ast::Loop*>(b[i])->loopType()) { return false; } } else if (a[i]->nodetype() == openvdb::ax::ast::Node::KeywordNode) { if (static_cast<const openvdb::ax::ast::Keyword*>(a[i])->keyword() != static_cast<const openvdb::ax::ast::Keyword*>(b[i])->keyword()) { return false; } } else if (a[i]->nodetype() == openvdb::ax::ast::Node::AttributeNode) { if (static_cast<const openvdb::ax::ast::Attribute*>(a[i])->type() != static_cast<const openvdb::ax::ast::Attribute*>(b[i])->type()) { return false; } if (static_cast<const openvdb::ax::ast::Attribute*>(a[i])->name() != static_cast<const openvdb::ax::ast::Attribute*>(b[i])->name()) { return false; } if (static_cast<const openvdb::ax::ast::Attribute*>(a[i])->inferred() != static_cast<const openvdb::ax::ast::Attribute*>(b[i])->inferred()) { return false; } } else if (a[i]->nodetype() == openvdb::ax::ast::Node::ExternalVariableNode) { if (static_cast<const openvdb::ax::ast::ExternalVariable*>(a[i])->type() != static_cast<const openvdb::ax::ast::ExternalVariable*>(b[i])->type()) { return false; } if (static_cast<const openvdb::ax::ast::ExternalVariable*>(a[i])->name() != static_cast<const openvdb::ax::ast::ExternalVariable*>(b[i])->name()) { return false; } } else if (a[i]->nodetype() == openvdb::ax::ast::Node::DeclareLocalNode) { if (static_cast<const openvdb::ax::ast::DeclareLocal*>(a[i])->type() != static_cast<const openvdb::ax::ast::DeclareLocal*>(b[i])->type()) { return false; } } else if (a[i]->nodetype() == openvdb::ax::ast::Node::LocalNode) { if (static_cast<const openvdb::ax::ast::Local*>(a[i])->name() != static_cast<const openvdb::ax::ast::Local*>(b[i])->name()) { return false; } } // @note Value methods does not compare child text data else if (a[i]->nodetype() == openvdb::ax::ast::Node::ValueBoolNode) { if (static_cast<const openvdb::ax::ast::Value<bool>*>(a[i])->value() != static_cast<const openvdb::ax::ast::Value<bool>*>(b[i])->value()) { return false; } } else if (a[i]->nodetype() == openvdb::ax::ast::Node::ValueInt16Node) { if (static_cast<const openvdb::ax::ast::Value<int16_t>*>(a[i])->value() != static_cast<const openvdb::ax::ast::Value<int16_t>*>(b[i])->value()) { return false; } } else if (a[i]->nodetype() == openvdb::ax::ast::Node::ValueInt32Node) { if (static_cast<const openvdb::ax::ast::Value<int32_t>*>(a[i])->value() != static_cast<const openvdb::ax::ast::Value<int32_t>*>(b[i])->value()) { return false; } } else if (a[i]->nodetype() == openvdb::ax::ast::Node::ValueInt64Node) { if (static_cast<const openvdb::ax::ast::Value<int64_t>*>(a[i])->value() != static_cast<const openvdb::ax::ast::Value<int64_t>*>(b[i])->value()) { return false; } } else if (a[i]->nodetype() == openvdb::ax::ast::Node::ValueFloatNode) { if (static_cast<const openvdb::ax::ast::Value<float>*>(a[i])->value() != static_cast<const openvdb::ax::ast::Value<float>*>(b[i])->value()) { return false; } } else if (a[i]->nodetype() == openvdb::ax::ast::Node::ValueDoubleNode) { if (static_cast<const openvdb::ax::ast::Value<double>*>(a[i])->value() != static_cast<const openvdb::ax::ast::Value<double>*>(b[i])->value()) { return false; } } else if (a[i]->nodetype() == openvdb::ax::ast::Node::ValueStrNode) { if (static_cast<const openvdb::ax::ast::Value<std::string>*>(a[i])->value() != static_cast<const openvdb::ax::ast::Value<std::string>*>(b[i])->value()) { return false; } } } return true; } inline std::vector<std::string> nameSequence(const std::string& base, const size_t number) { std::vector<std::string> names; if (number <= 0) return names; names.reserve(number); for (size_t i = 1; i <= number; i++) { names.emplace_back(base + std::to_string(i)); } return names; } } #endif // OPENVDB_AX_UNITTEST_UTIL_HAS_BEEN_INCLUDED
NVIDIA-Omniverse/ext-openvdb/openvdb_ax/openvdb_ax/test/integration/CompareGrids.cc
// Copyright Contributors to the OpenVDB Project // SPDX-License-Identifier: MPL-2.0 /// @file test/integration/CompareGrids.cc #include "CompareGrids.h" #include <openvdb/points/PointDataGrid.h> namespace unittest_util { #if (OPENVDB_LIBRARY_MAJOR_VERSION_NUMBER == 7 && \ OPENVDB_LIBRARY_MINOR_VERSION_NUMBER == 1) // Issue with TypeList where Unqiue defines recursively in 7.1 template <typename... Ts> struct TListFix; template<typename ListT, typename... Ts> struct TSAppendImpl; template<typename... Ts, typename... OtherTs> struct TSAppendImpl<TListFix<Ts...>, OtherTs...> { using type = TListFix<Ts..., OtherTs...>; }; template<typename... Ts, typename... OtherTs> struct TSAppendImpl<TListFix<Ts...>, TListFix<OtherTs...>> { using type = TListFix<Ts..., OtherTs...>; }; template<typename ListT, typename T> struct TSEraseImpl; template<typename T> struct TSEraseImpl<TListFix<>, T> { using type = TListFix<>; }; template<typename... Ts, typename T> struct TSEraseImpl<TListFix<T, Ts...>, T> { using type = typename TSEraseImpl<TListFix<Ts...>, T>::type; }; template<typename T2, typename... Ts, typename T> struct TSEraseImpl<TListFix<T2, Ts...>, T> { using type = typename TSAppendImpl<TListFix<T2>, typename TSEraseImpl<TListFix<Ts...>, T>::type>::type; }; template<typename ListT, typename... Ts> struct TSRemoveImpl; template<typename ListT> struct TSRemoveImpl<ListT> { using type = ListT; }; template<typename ListT, typename T, typename... Ts> struct TSRemoveImpl<ListT, T, Ts...> { using type = typename TSRemoveImpl<typename TSEraseImpl<ListT, T>::type, Ts...>::type; }; template<typename ListT, typename... Ts> struct TSRemoveImpl<ListT, TListFix<Ts...>> { using type = typename TSRemoveImpl<ListT, Ts...>::type; }; template <typename... Ts> struct TListFix { using Self = TListFix; template<typename... TypesToRemove> using Remove = typename TSRemoveImpl<Self, TypesToRemove...>::type; template<typename... TypesToAppend> using Append = typename TSAppendImpl<Self, TypesToAppend...>::type; template<typename OpT> static void foreach(OpT op) { openvdb::internal::TSForEachImpl<OpT, Ts...>(op); } }; using TypeList = TListFix< #else using TypeList = openvdb::TypeList< #endif double, float, int64_t, int32_t, int16_t, bool, openvdb::math::Vec2<double>, openvdb::math::Vec2<float>, openvdb::math::Vec2<int32_t>, openvdb::math::Vec3<double>, openvdb::math::Vec3<float>, openvdb::math::Vec3<int32_t>, openvdb::math::Vec4<double>, openvdb::math::Vec4<float>, openvdb::math::Vec4<int32_t>, openvdb::math::Mat3<double>, openvdb::math::Mat3<float>, openvdb::math::Mat4<double>, openvdb::math::Mat4<float>, std::string>; struct DiagnosticArrayData { DiagnosticArrayData() : mSizeMatch(true) , mTypesMatch(true) , mFlagsMatch(true) , mArrayValueFlags() {} inline void flagArrayValue(const size_t idx) { if (!mArrayValueFlags) mArrayValueFlags.reset(new std::vector<size_t>()); (*mArrayValueFlags).push_back(idx); } bool mSizeMatch; bool mTypesMatch; bool mFlagsMatch; std::unique_ptr<std::vector<size_t>> mArrayValueFlags; }; struct DiagnosticData { using Ptr = std::shared_ptr<DiagnosticData>; DiagnosticData() : mValid(true) , mBufferSizes(true) , mVoxelTopologyFlags(nullptr) , mVoxelValueFlags(nullptr) , mDescriptorsMatch(true) , mAttributeArrayData() {} inline bool hasValueFlags() const { return static_cast<bool>(mVoxelValueFlags); } inline bool hasTopologyFlags() const { return static_cast<bool>(mVoxelTopologyFlags); } inline void flagVoxelTopology(const int16_t idx) { if (!mVoxelTopologyFlags) { mVoxelTopologyFlags.reset(new std::array<bool,512>()); mVoxelTopologyFlags->fill(true); } (*mVoxelTopologyFlags)[idx] = false; } inline void flagVoxelValue(const int16_t idx) { if (!mVoxelValueFlags) { mVoxelValueFlags.reset(new std::array<bool,512>()); mVoxelValueFlags->fill(true); } (*mVoxelValueFlags)[idx] = false; } inline DiagnosticArrayData& getDiagnosticArrayData(const std::string& name) { if (!mAttributeArrayData) { mAttributeArrayData.reset(new std::map<std::string, DiagnosticArrayData>()); } return (*mAttributeArrayData)[name]; } inline bool hasDiagnosticArrayData() const { return (static_cast<bool>(mAttributeArrayData)); } inline bool hasDiagnosticArrayData(const std::string& name) const { return (hasDiagnosticArrayData() && mAttributeArrayData->find(name) != mAttributeArrayData->end()); } bool mValid; bool mBufferSizes; std::unique_ptr<std::array<bool,512>> mVoxelTopologyFlags; std::unique_ptr<std::array<bool,512>> mVoxelValueFlags; bool mDescriptorsMatch; std::unique_ptr<std::map<std::string, DiagnosticArrayData>> mAttributeArrayData; }; template <typename LeafNodeType, typename NodeMaskT> inline bool compareLeafBuffers(const LeafNodeType& firstLeaf, const LeafNodeType& secondLeaf, const NodeMaskT& mask, DiagnosticData& data, const ComparisonSettings& settings, const typename LeafNodeType::ValueType& tolerance) { using BufferT = typename LeafNodeType::Buffer; const BufferT& firstBuffer = firstLeaf.buffer(); const BufferT& secondBuffer = secondLeaf.buffer(); // if the buffers are not the same size the buffer most likely isn't // loaded or allocated if (firstBuffer.size() != secondBuffer.size()) { data.mBufferSizes = false; return false; } const NodeMaskT& firstMask = firstLeaf.getValueMask(); const NodeMaskT& secondMask = secondLeaf.getValueMask(); typename NodeMaskT::OnIterator iter = mask.beginOn(); for (; iter; ++iter) { const openvdb::Index n = iter.pos(); assert(n < firstBuffer.size() && n < secondBuffer.size()); if (settings.mCheckActiveStates && firstMask.isOn(n) ^ secondMask.isOn(n)) { data.flagVoxelTopology(static_cast<int16_t>(n)); } if (settings.mCheckBufferValues && !openvdb::math::isApproxEqual(firstBuffer[n], secondBuffer[n], tolerance)) { data.flagVoxelValue(static_cast<int16_t>(n)); } } return !data.hasValueFlags() && !data.hasTopologyFlags(); } void compareStringArrays(const openvdb::points::AttributeArray& a1, const openvdb::points::AttributeArray& a2, const openvdb::points::PointDataTree::LeafNodeType& leaf1, const openvdb::points::PointDataTree::LeafNodeType& leaf2, const std::string& name, DiagnosticData& data) { using LeafNodeT = openvdb::points::PointDataTree::LeafNodeType; if (a1.size() != a2.size()) { auto& arrayData = data.getDiagnosticArrayData(name); arrayData.mSizeMatch = false; } const openvdb::points::AttributeSet::Descriptor& descriptor1 = leaf1.attributeSet().descriptor(); const openvdb::points::AttributeSet::Descriptor& descriptor2 = leaf2.attributeSet().descriptor(); openvdb::points::StringAttributeHandle h1(a1, descriptor1.getMetadata()), h2(a2, descriptor2.getMetadata()); auto iter = leaf1.beginIndexAll(); for (; iter; ++iter) { if (h1.get(*iter) != h2.get(*iter)) break; } if (iter) { auto& arrayData = data.getDiagnosticArrayData(name); for (; iter; ++iter) { const openvdb::Index i = *iter; if (h1.get(i) != h2.get(i)) { arrayData.flagArrayValue(i); data.flagVoxelValue(static_cast<int16_t>(LeafNodeT::coordToOffset(iter.getCoord()))); } } } } template <typename ValueType> inline void compareArrays(const openvdb::points::AttributeArray& a1, const openvdb::points::AttributeArray& a2, const openvdb::points::PointDataTree::LeafNodeType& leaf, const std::string& name, DiagnosticData& data) { using LeafNodeT = openvdb::points::PointDataTree::LeafNodeType; if (a1.size() != a2.size()) { auto& arrayData = data.getDiagnosticArrayData(name); arrayData.mSizeMatch = false; } openvdb::points::AttributeHandle<ValueType> h1(a1), h2(a2); auto iter = leaf.beginIndexAll(); for (; iter; ++iter) { if (h1.get(*iter) != h2.get(*iter)) break; } if (iter) { auto& arrayData = data.getDiagnosticArrayData(name); for (; iter; ++iter) { const openvdb::Index i = *iter; if (h1.get(i) != h2.get(i)) { arrayData.flagArrayValue(i); data.flagVoxelValue(static_cast<int16_t>(LeafNodeT::coordToOffset(iter.getCoord()))); } } } } template <typename LeafNodeType> inline bool compareAttributes(const LeafNodeType&, const LeafNodeType&, DiagnosticData&, const ComparisonSettings&) { return true; } template <> inline bool compareAttributes<openvdb::points::PointDataTree::LeafNodeType> (const openvdb::points::PointDataTree::LeafNodeType& firstLeaf, const openvdb::points::PointDataTree::LeafNodeType& secondLeaf, DiagnosticData& data, const ComparisonSettings& settings) { using Descriptor = openvdb::points::AttributeSet::Descriptor; const Descriptor& firstDescriptor = firstLeaf.attributeSet().descriptor(); const Descriptor& secondDescriptor = secondLeaf.attributeSet().descriptor(); if (settings.mCheckDescriptors && !firstDescriptor.hasSameAttributes(secondDescriptor)) { data.mDescriptorsMatch = false; } // check common/miss-matching attributes std::set<std::string> attrs1, attrs2; for (const auto& nameToPos : firstDescriptor.map()) { attrs1.insert(nameToPos.first); } for (const auto& nameToPos : secondDescriptor.map()) { attrs2.insert(nameToPos.first); } std::vector<std::string> commonAttributes; std::set_intersection(attrs1.begin(), attrs1.end(), attrs2.begin(), attrs2.end(), std::back_inserter(commonAttributes)); for (const std::string& name : commonAttributes) { const size_t pos1 = firstDescriptor.find(name); const size_t pos2 = secondDescriptor.find(name); const auto& array1 = firstLeaf.constAttributeArray(pos1); const auto& array2 = secondLeaf.constAttributeArray(pos2); const std::string& type = array1.type().first; if (type != array2.type().first) { // this mismatch is also loged by differing descriptors auto& arrayData = data.getDiagnosticArrayData(name); arrayData.mTypesMatch = false; continue; } if (settings.mCheckArrayFlags && array1.flags() != array2.flags()) { auto& arrayData = data.getDiagnosticArrayData(name); arrayData.mFlagsMatch = false; } if (settings.mCheckArrayValues) { if (array1.type().second == "str") { compareStringArrays(array1, array2, firstLeaf, secondLeaf, name, data); } else { bool success = false; // Remove string types but add uint8_t types (used by group arrays) TypeList::Remove<std::string>::Append<uint8_t>::foreach([&](auto x) { if (type == openvdb::typeNameAsString<decltype(x)>()) { compareArrays<decltype(x)>(array1, array2, firstLeaf, name, data); success = true; } }); if (!success) { throw std::runtime_error("Unsupported array type for comparison: " + type); } } } } return !data.hasDiagnosticArrayData() && data.mDescriptorsMatch; } template<typename TreeType> struct CompareLeafNodes { using LeafManagerT = openvdb::tree::LeafManager<const openvdb::MaskTree>; using LeafNodeType = typename TreeType::LeafNodeType; using LeafManagerNodeType = typename LeafManagerT::LeafNodeType; using ConstGridAccessor = openvdb::tree::ValueAccessor<const TreeType>; CompareLeafNodes(std::vector<DiagnosticData::Ptr>& data, const TreeType& firstTree, const TreeType& secondTree, const typename TreeType::ValueType tolerance, const ComparisonSettings& settings, const bool useVoxelMask = true) : mDiagnosticData(data) , mFirst(firstTree) , mSecond(secondTree) , mTolerance(tolerance) , mSettings(settings) , mUseVoxelMask(useVoxelMask) {} void operator()(LeafManagerNodeType& leaf, size_t index) const { const openvdb::Coord& origin = leaf.origin(); // // // const LeafNodeType* const firstLeafNode = mFirst.probeConstLeaf(origin); const LeafNodeType* const secondLeafNode = mSecond.probeConstLeaf(origin); if (firstLeafNode == nullptr && secondLeafNode == nullptr) { return; } auto& data = mDiagnosticData[index]; data.reset(new DiagnosticData()); if (static_cast<bool>(firstLeafNode) ^ static_cast<bool>(secondLeafNode)) { data->mValid = false; return; } assert(firstLeafNode && secondLeafNode); const openvdb::util::NodeMask<LeafNodeType::LOG2DIM> mask(mUseVoxelMask ? leaf.valueMask() : true); if (compareLeafBuffers(*firstLeafNode, *secondLeafNode, mask, *data, mSettings, mTolerance) && compareAttributes(*firstLeafNode, *secondLeafNode, *data, mSettings)) { data.reset(); } } private: std::vector<DiagnosticData::Ptr>& mDiagnosticData; const ConstGridAccessor mFirst; const ConstGridAccessor mSecond; const typename TreeType::ValueType mTolerance; const ComparisonSettings& mSettings; const bool mUseVoxelMask; }; template <typename GridType> bool compareGrids(ComparisonResult& resultData, const GridType& firstGrid, const GridType& secondGrid, const ComparisonSettings& settings, const openvdb::MaskGrid::ConstPtr maskGrid, const typename GridType::ValueType tolerance) { using TreeType = typename GridType::TreeType; using LeafManagerT = openvdb::tree::LeafManager<const openvdb::MaskTree>; struct Local { // flag to string static std::string fts(const bool flag) { return (flag ? "[SUCCESS]" : "[FAILED]"); } }; bool result = true; bool flag = true; std::ostream& os = resultData.mOs; os << "[Diagnostic : Compare Leaf Nodes Result]" << std::endl << " First Grid: \"" << firstGrid.getName() << "\"" << std::endl << " Second Grid: \"" << secondGrid.getName() << "\"" << std::endl << std::endl; if (firstGrid.tree().hasActiveTiles() || secondGrid.tree().hasActiveTiles()) { os << "[Diagnostic : WARNING]: Grids contain active tiles which will not be compared." << std::endl; } if (settings.mCheckTransforms) { flag = (firstGrid.constTransform() == secondGrid.constTransform()); result &= flag; os << "[Diagnostic]: Grid transformations: " << Local::fts(flag) << std::endl; } const openvdb::Index64 leafCount1 = firstGrid.tree().leafCount(); const openvdb::Index64 leafCount2 = secondGrid.tree().leafCount(); flag = (leafCount1 == 0 && leafCount2 == 0); if (flag) { os << "[Diagnostic]: Both grids contain 0 leaf nodes." << std::endl; return result; } if (settings.mCheckTopologyStructure && !maskGrid) { flag = firstGrid.tree().hasSameTopology(secondGrid.tree()); result &= flag; os << "[Diagnostic]: Topology structures: " << Local::fts(flag) << std::endl; } openvdb::MaskGrid::Ptr mask = openvdb::MaskGrid::create(); if (maskGrid) { mask->topologyUnion(*maskGrid); } else { mask->topologyUnion(firstGrid); mask->topologyUnion(secondGrid); } openvdb::tools::pruneInactive(mask->tree()); LeafManagerT leafManager(mask->constTree()); std::vector<DiagnosticData::Ptr> data(leafManager.leafCount()); CompareLeafNodes<TreeType> op(data, firstGrid.constTree(), secondGrid.constTree(), tolerance, settings); leafManager.foreach(op); flag = true; for (const auto& diagnostic : data) { if (diagnostic) { flag = false; break; } } result &= flag; os << "[Diagnostic]: Leaf Node Comparison: " << Local::fts(flag) << std::endl; if (flag) return result; openvdb::MaskGrid& differingTopology = *(resultData.mDifferingTopology); openvdb::MaskGrid& differingValues = *(resultData.mDifferingValues); differingTopology.setTransform(firstGrid.transform().copy()); differingValues.setTransform(firstGrid.transform().copy()); differingTopology.setName("different_topology"); differingValues.setName("different_values"); // Print diagnostic info to the stream and intialise the result topologies openvdb::MaskGrid::Accessor accessorTopology = differingTopology.getAccessor(); openvdb::MaskGrid::Accessor accessorValues = differingValues.getAccessor(); auto range = leafManager.leafRange(); os << "[Diagnostic]: Leaf Node Diagnostics:" << std::endl << std::endl; for (auto leaf = range.begin(); leaf; ++leaf) { DiagnosticData::Ptr diagnostic = data[leaf.pos()]; if (!diagnostic) continue; const openvdb::Coord& origin = leaf->origin(); os << " Coord : " << origin << std::endl; os << " Both Valid : " << Local::fts(diagnostic->mValid) << std::endl; if (!diagnostic->mValid) { const bool second = firstGrid.constTree().probeConstLeaf(origin); os << " Missing in " << (second ? "second" : "first") << " grid." << std::endl; continue; } const auto& l1 = firstGrid.constTree().probeConstLeaf(origin); const auto& l2 = secondGrid.constTree().probeConstLeaf(origin); assert(l1 && l2); os << " Buffer Sizes : " << Local::fts(diagnostic->mBufferSizes) << std::endl; const bool topologyMatch = !static_cast<bool>(diagnostic->mVoxelTopologyFlags); os << " Topology : " << Local::fts(topologyMatch) << std::endl; if (!topologyMatch) { os << " The following voxel topologies differ : " << std::endl; openvdb::Index idx(0); for (const auto match : *(diagnostic->mVoxelTopologyFlags)) { if (!match) { const openvdb::Coord coord = leaf->offsetToGlobalCoord(idx); os << " [" << idx << "] "<< coord << " G1: " << l1->isValueOn(coord) << " - G2: " << l2->isValueOn(coord) << std::endl; accessorTopology.setValue(coord, true); } ++idx; } } const bool valueMatch = !static_cast<bool>(diagnostic->mVoxelValueFlags); os << " Values : " << Local::fts(valueMatch) << std::endl; if (!valueMatch) { os << " The following voxel values differ : " << std::endl; openvdb::Index idx(0); for (const auto match : *(diagnostic->mVoxelValueFlags)) { if (!match) { const openvdb::Coord coord = leaf->offsetToGlobalCoord(idx); os << " [" << idx << "] "<< coord << " G1: " << l1->getValue(coord) << " - G2: " << l2->getValue(coord) << std::endl; accessorValues.setValue(coord, true); } ++idx; } } if (firstGrid.template isType<openvdb::points::PointDataGrid>()) { os << " Descriptors : " << Local::fts(diagnostic->mDescriptorsMatch) << std::endl; const bool attributesMatch = !static_cast<bool>(diagnostic->mAttributeArrayData); os << " Array Data : " << Local::fts(attributesMatch) << std::endl; if (!attributesMatch) { os << " The following attribute values : " << std::endl; for (const auto& iter : *(diagnostic->mAttributeArrayData)) { const std::string& name = iter.first; const DiagnosticArrayData& arrayData = iter.second; os << " Attribute Array : [" << name << "] " << std::endl << " Size Match : " << Local::fts(arrayData.mSizeMatch) << std::endl << " Type Match : " << Local::fts(arrayData.mTypesMatch) << std::endl << " Flags Match : " << Local::fts(arrayData.mFlagsMatch) << std::endl; const bool arrayValuesMatch = !static_cast<bool>(arrayData.mArrayValueFlags); os << " Array Values : " << Local::fts(arrayValuesMatch) << std::endl; if (!arrayValuesMatch) { for (size_t idx : *(arrayData.mArrayValueFlags)) { os << " [" << idx << "] " << std::endl; } } } } } } return result; } template <typename ValueT> using ConverterT = typename openvdb::BoolGrid::ValueConverter<ValueT>::Type; bool compareUntypedGrids(ComparisonResult &resultData, const openvdb::GridBase &firstGrid, const openvdb::GridBase &secondGrid, const ComparisonSettings &settings, const openvdb::MaskGrid::ConstPtr maskGrid) { bool result = false, valid = false;; TypeList::foreach([&](auto x) { using GridT = ConverterT<decltype(x)>; if (firstGrid.isType<GridT>()) { valid = true; const GridT& firstGridTyped = static_cast<const GridT&>(firstGrid); const GridT& secondGridTyped = static_cast<const GridT&>(secondGrid); result = compareGrids(resultData, firstGridTyped, secondGridTyped, settings, maskGrid); } }); if (!valid) { if (firstGrid.isType<openvdb::points::PointDataGrid>()) { valid = true; const openvdb::points::PointDataGrid& firstGridTyped = static_cast<const openvdb::points::PointDataGrid&>(firstGrid); const openvdb::points::PointDataGrid& secondGridTyped = static_cast<const openvdb::points::PointDataGrid&>(secondGrid); result = compareGrids(resultData, firstGridTyped, secondGridTyped, settings, maskGrid); } } if (!valid) { OPENVDB_THROW(openvdb::TypeError, "Unsupported grid type: " + firstGrid.valueType()); } return result; } }
NVIDIA-Omniverse/ext-openvdb/openvdb_ax/openvdb_ax/test/integration/TestCast.cc
// Copyright Contributors to the OpenVDB Project // SPDX-License-Identifier: MPL-2.0 #include "TestHarness.h" #include "../test/util.h" #include <cppunit/extensions/HelperMacros.h> using namespace openvdb::points; class TestCast : public unittest_util::AXTestCase { public: std::string dir() const override { return GET_TEST_DIRECTORY(); } CPPUNIT_TEST_SUITE(TestCast); CPPUNIT_TEST(explicitScalar); CPPUNIT_TEST_SUITE_END(); void explicitScalar(); }; CPPUNIT_TEST_SUITE_REGISTRATION(TestCast); void TestCast::explicitScalar() { auto generate = [this](const auto& types) { for (const auto& t1 : types) { std::string code; size_t idx = 1; for (const auto& t2 : types) { if (t1 == t2) continue; std::string tmp = "_T1_@_A1_ = _T1_(_T2_@_A2_);"; unittest_util::replace(tmp, "_A1_", "test" + std::to_string(idx)); unittest_util::replace(tmp, "_A2_", "test" + t2); unittest_util::replace(tmp, "_T1_", t1); unittest_util::replace(tmp, "_T2_", t2); code += tmp + "\n"; ++idx; } this->registerTest(code, "cast_explicit." + t1 + ".ax"); } }; generate(std::vector<std::string>{ "bool", "int32", "int64", "float", "double" }); const auto names = unittest_util::nameSequence("test", 4); const std::map<std::string, std::function<void()>> expected = { { "bool", [&](){ mHarness.addAttribute<int32_t>("testint32", 1, 1); mHarness.addAttribute<int64_t>("testint64", 0, 0); mHarness.addAttribute<float>("testfloat", 2.3f, 2.3f); mHarness.addAttribute<double>("testdouble", 0.1, 0.1); mHarness.addAttributes<bool>(names, {true, false, true, true}); } }, { "int32", [&](){ mHarness.addAttribute<bool>("testbool", true, true); mHarness.addAttribute<int64_t>("testint64", 2, 2); mHarness.addAttribute<float>("testfloat", 2.3f, 2.3f); mHarness.addAttribute<double>("testdouble", 2.1, 2.1); mHarness.addAttributes<int32_t>(names, {1, 2, 2, 2}); } }, { "int64", [&]() { mHarness.addAttribute<bool>("testbool", true, true); mHarness.addAttribute<int32_t>("testint32", 2, 2); mHarness.addAttribute<float>("testfloat", 2.3f, 2.3f); mHarness.addAttribute<double>("testdouble", 2.1, 2.1); mHarness.addAttributes<int64_t>(names, {1, 2, 2, 2}); } }, { "float", [&]() { mHarness.addAttribute<bool>("testbool", true, true); mHarness.addAttribute<int32_t>("testint32", 1, 1); mHarness.addAttribute<int64_t>("testint64", 1, 1); mHarness.addAttribute<double>("testdouble", 1.1, 1.1); mHarness.addAttributes<float>(names, {1.0f, 1.0f, 1.0f, float(1.1)}); } }, { "double", [&]() { mHarness.addAttribute<bool>("testbool", true, true); mHarness.addAttribute<int32_t>("testint32", 1, 1); mHarness.addAttribute<int64_t>("testint64", 1, 1); mHarness.addAttribute<float>("testfloat", 1.1f, 1.1f); mHarness.addAttributes<double>(names, {1.0, 1.0, 1.0, double(1.1f)}); } } }; for (const auto& expc : expected) { mHarness.reset(); expc.second.operator()(); this->execute("cast_explicit." + expc.first + ".ax"); } }
NVIDIA-Omniverse/ext-openvdb/openvdb_ax/openvdb_ax/test/integration/TestVDBFunctions.cc
// Copyright Contributors to the OpenVDB Project // SPDX-License-Identifier: MPL-2.0 #include "TestHarness.h" #include "util.h" #include <openvdb_ax/ax.h> #include <openvdb_ax/codegen/Types.h> #include <openvdb_ax/codegen/Functions.h> #include <openvdb_ax/codegen/FunctionRegistry.h> #include <openvdb_ax/codegen/FunctionTypes.h> #include <openvdb_ax/compiler/PointExecutable.h> #include <openvdb_ax/compiler/VolumeExecutable.h> #include <openvdb/points/AttributeArray.h> #include <openvdb/points/PointConversion.h> #include <openvdb/points/PointGroup.h> #include <cppunit/extensions/HelperMacros.h> class TestVDBFunctions : public unittest_util::AXTestCase { public: CPPUNIT_TEST_SUITE(TestVDBFunctions); CPPUNIT_TEST(addremovefromgroup); CPPUNIT_TEST(deletepoint); CPPUNIT_TEST(getcoord); CPPUNIT_TEST(getvoxelpws); CPPUNIT_TEST(ingroupOrder); CPPUNIT_TEST(ingroup); CPPUNIT_TEST(testValidContext); CPPUNIT_TEST_SUITE_END(); void addremovefromgroup(); void deletepoint(); void getcoord(); void getvoxelpws(); void ingroupOrder(); void ingroup(); void testValidContext(); }; CPPUNIT_TEST_SUITE_REGISTRATION(TestVDBFunctions); void TestVDBFunctions::addremovefromgroup() { const std::vector<openvdb::math::Vec3s> positions = { {1, 1, 1}, {1, 2, 1}, {2, 1, 1}, {2, 2, 1}, }; const float voxelSize = 1.0f; const openvdb::math::Transform::ConstPtr transform = openvdb::math::Transform::createLinearTransform(voxelSize); const openvdb::points::PointAttributeVector<openvdb::math::Vec3s> pointList(positions); openvdb::tools::PointIndexGrid::Ptr pointIndexGrid = openvdb::tools::createPointIndexGrid<openvdb::tools::PointIndexGrid>( pointList, *transform); openvdb::points::PointDataGrid::Ptr dataGrid = openvdb::points::createPointDataGrid<openvdb::points::NullCodec, openvdb::points::PointDataGrid>( *pointIndexGrid, pointList, *transform); openvdb::points::PointDataTree& dataTree = dataGrid->tree(); // apppend a new attribute for stress testing openvdb::points::appendAttribute(dataTree, "existingTestAttribute", 2); openvdb::points::appendGroup(dataTree, "existingTestGroup"); const std::vector<short> membershipTestGroup1{1, 0, 1, 0}; openvdb::points::setGroup(dataTree, pointIndexGrid->tree(), membershipTestGroup1, "existingTestGroup"); // second pre-existing group. openvdb::points::appendGroup(dataTree, "existingTestGroup2"); openvdb::points::setGroup(dataTree, "existingTestGroup2", false); const std::string code = unittest_util::loadText("test/snippets/vdb_functions/addremovefromgroup"); openvdb::ax::run(code.c_str(), *dataGrid); auto leafIter = dataTree.cbeginLeaf(); const openvdb::points::AttributeSet& attributeSet = leafIter->attributeSet(); const openvdb::points::AttributeSet::Descriptor& desc = attributeSet.descriptor(); for (size_t i = 1; i <= 9; i++) { const std::string groupName = "newTestGroup" + std::to_string(i); CPPUNIT_ASSERT_MESSAGE(groupName + " doesn't exist", desc.hasGroup(groupName)); } openvdb::points::GroupHandle newTestGroupHandle = leafIter->groupHandle("newTestGroup9"); CPPUNIT_ASSERT(!newTestGroupHandle.get(0)); CPPUNIT_ASSERT(newTestGroupHandle.get(1)); CPPUNIT_ASSERT(!newTestGroupHandle.get(2)); CPPUNIT_ASSERT(newTestGroupHandle.get(3)); // other new groups should be untouched for (size_t i = 1; i <= 8; i++) { openvdb::points::GroupHandle handle = leafIter->groupHandle("newTestGroup" + std::to_string(i)); CPPUNIT_ASSERT(handle.get(0)); CPPUNIT_ASSERT(handle.get(1)); CPPUNIT_ASSERT(handle.get(2)); CPPUNIT_ASSERT(handle.get(3)); } openvdb::points::GroupHandle existingTestGroupHandle = leafIter->groupHandle("existingTestGroup"); CPPUNIT_ASSERT(existingTestGroupHandle.get(0)); CPPUNIT_ASSERT(!existingTestGroupHandle.get(1)); CPPUNIT_ASSERT(existingTestGroupHandle.get(2)); CPPUNIT_ASSERT(!existingTestGroupHandle.get(3)); // membership of this group should now mirror exisingTestGroup openvdb::points::GroupHandle existingTestGroup2Handle = leafIter->groupHandle("existingTestGroup2"); CPPUNIT_ASSERT(existingTestGroup2Handle.get(0)); CPPUNIT_ASSERT(!existingTestGroup2Handle.get(1)); CPPUNIT_ASSERT(existingTestGroup2Handle.get(2)); CPPUNIT_ASSERT(!existingTestGroup2Handle.get(3)); // check that "nonExistentGroup" was _not_ added to the tree, as it is removed from but not present CPPUNIT_ASSERT(!desc.hasGroup("nonExistentGroup")); // now check 2 new attributes added to tree openvdb::points::AttributeHandle<int> testResultAttributeHandle1(*attributeSet.get("newTestAttribute1")); openvdb::points::AttributeHandle<int> testResultAttributeHandle2(*attributeSet.get("newTestAttribute2")); for (openvdb::Index i = 0;i < 4; i++) { CPPUNIT_ASSERT(testResultAttributeHandle1.get(i)); } // should match "existingTestGroup" CPPUNIT_ASSERT(testResultAttributeHandle2.get(0)); CPPUNIT_ASSERT(!testResultAttributeHandle2.get(1)); CPPUNIT_ASSERT(testResultAttributeHandle2.get(2)); CPPUNIT_ASSERT(!testResultAttributeHandle2.get(3)); // pre-existing attribute should still be present with the correct value for (; leafIter; ++leafIter) { openvdb::points::AttributeHandle<int> handle(leafIter->attributeArray("existingTestAttribute")); CPPUNIT_ASSERT(handle.isUniform()); CPPUNIT_ASSERT_EQUAL(2, handle.get(0)); } } void TestVDBFunctions::deletepoint() { // NOTE: the "deletepoint" function doesn't actually directly delete points - it adds them // to the "dead" group which marks them for deletion afterwards mHarness.testVolumes(false); mHarness.addInputGroups({"dead"}, {false}); mHarness.addExpectedGroups({"dead"}, {true}); mHarness.executeCode("test/snippets/vdb_functions/deletepoint"); AXTESTS_STANDARD_ASSERT(); // test without existing dead group mHarness.reset(); mHarness.addExpectedGroups({"dead"}, {true}); mHarness.executeCode("test/snippets/vdb_functions/deletepoint"); AXTESTS_STANDARD_ASSERT(); } void TestVDBFunctions::getcoord() { // create 3 test grids std::vector<openvdb::Int32Grid::Ptr> testGrids(3); openvdb::math::Transform::Ptr transform = openvdb::math::Transform::createLinearTransform(0.1); int i = 0; for (auto& grid : testGrids) { grid = openvdb::Int32Grid::create(); grid->setTransform(transform); grid->setName("a" + std::to_string(i)); openvdb::Int32Grid::Accessor accessor = grid->getAccessor(); accessor.setValueOn(openvdb::Coord(1, 2, 3), 0); accessor.setValueOn(openvdb::Coord(1, 10, 3), 0); accessor.setValueOn(openvdb::Coord(-1, 1, 10), 0); ++i; } // convert to GridBase::Ptr openvdb::GridPtrVec testGridsBase(3); std::copy(testGrids.begin(), testGrids.end(), testGridsBase.begin()); const std::string code = unittest_util::loadText("test/snippets/vdb_functions/getcoord"); openvdb::ax::run(code.c_str(), testGridsBase); // each grid has 3 active voxels. These vectors hold the expected values of those voxels // for each grid std::vector<openvdb::Vec3I> expectedVoxelVals(3); expectedVoxelVals[0] = openvdb::Vec3I(1, 1, -1); expectedVoxelVals[1] = openvdb::Vec3I(2, 10, 1); expectedVoxelVals[2] = openvdb::Vec3I(3, 3, 10); std::vector<openvdb::Int32Grid::Ptr> expectedGrids(3); for (size_t i = 0; i < 3; i++) { openvdb::Int32Grid::Ptr grid = openvdb::Int32Grid::create(); grid->setTransform(transform); grid->setName("a" + std::to_string(i) + "_expected"); openvdb::Int32Grid::Accessor accessor = grid->getAccessor(); const openvdb::Vec3I& expectedVals = expectedVoxelVals[i]; accessor.setValueOn(openvdb::Coord(1, 2 ,3), expectedVals[0]); accessor.setValueOn(openvdb::Coord(1, 10, 3), expectedVals[1]); accessor.setValueOn(openvdb::Coord(-1, 1, 10), expectedVals[2]); expectedGrids[i] = grid; } // check grids bool check = true; std::stringstream outMessage; for (size_t i = 0; i < 3; i++){ std::stringstream stream; unittest_util::ComparisonSettings settings; unittest_util::ComparisonResult result(stream); check &= unittest_util::compareGrids(result, *testGrids[i], *expectedGrids[i], settings, nullptr); if (!check) outMessage << stream.str() << std::endl; } CPPUNIT_ASSERT_MESSAGE(outMessage.str(), check); } void TestVDBFunctions::getvoxelpws() { mHarness.testPoints(false); mHarness.addAttribute<openvdb::Vec3f>("a", openvdb::Vec3f(10.0f), openvdb::Vec3f(0.0f)); mHarness.executeCode("test/snippets/vdb_functions/getvoxelpws"); AXTESTS_STANDARD_ASSERT(); } void TestVDBFunctions::ingroupOrder() { // Test that groups inserted in a different alphabetical order are inferred // correctly (a regression test for a previous issue) mHarness.testVolumes(false); mHarness.addExpectedAttributes<int>({"test", "groupTest", "groupTest2"}, {1,1,1}); mHarness.addInputGroups({"b", "a"}, {false, true}); mHarness.addExpectedGroups({"b", "a"}, {false, true}); mHarness.executeCode("test/snippets/vdb_functions/ingroup", nullptr, true); AXTESTS_STANDARD_ASSERT(); } void TestVDBFunctions::ingroup() { // test a tree with no groups CPPUNIT_ASSERT(mHarness.mInputPointGrids.size() > 0); openvdb::points::PointDataGrid::Ptr pointDataGrid1 = mHarness.mInputPointGrids.back(); openvdb::points::PointDataTree& pointTree = pointDataGrid1->tree(); // compile and execute openvdb::ax::Compiler compiler; std::string code = unittest_util::loadText("test/snippets/vdb_functions/ingroup"); openvdb::ax::PointExecutable::Ptr executable = compiler.compile<openvdb::ax::PointExecutable>(code); CPPUNIT_ASSERT_NO_THROW(executable->execute(*pointDataGrid1)); // the snippet of code adds "groupTest" and groupTest2 attributes which should both have the values // "1" everywhere for (auto leafIter = pointTree.cbeginLeaf(); leafIter; ++leafIter) { openvdb::points::AttributeHandle<int> handle1(leafIter->attributeArray("groupTest")); openvdb::points::AttributeHandle<int> handle2(leafIter->attributeArray("groupTest2")); for (auto iter = leafIter->beginIndexAll(); iter; ++iter) { CPPUNIT_ASSERT_EQUAL(1, handle1.get(*iter)); CPPUNIT_ASSERT_EQUAL(1, handle2.get(*iter)); } } // there should be no groups - ensure none have been added by accident by query code auto leafIter = pointTree.cbeginLeaf(); const openvdb::points::AttributeSet& attributeSet = leafIter->attributeSet(); const openvdb::points::AttributeSet::Descriptor& descriptor1 = attributeSet.descriptor(); CPPUNIT_ASSERT_EQUAL(static_cast<size_t>(0), descriptor1.groupMap().size()); // now we add a single group and run the test again openvdb::points::appendGroup(pointTree, "testGroup"); setGroup(pointTree, "testGroup", false); executable = compiler.compile<openvdb::ax::PointExecutable>(code); CPPUNIT_ASSERT_NO_THROW(executable->execute(*pointDataGrid1)); for (auto leafIter = pointTree.cbeginLeaf(); leafIter; ++leafIter) { openvdb::points::AttributeHandle<int> handle1(leafIter->attributeArray("groupTest")); openvdb::points::AttributeHandle<int> handle2(leafIter->attributeArray("groupTest2")); for (auto iter = leafIter->beginIndexAll(); iter; ++iter) { CPPUNIT_ASSERT_EQUAL(1, handle1.get(*iter)); CPPUNIT_ASSERT_EQUAL(1, handle2.get(*iter)); } } // for the next couple of tests we create a small tree with 4 points. We wish to test queries of a single group // in a tree that has several groups const std::vector<openvdb::math::Vec3s> positions = { {1, 1, 1}, {1, 2, 1}, {2, 1, 1}, {2, 2, 1}, }; const float voxelSize = 1.0f; const openvdb::math::Transform::ConstPtr transform = openvdb::math::Transform::createLinearTransform(voxelSize); const openvdb::points::PointAttributeVector<openvdb::math::Vec3s> pointList(positions); openvdb::tools::PointIndexGrid::Ptr pointIndexGrid = openvdb::tools::createPointIndexGrid<openvdb::tools::PointIndexGrid> (pointList, *transform); openvdb::points::PointDataGrid::Ptr pointDataGrid2 = openvdb::points::createPointDataGrid<openvdb::points::NullCodec, openvdb::points::PointDataGrid> (*pointIndexGrid, pointList, *transform); openvdb::points::PointDataTree::Ptr pointDataTree2 = pointDataGrid2->treePtr(); // add 9 groups. 8 groups can be added by using a single group attribute, but this requires adding another attribute // and hence exercises the code better for (size_t i = 0; i < 9; i++) { openvdb::points::appendGroup(*pointDataTree2, "testGroup" + std::to_string(i)); } std::vector<short> membershipTestGroup2{0, 0, 1, 0}; openvdb::points::setGroup(*pointDataTree2, pointIndexGrid->tree(), membershipTestGroup2, "testGroup2"); executable = compiler.compile<openvdb::ax::PointExecutable>(code); CPPUNIT_ASSERT_NO_THROW(executable->execute(*pointDataGrid2)); auto leafIter2 = pointDataTree2->cbeginLeaf(); const openvdb::points::AttributeSet& attributeSet2 = leafIter2->attributeSet(); openvdb::points::AttributeHandle<int> testResultAttributeHandle(*attributeSet2.get("groupTest2")); // these should line up with the defined membership CPPUNIT_ASSERT_EQUAL(testResultAttributeHandle.get(0), 1); CPPUNIT_ASSERT_EQUAL(testResultAttributeHandle.get(1), 1); CPPUNIT_ASSERT_EQUAL(testResultAttributeHandle.get(2), 2); CPPUNIT_ASSERT_EQUAL(testResultAttributeHandle.get(3), 1); // check that no new groups have been created or deleted const openvdb::points::AttributeSet::Descriptor& descriptor2 = attributeSet2.descriptor(); CPPUNIT_ASSERT_EQUAL(static_cast<size_t>(9), descriptor2.groupMap().size()); for (size_t i = 0; i < 9; i++) { CPPUNIT_ASSERT(descriptor2.hasGroup("testGroup" + std::to_string(i))); } } void TestVDBFunctions::testValidContext() { std::shared_ptr<llvm::LLVMContext> C(new llvm::LLVMContext); openvdb::ax::Compiler compiler; openvdb::ax::FunctionOptions ops; ops.mLazyFunctions = false; /// Generate code which calls the given function auto generate = [&C](const openvdb::ax::codegen::Function::Ptr F, const std::string& name) -> std::string { std::vector<llvm::Type*> types; F->types(types, *C); std::string code; std::string args; size_t idx = 0; for (auto T : types) { const std::string axtype = openvdb::ax::ast::tokens::typeStringFromToken( openvdb::ax::codegen::tokenFromLLVMType(T)); code += axtype + " local" + std::to_string(idx) + ";\n"; args += "local" + std::to_string(idx) + ","; } // remove last "," if (!args.empty()) args.pop_back(); code += name + "(" + args + ");"; return code; }; /// Test Volumes fails when trying to call Point Functions { openvdb::ax::codegen::FunctionRegistry::UniquePtr registry(new openvdb::ax::codegen::FunctionRegistry); openvdb::ax::codegen::insertVDBPointFunctions(*registry, &ops); for (auto& func : registry->map()) { // Don't check internal functions if (func.second.isInternal()) continue; const openvdb::ax::codegen::FunctionGroup* const ptr = func.second.function(); CPPUNIT_ASSERT(ptr); const auto& signatures = ptr->list(); CPPUNIT_ASSERT(!signatures.empty()); const std::string code = generate(signatures.front(), func.first); CPPUNIT_ASSERT_THROW_MESSAGE(ERROR_MSG("Expected Compiler Error", code), compiler.compile<openvdb::ax::VolumeExecutable>(code), openvdb::AXCompilerError); } } /// Test Points fails when trying to call Volume Functions { openvdb::ax::codegen::FunctionRegistry::UniquePtr registry(new openvdb::ax::codegen::FunctionRegistry); openvdb::ax::codegen::insertVDBVolumeFunctions(*registry, &ops); for (auto& func : registry->map()) { // Don't check internal functions if (func.second.isInternal()) continue; const openvdb::ax::codegen::FunctionGroup* const ptr = func.second.function(); CPPUNIT_ASSERT(ptr); const auto& signatures = ptr->list(); CPPUNIT_ASSERT(!signatures.empty()); const std::string code = generate(signatures.front(), func.first); CPPUNIT_ASSERT_THROW_MESSAGE(ERROR_MSG("Expected Compiler Error", code), compiler.compile<openvdb::ax::PointExecutable>(code), openvdb::AXCompilerError); } } }
NVIDIA-Omniverse/ext-openvdb/openvdb_ax/openvdb_ax/test/integration/TestDeclare.cc
// Copyright Contributors to the OpenVDB Project // SPDX-License-Identifier: MPL-2.0 #include "TestHarness.h" #include "../test/util.h" #include <openvdb/Exceptions.h> #include <cppunit/extensions/HelperMacros.h> using namespace openvdb::points; class TestDeclare : public unittest_util::AXTestCase { public: CPPUNIT_TEST_SUITE(TestDeclare); CPPUNIT_TEST(testLocalVariables); CPPUNIT_TEST(testLocalVectorVariables); CPPUNIT_TEST(testAttributes); CPPUNIT_TEST(testVectorAttributes); CPPUNIT_TEST(testNewAttributes); CPPUNIT_TEST(testNewVectorAttributes); CPPUNIT_TEST(testVectorAttributeImplicit); CPPUNIT_TEST(testAmbiguousScalarAttributes); CPPUNIT_TEST(testAmbiguousVectorAttributes); CPPUNIT_TEST(testAmbiguousScalarExternals); CPPUNIT_TEST(testAmbiguousVectorExternals); CPPUNIT_TEST(testAttributesVolume); CPPUNIT_TEST_SUITE_END(); void testLocalVariables(); void testAttributes(); void testNewAttributes(); void testNewVectorAttributes(); void testLocalVectorVariables(); void testVectorAttributes(); void testVectorAttributeImplicit(); void testAmbiguousScalarAttributes(); void testAmbiguousVectorAttributes(); void testAmbiguousScalarExternals(); void testAmbiguousVectorExternals(); void testAttributesVolume(); }; CPPUNIT_TEST_SUITE_REGISTRATION(TestDeclare); void TestDeclare::testLocalVariables() { mHarness.executeCode("test/snippets/declare/declareLocalVariables"); // input data should not have changed AXTESTS_STANDARD_ASSERT(); } void TestDeclare::testLocalVectorVariables() { mHarness.executeCode("test/snippets/declare/declareLocalVectorVariables"); AXTESTS_STANDARD_ASSERT(); } void TestDeclare::testAttributes() { mHarness.addAttributes<float>(unittest_util::nameSequence("float_test", 4), {0.0f, 0.2f, 10.0f, 10.0f}); mHarness.addAttributes<int32_t>(unittest_util::nameSequence("int_test", 3), {0, 5, 10}); mHarness.addAttribute("short_test", int16_t(1)); mHarness.addAttribute("long_test", int64_t(3)); mHarness.addAttribute("double_test", 0.3); mHarness.executeCode("test/snippets/declare/declareAttributes"); AXTESTS_STANDARD_ASSERT(); } void TestDeclare::testAttributesVolume() { mHarness.addAttributes<float>(unittest_util::nameSequence("float_test", 4), {0.0f, 0.2f, 10.0f, 10.0f}); mHarness.addAttributes<int32_t>(unittest_util::nameSequence("int_test", 3), {0, 5, 10}); mHarness.addAttribute("long_test", int64_t(3)); mHarness.addAttribute("double_test", 0.3); mHarness.executeCode("test/snippets/declare/declareAttributesVolume"); AXTESTS_STANDARD_ASSERT(); } void TestDeclare::testNewAttributes() { mHarness.addExpectedAttributes<float>(unittest_util::nameSequence("float_test", 4), {0.0f, 0.2f, 10.0f, 10.0f}); mHarness.addExpectedAttributes<int32_t>(unittest_util::nameSequence("int_test", 3), {0, 5, 10}); mHarness.addExpectedAttribute("short_test", int16_t(1)); mHarness.addExpectedAttribute("long_test", int64_t(3)); mHarness.addExpectedAttribute("double_test", 0.3); // Volume data needs to exist to be tested mHarness.addInputVolumes<float>(unittest_util::nameSequence("float_test", 4), {0.0f, 0.2f, 10.0f, 10.0f}); mHarness.addInputVolumes<int32_t>(unittest_util::nameSequence("int_test", 3), {0, 5, 10}); mHarness.addInputVolumes<int16_t>({"short_test"}, {int16_t(1)}); mHarness.addInputVolumes<int64_t>({"long_test"}, {int64_t(3)}); mHarness.addInputVolumes<double>({"double_test"}, {0.3}); mHarness.executeCode("test/snippets/declare/declareAttributes", nullptr, true); AXTESTS_STANDARD_ASSERT(); } void TestDeclare::testNewVectorAttributes() { mHarness.addExpectedAttributes<openvdb::Vec3f>({"vec_float_test", "vec_float_test2"}, {openvdb::Vec3f::zero(), openvdb::Vec3f(0.2f, 0.3f, 0.4f)}); mHarness.addExpectedAttributes<openvdb::Vec3i>({"vec_int_test", "vec_int_test2"}, {openvdb::Vec3i::zero(), openvdb::Vec3i(5, 6, 7)}); mHarness.addExpectedAttribute<openvdb::Vec3d>("vec_double_test", openvdb::Vec3d(0.3, 0.4, 0.5)); // Volume data needs to exist to be tested mHarness.addInputVolumes<openvdb::Vec3f>({"vec_float_test", "vec_float_test2"}, {openvdb::Vec3f::zero(), openvdb::Vec3f(0.2f, 0.3f, 0.4f)}); mHarness.addInputVolumes<openvdb::Vec3i>({"vec_int_test", "vec_int_test2"}, {openvdb::Vec3i::zero(), openvdb::Vec3i(5, 6, 7)}); mHarness.addInputVolumes<openvdb::Vec3d>({"vec_double_test"}, {openvdb::Vec3d(0.3, 0.4, 0.5)}); mHarness.executeCode("test/snippets/declare/declareNewVectorAttributes", nullptr, true); AXTESTS_STANDARD_ASSERT(); } void TestDeclare::testVectorAttributes() { mHarness.addAttribute<openvdb::Vec3d>("vec_double_test", openvdb::Vec3d(0.3, 0.4, 0.5)); mHarness.addAttributes<openvdb::Vec3f>({"vec_float_test", "vec_float_test2"}, {openvdb::Vec3f::zero(), openvdb::Vec3f(0.2f, 0.3f, 0.4f)}); mHarness.addAttributes<openvdb::Vec3i>({"vec_int_test", "vec_int_test2"}, {openvdb::Vec3i::zero(), openvdb::Vec3i(5, 6, 7)}); mHarness.executeCode("test/snippets/declare/declareVectorAttributes"); AXTESTS_STANDARD_ASSERT(); } void TestDeclare::testVectorAttributeImplicit() { mHarness.addAttribute<openvdb::Vec3d>("vec_double_test", openvdb::Vec3d(1.0, 0.3, 0.4)); mHarness.executeCode("test/snippets/declare/declareVectorAttributeImplicit"); AXTESTS_STANDARD_ASSERT(); } void TestDeclare::testAmbiguousScalarAttributes() { const bool success = mHarness.executeCode("test/snippets/declare/declareAmbiguousScalarAttributes"); CPPUNIT_ASSERT(!success); } void TestDeclare::testAmbiguousVectorAttributes() { const bool success = mHarness.executeCode("test/snippets/declare/declareAmbiguousVectorAttributes"); CPPUNIT_ASSERT(!success); } void TestDeclare::testAmbiguousScalarExternals() { const bool success = mHarness.executeCode("test/snippets/declare/declareAmbiguousScalarExternals"); CPPUNIT_ASSERT(!success); } void TestDeclare::testAmbiguousVectorExternals() { const bool success = mHarness.executeCode("test/snippets/declare/declareAmbiguousVectorExternals"); CPPUNIT_ASSERT(!success); }
NVIDIA-Omniverse/ext-openvdb/openvdb_ax/openvdb_ax/test/integration/TestWorldSpaceAccessors.cc
// Copyright Contributors to the OpenVDB Project // SPDX-License-Identifier: MPL-2.0 #include "TestHarness.h" #include <openvdb_ax/ax.h> #include <openvdb/points/PointDataGrid.h> #include <openvdb/points/PointGroup.h> #include <openvdb/points/PointConversion.h> #include <openvdb/points/AttributeArray.h> #include <openvdb/math/Transform.h> #include <openvdb/openvdb.h> #include <cppunit/extensions/HelperMacros.h> #include <limits> using namespace openvdb::points; class TestWorldSpaceAccessors: public unittest_util::AXTestCase { public: CPPUNIT_TEST_SUITE(TestWorldSpaceAccessors); CPPUNIT_TEST(testWorldSpaceAssign); CPPUNIT_TEST(testWorldSpaceAssignComponent); CPPUNIT_TEST_SUITE_END(); void testWorldSpaceAssign(); void testWorldSpaceAssignComponent(); }; CPPUNIT_TEST_SUITE_REGISTRATION(TestWorldSpaceAccessors); void TestWorldSpaceAccessors::testWorldSpaceAssign() { std::vector<openvdb::Vec3d> positions = {openvdb::Vec3d(0.0, 0.0, 0.0), openvdb::Vec3d(0.0, 0.0, 0.05), openvdb::Vec3d(0.0, 1.0, 0.0), openvdb::Vec3d(1.0, 1.0, 0.0)}; CPPUNIT_ASSERT(mHarness.mInputPointGrids.size() > 0); PointDataGrid::Ptr grid = mHarness.mInputPointGrids.back(); openvdb::points::PointDataTree* tree = &(grid->tree()); // @note snippet moves all points to a single leaf node CPPUNIT_ASSERT_EQUAL(openvdb::points::pointCount(*tree), openvdb::Index64(4)); const std::string code = unittest_util::loadText("test/snippets/worldspace/worldSpaceAssign"); CPPUNIT_ASSERT_NO_THROW(openvdb::ax::run(code.c_str(), *grid)); // Tree is modified if points are moved tree = &(grid->tree()); CPPUNIT_ASSERT_EQUAL(openvdb::points::pointCount(*tree), openvdb::Index64(4)); // test that P_original has the world-space value of the P attribute prior to running this snippet. // test that P_new has the expected world-space P value PointDataTree::LeafCIter leaf = tree->cbeginLeaf(); const openvdb::math::Transform& transform = grid->transform(); for (; leaf; ++leaf) { CPPUNIT_ASSERT(leaf->pointCount() == 4); AttributeHandle<openvdb::Vec3f>::Ptr pOriginalHandle = AttributeHandle<openvdb::Vec3f>::create(leaf->attributeArray("P_original")); AttributeHandle<openvdb::Vec3f>::Ptr pNewHandle = AttributeHandle<openvdb::Vec3f>::create(leaf->attributeArray("P_new")); AttributeHandle<openvdb::Vec3f>::Ptr pHandle = AttributeHandle<openvdb::Vec3f>::create(leaf->attributeArray("P")); for (auto voxel = leaf->cbeginValueAll(); voxel; ++voxel) { const openvdb::Coord& coord = voxel.getCoord(); auto iter = leaf->beginIndexVoxel(coord); for (; iter; ++iter) { const openvdb::Index idx = *iter; // test that the value for P_original const openvdb::Vec3f& oldPosition = positions[idx]; const openvdb::Vec3f& pOriginal = pOriginalHandle->get(idx); CPPUNIT_ASSERT_EQUAL(oldPosition.x(), pOriginal.x()); CPPUNIT_ASSERT_EQUAL(oldPosition.y(), pOriginal.y()); CPPUNIT_ASSERT_EQUAL(oldPosition.z(), pOriginal.z()); // test that the value for P_new, which should be the world space value of the points const openvdb::Vec3f newPosition = openvdb::Vec3f(2.22f, 3.33f, 4.44f); const openvdb::Vec3f& pNew = pNewHandle->get(idx); CPPUNIT_ASSERT_EQUAL(newPosition.x(), pNew.x()); CPPUNIT_ASSERT_EQUAL(newPosition.y(), pNew.y()); CPPUNIT_ASSERT_EQUAL(newPosition.z(), pNew.z()); // test that the value for P, which should be the updated voxel space value of the points const openvdb::Vec3f voxelSpacePosition = openvdb::Vec3f(0.2f, 0.3f, 0.4f); const openvdb::Vec3f& pVoxelSpace = pHandle->get(idx); // @todo: look at improving precision CPPUNIT_ASSERT_DOUBLES_EQUAL(voxelSpacePosition.x(), pVoxelSpace.x(), 1e-5); CPPUNIT_ASSERT_DOUBLES_EQUAL(voxelSpacePosition.y(), pVoxelSpace.y(), 1e-5); CPPUNIT_ASSERT_DOUBLES_EQUAL(voxelSpacePosition.z(), pVoxelSpace.z(), 1e-5); // test that the value for P, which should be the updated world space value of the points const openvdb::Vec3f positionWS = openvdb::Vec3f(2.22f, 3.33f, 4.44f); const openvdb::Vec3f pWS = transform.indexToWorld(coord.asVec3d() + pHandle->get(idx)); CPPUNIT_ASSERT_DOUBLES_EQUAL(positionWS.x(), pWS.x(), std::numeric_limits<float>::epsilon()); CPPUNIT_ASSERT_DOUBLES_EQUAL(positionWS.y(), pWS.y(), std::numeric_limits<float>::epsilon()); CPPUNIT_ASSERT_DOUBLES_EQUAL(positionWS.z(), pWS.z(), std::numeric_limits<float>::epsilon()); } } } } void TestWorldSpaceAccessors::testWorldSpaceAssignComponent() { std::vector<openvdb::Vec3d> positions = {openvdb::Vec3d(0.0, 0.0, 0.0), openvdb::Vec3d(0.0, 0.0, 0.05), openvdb::Vec3d(0.0, 1.0, 0.0), openvdb::Vec3d(1.0, 1.0, 0.0)}; CPPUNIT_ASSERT(mHarness.mInputPointGrids.size() > 0); PointDataGrid::Ptr grid = mHarness.mInputPointGrids.back(); openvdb::points::PointDataTree& tree = grid->tree(); const openvdb::Index64 originalCount = pointCount(tree); CPPUNIT_ASSERT(originalCount > 0); const std::string code = unittest_util::loadText("test/snippets/worldspace/worldSpaceAssignComponent"); CPPUNIT_ASSERT_NO_THROW(openvdb::ax::run(code.c_str(), *grid)); // test that P_original has the world-space value of the P attribute prior to running this snippet. // test that P_new has the expected world-space P value PointDataTree::LeafCIter leaf = grid->tree().cbeginLeaf(); const openvdb::math::Transform& transform = grid->transform(); for (; leaf; ++leaf) { AttributeHandle<float>::Ptr pXOriginalHandle = AttributeHandle<float>::create(leaf->attributeArray("Px_original")); AttributeHandle<float>::Ptr pNewHandle = AttributeHandle<float>::create(leaf->attributeArray("Px_new")); AttributeHandle<openvdb::Vec3f>::Ptr pHandle = AttributeHandle<openvdb::Vec3f>::create(leaf->attributeArray("P")); for (auto voxel = leaf->cbeginValueAll(); voxel; ++voxel) { const openvdb::Coord& coord = voxel.getCoord(); auto iter = leaf->beginIndexVoxel(coord); for (; iter; ++iter) { const openvdb::Index idx = *iter; //@todo: requiring the point order, we should check the values of the px_original // test that the value for P_original // const float oldPosition = positions[idx].x(); // const float pXOriginal = pXOriginalHandle->get(idx); // CPPUNIT_ASSERT_EQUAL(oldPosition, pOriginal.x()); // test that the value for P_new, which should be the world space value of the points const float newX = 5.22f; const float pNewX = pNewHandle->get(idx); CPPUNIT_ASSERT_EQUAL(newX, pNewX); // test that the value for P, which should be the updated voxel space value of the points const float voxelSpacePosition = 0.2f; const openvdb::Vec3f& pVoxelSpace = pHandle->get(idx); // @todo: look at improving precision CPPUNIT_ASSERT_DOUBLES_EQUAL(voxelSpacePosition, pVoxelSpace.x(), 1e-5); //@todo: requiring point order, check the y and z components are unchanged // CPPUNIT_ASSERT_DOUBLES_EQUAL(voxelSpacePosition.y(), pVoxelSpace.y(), 1e-6); // CPPUNIT_ASSERT_DOUBLES_EQUAL(voxelSpacePosition.z(), pVoxelSpace.z(), 1e-6); // test that the value for P, which should be the updated world space value of the points const float positionWSX = 5.22f; const openvdb::Vec3f pWS = transform.indexToWorld(coord.asVec3d() + pHandle->get(idx)); CPPUNIT_ASSERT_DOUBLES_EQUAL(positionWSX, pWS.x(), std::numeric_limits<float>::epsilon()); //@todo: requiring point order, check the y and z components are unchanged // CPPUNIT_ASSERT_DOUBLES_EQUAL(positionWS.y(), pWS.y(), std::numeric_limits<float>::epsilon()); // CPPUNIT_ASSERT_DOUBLES_EQUAL(positionWS.z(), pWS.z(), std::numeric_limits<float>::epsilon()); } } } }
NVIDIA-Omniverse/ext-openvdb/openvdb_ax/openvdb_ax/test/integration/TestStandardFunctions.cc
// Copyright Contributors to the OpenVDB Project // SPDX-License-Identifier: MPL-2.0 #include "TestHarness.h" #include "../test/util.h" #include <openvdb_ax/compiler/CustomData.h> #include <openvdb_ax/math/OpenSimplexNoise.h> #include <openvdb_ax/compiler/PointExecutable.h> #include <openvdb_ax/compiler/VolumeExecutable.h> #include <openvdb/points/PointConversion.h> #include <openvdb/util/CpuTimer.h> #include <cppunit/extensions/HelperMacros.h> #include <iostream> #include <cstdlib> #include <cmath> #include <functional> #include <random> using namespace openvdb::points; using namespace openvdb::ax; class TestStandardFunctions : public unittest_util::AXTestCase { public: #ifdef PROFILE void setUp() override { // if PROFILE, generate more data for each test mHarness.reset(/*ppv*/8, openvdb::CoordBBox({0,0,0},{50,50,50})); } #endif CPPUNIT_TEST_SUITE(TestStandardFunctions); CPPUNIT_TEST(abs); CPPUNIT_TEST(acos); CPPUNIT_TEST(asin); CPPUNIT_TEST(atan); CPPUNIT_TEST(atan2); CPPUNIT_TEST(atof); CPPUNIT_TEST(atoi); CPPUNIT_TEST(cbrt); CPPUNIT_TEST(clamp); CPPUNIT_TEST(cosh); CPPUNIT_TEST(cross); CPPUNIT_TEST(curlsimplexnoise); CPPUNIT_TEST(determinant); CPPUNIT_TEST(diag); CPPUNIT_TEST(dot); CPPUNIT_TEST(euclideanmod); CPPUNIT_TEST(external); CPPUNIT_TEST(fit); CPPUNIT_TEST(floormod); CPPUNIT_TEST(hash); CPPUNIT_TEST(identity3); CPPUNIT_TEST(identity4); CPPUNIT_TEST(intrinsic); CPPUNIT_TEST(length); CPPUNIT_TEST(lengthsq); CPPUNIT_TEST(lerp); CPPUNIT_TEST(max); CPPUNIT_TEST(min); CPPUNIT_TEST(normalize); CPPUNIT_TEST(polardecompose); CPPUNIT_TEST(postscale); CPPUNIT_TEST(pow); CPPUNIT_TEST(prescale); CPPUNIT_TEST(pretransform); CPPUNIT_TEST(print); CPPUNIT_TEST(rand); CPPUNIT_TEST(rand32); CPPUNIT_TEST(sign); CPPUNIT_TEST(signbit); CPPUNIT_TEST(simplexnoise); CPPUNIT_TEST(sinh); CPPUNIT_TEST(tan); CPPUNIT_TEST(tanh); CPPUNIT_TEST(truncatemod); CPPUNIT_TEST(trace); CPPUNIT_TEST(transform); CPPUNIT_TEST(transpose); CPPUNIT_TEST_SUITE_END(); void abs(); void acos(); void asin(); void atan(); void atan2(); void atof(); void atoi(); void cbrt(); void clamp(); void cosh(); void cross(); void curlsimplexnoise(); void determinant(); void diag(); void dot(); void euclideanmod(); void external(); void fit(); void floormod(); void hash(); void identity3(); void identity4(); void intrinsic(); void length(); void lengthsq(); void lerp(); void max(); void min(); void normalize(); void polardecompose(); void postscale(); void pow(); void prescale(); void pretransform(); void print(); void rand(); void rand32(); void sign(); void signbit(); void simplexnoise(); void sinh(); void tan(); void tanh(); void truncatemod(); void trace(); void transform(); void transpose(); }; CPPUNIT_TEST_SUITE_REGISTRATION(TestStandardFunctions); inline void testFunctionOptions(unittest_util::AXTestHarness& harness, const std::string& name, CustomData::Ptr data = CustomData::create()) { const std::string file = "test/snippets/function/" + name; #ifdef PROFILE struct Timer : public openvdb::util::CpuTimer {} timer; const std::string code = unittest_util::loadText(file); timer.start(std::string("\n") + name + std::string(": Parsing")); const ast::Tree::Ptr syntaxTree = ast::parse(code.c_str()); timer.stop(); // @warning the first execution can take longer due to some llvm startup // so if you're profiling a single function be aware of this. // This also profiles execution AND compilation. auto profile = [&syntaxTree, &timer, &data] (const openvdb::ax::CompilerOptions& opts, std::vector<openvdb::points::PointDataGrid::Ptr>& points, openvdb::GridPtrVec& volumes, const bool doubleCompile = true) { if (!points.empty()) { openvdb::ax::Compiler compiler(opts); if (doubleCompile) { compiler.compile<PointExecutable>(*syntaxTree, data); } { timer.start(" Points/Compilation "); PointExecutable::Ptr executable = compiler.compile<PointExecutable>(*syntaxTree, data); timer.stop(); timer.start(" Points/Execution "); executable->execute(*points.front()); timer.stop(); } } if (!volumes.empty()) { openvdb::ax::Compiler compiler(opts); if (doubleCompile) { compiler.compile<VolumeExecutable>(*syntaxTree, data); } { timer.start(" Volumes/Compilation "); VolumeExecutable::Ptr executable = compiler.compile<VolumeExecutable>(*syntaxTree, data); timer.stop(); timer.start(" Volumes/Execution "); executable->execute(volumes); timer.stop(); } } }; #endif openvdb::ax::CompilerOptions opts; opts.mFunctionOptions.mConstantFoldCBindings = false; opts.mFunctionOptions.mPrioritiseIR = false; #ifdef PROFILE std::cerr << " C Bindings" << std::endl; profile(opts, harness.mInputPointGrids, harness.mInputVolumeGrids); #else harness.mOpts = opts; harness.mCustomData = data; harness.executeCode(file); AXTESTS_STANDARD_ASSERT_HARNESS(harness); #endif harness.resetInputsToZero(); opts.mFunctionOptions.mConstantFoldCBindings = false; opts.mFunctionOptions.mPrioritiseIR = true; #ifdef PROFILE std::cerr << " IR Functions " << std::endl; profile(opts, harness.mInputPointGrids, harness.mInputVolumeGrids); #else harness.mOpts = opts; harness.mCustomData = data; harness.executeCode(file); AXTESTS_STANDARD_ASSERT_HARNESS(harness); #endif harness.resetInputsToZero(); opts.mFunctionOptions.mConstantFoldCBindings = true; opts.mFunctionOptions.mPrioritiseIR = false; #ifdef PROFILE std::cerr << " C Folding " << std::endl; profile(opts, harness.mInputPointGrids, harness.mInputVolumeGrids); #else harness.mOpts = opts; harness.mCustomData = data; harness.executeCode(file); AXTESTS_STANDARD_ASSERT_HARNESS(harness); #endif } void TestStandardFunctions::abs() { mHarness.addAttributes<int32_t>(unittest_util::nameSequence("test", 3), { std::abs(-3), std::abs(3), std::abs(0) }); mHarness.addAttribute<int64_t>("test4", std::abs(-2147483649l)); mHarness.addAttribute<float>("test5", std::abs(0.3f)); mHarness.addAttribute<float>("test6", std::abs(-0.3f)); mHarness.addAttribute<double>("test7", std::abs(1.79769e+308)); mHarness.addAttribute<double>("test8", std::abs(-1.79769e+308)); testFunctionOptions(mHarness, "abs"); } void TestStandardFunctions::acos() { volatile double arg = 0.5; volatile float argf = 0.5f; mHarness.addAttribute<double>("test1", std::acos(arg)); mHarness.addAttribute<float>("test2", std::acos(argf)); testFunctionOptions(mHarness, "acos"); } void TestStandardFunctions::asin() { mHarness.addAttribute<double>("test1", std::asin(-0.5)); mHarness.addAttribute<float>("test2", std::asin(-0.5f)); testFunctionOptions(mHarness, "asin"); } void TestStandardFunctions::atan() { mHarness.addAttribute<double>("test1", std::atan(1.0)); mHarness.addAttribute<float>("test2", std::atan(1.0f)); testFunctionOptions(mHarness, "atan"); } void TestStandardFunctions::atan2() { mHarness.addAttribute<double>("test1", std::atan2(1.0, 1.0)); mHarness.addAttribute<float>("test2", std::atan2(1.0f, 1.0f)); testFunctionOptions(mHarness, "atan2"); } void TestStandardFunctions::atoi() { const std::vector<int32_t> values { std::atoi(""), std::atoi("-0"), std::atoi("+0"), std::atoi("-1"), std::atoi("1"), std::atoi("1s"), std::atoi("1s"), std::atoi(" 1"), std::atoi("1s1"), std::atoi("1 1"), std::atoi("11"), std::atoi("2147483647"), // int max std::atoi("-2147483648") }; mHarness.addAttributes<int32_t>(unittest_util::nameSequence("test", 13), values); testFunctionOptions(mHarness, "atoi"); } void TestStandardFunctions::atof() { const std::vector<double> values { std::atof(""), std::atof("-0.0"), std::atof("+0.0"), std::atof("-1.1"), std::atof("1.5"), std::atof("1.s9"), std::atof("1s.9"), std::atof(" 1.6"), std::atof("1.5s1"), std::atof("1. 1.3"), std::atof("11.11"), std::atof("1.79769e+308"), std::atof("2.22507e-308") }; mHarness.addAttributes<double>(unittest_util::nameSequence("test", 13), values); testFunctionOptions(mHarness, "atof"); } void TestStandardFunctions::cbrt() { volatile double arg = 729.0; volatile float argf = 729.0f; mHarness.addAttribute<double>("test1", std::cbrt(arg)); mHarness.addAttribute<float>("test2", std::cbrt(argf)); testFunctionOptions(mHarness, "cbrt"); } void TestStandardFunctions::clamp() { mHarness.addAttributes<double>(unittest_util::nameSequence("double_test", 3), {-1.5, 0.0, 1.5}); testFunctionOptions(mHarness, "clamp"); } void TestStandardFunctions::cosh() { volatile float arg = 1.0f; mHarness.addAttribute<double>("test1", std::cosh(1.0)); mHarness.addAttribute<float>("test2", std::cosh(arg)); testFunctionOptions(mHarness, "cosh"); } void TestStandardFunctions::cross() { const openvdb::Vec3d ad(1.0,2.2,3.4), bd(4.1,5.3,6.2); const openvdb::Vec3f af(1.0f,2.2f,3.4f), bf(4.1f,5.3f,6.2f); const openvdb::Vec3i ai(1,2,3), bi(4,5,6); mHarness.addAttribute<openvdb::Vec3d>("test1", ad.cross(bd)); mHarness.addAttribute<openvdb::Vec3f>("test2", af.cross(bf)); mHarness.addAttribute<openvdb::Vec3i>("test3", ai.cross(bi)); testFunctionOptions(mHarness, "cross"); } void TestStandardFunctions::curlsimplexnoise() { struct Local { static inline double noise(double x, double y, double z) { const OSN::OSNoise gen; const double result = gen.eval<double>(x, y, z); return (result + 1.0) * 0.5; } }; double result[3]; openvdb::ax::math::curlnoise<Local>(&result, 4.3, 5.7, -6.2); const openvdb::Vec3d expected(result[0], result[1], result[2]); mHarness.addAttributes<openvdb::Vec3d> (unittest_util::nameSequence("test", 2), {expected,expected}); testFunctionOptions(mHarness, "curlsimplexnoise"); } void TestStandardFunctions::determinant() { mHarness.addAttribute<float>("det3_float", 600.0f); mHarness.addAttribute<double>("det3_double", 600.0); mHarness.addAttribute<float>("det4_float", 24.0f); mHarness.addAttribute<double>("det4_double", 2400.0); testFunctionOptions(mHarness, "determinant"); } void TestStandardFunctions::diag() { mHarness.addAttribute<openvdb::math::Mat3<double>> ("test1", openvdb::math::Mat3<double>(-1,0,0, 0,-2,0, 0,0,-3)); mHarness.addAttribute<openvdb::math::Mat3<float>> ("test2", openvdb::math::Mat3<float>(-1,0,0, 0,-2,0, 0,0,-3)); mHarness.addAttribute<openvdb::math::Mat4<double>> ("test3", openvdb::math::Mat4<double>(-1,0,0,0, 0,-2,0,0, 0,0,-3,0, 0,0,0,-4)); mHarness.addAttribute<openvdb::math::Mat4<float>> ("test4", openvdb::math::Mat4<float>(-1,0,0,0, 0,-2,0,0, 0,0,-3,0, 0,0,0,-4)); mHarness.addAttribute<openvdb::math::Vec3<double>>("test5", openvdb::math::Vec3<float>(-1,-5,-9)); mHarness.addAttribute<openvdb::math::Vec3<float>>("test6", openvdb::math::Vec3<float>(-1,-5,-9)); mHarness.addAttribute<openvdb::math::Vec4<double>>("test7", openvdb::math::Vec4<double>(-1,-6,-11,-16)); mHarness.addAttribute<openvdb::math::Vec4<float>>("test8", openvdb::math::Vec4<float>(-1,-6,-11,-16)); testFunctionOptions(mHarness, "diag"); } void TestStandardFunctions::dot() { const openvdb::Vec3d ad(1.0,2.2,3.4), bd(4.1,5.3,6.2); const openvdb::Vec3f af(1.0f,2.2f,3.4f), bf(4.1f,5.3f,6.2f); const openvdb::Vec3i ai(1,2,3), bi(4,5,6); mHarness.addAttribute<double>("test1", ad.dot(bd)); mHarness.addAttribute<float>("test2", af.dot(bf)); mHarness.addAttribute<int32_t>("test3", ai.dot(bi)); testFunctionOptions(mHarness, "dot"); } void TestStandardFunctions::euclideanmod() { static auto emod = [](auto D, auto d) -> auto { using ValueType = decltype(D); return ValueType(D - d * (d < 0 ? std::ceil(D/double(d)) : std::floor(D/double(d)))); }; // @note these also test that these match % op const std::vector<int32_t> ivalues{ emod(7, 5), emod(-7, 5), emod(7,-5), emod(-7,-5) }; const std::vector<float> fvalues{ emod(7.2f, 5.7f), emod(-7.2f, 5.7f), emod(7.2f, -5.7f), emod(-7.2f, -5.7f) }; const std::vector<double> dvalues{ emod(7.2, 5.7), emod(-7.2, 5.7), emod(7.2, -5.7), emod(-7.2, -5.7) }; mHarness.addAttributes<int32_t>(unittest_util::nameSequence("itest", 4), ivalues); mHarness.addAttributes<float>(unittest_util::nameSequence("ftest", 4), fvalues); mHarness.addAttributes<double>(unittest_util::nameSequence("dtest", 4), dvalues); testFunctionOptions(mHarness, "euclideanmod"); } void TestStandardFunctions::external() { mHarness.addAttribute<float>("foo", 2.0f); mHarness.addAttribute<openvdb::Vec3f>("v", openvdb::Vec3f(1.0f, 2.0f, 3.0f)); using FloatMeta = openvdb::TypedMetadata<float>; using VectorFloatMeta = openvdb::TypedMetadata<openvdb::math::Vec3<float>>; FloatMeta customFloatData(2.0f); VectorFloatMeta customVecData(openvdb::math::Vec3<float>(1.0f, 2.0f, 3.0f)); // test initialising the data before compile CustomData::Ptr data = CustomData::create(); data->insertData("float1", customFloatData.copy()); data->insertData("vector1", customVecData.copy()); testFunctionOptions(mHarness, "external", data); mHarness.reset(); mHarness.addAttribute<float>("foo", 2.0f); mHarness.addAttribute<openvdb::Vec3f>("v", openvdb::Vec3f(1.0f, 2.0f, 3.0f)); // test post compilation data->reset(); const std::string code = unittest_util::loadText("test/snippets/function/external"); Compiler compiler; PointExecutable::Ptr pointExecutable = compiler.compile<PointExecutable>(code, data); VolumeExecutable::Ptr volumeExecutable = compiler.compile<VolumeExecutable>(code, data); data->insertData("float1", customFloatData.copy()); VectorFloatMeta::Ptr customTypedVecData = openvdb::StaticPtrCast<VectorFloatMeta>(customVecData.copy()); data->insertData<VectorFloatMeta>("vector1", customTypedVecData); for (auto& grid : mHarness.mInputPointGrids) { pointExecutable->execute(*grid); } volumeExecutable->execute(mHarness.mInputVolumeGrids); AXTESTS_STANDARD_ASSERT() } void TestStandardFunctions::fit() { std::vector<double> values{23.0, -23.0, -25.0, -15.0, -15.0, -18.0, -24.0, 0.0, 10.0, -5.0, 0.0, -1.0, 4.5, 4.5, 4.5, 4.5, 4.5}; mHarness.addAttributes<double>(unittest_util::nameSequence("double_test", 17), values); testFunctionOptions(mHarness, "fit"); } void TestStandardFunctions::floormod() { auto axmod = [](auto D, auto d) -> auto { auto r = std::fmod(D, d); if ((r > 0 && d < 0) || (r < 0 && d > 0)) r = r+d; return r; }; // @note these also test that these match % op const std::vector<int32_t> ivalues{ 2,2, 3,3, -3,-3, -2,-2 }; const std::vector<float> fvalues{ axmod(7.2f,5.7f),axmod(7.2f,5.7f), axmod(-7.2f,5.7f),axmod(-7.2f,5.7f), axmod(7.2f,-5.7f),axmod(7.2f,-5.7f), axmod(-7.2f,-5.7f),axmod(-7.2f,-5.7f) }; const std::vector<double> dvalues{ axmod(7.2,5.7),axmod(7.2,5.7), axmod(-7.2,5.7),axmod(-7.2,5.7), axmod(7.2,-5.7),axmod(7.2,-5.7), axmod(-7.2,-5.7),axmod(-7.2,-5.7) }; mHarness.addAttributes<int32_t>(unittest_util::nameSequence("itest", 8), ivalues); mHarness.addAttributes<float>(unittest_util::nameSequence("ftest", 8), fvalues); mHarness.addAttributes<double>(unittest_util::nameSequence("dtest", 8), dvalues); testFunctionOptions(mHarness, "floormod"); } void TestStandardFunctions::hash() { const std::vector<int64_t> values{ static_cast<int64_t>(std::hash<std::string>{}("")), static_cast<int64_t>(std::hash<std::string>{}("0")), static_cast<int64_t>(std::hash<std::string>{}("abc")), static_cast<int64_t>(std::hash<std::string>{}("123")), }; mHarness.addAttributes<int64_t>(unittest_util::nameSequence("test", 4), values); testFunctionOptions(mHarness, "hash"); } void TestStandardFunctions::identity3() { mHarness.addAttribute<openvdb::Mat3d>("test", openvdb::Mat3d::identity()); testFunctionOptions(mHarness, "identity3"); } void TestStandardFunctions::identity4() { mHarness.addAttribute<openvdb::Mat4d>("test", openvdb::Mat4d::identity()); testFunctionOptions(mHarness, "identity4"); } void TestStandardFunctions::intrinsic() { mHarness.addAttributes<double>(unittest_util::nameSequence("dtest", 12), { std::sqrt(9.0), std::cos(0.0), std::sin(0.0), std::log(1.0), std::log10(1.0), std::log2(2.0), std::exp(0.0), std::exp2(4.0), std::fabs(-10.321), std::floor(2194.213), std::ceil(2194.213), std::round(0.5) }); mHarness.addAttributes<float>(unittest_util::nameSequence("ftest", 12), { std::sqrt(9.0f), std::cos(0.0f), std::sin(0.0f), std::log(1.0f), std::log10(1.0f), std::log2(2.0f), std::exp(0.0f), std::exp2(4.0f), std::fabs(-10.321f), std::floor(2194.213f), std::ceil(2194.213f), std::round(0.5f) }); testFunctionOptions(mHarness, "intrinsic"); } void TestStandardFunctions::length() { mHarness.addAttribute("test1", openvdb::Vec2d(2.2, 3.3).length()); mHarness.addAttribute("test2", openvdb::Vec2f(2.2f, 3.3f).length()); mHarness.addAttribute("test3", std::sqrt(double(openvdb::Vec2i(2, 3).lengthSqr()))); mHarness.addAttribute("test4", openvdb::Vec3d(2.2, 3.3, 6.6).length()); mHarness.addAttribute("test5", openvdb::Vec3f(2.2f, 3.3f, 6.6f).length()); mHarness.addAttribute("test6", std::sqrt(double(openvdb::Vec3i(2, 3, 6).lengthSqr()))); mHarness.addAttribute("test7", openvdb::Vec4d(2.2, 3.3, 6.6, 7.7).length()); mHarness.addAttribute("test8", openvdb::Vec4f(2.2f, 3.3f, 6.6f, 7.7f).length()); mHarness.addAttribute("test9", std::sqrt(double(openvdb::Vec4i(2, 3, 6, 7).lengthSqr()))); testFunctionOptions(mHarness, "length"); } void TestStandardFunctions::lengthsq() { mHarness.addAttribute("test1", openvdb::Vec2d(2.2, 3.3).lengthSqr()); mHarness.addAttribute("test2", openvdb::Vec2f(2.2f, 3.3f).lengthSqr()); mHarness.addAttribute("test3", openvdb::Vec2i(2, 3).lengthSqr()); mHarness.addAttribute("test4", openvdb::Vec3d(2.2, 3.3, 6.6).lengthSqr()); mHarness.addAttribute("test5", openvdb::Vec3f(2.2f, 3.3f, 6.6f).lengthSqr()); mHarness.addAttribute("test6", openvdb::Vec3i(2, 3, 6).lengthSqr()); mHarness.addAttribute("test7", openvdb::Vec4d(2.2, 3.3, 6.6, 7.7).lengthSqr()); mHarness.addAttribute("test8", openvdb::Vec4f(2.2f, 3.3f, 6.6f, 7.7f).lengthSqr()); mHarness.addAttribute("test9", openvdb::Vec4i(2, 3, 6, 7).lengthSqr()); testFunctionOptions(mHarness, "lengthsq"); } void TestStandardFunctions::lerp() { mHarness.addAttributes<double>(unittest_util::nameSequence("test", 9), {-1.1, 1.0000001, 1.0000001, -1.0000001, 1.1, -1.1, 6.0, 21.0, -19.0}); mHarness.addAttribute<float>("test10", 6.0f); testFunctionOptions(mHarness, "lerp"); } void TestStandardFunctions::max() { mHarness.addAttribute("test1", std::max(-1.5, 1.5)); mHarness.addAttribute("test2", std::max(-1.5f, 1.5f)); mHarness.addAttribute("test3", std::max(-1, 1)); testFunctionOptions(mHarness, "max"); } void TestStandardFunctions::min() { mHarness.addAttribute("test1", std::min(-1.5, 1.5)); mHarness.addAttribute("test2", std::min(-1.5f, 1.5f)); mHarness.addAttribute("test3", std::min(-1, 1)); testFunctionOptions(mHarness, "min"); } void TestStandardFunctions::normalize() { openvdb::Vec3f expectedf(1.f, 2.f, 3.f); openvdb::Vec3d expectedd(1., 2., 3.); openvdb::Vec3d expectedi(1, 2, 3); expectedf.normalize(); expectedd.normalize(); expectedi.normalize(); mHarness.addAttribute("test1", expectedf); mHarness.addAttribute("test2", expectedd); mHarness.addAttribute("test3", expectedi); testFunctionOptions(mHarness, "normalize"); } void TestStandardFunctions::polardecompose() { // See snippet/polardecompose for details const openvdb::Mat3d composite( 1.41421456236949, 0.0, -5.09116882455613, 0.0, 3.3, 0.0, -1.41421356237670, 0.0, -5.09116882453015); openvdb::Mat3d rot, symm; openvdb::math::polarDecomposition(composite, rot, symm); mHarness.addAttribute<openvdb::Mat3d>("rotation", rot); mHarness.addAttribute<openvdb::Mat3d>("symm", symm); testFunctionOptions(mHarness, "polardecompose"); } void TestStandardFunctions::postscale() { mHarness.addAttributes<openvdb::math::Mat4<float>> ({"mat1", "mat3", "mat5"}, { openvdb::math::Mat4<float>( 10.0f, 22.0f, 36.0f, 4.0f, 50.0f, 66.0f, 84.0f, 8.0f, 90.0f, 110.0f,132.0f,12.0f, 130.0f,154.0f,180.0f,16.0f), openvdb::math::Mat4<float>( -1.0f, -4.0f, -9.0f, 4.0f, -5.0f, -12.0f,-21.0f, 8.0f, -9.0f, -20.0f,-33.0f,12.0f, -13.0f,-28.0f,-45.0f,16.0f), openvdb::math::Mat4<float>( 0.0f, 100.0f, 200.0f, 100.0f, 0.0f, 200.0f, 400.0f, 200.0f, 0.0f, 300.0f, 600.0f, 300.0f, 0.0f, 400.0f, 800.0f, 400.0f) }); mHarness.addAttributes<openvdb::math::Mat4<double>> ({"mat2", "mat4", "mat6"}, { openvdb::math::Mat4<double>( 10.0, 22.0, 36.0, 4.0, 50.0, 66.0, 84.0, 8.0, 90.0, 110.0,132.0,12.0, 130.0,154.0,180.0,16.0), openvdb::math::Mat4<double>( -1.0, -4.0, -9.0, 4.0, -5.0, -12.0,-21.0, 8.0, -9.0, -20.0,-33.0,12.0, -13.0,-28.0,-45.0,16.0), openvdb::math::Mat4<double>( 0.0, 100.0, 200.0, 100.0, 0.0, 200.0, 400.0, 200.0, 0.0, 300.0, 600.0, 300.0, 0.0, 400.0, 800.0, 400.0) }); testFunctionOptions(mHarness, "postscale"); } void TestStandardFunctions::pow() { mHarness.addAttributes<float>(unittest_util::nameSequence("float_test", 5),{ 1.0f, static_cast<float>(std::pow(3.0, -2.1)), std::pow(4.7f, -4.3f), static_cast<float>(std::pow(4.7f, 3)), 0.00032f }); mHarness.addAttribute<int>("int_test1", static_cast<int>(std::pow(3, 5))); testFunctionOptions(mHarness, "pow"); } void TestStandardFunctions::prescale() { mHarness.addAttributes<openvdb::math::Mat4<float>> ({"mat1", "mat3", "mat5"}, { openvdb::math::Mat4<float>( 10.0f, 20.0f, 30.0f, 40.0f, 55.0f, 66.0f, 77.0f, 88.0f, 108.0f, 120.0f,132.0f,144.0f, 13.0f,14.0f,15.0f,16.0f), openvdb::math::Mat4<float>( -1.0f,-2.0f,-3.0f,-4.0f, -10.0f,-12.0f,-14.0f,-16.0f, -27.0f,-30.0f,-33.0f,-36.0f, 13.0f,14.0f,15.0f,16.0f), openvdb::math::Mat4<float>( 0.0f, 0.0f, 0.0f, 0.0f, 200.0f, 200.0f, 200.0f, 200.0f, 600.0f, 600.0f, 600.0f, 600.0f, 400.0f, 400.0f, 400.0f, 400.0f) }); mHarness.addAttributes<openvdb::math::Mat4<double>> ({"mat2", "mat4", "mat6"}, { openvdb::math::Mat4<double>( 10.0, 20.0, 30.0, 40.0, 55.0, 66.0, 77.0, 88.0, 108.0, 120.0,132.0,144.0, 13.0,14.0,15.0,16.0), openvdb::math::Mat4<double>( -1.0,-2.0,-3.0,-4.0, -10.0,-12.0,-14.0,-16.0, -27.0,-30.0,-33.0,-36.0, 13.0,14.0,15.0,16.0), openvdb::math::Mat4<double>( 0.0, 0.0, 0.0, 0.0, 200.0, 200.0, 200.0, 200.0, 600.0, 600.0, 600.0, 600.0, 400.0, 400.0, 400.0, 400.0) }); testFunctionOptions(mHarness, "prescale"); } void TestStandardFunctions::pretransform() { mHarness.addAttributes<openvdb::math::Vec3<double>> ({"test1", "test3", "test7"}, { openvdb::math::Vec3<double>(14.0, 32.0, 50.0), openvdb::math::Vec3<double>(18.0, 46.0, 74.0), openvdb::math::Vec3<double>(18.0, 46.0, 74.0), }); mHarness.addAttribute<openvdb::math::Vec4<double>>("test5", openvdb::math::Vec4<double>(30.0, 70.0, 110.0, 150.0)); mHarness.addAttributes<openvdb::math::Vec3<float>> ({"test2", "test4", "test8"}, { openvdb::math::Vec3<float>(14.0f, 32.0f, 50.0f), openvdb::math::Vec3<float>(18.0f, 46.0f, 74.0f), openvdb::math::Vec3<float>(18.0f, 46.0f, 74.0f), }); mHarness.addAttribute<openvdb::math::Vec4<float>>("test6", openvdb::math::Vec4<float>(30.0f, 70.0f, 110.0f, 150.0f)); testFunctionOptions(mHarness, "pretransform"); } void TestStandardFunctions::print() { openvdb::math::Transform::Ptr transform = openvdb::math::Transform::createLinearTransform(); const std::vector<openvdb::Vec3d> single = { openvdb::Vec3d::zero() }; openvdb::points::PointDataGrid::Ptr grid = openvdb::points::createPointDataGrid <openvdb::points::NullCodec, openvdb::points::PointDataGrid> (single, *transform); const std::string code = unittest_util::loadText("test/snippets/function/print"); openvdb::ax::Compiler::UniquePtr compiler = openvdb::ax::Compiler::create(); openvdb::ax::PointExecutable::Ptr executable = compiler->compile<openvdb::ax::PointExecutable>(code); std::streambuf* sbuf = std::cout.rdbuf(); try { // Redirect cout std::stringstream buffer; std::cout.rdbuf(buffer.rdbuf()); executable->execute(*grid); const std::string& result = buffer.str(); std::string expected = "a\n1\n2e-10\n"; expected += openvdb::Vec4i(3,4,5,6).str() + "\n"; expected += "bcd\n"; CPPUNIT_ASSERT_EQUAL(expected, result); } catch (...) { std::cout.rdbuf(sbuf); throw; } std::cout.rdbuf(sbuf); } void TestStandardFunctions::rand() { std::mt19937_64 engine; std::uniform_real_distribution<double> uniform(0.0,1.0); size_t hash = std::hash<double>()(2.0); engine.seed(hash); const double expected1 = uniform(engine); hash = std::hash<double>()(3.0); engine.seed(hash); const double expected2 = uniform(engine); const double expected3 = uniform(engine); mHarness.addAttributes<double>({"test0", "test1", "test2", "test3"}, {expected1, expected1, expected2, expected3}); testFunctionOptions(mHarness, "rand"); } void TestStandardFunctions::rand32() { auto hashToSeed = [](size_t hash) -> std::mt19937::result_type { unsigned int seed = 0; do { seed ^= (uint32_t) hash; } while (hash >>= sizeof(uint32_t) * 8); return std::mt19937::result_type(seed); }; std::mt19937 engine; std::uniform_real_distribution<double> uniform(0.0,1.0); size_t hash = std::hash<double>()(2.0); engine.seed(hashToSeed(hash)); const double expected1 = uniform(engine); hash = std::hash<double>()(3.0); engine.seed(hashToSeed(hash)); const double expected2 = uniform(engine); const double expected3 = uniform(engine); mHarness.addAttributes<double>({"test0", "test1", "test2", "test3"}, {expected1, expected1, expected2, expected3}); testFunctionOptions(mHarness, "rand32"); } void TestStandardFunctions::sign() { mHarness.addAttributes<int32_t>(unittest_util::nameSequence("test", 13), { 0,0,0,0,0,0,0, -1,-1,-1, 1,1,1 }); testFunctionOptions(mHarness, "sign"); } void TestStandardFunctions::signbit() { mHarness.addAttributes<bool>(unittest_util::nameSequence("test", 5), {true,false,true,false,false}); testFunctionOptions(mHarness, "signbit"); } void TestStandardFunctions::simplexnoise() { const OSN::OSNoise noiseGenerator; const double noise1 = noiseGenerator.eval<double>(1.0, 2.0, 3.0); const double noise2 = noiseGenerator.eval<double>(1.0, 2.0, 0.0); const double noise3 = noiseGenerator.eval<double>(1.0, 0.0, 0.0); const double noise4 = noiseGenerator.eval<double>(4.0, 14.0, 114.0); mHarness.addAttribute<double>("noise1", (noise1 + 1.0) * 0.5); mHarness.addAttribute<double>("noise2", (noise2 + 1.0) * 0.5); mHarness.addAttribute<double>("noise3", (noise3 + 1.0) * 0.5); mHarness.addAttribute<double>("noise4", (noise4 + 1.0) * 0.5); testFunctionOptions(mHarness, "simplexnoise"); } void TestStandardFunctions::sinh() { mHarness.addAttribute<double>("test1", std::sinh(1.0)); mHarness.addAttribute<float>("test2", std::sinh(1.0f)); testFunctionOptions(mHarness, "sinh"); } void TestStandardFunctions::tan() { mHarness.addAttribute<double>("test1", std::tan(1.0)); mHarness.addAttribute<float>("test2", std::tan(1.0f)); testFunctionOptions(mHarness, "tan"); } void TestStandardFunctions::tanh() { mHarness.addAttribute<double>("test1", std::tanh(1.0)); mHarness.addAttribute<float>("test2", std::tanh(1.0f)); testFunctionOptions(mHarness, "tanh"); } void TestStandardFunctions::trace() { mHarness.addAttribute<double>("test1", 6.0); mHarness.addAttribute<float>("test2", 6.0f); testFunctionOptions(mHarness, "trace"); } void TestStandardFunctions::truncatemod() { // @note these also test that these match % op const std::vector<int32_t> ivalues{ 2,-2,2,-2, }; const std::vector<float> fvalues{ std::fmod(7.2f, 5.7f), std::fmod(-7.2f, 5.7f), std::fmod(7.2f, -5.7f), std::fmod(-7.2f, -5.7f) }; const std::vector<double> dvalues{ std::fmod(7.2, 5.7), std::fmod(-7.2, 5.7), std::fmod(7.2, -5.7), std::fmod(-7.2, -5.7) }; mHarness.addAttributes<int32_t>(unittest_util::nameSequence("itest", 4), ivalues); mHarness.addAttributes<float>(unittest_util::nameSequence("ftest", 4), fvalues); mHarness.addAttributes<double>(unittest_util::nameSequence("dtest", 4), dvalues); testFunctionOptions(mHarness, "truncatemod"); } void TestStandardFunctions::transform() { mHarness.addAttributes<openvdb::math::Vec3<double>> ({"test1", "test3", "test7"}, { openvdb::math::Vec3<double>(30.0, 36.0, 42.0), openvdb::math::Vec3<double>(51.0, 58, 65.0), openvdb::math::Vec3<double>(51.0, 58, 65.0), }); mHarness.addAttribute<openvdb::math::Vec4<double>>("test5", openvdb::math::Vec4<double>(90.0, 100.0, 110.0, 120.0)); mHarness.addAttributes<openvdb::math::Vec3<float>> ({"test2", "test4", "test8"}, { openvdb::math::Vec3<float>(30.0f, 36.0f, 42.0f), openvdb::math::Vec3<float>(51.0f, 58.0f, 65.0f), openvdb::math::Vec3<float>(51.0f, 58.0f, 65.0f), }); mHarness.addAttribute<openvdb::math::Vec4<float>>("test6", openvdb::math::Vec4<float>(90.0f, 100.0f, 110.0f, 120.0f)); testFunctionOptions(mHarness, "transform"); } void TestStandardFunctions::transpose() { mHarness.addAttribute("test1", openvdb::math::Mat3<double>( 1.0, 4.0, 7.0, 2.0, 5.0, 8.0, 3.0, 6.0, 9.0)); mHarness.addAttribute("test2", openvdb::math::Mat3<float>( 1.0f, 4.0f, 7.0f, 2.0f, 5.0f, 8.0f, 3.0f, 6.0f, 9.0f)); mHarness.addAttribute("test3", openvdb::math::Mat4<double>( 1.0, 5.0, 9.0,13.0, 2.0, 6.0,10.0,14.0, 3.0, 7.0,11.0,15.0, 4.0, 8.0,12.0,16.0)); mHarness.addAttribute("test4", openvdb::math::Mat4<float>( 1.0f, 5.0f, 9.0f,13.0f, 2.0f, 6.0f,10.0f,14.0f, 3.0f, 7.0f,11.0f,15.0f, 4.0f, 8.0f,12.0f,16.0f)); testFunctionOptions(mHarness, "transpose"); }
NVIDIA-Omniverse/ext-openvdb/openvdb_ax/openvdb_ax/test/integration/TestHarness.cc
// Copyright Contributors to the OpenVDB Project // SPDX-License-Identifier: MPL-2.0 #include "TestHarness.h" #include "util.h" #include <openvdb_ax/compiler/PointExecutable.h> #include <openvdb_ax/compiler/VolumeExecutable.h> #include <openvdb/points/PointConversion.h> namespace unittest_util { std::string loadText(const std::string& codeFileName) { std::ostringstream sstream; std::ifstream fs(codeFileName); if (fs.fail()) { throw std::runtime_error(std::string("Failed to open ") + std::string(codeFileName)); } sstream << fs.rdbuf(); return sstream.str(); } bool wrapExecution(openvdb::points::PointDataGrid& grid, const std::string& codeFileName, const std::string * const group, openvdb::ax::Logger& logger, const openvdb::ax::CustomData::Ptr& data, const openvdb::ax::CompilerOptions& opts, const bool createMissing) { using namespace openvdb::ax; Compiler compiler(opts); const std::string code = loadText(codeFileName); ast::Tree::ConstPtr syntaxTree = ast::parse(code.c_str(), logger); PointExecutable::Ptr executable = compiler.compile<PointExecutable>(*syntaxTree, logger, data); if (!executable) return false; executable->setCreateMissing(createMissing); if (group) executable->setGroupExecution(*group); executable->execute(grid); return true; } bool wrapExecution(openvdb::GridPtrVec& grids, const std::string& codeFileName, openvdb::ax::Logger& logger, const openvdb::ax::CustomData::Ptr& data, const openvdb::ax::CompilerOptions& opts, const bool createMissing) { using namespace openvdb::ax; Compiler compiler(opts); const std::string code = loadText(codeFileName); ast::Tree::ConstPtr syntaxTree = ast::parse(code.c_str(), logger); VolumeExecutable::Ptr executable = compiler.compile<VolumeExecutable>(*syntaxTree, logger, data); if (!executable) return false; executable->setCreateMissing(createMissing); executable->setValueIterator(VolumeExecutable::IterType::ON); executable->execute(grids); return true; } void AXTestHarness::addInputGroups(const std::vector<std::string> &names, const std::vector<bool> &defaults) { for (size_t i = 0; i < names.size(); i++) { for (auto& grid : mInputPointGrids) { openvdb::points::appendGroup(grid->tree(), names[i]); openvdb::points::setGroup(grid->tree(), names[i], defaults[i]); } } } void AXTestHarness::addExpectedGroups(const std::vector<std::string> &names, const std::vector<bool> &defaults) { for (size_t i = 0; i < names.size(); i++) { for (auto& grid : mOutputPointGrids) { openvdb::points::appendGroup(grid->tree(), names[i]); openvdb::points::setGroup(grid->tree(), names[i], defaults[i]); } } } bool AXTestHarness::executeCode(const std::string& codeFile, const std::string* const group, const bool createMissing) { bool success = false; if (mUsePoints) { for (auto& grid : mInputPointGrids) { mLogger.clear(); success = wrapExecution(*grid, codeFile, group, mLogger, mCustomData, mOpts, createMissing); if (!success) break; } } if (mUseVolumes) { mLogger.clear(); success = wrapExecution(mInputVolumeGrids, codeFile, mLogger, mCustomData, mOpts, createMissing); } return success; } template <typename T> void AXTestHarness::addInputPtAttributes(const std::vector<std::string>& names, const std::vector<T>& values) { for (size_t i = 0; i < names.size(); i++) { for (auto& grid : mInputPointGrids) { openvdb::points::appendAttribute<T>(grid->tree(), names[i], values[i]); } } } template <typename T> void AXTestHarness::addInputVolumes(const std::vector<std::string>& names, const std::vector<T>& values) { using GridType = typename openvdb::BoolGrid::ValueConverter<T>::Type; for (size_t i = 0; i < names.size(); i++) { typename GridType::Ptr grid = GridType::create(); grid->denseFill(mVolumeBounds, values[i], true/*active*/); grid->setName(names[i]); mInputVolumeGrids.emplace_back(grid); } } template <typename T> void AXTestHarness::addExpectedPtAttributes(const std::vector<std::string>& names, const std::vector<T>& values) { for (size_t i = 0; i < names.size(); i++) { for (auto& grid : mOutputPointGrids) { openvdb::points::appendAttribute<T>(grid->tree(), names[i], values[i]); } } } template <typename T> void AXTestHarness::addExpectedVolumes(const std::vector<std::string>& names, const std::vector<T>& values) { using GridType = typename openvdb::BoolGrid::ValueConverter<T>::Type; for (size_t i = 0; i < names.size(); i++) { typename GridType::Ptr grid = GridType::create(); grid->denseFill(mVolumeBounds, values[i], true/*active*/); grid->setName(names[i] + "_expected"); mOutputVolumeGrids.emplace_back(grid); } } bool AXTestHarness::checkAgainstExpected(std::ostream& sstream) { unittest_util::ComparisonSettings settings; bool success = true; if (mUsePoints) { std::stringstream resultStream; unittest_util::ComparisonResult result(resultStream); const size_t count = mInputPointGrids.size(); for (size_t i = 0; i < count; ++i) { const auto& input = mInputPointGrids[i]; const auto& expected = mOutputPointGrids[i]; const bool pass = unittest_util::compareGrids(result, *expected, *input, settings, nullptr); if (!pass) sstream << resultStream.str() << std::endl; success &= pass; } } if (mUseVolumes) { for (size_t i = 0; i < mInputVolumeGrids.size(); i++) { std::stringstream resultStream; unittest_util::ComparisonResult result(resultStream); const bool volumeSuccess = unittest_util::compareUntypedGrids(result, *mOutputVolumeGrids[i], *mInputVolumeGrids[i], settings, nullptr); success &= volumeSuccess; if (!volumeSuccess) sstream << resultStream.str() << std::endl; } } return success; } void AXTestHarness::testVolumes(const bool enable) { mUseVolumes = enable; } void AXTestHarness::testPoints(const bool enable) { mUsePoints = enable; } void AXTestHarness::reset(const openvdb::Index64 ppv, const openvdb::CoordBBox& bounds) { using openvdb::points::PointDataGrid; using openvdb::points::NullCodec; mInputPointGrids.clear(); mOutputPointGrids.clear(); mInputVolumeGrids.clear(); mOutputVolumeGrids.clear(); openvdb::math::Transform::Ptr transform = openvdb::math::Transform::createLinearTransform(1.0); openvdb::MaskGrid::Ptr mask = openvdb::MaskGrid::create(); mask->setTransform(transform); mask->sparseFill(bounds, true, true); openvdb::points::PointDataGrid::Ptr points = openvdb::points::denseUniformPointScatter(*mask, static_cast<float>(ppv)); mask.reset(); mInputPointGrids.emplace_back(points); mOutputPointGrids.emplace_back(points->deepCopy()); mOutputPointGrids.back()->setName("custom_expected"); mVolumeBounds = bounds; mLogger.clear(); } void AXTestHarness::reset() { using openvdb::points::PointDataGrid; using openvdb::points::NullCodec; mInputPointGrids.clear(); mOutputPointGrids.clear(); mInputVolumeGrids.clear(); mOutputVolumeGrids.clear(); std::vector<openvdb::Vec3d> coordinates = {openvdb::Vec3d(0.0, 0.0, 0.0), openvdb::Vec3d(0.0, 0.0, 0.05), openvdb::Vec3d(0.0, 1.0, 0.0), openvdb::Vec3d(1.0, 1.0, 0.0)}; openvdb::math::Transform::Ptr transform1 = openvdb::math::Transform::createLinearTransform(1.0); openvdb::points::PointDataGrid::Ptr onePointGrid = openvdb::points::createPointDataGrid<NullCodec, PointDataGrid> (std::vector<openvdb::Vec3d>{coordinates[0]}, *transform1); onePointGrid->setName("1_point"); mInputPointGrids.emplace_back(onePointGrid); mOutputPointGrids.emplace_back(onePointGrid->deepCopy()); mOutputPointGrids.back()->setName("1_point_expected"); openvdb::math::Transform::Ptr transform2 = openvdb::math::Transform::createLinearTransform(0.1); openvdb::points::PointDataGrid::Ptr fourPointGrid = openvdb::points::createPointDataGrid<NullCodec, PointDataGrid> (coordinates, *transform2); fourPointGrid->setName("4_points"); mInputPointGrids.emplace_back(fourPointGrid); mOutputPointGrids.emplace_back(fourPointGrid->deepCopy()); mOutputPointGrids.back()->setName("4_points_expected"); mVolumeBounds = openvdb::CoordBBox({0,0,0}, {0,0,0}); mLogger.clear(); } template <typename ValueT> using ConverterT = typename openvdb::BoolGrid::ValueConverter<ValueT>::Type; void AXTestHarness::resetInputsToZero() { for (auto& grid : mInputPointGrids) { openvdb::tree::LeafManager<openvdb::points::PointDataTree> manager(grid->tree()); manager.foreach([](openvdb::points::PointDataTree::LeafNodeType& leaf, size_t) { const size_t attrs = leaf.attributeSet().size(); const size_t pidx = leaf.attributeSet().descriptor().find("P"); for (size_t idx = 0; idx < attrs; ++idx) { if (idx == pidx) continue; leaf.attributeArray(idx).collapse(); } }); } /// @todo: share with volume executable when the move to header files is made /// for customization of grid types. using SupportedTypeList = openvdb::TypeList< ConverterT<double>, ConverterT<float>, ConverterT<int64_t>, ConverterT<int32_t>, ConverterT<int16_t>, ConverterT<bool>, ConverterT<openvdb::math::Vec2<double>>, ConverterT<openvdb::math::Vec2<float>>, ConverterT<openvdb::math::Vec2<int32_t>>, ConverterT<openvdb::math::Vec3<double>>, ConverterT<openvdb::math::Vec3<float>>, ConverterT<openvdb::math::Vec3<int32_t>>, ConverterT<openvdb::math::Vec4<double>>, ConverterT<openvdb::math::Vec4<float>>, ConverterT<openvdb::math::Vec4<int32_t>>, ConverterT<openvdb::math::Mat3<double>>, ConverterT<openvdb::math::Mat3<float>>, ConverterT<openvdb::math::Mat4<double>>, ConverterT<openvdb::math::Mat4<float>>, ConverterT<std::string>>; for (auto& grid : mInputVolumeGrids) { const bool success = grid->apply<SupportedTypeList>([](auto& typed) { using GridType = typename std::decay<decltype(typed)>::type; openvdb::tree::LeafManager<typename GridType::TreeType> manager(typed.tree()); manager.foreach([](typename GridType::TreeType::LeafNodeType& leaf, size_t) { leaf.fill(openvdb::zeroVal<typename GridType::ValueType>()); }); }); if (!success) { throw std::runtime_error("Unable to reset input grid of an unsupported type"); } } } #define REGISTER_HARNESS_METHODS(T) \ template void AXTestHarness::addInputPtAttributes<T>(const std::vector<std::string>&, const std::vector<T>&); \ template void AXTestHarness::addInputVolumes<T>(const std::vector<std::string>&, const std::vector<T>&); \ template void AXTestHarness::addExpectedPtAttributes<T>(const std::vector<std::string>&, const std::vector<T>&); \ template void AXTestHarness::addExpectedVolumes<T>(const std::vector<std::string>&, const std::vector<T>&); REGISTER_HARNESS_METHODS(double) REGISTER_HARNESS_METHODS(float) REGISTER_HARNESS_METHODS(int64_t) REGISTER_HARNESS_METHODS(int32_t) REGISTER_HARNESS_METHODS(int16_t) REGISTER_HARNESS_METHODS(bool) REGISTER_HARNESS_METHODS(openvdb::math::Vec2<double>) REGISTER_HARNESS_METHODS(openvdb::math::Vec2<float>) REGISTER_HARNESS_METHODS(openvdb::math::Vec2<int32_t>) REGISTER_HARNESS_METHODS(openvdb::math::Vec3<double>) REGISTER_HARNESS_METHODS(openvdb::math::Vec3<float>) REGISTER_HARNESS_METHODS(openvdb::math::Vec3<int32_t>) REGISTER_HARNESS_METHODS(openvdb::math::Vec4<double>) REGISTER_HARNESS_METHODS(openvdb::math::Vec4<float>) REGISTER_HARNESS_METHODS(openvdb::math::Vec4<int32_t>) REGISTER_HARNESS_METHODS(openvdb::math::Mat3<double>) REGISTER_HARNESS_METHODS(openvdb::math::Mat3<float>) REGISTER_HARNESS_METHODS(openvdb::math::Mat4<double>) REGISTER_HARNESS_METHODS(openvdb::math::Mat4<float>) REGISTER_HARNESS_METHODS(std::string) }
NVIDIA-Omniverse/ext-openvdb/openvdb_ax/openvdb_ax/test/integration/TestTernary.cc
// Copyright Contributors to the OpenVDB Project // SPDX-License-Identifier: MPL-2.0 #include "TestHarness.h" #include <cppunit/extensions/HelperMacros.h> using namespace openvdb::points; class TestTernary : public unittest_util::AXTestCase { public: CPPUNIT_TEST_SUITE(TestTernary); CPPUNIT_TEST(testTernary); CPPUNIT_TEST(testTernaryVoid); CPPUNIT_TEST(testTernaryErrors); CPPUNIT_TEST_SUITE_END(); void testTernary(); void testTernaryVoid(); void testTernaryErrors(); }; CPPUNIT_TEST_SUITE_REGISTRATION(TestTernary); void TestTernary::testTernary() { mHarness.addAttribute<bool>("ternary_test1", true); mHarness.addAttribute<bool>("ternary_test2", true); mHarness.addAttribute<int>("ternary_test3", 3); mHarness.addAttribute<int>("ternary_test4", 1); mHarness.addAttribute<int>("ternary_test5", 2); mHarness.addAttribute<float>("ternary_test6", 10.f); mHarness.addAttribute<double>("ternary_test7", 0.75); mHarness.addAttribute<openvdb::Vec3i>("ternary_test8", openvdb::Vec3i(1,2,3)); mHarness.addAttribute<openvdb::Vec3d>("ternary_test9", openvdb::Vec3f(4.5,5.5,6.5)); mHarness.addAttribute<int>("ternary_test10", 1); mHarness.addAttribute<int>("ternary_test11", 123); mHarness.addAttribute<int>("ternary_test12", 2); mHarness.addAttribute<int>("ternary_test13", 2); mHarness.addAttribute<int>("ternary_test14", 123); mHarness.addAttribute<float>("ternary_test15", 2.f); mHarness.addAttribute<float>("ternary_test16", 1.5f); mHarness.addAttribute<openvdb::Vec3i>("ternary_test17", openvdb::Vec3i(1,2,3)); mHarness.addAttribute<openvdb::Vec3i>("ternary_test18", openvdb::Vec3i(4,5,6)); mHarness.addAttribute<std::string>("ternary_test19", "foo"); mHarness.addAttribute<std::string>("ternary_test20", "foo"); mHarness.addAttribute<std::string>("ternary_test21", "bar"); mHarness.addAttribute<openvdb::Vec3f>("ternary_test22", openvdb::Vec3f(1.5f,1.5f,1.5f)); mHarness.addAttribute<openvdb::Vec3f>("ternary_test23", openvdb::Vec3f(1.6f,1.6f,1.6f)); mHarness.addAttribute<openvdb::math::Mat3<double>>("ternary_test24", openvdb::math::Mat3<double>(1.8,0.0,0.0, 0.0,1.8,0.0, 0.0,0.0,1.8)); mHarness.addAttribute<openvdb::math::Mat3<double>>("ternary_test25", openvdb::math::Mat3<double>(1.9,0.0,0.0, 0.0,1.9,0.0, 0.0,0.0,1.9)); mHarness.addAttribute<openvdb::math::Mat4<double>>("ternary_test26", openvdb::math::Mat4<double>(1.8,0.0,0.0,0.0, 0.0,1.8,0.0,0.0, 0.0,0.0,1.8,0.0, 0.0,0.0,0.0,1.8)); mHarness.addAttribute<openvdb::math::Mat4<double>>("ternary_test27", openvdb::math::Mat4<double>(1.9,0.0,0.0,0.0, 0.0,1.9,0.0,0.0, 0.0,0.0,1.9,0.0, 0.0,0.0,0.0,1.9)); mHarness.addAttribute<openvdb::Vec3f>("ternary_test28", openvdb::Vec3f(1.76f,1.76f,1.76f)); mHarness.addAttribute<openvdb::Vec3f>("ternary_test29", openvdb::Vec3f(1.76f,1.76f,1.76f)); mHarness.addAttribute<float>("ternary_test30", openvdb::Vec3f(1.3f,1.3f,1.3f).length()); mHarness.addAttribute<float>("ternary_test31", openvdb::Vec3f(1.3f,1.3f,1.3f).length()); mHarness.addAttribute<float>("ternary_test32", openvdb::Vec3f(1.5f,2.5f,3.5f).length()); mHarness.addAttribute<float>("ternary_test33", openvdb::Vec3f(1.5f,2.5f,3.5f).length()); mHarness.executeCode("test/snippets/ternary/ternary"); AXTESTS_STANDARD_ASSERT(); } void TestTernary::testTernaryVoid() { mHarness.testVolumes(false); mHarness.addExpectedGroups({"notdead"}, {true}); mHarness.executeCode("test/snippets/ternary/ternaryVoid"); AXTESTS_STANDARD_ASSERT(); } void TestTernary::testTernaryErrors() { const bool success = mHarness.executeCode("test/snippets/ternary/ternaryErrors"); CPPUNIT_ASSERT(!success); }
NVIDIA-Omniverse/ext-openvdb/openvdb_ax/openvdb_ax/test/integration/TestExternals.cc
// Copyright Contributors to the OpenVDB Project // SPDX-License-Identifier: MPL-2.0 #include "CompareGrids.h" #include "TestHarness.h" #include "../test/util.h" #include <openvdb_ax/compiler/CustomData.h> #include <openvdb_ax/Exceptions.h> #include <cppunit/extensions/HelperMacros.h> using namespace openvdb::points; class TestExternals : public unittest_util::AXTestCase { public: std::string dir() const override { return GET_TEST_DIRECTORY(); } CPPUNIT_TEST_SUITE(TestExternals); CPPUNIT_TEST(assignFrom); CPPUNIT_TEST_SUITE_END(); void assignFrom(); }; CPPUNIT_TEST_SUITE_REGISTRATION(TestExternals); void TestExternals::assignFrom() { const std::string code = R"( _T1_@test1 = _T1_$ext1;)"; auto generate = [&](const auto& types) { for (const auto& type : types) { std::string repl = code; unittest_util::replace(repl, "_T1_", type); this->registerTest(repl, "external_assign_from." + type + ".ax"); } }; generate(std::vector<std::string>{ "bool", "int32", "int64", "float", "double", "vec2i", "vec2f", "vec2d", "vec3i", "vec3f", "vec3d", "vec4i", "vec4f", "vec4d", "mat3f", "mat3d", "mat4f", "mat4d", "string" }); const std::map<std::string, std::function<void()>> expected = { { "bool", [&](){ mHarness.addAttribute<bool>("test1", true); mHarness.mCustomData.reset(new openvdb::ax::CustomData()); mHarness.mCustomData->insertData("ext1", openvdb::TypedMetadata<bool>(true).copy()); }, }, { "int32", [&](){ mHarness.addAttribute<int32_t>("test1", -2); mHarness.mCustomData.reset(new openvdb::ax::CustomData()); mHarness.mCustomData->insertData("ext1", openvdb::TypedMetadata<int32_t>(-2).copy()); }, }, { "int64", [&](){ mHarness.addAttribute<int64_t>("test1", 3); mHarness.mCustomData.reset(new openvdb::ax::CustomData()); mHarness.mCustomData->insertData("ext1", openvdb::TypedMetadata<int64_t>(3).copy()); }, }, { "float", [&](){ mHarness.addAttribute<float>("test1", 4.5f); mHarness.mCustomData.reset(new openvdb::ax::CustomData()); mHarness.mCustomData->insertData("ext1", openvdb::TypedMetadata<float>(4.5f).copy()); }, }, { "double", [&](){ mHarness.addAttribute<double>("test1", -3); mHarness.mCustomData.reset(new openvdb::ax::CustomData()); mHarness.mCustomData->insertData("ext1", openvdb::TypedMetadata<double>(-3).copy()); }, }, { "vec2i", [&](){ const openvdb::math::Vec2<int32_t> value(5,-6); mHarness.addAttribute<openvdb::math::Vec2<int32_t>>("test1", value); mHarness.mCustomData.reset(new openvdb::ax::CustomData()); mHarness.mCustomData->insertData("ext1", openvdb::TypedMetadata<openvdb::math::Vec2<int32_t>>(value).copy()); }, }, { "vec2f", [&](){ const openvdb::math::Vec2<float> value(2.3f,-7.8f); mHarness.addAttribute<openvdb::math::Vec2<float>>("test1", value); mHarness.mCustomData.reset(new openvdb::ax::CustomData()); mHarness.mCustomData->insertData("ext1", openvdb::TypedMetadata<openvdb::math::Vec2<float>>(value).copy()); }, }, { "vec2d", [&](){ const openvdb::math::Vec2<double> value(-1.3,9.8); mHarness.addAttribute<openvdb::math::Vec2<double>>("test1", value); mHarness.mCustomData.reset(new openvdb::ax::CustomData()); mHarness.mCustomData->insertData("ext1", openvdb::TypedMetadata<openvdb::math::Vec2<double>>(value).copy()); }, }, { "vec3i", [&](){ const openvdb::math::Vec3<int32_t> value(-1,3,8); mHarness.addAttribute<openvdb::math::Vec3<int32_t>>("test1", value); mHarness.mCustomData.reset(new openvdb::ax::CustomData()); mHarness.mCustomData->insertData("ext1", openvdb::TypedMetadata<openvdb::math::Vec3<int32_t>>(value).copy()); }, }, { "vec3f", [&](){ const openvdb::math::Vec3<float> value(4.3f,-9.0f, 1.1f); mHarness.addAttribute<openvdb::math::Vec3<float>>("test1", value); mHarness.mCustomData.reset(new openvdb::ax::CustomData()); mHarness.mCustomData->insertData("ext1", openvdb::TypedMetadata<openvdb::math::Vec3<float>>(value).copy()); }, }, { "vec3d", [&](){ const openvdb::math::Vec3<double> value(8.2, 5.9, 1.6); mHarness.addAttribute<openvdb::math::Vec3<double>>("test1", value); mHarness.mCustomData.reset(new openvdb::ax::CustomData()); mHarness.mCustomData->insertData("ext1", openvdb::TypedMetadata<openvdb::math::Vec3<double>>(value).copy()); }, }, { "vec4i", [&](){ const openvdb::math::Vec4<int32_t> value(10,1,3,-8); mHarness.addAttribute<openvdb::math::Vec4<int32_t>>("test1", value); mHarness.mCustomData.reset(new openvdb::ax::CustomData()); mHarness.mCustomData->insertData("ext1", openvdb::TypedMetadata<openvdb::math::Vec4<int32_t>>(value).copy()); }, }, { "vec4f", [&](){ const openvdb::math::Vec4<float> value(4.4f, 3.3f, -0.1f, 0.3f); mHarness.addAttribute<openvdb::math::Vec4<float>>("test1", value); mHarness.mCustomData.reset(new openvdb::ax::CustomData()); mHarness.mCustomData->insertData("ext1", openvdb::TypedMetadata<openvdb::math::Vec4<float>>(value).copy()); }, }, { "vec4d", [&](){ const openvdb::math::Vec4<double> value(4.5, 5.3, 1.1, 3.3); mHarness.addAttribute<openvdb::math::Vec4<double>>("test1", value); mHarness.mCustomData.reset(new openvdb::ax::CustomData()); mHarness.mCustomData->insertData("ext1", openvdb::TypedMetadata<openvdb::math::Vec4<double>>(value).copy()); }, }, { "mat3f", [&](){ const openvdb::math::Mat3<float> value(1.1f, 2.3f, 4.3f, 5.4f, 6.7f, 7.8f, 9.1f, 4.5f, 8.2f); mHarness.addAttribute<openvdb::math::Mat3<float>>("test1", value); mHarness.mCustomData.reset(new openvdb::ax::CustomData()); mHarness.mCustomData->insertData("ext1", openvdb::TypedMetadata<openvdb::math::Mat3<float>>(value).copy()); }, }, { "mat3d", [&](){ const openvdb::math::Mat3<double> value(6.7f, 2.9f,-1.1f, 3.2f, 2.2f, 0.8f, -5.1f, 9.3f, 2.5f); mHarness.addAttribute<openvdb::math::Mat3<double>>("test1", value); mHarness.mCustomData.reset(new openvdb::ax::CustomData()); mHarness.mCustomData->insertData("ext1", openvdb::TypedMetadata<openvdb::math::Mat3<double>>(value).copy()); }, }, { "mat4f", [&](){ const openvdb::math::Mat4<float> value(1.1f,-2.3f,-0.3f, 7.8f, -9.1f,-4.5f, 1.1f, 8.2f, -4.3f, 5.4f, 6.7f,-0.2f, 8.8f, 5.5f, -6.6f, 7.7f); mHarness.addAttribute<openvdb::math::Mat4<float>>("test1", value); mHarness.mCustomData.reset(new openvdb::ax::CustomData()); mHarness.mCustomData->insertData("ext1", openvdb::TypedMetadata<openvdb::math::Mat4<float>>(value).copy()); }, }, { "mat4d", [&](){ const openvdb::math::Mat4<double> value(-2.3,0.0,-0.3,9.8, 0.0, 6.5, 3.7, 1.2, -7.8,-0.3,-5.5,3.3, -0.2, 9.1, 0.1,-9.1); mHarness.addAttribute<openvdb::math::Mat4<double>>("test1", value); mHarness.mCustomData.reset(new openvdb::ax::CustomData()); mHarness.mCustomData->insertData("ext1", openvdb::TypedMetadata<openvdb::math::Mat4<double>>(value).copy()); }, }, { "string", [&](){ mHarness.addAttribute<std::string>("test1", "foo"); mHarness.mCustomData.reset(new openvdb::ax::CustomData()); mHarness.mCustomData->insertData("ext1", openvdb::ax::AXStringMetadata("foo").copy()); }, } }; for (const auto& expc : expected) { mHarness.reset(); expc.second.operator()(); this->execute("external_assign_from." + expc.first + ".ax"); } }
NVIDIA-Omniverse/ext-openvdb/openvdb_ax/openvdb_ax/test/integration/TestHarness.h
// Copyright Contributors to the OpenVDB Project // SPDX-License-Identifier: MPL-2.0 /// @file test/integration/TestHarness.h /// /// @authors Francisco Gochez, Nick Avramoussis /// /// @brief Test harness and base methods #ifndef OPENVDB_POINTS_UNITTEST_TEST_HARNESS_INCLUDED #define OPENVDB_POINTS_UNITTEST_TEST_HARNESS_INCLUDED #include "CompareGrids.h" #include <openvdb_ax/ast/Tokens.h> #include <openvdb_ax/compiler/Compiler.h> #include <openvdb_ax/compiler/CustomData.h> #include <openvdb/points/PointAttribute.h> #include <openvdb/points/PointScatter.h> #include <cppunit/TestCase.h> #include <unordered_map> extern int sGenerateAX; namespace unittest_util { std::string loadText(const std::string& codeFileName); bool wrapExecution(openvdb::points::PointDataGrid& grid, const std::string& codeFileName, const std::string * const group, openvdb::ax::Logger& logger, const openvdb::ax::CustomData::Ptr& data, const openvdb::ax::CompilerOptions& opts, const bool createMissing); bool wrapExecution(openvdb::GridPtrVec& grids, const std::string& codeFileName, openvdb::ax::Logger& logger, const openvdb::ax::CustomData::Ptr& data, const openvdb::ax::CompilerOptions& opts, const bool createMissing); /// @brief Structure for wrapping up most of the existing integration /// tests with a simple interface struct AXTestHarness { AXTestHarness() : mInputPointGrids() , mOutputPointGrids() , mInputVolumeGrids() , mOutputVolumeGrids() , mUseVolumes(true) , mUsePoints(true) , mVolumeBounds({0,0,0},{0,0,0}) , mOpts(openvdb::ax::CompilerOptions()) , mCustomData(openvdb::ax::CustomData::create()) , mLogger([](const std::string&) {}) { reset(); } void addInputGroups(const std::vector<std::string>& names, const std::vector<bool>& defaults); void addExpectedGroups(const std::vector<std::string>& names, const std::vector<bool>& defaults); /// @brief adds attributes to input data set template <typename T> void addInputAttributes(const std::vector<std::string>& names, const std::vector<T>& values) { if (mUsePoints) addInputPtAttributes<T>(names, values); if (mUseVolumes) addInputVolumes(names, values); } template <typename T> void addInputAttribute(const std::string& name, const T& inputVal) { addInputAttributes<T>({name}, {inputVal}); } /// @brief adds attributes to expected output data sets template <typename T> void addExpectedAttributes(const std::vector<std::string>& names, const std::vector<T>& values) { if (mUsePoints) addExpectedPtAttributes<T>(names, values); if (mUseVolumes) addExpectedVolumes<T>(names, values); } /// @brief adds attributes to both input and expected data template <typename T> void addAttributes(const std::vector<std::string>& names, const std::vector<T>& inputValues, const std::vector<T>& expectedValues) { if (inputValues.size() != expectedValues.size() || inputValues.size() != names.size()) { throw std::runtime_error("bad unittest setup - input/expected value counts don't match"); } addInputAttributes(names, inputValues); addExpectedAttributes(names, expectedValues); } /// @brief adds attributes to both input and expected data, with input data set to 0 values template <typename T> void addAttributes(const std::vector<std::string>& names, const std::vector<T>& expectedValues) { std::vector<T> zeroVals(expectedValues.size(), openvdb::zeroVal<T>()); addAttributes(names, zeroVals, expectedValues); } template <typename T> void addAttribute(const std::string& name, const T& inVal, const T& expVal) { addAttributes<T>({name}, {inVal}, {expVal}); } template <typename T> void addAttribute(const std::string& name, const T& expVal) { addAttribute<T>(name, openvdb::zeroVal<T>(), expVal); } template <typename T> void addExpectedAttribute(const std::string& name, const T& expVal) { addExpectedAttributes<T>({name}, {expVal}); } /// @brief excecutes a snippet of code contained in a file to the input data sets bool executeCode(const std::string& codeFile, const std::string* const group = nullptr, const bool createMissing = false); /// @brief rebuilds the input and output data sets to their default harness states. This /// sets the bounds of volumes to a single voxel, with a single and four point grid void reset(); /// @brief reset the input data to a set amount of points per voxel within a given bounds /// @note The bounds is also used to fill the volume data of numerical vdb volumes when /// calls to addAttribute functions are made, where as points have their positions /// generated here void reset(const openvdb::Index64, const openvdb::CoordBBox&); /// @brief reset all grids without changing the harness data. This has the effect of zeroing /// out all volume voxel data and point data attributes (except for position) without /// changing the number of points or voxels void resetInputsToZero(); /// @brief compares the input and expected point grids and outputs a report of differences to /// the provided stream bool checkAgainstExpected(std::ostream& sstream); /// @brief Toggle whether to execute tests for points or volumes void testVolumes(const bool); void testPoints(const bool); template <typename T> void addInputPtAttributes(const std::vector<std::string>& names, const std::vector<T>& values); template <typename T> void addInputVolumes(const std::vector<std::string>& names, const std::vector<T>& values); template <typename T> void addExpectedPtAttributes(const std::vector<std::string>& names, const std::vector<T>& values); template <typename T> void addExpectedVolumes(const std::vector<std::string>& names, const std::vector<T>& values); std::vector<openvdb::points::PointDataGrid::Ptr> mInputPointGrids; std::vector<openvdb::points::PointDataGrid::Ptr> mOutputPointGrids; openvdb::GridPtrVec mInputVolumeGrids; openvdb::GridPtrVec mOutputVolumeGrids; bool mUseVolumes; bool mUsePoints; openvdb::CoordBBox mVolumeBounds; openvdb::ax::CompilerOptions mOpts; openvdb::ax::CustomData::Ptr mCustomData; openvdb::ax::Logger mLogger; }; class AXTestCase : public CppUnit::TestCase { public: void tearDown() override { std::string out; for (auto& test : mTestFiles) { if (!test.second) out += test.first + "\n"; } CPPUNIT_ASSERT_MESSAGE("unused tests left in test case:\n" + out, out.empty()); } // @todo make pure virtual std::string dir() const { return ""; } /// @brief Register an AX code snippet with this test. If the tests /// have been launched with -g, the code is also serialized /// into the test directory void registerTest(const std::string& code, const std::string& filename, const std::ios_base::openmode flags = std::ios_base::out) { if (flags & std::ios_base::out) { CPPUNIT_ASSERT_MESSAGE( "duplicate test file found during test setup:\n" + filename, mTestFiles.find(filename) == mTestFiles.end()); mTestFiles[filename] = false; } if (flags & std::ios_base::app) { CPPUNIT_ASSERT_MESSAGE( "test not found during ofstream append:\n" + filename, mTestFiles.find(filename) != mTestFiles.end()); } if (sGenerateAX) { std::ofstream outfile; outfile.open(this->dir() + "/" + filename, flags); outfile << code << std::endl; outfile.close(); } } template <typename ...Args> void execute(const std::string& filename, Args&&... args) { CPPUNIT_ASSERT_MESSAGE( "test not found during execution:\n" + this->dir() + "/" + filename, mTestFiles.find(filename) != mTestFiles.end()); mTestFiles[filename] = true; // has been used // execute const bool success = mHarness.executeCode(this->dir() + "/" + filename, args...); CPPUNIT_ASSERT_MESSAGE("error thrown during test: " + filename, success); //@todo: print error message here // check std::stringstream out; const bool correct = mHarness.checkAgainstExpected(out); CPPUNIT_ASSERT_MESSAGE(out.str(), correct); } protected: AXTestHarness mHarness; std::unordered_map<std::string, bool> mTestFiles; }; } // namespace unittest_util #define GET_TEST_DIRECTORY() \ std::string(__FILE__).substr(0, std::string(__FILE__).find_last_of('.')); \ #define AXTESTS_STANDARD_ASSERT_HARNESS(harness) \ { std::stringstream out; \ const bool correct = harness.checkAgainstExpected(out); \ CPPUNIT_ASSERT_MESSAGE(out.str(), correct); } #define AXTESTS_STANDARD_ASSERT() \ AXTESTS_STANDARD_ASSERT_HARNESS(mHarness); #endif // OPENVDB_POINTS_UNITTEST_TEST_HARNESS_INCLUDED
NVIDIA-Omniverse/ext-openvdb/openvdb_ax/openvdb_ax/test/integration/TestEmpty.cc
// Copyright Contributors to the OpenVDB Project // SPDX-License-Identifier: MPL-2.0 #include "TestHarness.h" #include <openvdb_ax/Exceptions.h> #include <cppunit/extensions/HelperMacros.h> using namespace openvdb::points; class TestEmpty : public unittest_util::AXTestCase { public: CPPUNIT_TEST_SUITE(TestEmpty); CPPUNIT_TEST(testEmpty); CPPUNIT_TEST_SUITE_END(); void testEmpty(); }; CPPUNIT_TEST_SUITE_REGISTRATION(TestEmpty); void TestEmpty::testEmpty() { unittest_util::AXTestHarness harness; harness.executeCode("test/snippets/empty/empty"); AXTESTS_STANDARD_ASSERT_HARNESS(harness); }
NVIDIA-Omniverse/ext-openvdb/openvdb_ax/openvdb_ax/test/integration/TestString.cc
// Copyright Contributors to the OpenVDB Project // SPDX-License-Identifier: MPL-2.0 #include "TestHarness.h" #include "../test/util.h" #include <cppunit/extensions/HelperMacros.h> using namespace openvdb::points; class TestString : public unittest_util::AXTestCase { public: void setUp() override { unittest_util::AXTestCase::setUp(); } CPPUNIT_TEST_SUITE(TestString); CPPUNIT_TEST(testAssignCompound); CPPUNIT_TEST(testAssignFromAttributes); CPPUNIT_TEST(testAssignFromLocals); CPPUNIT_TEST(testAssignNewOverwrite); CPPUNIT_TEST(testBinaryConcat); CPPUNIT_TEST(testDeclare); CPPUNIT_TEST_SUITE_END(); void testAssignCompound(); void testAssignFromAttributes(); void testAssignFromLocals(); void testAssignNewOverwrite(); void testBinaryConcat(); void testDeclare(); }; CPPUNIT_TEST_SUITE_REGISTRATION(TestString); void TestString::testAssignCompound() { mHarness.addAttributes<std::string>(unittest_util::nameSequence("test", 3), {"foo", "foobar", "aaaaaaaaaa"}); mHarness.executeCode("test/snippets/string/assignCompound"); AXTESTS_STANDARD_ASSERT(); } void TestString::testAssignFromAttributes() { mHarness.addInputPtAttributes<std::string>({"string_test1"}, {"test"}); mHarness.addExpectedAttributes<std::string>(unittest_util::nameSequence("string_test", 6), {"new value", "test", "new value", "new value", "", ""}); // Volume data needs to exist mHarness.addInputVolumes<std::string>(unittest_util::nameSequence("string_test", 6), {"test", "test", "new value", "new value", "", ""}); mHarness.executeCode("test/snippets/string/assignFromAttributes", nullptr, true); AXTESTS_STANDARD_ASSERT(); } void TestString::testAssignFromLocals() { mHarness.addAttributes<std::string>(unittest_util::nameSequence("string_test", 4), {"test", "test", "new string size", ""}); mHarness.executeCode("test/snippets/string/assignFromLocals"); AXTESTS_STANDARD_ASSERT(); } void TestString::testAssignNewOverwrite() { mHarness.addExpectedAttributes<std::string>({"string_test1", "string_test2"}, {"next_value", "new_value"}); // Volume data needs to exist mHarness.addInputVolumes<std::string>({"string_test1", "string_test2"}, {"next_value", "new_value"}); mHarness.executeCode("test/snippets/string/assignNewOverwrite", nullptr, true); AXTESTS_STANDARD_ASSERT(); } void TestString::testBinaryConcat() { mHarness.addExpectedAttributes<std::string>(unittest_util::nameSequence("string_test", 6), {"test new value", "test new value", "test new value", "test new value", "", "test new value"}); // Volume data needs to exist mHarness.addInputVolumes<std::string>(unittest_util::nameSequence("string_test", 6), {"test new value", "test new value", "test new value", "test new value", "", "test new value"}); mHarness.executeCode("test/snippets/string/binaryConcat", nullptr, true); AXTESTS_STANDARD_ASSERT(); } void TestString::testDeclare() { mHarness.addAttribute<std::string>("string_test", "test"); mHarness.executeCode("test/snippets/string/declare"); AXTESTS_STANDARD_ASSERT(); }
NVIDIA-Omniverse/ext-openvdb/openvdb_ax/openvdb_ax/test/integration/TestArrayUnpack.cc
// Copyright Contributors to the OpenVDB Project // SPDX-License-Identifier: MPL-2.0 #include "CompareGrids.h" #include "TestHarness.h" #include "../test/util.h" #include <openvdb_ax/compiler/CustomData.h> #include <openvdb_ax/Exceptions.h> #include <cppunit/extensions/HelperMacros.h> using namespace openvdb::points; class TestArrayUnpack : public unittest_util::AXTestCase { public: std::string dir() const override { return GET_TEST_DIRECTORY(); } CPPUNIT_TEST_SUITE(TestArrayUnpack); CPPUNIT_TEST(componentVectorAssignment); CPPUNIT_TEST(componentMatrixAssignment); CPPUNIT_TEST_SUITE_END(); void componentVectorAssignment(); void componentMatrixAssignment(); }; CPPUNIT_TEST_SUITE_REGISTRATION(TestArrayUnpack); void TestArrayUnpack::componentVectorAssignment() { const std::string code = R"( vec2@test1[0] = vec2@test2[1]; vec2@test2[1] = vec2@test1[0]; vec3@test3[1] = vec3@test3[2]; vec3@test4[2] = vec3@test4[0]; vec3@test3[0] = vec3@test4[1]; vec4@test5[0] = vec4@test6[2]; vec4@test5[3] = vec4@test5[1]; vec4@test5[2] = vec4@test6[3]; vec4@test6[1] = vec4@test6[0]; )"; auto generate = [&](const auto& suffixes) { for (const auto& s : suffixes) { std::string repl = code; const std::string type = (s == 'i' ? "int" : (s == 'f' ? "float" : (s == 'd' ? "double" : ""))); CPPUNIT_ASSERT(!type.empty()); unittest_util::replace(repl, "vec2", std::string("vec2").append(1, s)); unittest_util::replace(repl, "vec3", std::string("vec3").append(1, s)); unittest_util::replace(repl, "vec4", std::string("vec4").append(1, s)); this->registerTest(repl, "array_unpack.vec." + type + ".ax"); unittest_util::replace(repl, "[0]", ".x"); unittest_util::replace(repl, "[1]", ".y"); unittest_util::replace(repl, "[2]", ".z"); this->registerTest(repl, "array_unpack.vec." + type + ".xyz" + ".ax"); unittest_util::replace(repl, ".x", ".r"); unittest_util::replace(repl, ".y", ".g"); unittest_util::replace(repl, ".z", ".b"); this->registerTest(repl, "array_unpack.vec." + type + ".rgb" + ".ax"); } }; generate(std::vector<char>{'i', 'f', 'd'}); const std::map<std::string, std::function<void()>> expected = { { "int", [&]() { mHarness.addAttribute<openvdb::math::Vec2<int32_t>>("test1", openvdb::math::Vec2<int32_t>( 1, 2), openvdb::math::Vec2<int32_t>( 4,2)); mHarness.addAttribute<openvdb::math::Vec2<int32_t>>("test2", openvdb::math::Vec2<int32_t>( 3, 4), openvdb::math::Vec2<int32_t>( 3, 4)); mHarness.addAttribute<openvdb::math::Vec3<int32_t>>("test3", openvdb::math::Vec3<int32_t>( 5 ,6, 7), openvdb::math::Vec3<int32_t>( 8 ,7, 7)); mHarness.addAttribute<openvdb::math::Vec3<int32_t>>("test4", openvdb::math::Vec3<int32_t>( 9, 8,-1), openvdb::math::Vec3<int32_t>( 9, 8, 9)); mHarness.addAttribute<openvdb::math::Vec4<int32_t>>("test5", openvdb::math::Vec4<int32_t>(-1,-2,-3,-4), openvdb::math::Vec4<int32_t>(-7,-2,-8,-2)); mHarness.addAttribute<openvdb::math::Vec4<int32_t>>("test6", openvdb::math::Vec4<int32_t>(-5,-6,-7,-8), openvdb::math::Vec4<int32_t>(-5,-5,-7,-8)); } }, { "float", [&]() { mHarness.addAttribute<openvdb::math::Vec2<float>>("test1", openvdb::math::Vec2<float>( 1.2f, 2.7f), openvdb::math::Vec2<float>(4.7f, 2.7f)); mHarness.addAttribute<openvdb::math::Vec2<float>>("test2", openvdb::math::Vec2<float>( 3.2f, 4.7f), openvdb::math::Vec2<float>(3.2f ,4.7f)); mHarness.addAttribute<openvdb::math::Vec3<float>>("test3", openvdb::math::Vec3<float>( 5.2f ,6.7f, 7.4f), openvdb::math::Vec3<float>( 8.7f ,7.4f, 7.4f)); mHarness.addAttribute<openvdb::math::Vec3<float>>("test4", openvdb::math::Vec3<float>( 9.2f, 8.7f,-1.4f), openvdb::math::Vec3<float>( 9.2f, 8.7f, 9.2f)); mHarness.addAttribute<openvdb::math::Vec4<float>>("test5", openvdb::math::Vec4<float>(-1.2f,-2.7f,-3.4f,-4.1f), openvdb::math::Vec4<float>(-7.4f,-2.7f,-8.1f,-2.7f)); mHarness.addAttribute<openvdb::math::Vec4<float>>("test6", openvdb::math::Vec4<float>(-5.2f,-6.7f,-7.4f,-8.1f), openvdb::math::Vec4<float>(-5.2f,-5.2f,-7.4f,-8.1f)); } }, { "double", [&]() { mHarness.addAttribute<openvdb::math::Vec2<double>>("test1", openvdb::math::Vec2<double>( 1.2, 2.7), openvdb::math::Vec2<double>(4.7, 2.7)); mHarness.addAttribute<openvdb::math::Vec2<double>>("test2", openvdb::math::Vec2<double>( 3.2, 4.7), openvdb::math::Vec2<double>(3.2, 4.7)); mHarness.addAttribute<openvdb::math::Vec3<double>>("test3", openvdb::math::Vec3<double>( 5.2 ,6.7, 7.4), openvdb::math::Vec3<double>( 8.7 ,7.4, 7.4)); mHarness.addAttribute<openvdb::math::Vec3<double>>("test4", openvdb::math::Vec3<double>( 9.2, 8.7,-1.4), openvdb::math::Vec3<double>( 9.2, 8.7, 9.2)); mHarness.addAttribute<openvdb::math::Vec4<double>>("test5", openvdb::math::Vec4<double>(-1.2,-2.7,-3.4,-4.1), openvdb::math::Vec4<double>(-7.4,-2.7,-8.1,-2.7)); mHarness.addAttribute<openvdb::math::Vec4<double>>("test6", openvdb::math::Vec4<double>(-5.2,-6.7,-7.4,-8.1), openvdb::math::Vec4<double>(-5.2,-5.2,-7.4,-8.1)); } }, }; const std::array<std::string, 3> suffixes {{ "", ".xyz", ".rgb" }}; for (const auto& expc : expected) { for (const auto& suffix : suffixes) { mHarness.reset(); expc.second.operator()(); this->execute("array_unpack.vec." + expc.first + suffix + ".ax"); } } } void TestArrayUnpack::componentMatrixAssignment() { const std::string code = R"( mat3@test1[0] = mat3@test2[4]; mat3@test2[1] = mat3@test1[0]; mat3@test1[2] = mat3@test2[5]; mat3@test2[3] = mat3@test1[6]; mat3@test1[4] = mat3@test2[3]; mat3@test2[5] = mat3@test1[1]; mat3@test1[6] = mat3@test2[7]; mat3@test2[7] = mat3@test1[8]; mat3@test1[8] = mat3@test2[2]; mat3@test3[0,0] = mat3@test4[1,1]; mat3@test4[0,1] = mat3@test3[0,0]; mat3@test3[0,2] = mat3@test4[1,2]; mat3@test4[1,0] = mat3@test3[2,0]; mat3@test3[1,1] = mat3@test4[1,0]; mat3@test4[1,2] = mat3@test3[0,1]; mat3@test3[2,0] = mat3@test4[2,1]; mat3@test4[2,1] = mat3@test3[2,2]; mat3@test3[2,2] = mat3@test4[0,2]; mat4@test5[0] = mat4@test6[15]; mat4@test6[1] = mat4@test5[0]; mat4@test5[2] = mat4@test6[11]; mat4@test6[3] = mat4@test5[6]; mat4@test5[4] = mat4@test6[13]; mat4@test6[5] = mat4@test5[1]; mat4@test5[6] = mat4@test6[10]; mat4@test6[7] = mat4@test5[8]; mat4@test5[8] = mat4@test6[2]; mat4@test6[9] = mat4@test5[7]; mat4@test5[10] = mat4@test6[14]; mat4@test6[11] = mat4@test5[3]; mat4@test5[12] = mat4@test6[4]; mat4@test6[13] = mat4@test5[12]; mat4@test5[14] = mat4@test6[5]; mat4@test6[15] = mat4@test5[9]; mat4@test7[0,0] = mat4@test8[3,3]; mat4@test8[0,1] = mat4@test7[0,0]; mat4@test7[0,2] = mat4@test8[2,3]; mat4@test8[0,3] = mat4@test7[1,2]; mat4@test7[1,0] = mat4@test8[3,1]; mat4@test8[1,1] = mat4@test7[0,1]; mat4@test7[1,2] = mat4@test8[2,2]; mat4@test8[1,3] = mat4@test7[2,0]; mat4@test7[2,0] = mat4@test8[0,2]; mat4@test8[2,1] = mat4@test7[1,3]; mat4@test7[2,2] = mat4@test8[3,2]; mat4@test8[2,3] = mat4@test7[0,3]; mat4@test7[3,0] = mat4@test8[1,0]; mat4@test8[3,1] = mat4@test7[3,0]; mat4@test7[3,2] = mat4@test8[1,1]; mat4@test8[3,3] = mat4@test7[2,1]; )"; auto generate = [&](const auto& suffixes) { for (const auto& s : suffixes) { std::string repl = code; unittest_util::replace(repl, "mat3", std::string("mat3").append(1,s)); unittest_util::replace(repl, "mat4", std::string("mat4").append(1,s)); const std::string type = s == 'f' ? "float" : s == 'd' ? "double" : ""; CPPUNIT_ASSERT(!type.empty()); this->registerTest(repl, "array_unpack.mat." + type + ".ax"); } }; generate(std::vector<char>{'f', 'd'}); const std::map<std::string, std::function<void()>> expected = { { "float", [&]() { mHarness.addAttribute<openvdb::math::Mat3<float>>("test1", openvdb::math::Mat3<float>( 1.1f, 2.3f, 4.3f, 5.4f, 6.7f, 7.8f, 9.1f, 4.5f, 8.2f), // in openvdb::math::Mat3<float>(-6.7f, 2.3f, 0.8f, 5.4f, 9.1f, 7.8f, -0.5f, 4.5f,-1.3f)); // expected mHarness.addAttribute<openvdb::math::Mat3<float>>("test2", openvdb::math::Mat3<float>(9.1f, 7.3f, -1.3f, 4.4f, -6.7f, 0.8f, 9.1f,-0.5f, 8.2f), openvdb::math::Mat3<float>(9.1f,-6.7f, -1.3f, 9.1f, -6.7f, 2.3f, 9.1f, 8.2f, 8.2f)); mHarness.addAttribute<openvdb::math::Mat3<float>>("test3", openvdb::math::Mat3<float>( 1.1f, 2.3f, 4.3f, 5.4f, 6.7f, 7.8f, 9.1f, 4.5f, 8.2f), // in openvdb::math::Mat3<float>(-6.7f, 2.3f, 0.8f, 5.4f, 9.1f, 7.8f, -0.5f, 4.5f,-1.3f)); // expected mHarness.addAttribute<openvdb::math::Mat3<float>>("test4", openvdb::math::Mat3<float>(9.1f, 7.3f, -1.3f, 4.4f, -6.7f, 0.8f, 9.1f,-0.5f, 8.2f), openvdb::math::Mat3<float>(9.1f,-6.7f, -1.3f, 9.1f, -6.7f, 2.3f, 9.1f, 8.2f, 8.2f)); mHarness.addAttribute<openvdb::math::Mat4<float>>("test5", openvdb::math::Mat4<float>( 1.1f, 2.3f, 4.3f, 5.4f, 6.7f, 7.8f, 9.1f, 4.5f, 8.2f, 3.3f, 2.9f, 5.9f, 0.1f, 0.3f, 5.1f, 1.9f), // in openvdb::math::Mat4<float>(-1.7f, 2.3f, 2.5f, 5.4f, 0.5f, 7.8f,-0.3f, 4.5f, -9.3f, 3.3f, 8.1f, 5.9f, -1.7f, 0.3f, 2.3f, 1.9f)); // expected mHarness.addAttribute<openvdb::math::Mat4<float>>("test6", openvdb::math::Mat4<float>(0.1f, 2.3f,-9.3f, 4.5f, -1.7f, 7.8f, 2.1f, 3.3f, 3.3f,-3.3f,-0.3f, 2.5f, 5.1f, 0.5f, 8.1f,-1.7f), openvdb::math::Mat4<float>(0.1f,-1.7f,-9.3f, 9.1f, -1.7f, 2.3f, 2.1f, 8.2f, 3.3f, 4.5f,-0.3f, 5.4f, 5.1f,-1.7f, 8.1f, 3.3f)); mHarness.addAttribute<openvdb::math::Mat4<float>>("test7", openvdb::math::Mat4<float>( 1.1f, 2.3f, 4.3f, 5.4f, 6.7f, 7.8f, 9.1f, 4.5f, 8.2f, 3.3f, 2.9f, 5.9f, 0.1f, 0.3f, 5.1f, 1.9f), // in openvdb::math::Mat4<float>(-1.7f, 2.3f, 2.5f, 5.4f, 0.5f, 7.8f,-0.3f, 4.5f, -9.3f, 3.3f, 8.1f, 5.9f, -1.7f, 0.3f, 2.3f, 1.9f)); // expected mHarness.addAttribute<openvdb::math::Mat4<float>>("test8", openvdb::math::Mat4<float>(0.1f, 2.3f,-9.3f, 4.5f, -1.7f, 7.8f, 2.1f, 3.3f, 3.3f,-3.3f,-0.3f, 2.5f, 5.1f, 0.5f, 8.1f,-1.7f), openvdb::math::Mat4<float>(0.1f,-1.7f,-9.3f, 9.1f, -1.7f, 2.3f, 2.1f, 8.2f, 3.3f, 4.5f,-0.3f, 5.4f, 5.1f,-1.7f, 8.1f, 3.3f)); } }, { "double", [&]() { mHarness.addAttribute<openvdb::math::Mat3<double>>("test1", openvdb::math::Mat3<double>( 1.1, 2.3, 4.3, 5.4, 6.7, 7.8, 9.1, 4.5, 8.2), // in openvdb::math::Mat3<double>(-6.7, 2.3, 0.8, 5.4, 9.1, 7.8, -0.5, 4.5,-1.3)); // expected mHarness.addAttribute<openvdb::math::Mat3<double>>("test2", openvdb::math::Mat3<double>(9.1, 7.3, -1.3, 4.4, -6.7, 0.8, 9.1,-0.5, 8.2), openvdb::math::Mat3<double>(9.1,-6.7, -1.3, 9.1, -6.7, 2.3, 9.1, 8.2, 8.2)); mHarness.addAttribute<openvdb::math::Mat3<double>>("test3", openvdb::math::Mat3<double>( 1.1, 2.3, 4.3, 5.4, 6.7, 7.8, 9.1, 4.5, 8.2), // in openvdb::math::Mat3<double>(-6.7, 2.3, 0.8, 5.4, 9.1, 7.8, -0.5, 4.5,-1.3)); // expected mHarness.addAttribute<openvdb::math::Mat3<double>>("test4", openvdb::math::Mat3<double>(9.1, 7.3, -1.3, 4.4, -6.7, 0.8, 9.1,-0.5, 8.2), openvdb::math::Mat3<double>(9.1,-6.7, -1.3, 9.1, -6.7, 2.3, 9.1, 8.2, 8.2)); mHarness.addAttribute<openvdb::math::Mat4<double>>("test5", openvdb::math::Mat4<double>( 1.1, 2.3, 4.3, 5.4, 6.7, 7.8, 9.1, 4.5, 8.2, 3.3, 2.9, 5.9, 0.1, 0.3, 5.1, 1.9), // in openvdb::math::Mat4<double>(-1.7, 2.3, 2.5, 5.4, 0.5, 7.8,-0.3, 4.5, -9.3, 3.3, 8.1, 5.9, -1.7, 0.3, 2.3, 1.9)); // expected mHarness.addAttribute<openvdb::math::Mat4<double>>("test6", openvdb::math::Mat4<double>(0.1, 2.3,-9.3, 4.5, -1.7, 7.8, 2.1, 3.3, 3.3,-3.3,-0.3, 2.5, 5.1, 0.5, 8.1,-1.7), openvdb::math::Mat4<double>(0.1,-1.7,-9.3, 9.1, -1.7, 2.3, 2.1, 8.2, 3.3, 4.5,-0.3, 5.4, 5.1,-1.7, 8.1, 3.3)); mHarness.addAttribute<openvdb::math::Mat4<double>>("test7", openvdb::math::Mat4<double>( 1.1, 2.3, 4.3, 5.4, 6.7, 7.8, 9.1, 4.5, 8.2, 3.3, 2.9, 5.9, 0.1, 0.3, 5.1, 1.9), // in openvdb::math::Mat4<double>(-1.7, 2.3, 2.5, 5.4, 0.5, 7.8,-0.3, 4.5, -9.3, 3.3, 8.1, 5.9, -1.7, 0.3, 2.3, 1.9)); // expected mHarness.addAttribute<openvdb::math::Mat4<double>>("test8", openvdb::math::Mat4<double>(0.1, 2.3,-9.3, 4.5, -1.7, 7.8, 2.1, 3.3, 3.3,-3.3,-0.3, 2.5, 5.1, 0.5, 8.1,-1.7), openvdb::math::Mat4<double>(0.1,-1.7,-9.3, 9.1, -1.7, 2.3, 2.1, 8.2, 3.3, 4.5,-0.3, 5.4, 5.1,-1.7, 8.1, 3.3)); } } }; for (const auto& expc : expected) { mHarness.reset(); expc.second.operator()(); this->execute("array_unpack.mat." + expc.first + ".ax"); } }
NVIDIA-Omniverse/ext-openvdb/openvdb_ax/openvdb_ax/test/integration/TestUnary.cc
// Copyright Contributors to the OpenVDB Project // SPDX-License-Identifier: MPL-2.0 #include "TestHarness.h" #include "util.h" #include <cppunit/extensions/HelperMacros.h> class TestUnary : public unittest_util::AXTestCase { public: CPPUNIT_TEST_SUITE(TestUnary); CPPUNIT_TEST(testBitwiseNot); CPPUNIT_TEST(testNegate); CPPUNIT_TEST(testNot); CPPUNIT_TEST(testUnaryVector); CPPUNIT_TEST_SUITE_END(); void testBitwiseNot(); void testNegate(); void testNot(); void testUnaryVector(); }; CPPUNIT_TEST_SUITE_REGISTRATION(TestUnary); void TestUnary::testBitwiseNot() { mHarness.addAttributes<int>({"int_test", "int_test2"}, {-9, -8}); mHarness.executeCode("test/snippets/unary/unaryBitwiseNot"); AXTESTS_STANDARD_ASSERT(); } void TestUnary::testNegate() { mHarness.addAttribute<int>("int_test", -3); mHarness.addAttribute<float>("float_test", -5.5f); mHarness.executeCode("test/snippets/unary/unaryNegate"); AXTESTS_STANDARD_ASSERT(); } void TestUnary::testNot() { mHarness.addAttributes<bool>({"bool_test", "bool_test2"}, {false, true}); mHarness.executeCode("test/snippets/unary/unaryNot"); AXTESTS_STANDARD_ASSERT(); } void TestUnary::testUnaryVector() { // vec3 mHarness.addAttributes<openvdb::math::Vec3<int32_t>> (unittest_util::nameSequence("v3i", 4), { openvdb::math::Vec3<int32_t>(0, 1,-1), openvdb::math::Vec3<int32_t>(0,-1, 1), openvdb::math::Vec3<int32_t>(-1,-2,0), openvdb::math::Vec3<int32_t>(1, 0, 0) }); mHarness.addAttributes<openvdb::math::Vec3<float>> (unittest_util::nameSequence("v3f", 2), { openvdb::math::Vec3<float>(0.0f, 1.1f,-1.1f), openvdb::math::Vec3<float>(0.0f,-1.1f, 1.1f), }); mHarness.addAttributes<openvdb::math::Vec3<double>> (unittest_util::nameSequence("v3d", 2), { openvdb::math::Vec3<double>(0.0, 1.1,-1.1), openvdb::math::Vec3<double>(0.0,-1.1, 1.1), }); // vec4 mHarness.addAttributes<openvdb::math::Vec4<int32_t>> (unittest_util::nameSequence("v4i", 4), { openvdb::math::Vec4<int32_t>(0, 1,-1, 2), openvdb::math::Vec4<int32_t>(0,-1, 1, -2), openvdb::math::Vec4<int32_t>(-1,-2,0,-3), openvdb::math::Vec4<int32_t>(1, 0, 0, 0) }); mHarness.addAttributes<openvdb::math::Vec4<float>> (unittest_util::nameSequence("v4f", 2), { openvdb::math::Vec4<float>(0.0f, 1.1f,-1.1f, 2.1f), openvdb::math::Vec4<float>(0.0f,-1.1f, 1.1f, -2.1f) }); mHarness.addAttributes<openvdb::math::Vec4<double>> (unittest_util::nameSequence("v4d", 2), { openvdb::math::Vec4<double>(0.0, 1.1,-1.1, 2.1), openvdb::math::Vec4<double>(0.0,-1.1, 1.1, -2.1) }); mHarness.executeCode("test/snippets/unary/unaryVector"); AXTESTS_STANDARD_ASSERT(); }
NVIDIA-Omniverse/ext-openvdb/openvdb_ax/openvdb_ax/test/integration/TestLoop.cc
// Copyright Contributors to the OpenVDB Project // SPDX-License-Identifier: MPL-2.0 #include "TestHarness.h" #include <cppunit/extensions/HelperMacros.h> using namespace openvdb::points; class TestLoop : public unittest_util::AXTestCase { public: CPPUNIT_TEST_SUITE(TestLoop); CPPUNIT_TEST(testLoopForLoop); CPPUNIT_TEST(testLoopWhileLoop); CPPUNIT_TEST(testLoopDoWhileLoop); CPPUNIT_TEST(testLoopOverflow); CPPUNIT_TEST(testLoopErrors); CPPUNIT_TEST_SUITE_END(); void testLoopForLoop(); void testLoopWhileLoop(); void testLoopDoWhileLoop(); void testLoopOverflow(); void testLoopErrors(); }; CPPUNIT_TEST_SUITE_REGISTRATION(TestLoop); void TestLoop::testLoopForLoop() { mHarness.addAttribute<openvdb::Vec3f>("loop_test1", openvdb::Vec3f(1.0,2.0,3.0)); mHarness.addAttribute<openvdb::Vec3f>("loop_test2", openvdb::Vec3f(1.0,2.0,3.0)); mHarness.addAttribute<openvdb::Vec3f>("loop_test3", openvdb::Vec3f(1.0,2.0,3.0)); mHarness.addAttribute<openvdb::Vec3f>("loop_test15", openvdb::Vec3f(0.0,0.0,0.0)); mHarness.addAttribute<openvdb::math::Mat3s>("loop_test18", openvdb::math::Mat3s(1.0,2.0,3.0, 4.0,5.0,6.0, 7.0,8.0,9.0)); mHarness.addAttribute<int32_t>("loop_test22", 3); mHarness.addAttribute<int32_t>("loop_test23", 4); mHarness.addAttribute<int32_t>("loop_test25", 1); mHarness.addAttribute<int32_t>("loop_test27", 14); mHarness.addAttribute<int32_t>("loop_test30", 19); mHarness.executeCode("test/snippets/loop/forLoop"); AXTESTS_STANDARD_ASSERT(); } void TestLoop::testLoopWhileLoop() { mHarness.addAttribute<openvdb::Vec3f>("loop_test9", openvdb::Vec3f(1.0,2.0,3.0)); mHarness.addAttribute<openvdb::Vec3f>("loop_test16", openvdb::Vec3f(0.0,0.0,0.0)); mHarness.addAttribute<openvdb::Vec3f>("loop_test28", openvdb::Vec3f(0.0,0.0,0.0)); mHarness.addAttribute<int32_t>("loop_test31", 2); mHarness.executeCode("test/snippets/loop/whileLoop"); AXTESTS_STANDARD_ASSERT(); } void TestLoop::testLoopDoWhileLoop() { mHarness.addAttribute<openvdb::Vec3f>("loop_test12", openvdb::Vec3f(1.0,2.0,3.0)); mHarness.addAttribute<openvdb::Vec3f>("loop_test17", openvdb::Vec3f(1.0,0.0,0.0)); mHarness.addAttribute<openvdb::Vec3f>("loop_test29", openvdb::Vec3f(1.0,0.0,0.0)); mHarness.addAttribute<int32_t>("loop_test32", 2); mHarness.executeCode("test/snippets/loop/doWhileLoop"); AXTESTS_STANDARD_ASSERT(); } void TestLoop::testLoopOverflow() { // Disable all optimizations to force the loop to not remove the interior // allocation. The loop should generate its allocas in the function prologue // to avoid stack overflow openvdb::ax::CompilerOptions opts; opts.mOptLevel = openvdb::ax::CompilerOptions::OptLevel::NONE; mHarness.mOpts = opts; mHarness.executeCode("test/snippets/loop/loopOverflow"); } void TestLoop::testLoopErrors() { const bool success = mHarness.executeCode("test/snippets/loop/loopErrors"); CPPUNIT_ASSERT(!success); }
NVIDIA-Omniverse/ext-openvdb/openvdb_ax/openvdb_ax/test/integration/TestConditional.cc
// Copyright Contributors to the OpenVDB Project // SPDX-License-Identifier: MPL-2.0 #include "TestHarness.h" #include <cppunit/extensions/HelperMacros.h> using namespace openvdb::points; class TestConditional : public unittest_util::AXTestCase { public: CPPUNIT_TEST_SUITE(TestConditional); CPPUNIT_TEST(testConditionalIfWithinElse); CPPUNIT_TEST(testConditionalScopingStatement); CPPUNIT_TEST(testConditionalSimpleStatement); CPPUNIT_TEST(testConditionalSimpleElseIf); CPPUNIT_TEST(testConditionalErrors); CPPUNIT_TEST_SUITE_END(); void testConditionalIfWithinElse(); void testConditionalSimpleStatement(); void testConditionalScopingStatement(); void testConditionalSimpleElseIf(); void testConditionalErrors(); }; CPPUNIT_TEST_SUITE_REGISTRATION(TestConditional); void TestConditional::testConditionalIfWithinElse() { mHarness.addAttribute<bool>("bool_test", true); mHarness.executeCode("test/snippets/conditional/conditionalIfWithinElse"); AXTESTS_STANDARD_ASSERT(); } void TestConditional::testConditionalSimpleStatement() { mHarness.addAttribute<bool>("bool_test", true); mHarness.addAttribute<float>("float_test", 1.0f); mHarness.executeCode("test/snippets/conditional/conditionalSimpleStatement"); AXTESTS_STANDARD_ASSERT(); } void TestConditional::testConditionalScopingStatement() { mHarness.addAttribute<int32_t>("int_test", 1); mHarness.executeCode("test/snippets/conditional/conditionalScopingStatement"); AXTESTS_STANDARD_ASSERT(); } void TestConditional::testConditionalSimpleElseIf() { mHarness.addAttribute("bool_test", true); mHarness.addAttribute("int_test", 2); mHarness.executeCode("test/snippets/conditional/conditionalSimpleElseIf"); AXTESTS_STANDARD_ASSERT(); } void TestConditional::testConditionalErrors() { const bool success = mHarness.executeCode("test/snippets/conditional/conditionalErrors"); CPPUNIT_ASSERT(!success); }
NVIDIA-Omniverse/ext-openvdb/openvdb_ax/openvdb_ax/test/integration/CompareGrids.h
// Copyright Contributors to the OpenVDB Project // SPDX-License-Identifier: MPL-2.0 /// @file test/integration/CompareGrids.h /// /// @authors Francisco Gochez, Nick Avramoussis /// /// @brief Functions for comparing entire VDB grids and generating /// reports on their differences /// #ifndef OPENVDB_POINTS_UNITTEST_COMPARE_GRIDS_INCLUDED #define OPENVDB_POINTS_UNITTEST_COMPARE_GRIDS_INCLUDED #include <openvdb/openvdb.h> #include <openvdb/points/PointDataGrid.h> #include <openvdb/tree/LeafManager.h> #include <openvdb/tools/Prune.h> namespace unittest_util { struct ComparisonSettings { bool mCheckTransforms = true; // Check grid transforms bool mCheckTopologyStructure = true; // Checks node (voxel/leaf/tile) layout bool mCheckActiveStates = true; // Checks voxel active states match bool mCheckBufferValues = true; // Checks voxel buffer values match bool mCheckDescriptors = true; // Check points leaf descriptors bool mCheckArrayValues = true; // Checks attribute array sizes and values bool mCheckArrayFlags = true; // Checks attribute array flags }; /// @brief The results collected from compareGrids() /// struct ComparisonResult { ComparisonResult(std::ostream& os = std::cout) : mOs(os) , mDifferingTopology(openvdb::MaskGrid::create()) , mDifferingValues(openvdb::MaskGrid::create()) {} std::ostream& mOs; openvdb::MaskGrid::Ptr mDifferingTopology; // Always empty if mCheckActiveStates is false openvdb::MaskGrid::Ptr mDifferingValues; // Always empty if mCheckBufferValues is false // or if mCheckBufferValues and mCheckArrayValues // is false for point data grids }; template <typename GridType> bool compareGrids(ComparisonResult& resultData, const GridType& firstGrid, const GridType& secondGrid, const ComparisonSettings& settings, const openvdb::MaskGrid::ConstPtr maskGrid, const typename GridType::ValueType tolerance = openvdb::zeroVal<typename GridType::ValueType>()); bool compareUntypedGrids(ComparisonResult& resultData, const openvdb::GridBase& firstGrid, const openvdb::GridBase& secondGrid, const ComparisonSettings& settings, const openvdb::MaskGrid::ConstPtr maskGrid); } // namespace unittest_util #endif // OPENVDB_POINTS_UNITTEST_COMPARE_GRIDS_INCLUDED
NVIDIA-Omniverse/ext-openvdb/openvdb_ax/openvdb_ax/test/integration/TestAssign.cc
// Copyright Contributors to the OpenVDB Project // SPDX-License-Identifier: MPL-2.0 #include "CompareGrids.h" #include "TestHarness.h" #include "../test/util.h" #include <openvdb_ax/compiler/CustomData.h> #include <openvdb_ax/Exceptions.h> #include <cppunit/extensions/HelperMacros.h> using namespace openvdb::points; // Configuration values for assignment code using ConfigMap = std::unordered_map<std::string, std::unordered_map<std::string, std::string>>; static const ConfigMap integral = { { "bool", { { "_l1_", "true" }, { "_l2_", "false" } } }, { "int32", { { "_l1_", "2" }, { "_l2_", "3" } } }, { "int64", { { "_l1_", "2l" }, { "_l2_", "3l" } } } }; static const ConfigMap floating = { { "float", { { "_l1_", "1.1f" }, { "_l2_", "2.3f" } } }, { "double", { { "_l1_", "1.1" }, { "_l2_", "2.3" } } } }; static const ConfigMap vec2 = { { "vec2i", { { "_l1_", "{1, 2}" }, { "_l2_", "{3, 4}" } } }, { "vec2f", { { "_l1_", "{1.1f, 2.3f}" }, { "_l2_", "{4.1f, 5.3f}" } } }, { "vec2d", { { "_l1_", "{1.1, 2.3}" }, { "_l2_", "{4.1, 5.3}" } } } }; static const ConfigMap vec3 = { { "vec3i", { { "_l1_", "{1, 2, 3}" }, { "_l2_", "{4, 5, 6}" } } }, { "vec3f", { { "_l1_", "{1.1f, 2.3f, 4.3f}" }, { "_l2_", "{4.1f, 5.3f, 6.3f}" } } }, { "vec3d", { { "_l1_", "{1.1, 2.3 , 4.3}" }, { "_l2_", "{4.1, 5.3, 6.3}" } } } }; static const ConfigMap vec4 = { { "vec4i", { { "_l1_", "{1, 2, 3, 4}" }, { "_l2_", "{5, 6, 7, 8}" } } }, { "vec4f", { { "_l1_", "{1.1f, 2.3f, 4.3f, 5.4f}" }, { "_l2_", "{5.1f, 6.3f, 7.3f, 8.4f}" } } }, { "vec4d", { { "_l1_", "{1.1, 2.3, 4.3, 5.4}" }, { "_l2_", "{5.1, 6.3, 7.3, 8.4}" } } } }; static const ConfigMap mat3 = { { "mat3f", { { "_l1_", "{1.1f, 2.3f, 4.3f, 5.4f, 6.7f, 7.8f, 9.1f, 4.5f, 8.2f }" }, { "_l2_", "{9.1f, 7.3f, -1.3f, 4.4f, -6.7f, 0.8f, 9.1f,-0.5f, 8.2f }" } } }, { "mat3d", { { "_l1_", "{1.1, 2.3, 4.3, 5.4, 6.7, 7.8, 9.1, 4.5, 8.2 }" }, { "_l2_", "{9.1, 7.3, -1.3, 4.4, -6.7, 0.8, 9.1,-0.5, 8.2 }" } } } }; static const ConfigMap mat4 = { { "mat4f", { { "_l1_", "{1.1f, 2.3f, 4.3f, 5.4f, 6.7f, 7.8f, 9.1f, 4.5f, 8.2f, 3.3f, 2.9f, 5.9f, 0.1f, 0.3f, 5.1f, 1.9f}" }, { "_l2_", "{0.1f, 2.3f,-9.3f, 4.5f, -1.7f, 7.8f, 2.1f, 3.3f, 3.3f,-3.3f,-0.3f, 2.5f, 5.1f, 0.5f, 8.1f,-1.7f}" } } }, { "mat4d", { { "_l1_", "{1.1, 2.3, 4.3, 5.4, 6.7, 7.8, 9.1, 4.5, 8.2, 3.3, 2.9, 5.9, 0.1, 0.3, 5.1, 1.9}" }, { "_l2_", "{0.1, 2.3,-9.3, 4.5, -1.7, 7.8, 2.1, 3.3, 3.3,-3.3,-0.3, 2.5, 5.1, 0.5, 8.1,-1.7}" } } } }; static const ConfigMap string = { { "string", { { "_l1_", "\"foo\"" }, { "_l2_", "\"bar\"" } } } }; // class TestAssign : public unittest_util::AXTestCase { public: std::string dir() const override { return GET_TEST_DIRECTORY(); } CPPUNIT_TEST_SUITE(TestAssign); CPPUNIT_TEST(directAssignment); CPPUNIT_TEST(compoundIntegralAssignment); CPPUNIT_TEST(compoundFloatingAssignment); CPPUNIT_TEST(compoundVectorAssignment); CPPUNIT_TEST(compoundMatrixAssignment); CPPUNIT_TEST(compoundStringAssignment); CPPUNIT_TEST(implicitScalarAssignment); CPPUNIT_TEST(implicitContainerAssignment); CPPUNIT_TEST(implicitContainerScalarAssignment); CPPUNIT_TEST(scopedAssign); CPPUNIT_TEST_SUITE_END(); void directAssignment(); void compoundIntegralAssignment(); void compoundFloatingAssignment(); void compoundVectorAssignment(); void compoundMatrixAssignment(); void compoundStringAssignment(); void implicitScalarAssignment(); void implicitContainerAssignment(); void implicitContainerScalarAssignment(); void scopedAssign(); }; CPPUNIT_TEST_SUITE_REGISTRATION(TestAssign); void TestAssign::directAssignment() { const std::string code = R"( _T1_@test1 = _l1_; _T1_ local1 = _l1_; _T1_@test2 = local1; _T1_@test3 = _T1_@test4 = _T1_@test2; _T1_ local3, local2 = _l2_; _T1_@test5 = local3 = local2; _T1_@test6 = _l2_, _T1_@test7 = _l1_; _T1_@test8 = _l2_; _T1_@test8 = _l1_; )"; auto generate = [&](const auto& map) { for (const auto& config : map) { std::string repl = code; unittest_util::replace(repl, "_T1_", config.first); // replace type // replace literal values for (const auto& settings : config.second) { unittest_util::replace(repl, settings.first, settings.second); } this->registerTest(repl, "assign." + config.first + ".ax"); } }; generate(integral); generate(floating); generate(vec2); generate(vec3); generate(vec4); generate(mat3); generate(mat4); generate(string); const auto names = unittest_util::nameSequence("test", 8); const std::map<std::string, std::function<void()>> expected = { { "bool", [&](){ mHarness.addAttributes<bool>(names, { true, true, true, true, false, false, true, true }); }, }, { "int32", [&](){ mHarness.addAttributes<int32_t>(names, { 2, 2, 2, 2, 3, 3, 2, 2 }); }, }, { "int64", [&](){ mHarness.addAttributes<int64_t>(names, { 2, 2, 2, 2, 3, 3, 2, 2 }); }, }, { "float", [&](){ mHarness.addAttributes<float>(names, { 1.1f, 1.1f, 1.1f, 1.1f, 2.3f, 2.3f, 1.1f, 1.1f }); }, }, { "double", [&](){ mHarness.addAttributes<double>(names, { 1.1, 1.1, 1.1, 1.1, 2.3, 2.3, 1.1, 1.1 }); }, }, { "vec2i", [&](){ mHarness.addAttributes<openvdb::math::Vec2<int32_t>>(names, { openvdb::math::Vec2<int32_t>(1,2), openvdb::math::Vec2<int32_t>(1,2), openvdb::math::Vec2<int32_t>(1,2), openvdb::math::Vec2<int32_t>(1,2), openvdb::math::Vec2<int32_t>(3,4), openvdb::math::Vec2<int32_t>(3,4), openvdb::math::Vec2<int32_t>(1,2), openvdb::math::Vec2<int32_t>(1,2) }); }, }, { "vec2f", [&](){ mHarness.addAttributes<openvdb::math::Vec2<float>>(names, { openvdb::math::Vec2<float>(1.1f, 2.3f), openvdb::math::Vec2<float>(1.1f, 2.3f), openvdb::math::Vec2<float>(1.1f, 2.3f), openvdb::math::Vec2<float>(1.1f, 2.3f), openvdb::math::Vec2<float>(4.1f, 5.3f), openvdb::math::Vec2<float>(4.1f, 5.3f), openvdb::math::Vec2<float>(1.1f, 2.3f), openvdb::math::Vec2<float>(1.1f, 2.3f) }); }, }, { "vec2d", [&](){ mHarness.addAttributes<openvdb::math::Vec2<double>>(names, { openvdb::math::Vec2<double>(1.1, 2.3), openvdb::math::Vec2<double>(1.1, 2.3), openvdb::math::Vec2<double>(1.1, 2.3), openvdb::math::Vec2<double>(1.1, 2.3), openvdb::math::Vec2<double>(4.1, 5.3), openvdb::math::Vec2<double>(4.1, 5.3), openvdb::math::Vec2<double>(1.1, 2.3), openvdb::math::Vec2<double>(1.1, 2.3) }); }, }, { "vec3i", [&](){ mHarness.addAttributes<openvdb::math::Vec3<int32_t>>(names, { openvdb::math::Vec3<int32_t>(1,2,3), openvdb::math::Vec3<int32_t>(1,2,3), openvdb::math::Vec3<int32_t>(1,2,3), openvdb::math::Vec3<int32_t>(1,2,3), openvdb::math::Vec3<int32_t>(4,5,6), openvdb::math::Vec3<int32_t>(4,5,6), openvdb::math::Vec3<int32_t>(1,2,3), openvdb::math::Vec3<int32_t>(1,2,3) }); }, }, { "vec3f", [&](){ mHarness.addAttributes<openvdb::math::Vec3<float>>(names, { openvdb::math::Vec3<float>(1.1f, 2.3f, 4.3f), openvdb::math::Vec3<float>(1.1f, 2.3f, 4.3f), openvdb::math::Vec3<float>(1.1f, 2.3f, 4.3f), openvdb::math::Vec3<float>(1.1f, 2.3f, 4.3f), openvdb::math::Vec3<float>(4.1f, 5.3f, 6.3f), openvdb::math::Vec3<float>(4.1f, 5.3f, 6.3f), openvdb::math::Vec3<float>(1.1f, 2.3f, 4.3f), openvdb::math::Vec3<float>(1.1f, 2.3f, 4.3f) }); }, }, { "vec3d", [&](){ mHarness.addAttributes<openvdb::math::Vec3<double>>(names, { openvdb::math::Vec3<double>(1.1, 2.3, 4.3), openvdb::math::Vec3<double>(1.1, 2.3, 4.3), openvdb::math::Vec3<double>(1.1, 2.3, 4.3), openvdb::math::Vec3<double>(1.1, 2.3, 4.3), openvdb::math::Vec3<double>(4.1, 5.3, 6.3), openvdb::math::Vec3<double>(4.1, 5.3, 6.3), openvdb::math::Vec3<double>(1.1, 2.3, 4.3), openvdb::math::Vec3<double>(1.1, 2.3, 4.3) }); }, }, { "vec4i", [&](){ mHarness.addAttributes<openvdb::math::Vec4<int32_t>>(names, { openvdb::math::Vec4<int32_t>(1, 2, 3, 4), openvdb::math::Vec4<int32_t>(1, 2, 3, 4), openvdb::math::Vec4<int32_t>(1, 2, 3, 4), openvdb::math::Vec4<int32_t>(1, 2, 3, 4), openvdb::math::Vec4<int32_t>(5, 6, 7, 8), openvdb::math::Vec4<int32_t>(5, 6, 7, 8), openvdb::math::Vec4<int32_t>(1, 2, 3, 4), openvdb::math::Vec4<int32_t>(1, 2, 3, 4) }); }, }, { "vec4f", [&](){ mHarness.addAttributes<openvdb::math::Vec4<float>>(names, { openvdb::math::Vec4<float>(1.1f, 2.3f, 4.3f, 5.4f), openvdb::math::Vec4<float>(1.1f, 2.3f, 4.3f, 5.4f), openvdb::math::Vec4<float>(1.1f, 2.3f, 4.3f, 5.4f), openvdb::math::Vec4<float>(1.1f, 2.3f, 4.3f, 5.4f), openvdb::math::Vec4<float>(5.1f, 6.3f, 7.3f, 8.4f), openvdb::math::Vec4<float>(5.1f, 6.3f, 7.3f, 8.4f), openvdb::math::Vec4<float>(1.1f, 2.3f, 4.3f, 5.4f), openvdb::math::Vec4<float>(1.1f, 2.3f, 4.3f, 5.4f) }); }, }, { "vec4d", [&](){ mHarness.addAttributes<openvdb::math::Vec4<double>>(names, { openvdb::math::Vec4<double>(1.1, 2.3, 4.3, 5.4), openvdb::math::Vec4<double>(1.1, 2.3, 4.3, 5.4), openvdb::math::Vec4<double>(1.1, 2.3, 4.3, 5.4), openvdb::math::Vec4<double>(1.1, 2.3, 4.3, 5.4), openvdb::math::Vec4<double>(5.1, 6.3, 7.3, 8.4), openvdb::math::Vec4<double>(5.1, 6.3, 7.3, 8.4), openvdb::math::Vec4<double>(1.1, 2.3, 4.3, 5.4), openvdb::math::Vec4<double>(1.1, 2.3, 4.3, 5.4) }); }, }, { "mat3f", [&](){ mHarness.addAttributes<openvdb::math::Mat3<float>>(names, { openvdb::math::Mat3<float>(1.1f, 2.3f, 4.3f, 5.4f, 6.7f, 7.8f, 9.1f, 4.5f, 8.2f), openvdb::math::Mat3<float>(1.1f, 2.3f, 4.3f, 5.4f, 6.7f, 7.8f, 9.1f, 4.5f, 8.2f), openvdb::math::Mat3<float>(1.1f, 2.3f, 4.3f, 5.4f, 6.7f, 7.8f, 9.1f, 4.5f, 8.2f), openvdb::math::Mat3<float>(1.1f, 2.3f, 4.3f, 5.4f, 6.7f, 7.8f, 9.1f, 4.5f, 8.2f), openvdb::math::Mat3<float>(9.1f, 7.3f, -1.3f, 4.4f, -6.7f, 0.8f, 9.1f, -0.5f, 8.2f), openvdb::math::Mat3<float>(9.1f, 7.3f, -1.3f, 4.4f, -6.7f, 0.8f, 9.1f, -0.5f, 8.2f), openvdb::math::Mat3<float>(1.1f, 2.3f, 4.3f, 5.4f, 6.7f, 7.8f, 9.1f, 4.5f, 8.2f), openvdb::math::Mat3<float>(1.1f, 2.3f, 4.3f, 5.4f, 6.7f, 7.8f, 9.1f, 4.5f, 8.2f) }); }, }, { "mat3d", [&](){ mHarness.addAttributes<openvdb::math::Mat3<double>>(names, { openvdb::math::Mat3<double>(1.1, 2.3, 4.3, 5.4, 6.7, 7.8, 9.1, 4.5, 8.2), openvdb::math::Mat3<double>(1.1, 2.3, 4.3, 5.4, 6.7, 7.8, 9.1, 4.5, 8.2), openvdb::math::Mat3<double>(1.1, 2.3, 4.3, 5.4, 6.7, 7.8, 9.1, 4.5, 8.2), openvdb::math::Mat3<double>(1.1, 2.3, 4.3, 5.4, 6.7, 7.8, 9.1, 4.5, 8.2), openvdb::math::Mat3<double>(9.1, 7.3, -1.3, 4.4, -6.7, 0.8, 9.1, -0.5, 8.2), openvdb::math::Mat3<double>(9.1, 7.3, -1.3, 4.4, -6.7, 0.8, 9.1, -0.5, 8.2), openvdb::math::Mat3<double>(1.1, 2.3, 4.3, 5.4, 6.7, 7.8, 9.1, 4.5, 8.2), openvdb::math::Mat3<double>(1.1, 2.3, 4.3, 5.4, 6.7, 7.8, 9.1, 4.5, 8.2) }); }, }, { "mat4f", [&](){ mHarness.addAttributes<openvdb::math::Mat4<float>>(names, { openvdb::math::Mat4<float>(1.1f, 2.3f, 4.3f, 5.4f, 6.7f, 7.8f, 9.1f, 4.5f, 8.2f, 3.3f, 2.9f, 5.9f, 0.1f, 0.3f, 5.1f, 1.9f), openvdb::math::Mat4<float>(1.1f, 2.3f, 4.3f, 5.4f, 6.7f, 7.8f, 9.1f, 4.5f, 8.2f, 3.3f, 2.9f, 5.9f, 0.1f, 0.3f, 5.1f, 1.9f), openvdb::math::Mat4<float>(1.1f, 2.3f, 4.3f, 5.4f, 6.7f, 7.8f, 9.1f, 4.5f, 8.2f, 3.3f, 2.9f, 5.9f, 0.1f, 0.3f, 5.1f, 1.9f), openvdb::math::Mat4<float>(1.1f, 2.3f, 4.3f, 5.4f, 6.7f, 7.8f, 9.1f, 4.5f, 8.2f, 3.3f, 2.9f, 5.9f, 0.1f, 0.3f, 5.1f, 1.9f), openvdb::math::Mat4<float>(0.1f, 2.3f,-9.3f, 4.5f, -1.7f, 7.8f, 2.1f, 3.3f, 3.3f,-3.3f,-0.3f, 2.5f, 5.1f, 0.5f, 8.1f,-1.7f), openvdb::math::Mat4<float>(0.1f, 2.3f,-9.3f, 4.5f, -1.7f, 7.8f, 2.1f, 3.3f, 3.3f,-3.3f,-0.3f, 2.5f, 5.1f, 0.5f, 8.1f,-1.7f), openvdb::math::Mat4<float>(1.1f, 2.3f, 4.3f, 5.4f, 6.7f, 7.8f, 9.1f, 4.5f, 8.2f, 3.3f, 2.9f, 5.9f, 0.1f, 0.3f, 5.1f, 1.9f), openvdb::math::Mat4<float>(1.1f, 2.3f, 4.3f, 5.4f, 6.7f, 7.8f, 9.1f, 4.5f, 8.2f, 3.3f, 2.9f, 5.9f, 0.1f, 0.3f, 5.1f, 1.9f) }); }, }, { "mat4d", [&](){ mHarness.addAttributes<openvdb::math::Mat4<double>>(names, { openvdb::math::Mat4<double>(1.1, 2.3, 4.3, 5.4, 6.7, 7.8, 9.1, 4.5, 8.2, 3.3, 2.9, 5.9, 0.1, 0.3, 5.1, 1.9), openvdb::math::Mat4<double>(1.1, 2.3, 4.3, 5.4, 6.7, 7.8, 9.1, 4.5, 8.2, 3.3, 2.9, 5.9, 0.1, 0.3, 5.1, 1.9), openvdb::math::Mat4<double>(1.1, 2.3, 4.3, 5.4, 6.7, 7.8, 9.1, 4.5, 8.2, 3.3, 2.9, 5.9, 0.1, 0.3, 5.1, 1.9), openvdb::math::Mat4<double>(1.1, 2.3, 4.3, 5.4, 6.7, 7.8, 9.1, 4.5, 8.2, 3.3, 2.9, 5.9, 0.1, 0.3, 5.1, 1.9), openvdb::math::Mat4<double>(0.1, 2.3,-9.3, 4.5, -1.7, 7.8, 2.1, 3.3, 3.3,-3.3,-0.3, 2.5, 5.1, 0.5, 8.1,-1.7), openvdb::math::Mat4<double>(0.1, 2.3,-9.3, 4.5, -1.7, 7.8, 2.1, 3.3, 3.3,-3.3,-0.3, 2.5, 5.1, 0.5, 8.1,-1.7), openvdb::math::Mat4<double>(1.1, 2.3, 4.3, 5.4, 6.7, 7.8, 9.1, 4.5, 8.2, 3.3, 2.9, 5.9, 0.1, 0.3, 5.1, 1.9), openvdb::math::Mat4<double>(1.1, 2.3, 4.3, 5.4, 6.7, 7.8, 9.1, 4.5, 8.2, 3.3, 2.9, 5.9, 0.1, 0.3, 5.1, 1.9) }); }, }, { "string", [&](){ mHarness.addAttributes<std::string>(names, { "foo", "foo", "foo", "foo", "bar", "bar", "foo", "foo" }); }, } }; for (const auto& expc : expected) { mHarness.reset(); expc.second.operator()(); this->execute("assign." + expc.first + ".ax"); } } void TestAssign::compoundIntegralAssignment() { const std::string code = R"( _T1_@test1 += _l1_; _T1_@test2 -= _l1_; _T1_@test3 *= _l1_; _T1_@test4 /= _l1_; _T1_@test5 %= _l1_; _T1_@test6 <<= _l1_; _T1_@test7 >>= _l1_; _T1_@test8 &= _l1_; _T1_@test9 ^= _l1_; _T1_@test10 |= _l1_; _T1_ local1 = _l1_, local2 = _l2_; local1 += local2; _T1_@test11 = local1; _T1_@test12 += _T1_@test13; _T1_@test14 += local2; )"; auto generate = [&](const auto& map) { for (const auto& config : map) { std::string repl = code; unittest_util::replace(repl, "_T1_", config.first); // replace type // replace literal values for (const auto& settings : config.second) { unittest_util::replace(repl, settings.first, settings.second); } this->registerTest(repl, "assign_compound." + config.first + ".ax"); } }; generate(integral); const auto names = unittest_util::nameSequence("test", 14); const std::map<std::string, std::vector<std::function<void()>>> expected = { { "bool", { [&](){ mHarness.addAttributes<bool>(names, { true, true, false, false, false, false, false, false, true, true, true, false, false, false }); }, [&](){ mHarness.addAttributes<bool>(names, { true, true, true, true, true, true, true, true, true, true, false, true, true, true }, // in { true, false, true, true, false, true, false, true, false, true, true, true, true, true }); // expected }, } }, { "int32", { [&](){ mHarness.addAttributes<int32_t>(names, { 2, -2, 0, 0, 0, 0, 0, 0, 2, 2, 5, 0, 0, 3 }); }, [&](){ mHarness.addAttributes<int32_t>(names, { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 0, 12, 13, 14 }, // in { 3, 0, 6, 2, 1, 24, 1, 0, 11, 10, 5, 25, 13, 17 }); // expected }, } }, { "int64", { [&](){ mHarness.addAttributes<int64_t>(names, { 2, -2, 0, 0, 0, 0, 0, 0, 2, 2, 5, 0, 0, 3 }); }, [&](){ mHarness.addAttributes<int64_t>(names, { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 0, 12, 13, 14 }, // in { 3, 0, 6, 2, 1, 24, 1, 0, 11, 10, 5, 25, 13, 17 }); // expected }, } } }; for (const auto& expc : expected) { for (const auto& test : expc.second) { mHarness.reset(); test.operator()(); this->execute("assign_compound." + expc.first + ".ax"); } } } void TestAssign::compoundFloatingAssignment() { const std::string code = R"( _T1_@test1 += _l1_; _T1_@test2 -= _l1_; _T1_@test3 *= _l1_; _T1_@test4 /= _l1_; _T1_@test5 %= _l1_; _T1_ local1 = _l1_, local2 = _l2_; local1 += local2; _T1_@test6 = local1; _T1_@test7 += _T1_@test8; _T1_@test9 += local2; )"; auto generate = [&](const auto& map) { for (const auto& config : map) { std::string repl = code; unittest_util::replace(repl, "_T1_", config.first); // replace type // replace literal values for (const auto& settings : config.second) { unittest_util::replace(repl, settings.first, settings.second); } this->registerTest(repl, "assign_compound." + config.first + ".ax"); } }; generate(floating); const auto names = unittest_util::nameSequence("test", 9); const std::map<std::string, std::vector<std::function<void()>>> expected = { { "float", { [&](){ mHarness.addAttributes<float>(names, { 1.1f, -1.1f, 0.0f, 0.0f, 0.0f, (1.1f+2.3f), 0.0f, 0.0f, 2.3f }); }, [&](){ mHarness.addAttributes<float>(names, { 1.1f, 2.3f, 4.5f, 6.7f, 8.9f, -1.1f, -2.3f, -4.5f, 6.1f }, // in { (1.1f+1.1f), (2.3f-1.1f), (4.5f*1.1f), (6.7f/1.1f), std::fmod(8.9f,1.1f), (1.1f+2.3f), (-2.3f+-4.5f), (-4.5f), (6.1f+2.3f) }); // expected } } }, { "double", { [&](){ mHarness.addAttributes<double>(names, { 1.1, -1.1, 0.0, 0.0, 0.0, (1.1+2.3), 0.0, 0.0, 2.3 }); }, [&](){ mHarness.addAttributes<double>(names, { 1.1, 2.3, 4.5, 6.7, 8.9, -1.1, -2.3, -4.5, 6.1 }, // in { (1.1+1.1), (2.3-1.1), (4.5*1.1), (6.7/1.1), std::fmod(8.9,1.1), (1.1+2.3), (-2.3+-4.5), (-4.5), (6.1+2.3) }); // expected } } }, }; for (const auto& expc : expected) { for (const auto& test : expc.second) { mHarness.reset(); test.operator()(); this->execute("assign_compound." + expc.first + ".ax"); } } } void TestAssign::compoundVectorAssignment() { const std::string code = R"( _T1_@test1 += _l1_; _T1_@test2 -= _l1_; _T1_@test3 *= _l1_; _T1_@test4 /= _l1_; _T1_@test5 %= _l1_; _T1_ local1 = _l1_, local2 = _l2_; local1 += local2; _T1_@test6 = local1; _T1_@test7 += _T1_@test8; _T1_@test9 += local2; )"; auto generate = [&](const auto& map) { for (const auto& config : map) { std::string repl = code; unittest_util::replace(repl, "_T1_", config.first); // replace type // replace literal values for (const auto& settings : config.second) { unittest_util::replace(repl, settings.first, settings.second); } this->registerTest(repl, "assign_compound." + config.first + ".ax"); } }; generate(vec2); generate(vec3); generate(vec4); const auto names = unittest_util::nameSequence("test", 9); const std::map<std::string, std::vector<std::function<void()>>> expected = { { "vec2i", { [&](){ mHarness.addAttributes<openvdb::math::Vec2<int32_t>>(names, { openvdb::math::Vec2<int32_t>(1,2), openvdb::math::Vec2<int32_t>(-1,-2), openvdb::math::Vec2<int32_t>(0,0), openvdb::math::Vec2<int32_t>(0,0), openvdb::math::Vec2<int32_t>(0,0), openvdb::math::Vec2<int32_t>(4,6), openvdb::math::Vec2<int32_t>(0,0), openvdb::math::Vec2<int32_t>(0,0), openvdb::math::Vec2<int32_t>(3,4) }); }, [&](){ mHarness.addAttributes<openvdb::math::Vec2<int32_t>>(names, { openvdb::math::Vec2<int32_t>(1,2), openvdb::math::Vec2<int32_t>(3,4), openvdb::math::Vec2<int32_t>(5,6), openvdb::math::Vec2<int32_t>(7,8), openvdb::math::Vec2<int32_t>(3,9), openvdb::math::Vec2<int32_t>(9,-1), openvdb::math::Vec2<int32_t>(-2,-3), openvdb::math::Vec2<int32_t>(-4,-5), openvdb::math::Vec2<int32_t>(-6,-7) }, // in { openvdb::math::Vec2<int32_t>(2,4), openvdb::math::Vec2<int32_t>(2,2), openvdb::math::Vec2<int32_t>(5,12), openvdb::math::Vec2<int32_t>(7,4), openvdb::math::Vec2<int32_t>(0,1), openvdb::math::Vec2<int32_t>(4,6), openvdb::math::Vec2<int32_t>(-6,-8), openvdb::math::Vec2<int32_t>(-4,-5), openvdb::math::Vec2<int32_t>(-3,-3) }); // expected } } }, { "vec2f", { [&](){ mHarness.addAttributes<openvdb::math::Vec2<float>>(names, { openvdb::math::Vec2<float>(1.1f,2.3f), openvdb::math::Vec2<float>(-1.1f,-2.3f), openvdb::math::Vec2<float>(0.0f,0.0f), openvdb::math::Vec2<float>(0.0f,0.0f), openvdb::math::Vec2<float>(0.0f,0.0f), openvdb::math::Vec2<float>(1.1f, 2.3f) + openvdb::math::Vec2<float>(4.1f, 5.3f), openvdb::math::Vec2<float>(0.0f,0.0f), openvdb::math::Vec2<float>(0.0f,0.0f), openvdb::math::Vec2<float>(4.1f,5.3f) }); }, [&](){ mHarness.addAttributes<openvdb::math::Vec2<float>>(names, { openvdb::math::Vec2<float>(1.1f,2.2f), openvdb::math::Vec2<float>(3.3f,4.4f), openvdb::math::Vec2<float>(5.5f,6.6f), openvdb::math::Vec2<float>(7.7f,8.8f), openvdb::math::Vec2<float>(2.3f,5.5f), openvdb::math::Vec2<float>(9.9f,-1.1f), openvdb::math::Vec2<float>(-2.2f,-3.3f), openvdb::math::Vec2<float>(-4.3f,-5.5f), openvdb::math::Vec2<float>(-6.1f,-8.2f) }, // in { openvdb::math::Vec2<float>(1.1f,2.2f) + openvdb::math::Vec2<float>(1.1f,2.3f), openvdb::math::Vec2<float>(3.3f,4.4f) - openvdb::math::Vec2<float>(1.1f,2.3f), openvdb::math::Vec2<float>(5.5f,6.6f) * openvdb::math::Vec2<float>(1.1f,2.3f), openvdb::math::Vec2<float>(7.7f,8.8f) / openvdb::math::Vec2<float>(1.1f,2.3f), openvdb::math::Vec2<float>(std::fmod(2.3f, 1.1f), std::fmod(5.5f, 2.3f)), openvdb::math::Vec2<float>(1.1f, 2.3f) + openvdb::math::Vec2<float>(4.1f, 5.3f), openvdb::math::Vec2<float>(-2.2f,-3.3f) + openvdb::math::Vec2<float>(-4.3f,-5.5f), openvdb::math::Vec2<float>(-4.3f,-5.5f), openvdb::math::Vec2<float>(-6.1f,-8.2f) + openvdb::math::Vec2<float>(4.1f,5.3f) }); // expected } } }, { "vec2d", { [&](){ mHarness.addAttributes<openvdb::math::Vec2<double>>(names, { openvdb::math::Vec2<double>(1.1,2.3), openvdb::math::Vec2<double>(-1.1,-2.3), openvdb::math::Vec2<double>(0.0,0.0), openvdb::math::Vec2<double>(0.0,0.0), openvdb::math::Vec2<double>(0.0,0.0), openvdb::math::Vec2<double>(1.1, 2.3) + openvdb::math::Vec2<double>(4.1, 5.3), openvdb::math::Vec2<double>(0.0,0.0), openvdb::math::Vec2<double>(0.0,0.0), openvdb::math::Vec2<double>(4.1,5.3) }); }, [&](){ mHarness.addAttributes<openvdb::math::Vec2<double>>(names, { openvdb::math::Vec2<double>(1.1,2.2), openvdb::math::Vec2<double>(3.3,4.4), openvdb::math::Vec2<double>(5.5,6.6), openvdb::math::Vec2<double>(7.7,8.8), openvdb::math::Vec2<double>(2.3,5.5), openvdb::math::Vec2<double>(9.9,-1.1), openvdb::math::Vec2<double>(-2.2,-3.3), openvdb::math::Vec2<double>(-4.3,-5.5), openvdb::math::Vec2<double>(-6.1,-8.2) }, // in { openvdb::math::Vec2<double>(1.1,2.2) + openvdb::math::Vec2<double>(1.1,2.3), openvdb::math::Vec2<double>(3.3,4.4) - openvdb::math::Vec2<double>(1.1,2.3), openvdb::math::Vec2<double>(5.5,6.6) * openvdb::math::Vec2<double>(1.1,2.3), openvdb::math::Vec2<double>(7.7,8.8) / openvdb::math::Vec2<double>(1.1,2.3), openvdb::math::Vec2<double>(std::fmod(2.3, 1.1), std::fmod(5.5, 2.3)), openvdb::math::Vec2<double>(1.1, 2.3) + openvdb::math::Vec2<double>(4.1, 5.3), openvdb::math::Vec2<double>(-2.2,-3.3) + openvdb::math::Vec2<double>(-4.3,-5.5), openvdb::math::Vec2<double>(-4.3,-5.5), openvdb::math::Vec2<double>(-6.1,-8.2) + openvdb::math::Vec2<double>(4.1,5.3) }); // expected } } }, { "vec3i", { [&](){ mHarness.addAttributes<openvdb::math::Vec3<int32_t>>(names, { openvdb::math::Vec3<int32_t>(1,2,3), openvdb::math::Vec3<int32_t>(-1,-2,-3), openvdb::math::Vec3<int32_t>(0,0,0), openvdb::math::Vec3<int32_t>(0,0,0), openvdb::math::Vec3<int32_t>(0,0,0), openvdb::math::Vec3<int32_t>(5,7,9), openvdb::math::Vec3<int32_t>(0,0,0), openvdb::math::Vec3<int32_t>(0,0,0), openvdb::math::Vec3<int32_t>(4,5,6) }); }, [&](){ mHarness.addAttributes<openvdb::math::Vec3<int32_t>>(names, { openvdb::math::Vec3<int32_t>(1,2,3), openvdb::math::Vec3<int32_t>(4,5,6), openvdb::math::Vec3<int32_t>(7,8,9), openvdb::math::Vec3<int32_t>(-1,-2,-3), openvdb::math::Vec3<int32_t>(4,-5,6), openvdb::math::Vec3<int32_t>(5,7,9), openvdb::math::Vec3<int32_t>(-7,-8,-9), openvdb::math::Vec3<int32_t>(-1,2,-3), openvdb::math::Vec3<int32_t>(-4,5,-6) }, // in { openvdb::math::Vec3<int32_t>(2,4,6), openvdb::math::Vec3<int32_t>(3,3,3), openvdb::math::Vec3<int32_t>(7,16,27), openvdb::math::Vec3<int32_t>(-1,-1,-1), openvdb::math::Vec3<int32_t>(0,1,0), openvdb::math::Vec3<int32_t>(5,7,9), openvdb::math::Vec3<int32_t>(-8,-6,-12), openvdb::math::Vec3<int32_t>(-1,2,-3), openvdb::math::Vec3<int32_t>(0,10,0) }); // expected } } }, { "vec3f", { [&](){ mHarness.addAttributes<openvdb::math::Vec3<float>>(names, { openvdb::math::Vec3<float>(1.1f,2.3f,4.3f), openvdb::math::Vec3<float>(-1.1f,-2.3f,-4.3f), openvdb::math::Vec3<float>(0.0f,0.0f,0.0f), openvdb::math::Vec3<float>(0.0f,0.0f,0.0f), openvdb::math::Vec3<float>(0.0f,0.0f,0.0f), openvdb::math::Vec3<float>(1.1f, 2.3f, 4.3f) + openvdb::math::Vec3<float>(4.1f, 5.3f, 6.3f), openvdb::math::Vec3<float>(0.0f,0.0f,0.0f), openvdb::math::Vec3<float>(0.0f,0.0f,0.0f), openvdb::math::Vec3<float>(4.1f, 5.3f, 6.3f) }); }, [&](){ mHarness.addAttributes<openvdb::math::Vec3<float>>(names, { openvdb::math::Vec3<float>(1.1f,2.2f,3.3f), openvdb::math::Vec3<float>(3.3f,4.4f,5.5f), openvdb::math::Vec3<float>(5.5f,6.6f,7.7f), openvdb::math::Vec3<float>(7.7f,8.8f,9.9f), openvdb::math::Vec3<float>(7.7f,8.8f,9.9f), openvdb::math::Vec3<float>(9.9f,-1.1f,-2.2f), openvdb::math::Vec3<float>(-2.2f,-3.3f,-4.4f), openvdb::math::Vec3<float>(-4.3f,-5.5f,-6.6f), openvdb::math::Vec3<float>(-7.1f,8.5f,-9.9f), }, // in { openvdb::math::Vec3<float>(1.1f,2.2f,3.3f) + openvdb::math::Vec3<float>(1.1f,2.3f,4.3f), openvdb::math::Vec3<float>(3.3f,4.4f,5.5f) - openvdb::math::Vec3<float>(1.1f,2.3f,4.3f), openvdb::math::Vec3<float>(5.5f,6.6f,7.7f) * openvdb::math::Vec3<float>(1.1f,2.3f,4.3f), openvdb::math::Vec3<float>(7.7f,8.8f,9.9f) / openvdb::math::Vec3<float>(1.1f,2.3f,4.3f), openvdb::math::Vec3<float>(std::fmod(7.7f,1.1f), std::fmod(8.8f,2.3f), std::fmod(9.9f,4.3f)), openvdb::math::Vec3<float>(1.1f, 2.3f, 4.3f) + openvdb::math::Vec3<float>(4.1f, 5.3f, 6.3f), openvdb::math::Vec3<float>(-2.2f,-3.3f,-4.4f) + openvdb::math::Vec3<float>(-4.3f,-5.5f,-6.6f), openvdb::math::Vec3<float>(-4.3f,-5.5f,-6.6f), openvdb::math::Vec3<float>(-7.1f,8.5f,-9.9f) + openvdb::math::Vec3<float>(4.1f, 5.3f, 6.3f) }); // expected } } }, { "vec3d", { [&](){ mHarness.addAttributes<openvdb::math::Vec3<double>>(names, { openvdb::math::Vec3<double>(1.1,2.3,4.3), openvdb::math::Vec3<double>(-1.1,-2.3,-4.3), openvdb::math::Vec3<double>(0.0,0.0,0.0), openvdb::math::Vec3<double>(0.0,0.0,0.0), openvdb::math::Vec3<double>(0.0,0.0,0.0), openvdb::math::Vec3<double>(1.1, 2.3, 4.3) + openvdb::math::Vec3<double>(4.1, 5.3, 6.3), openvdb::math::Vec3<double>(0.0,0.0,0.0), openvdb::math::Vec3<double>(0.0,0.0,0.0), openvdb::math::Vec3<double>(4.1, 5.3, 6.3) }); }, [&](){ mHarness.addAttributes<openvdb::math::Vec3<double>>(names, { openvdb::math::Vec3<double>(1.1,2.2,3.3), openvdb::math::Vec3<double>(3.3,4.4,5.5), openvdb::math::Vec3<double>(5.5,6.6,7.7), openvdb::math::Vec3<double>(7.7,8.8,9.9), openvdb::math::Vec3<double>(7.7,8.8,9.9), openvdb::math::Vec3<double>(9.9,-1.1,-2.2), openvdb::math::Vec3<double>(-2.2,-3.3,-4.4), openvdb::math::Vec3<double>(-4.3,-5.5,-6.6), openvdb::math::Vec3<double>(-7.1,8.5,-9.9), }, // in { openvdb::math::Vec3<double>(1.1,2.2,3.3) + openvdb::math::Vec3<double>(1.1,2.3,4.3), openvdb::math::Vec3<double>(3.3,4.4,5.5) - openvdb::math::Vec3<double>(1.1,2.3,4.3), openvdb::math::Vec3<double>(5.5,6.6,7.7) * openvdb::math::Vec3<double>(1.1,2.3,4.3), openvdb::math::Vec3<double>(7.7,8.8,9.9) / openvdb::math::Vec3<double>(1.1,2.3,4.3), openvdb::math::Vec3<double>(std::fmod(7.7,1.1), std::fmod(8.8,2.3), std::fmod(9.9,4.3)), openvdb::math::Vec3<double>(1.1, 2.3, 4.3) + openvdb::math::Vec3<double>(4.1, 5.3, 6.3), openvdb::math::Vec3<double>(-2.2,-3.3,-4.4) + openvdb::math::Vec3<double>(-4.3,-5.5,-6.6), openvdb::math::Vec3<double>(-4.3,-5.5,-6.6), openvdb::math::Vec3<double>(-7.1,8.5,-9.9) + openvdb::math::Vec3<double>(4.1, 5.3, 6.3) }); // expected } } }, { "vec4i", { [&](){ mHarness.addAttributes<openvdb::math::Vec4<int32_t>>(names, { openvdb::math::Vec4<int32_t>(1,2,3,4), openvdb::math::Vec4<int32_t>(-1,-2,-3,-4), openvdb::math::Vec4<int32_t>(0,0,0,0), openvdb::math::Vec4<int32_t>(0,0,0,0), openvdb::math::Vec4<int32_t>(0,0,0,0), openvdb::math::Vec4<int32_t>(6,8,10,12), openvdb::math::Vec4<int32_t>(0,0,0,0), openvdb::math::Vec4<int32_t>(0,0,0,0), openvdb::math::Vec4<int32_t>(5,6,7,8) }); }, [&](){ mHarness.addAttributes<openvdb::math::Vec4<int32_t>>(names, { openvdb::math::Vec4<int32_t>(1,2,3,4), openvdb::math::Vec4<int32_t>(4,5,6,7), openvdb::math::Vec4<int32_t>(7,8,9,-1), openvdb::math::Vec4<int32_t>(-1,-2,-3,1), openvdb::math::Vec4<int32_t>(-4,-5,-6,2), openvdb::math::Vec4<int32_t>(4,5,-6,2), openvdb::math::Vec4<int32_t>(-7,-8,-9,3), openvdb::math::Vec4<int32_t>(-1,2,-3,4), openvdb::math::Vec4<int32_t>(-5,6,-7,8) }, // in { openvdb::math::Vec4<int32_t>(2,4,6,8), openvdb::math::Vec4<int32_t>(3,3,3,3), openvdb::math::Vec4<int32_t>(7,16,27,-4), openvdb::math::Vec4<int32_t>(-1,-1,-1,0), openvdb::math::Vec4<int32_t>(0,1,0,2), openvdb::math::Vec4<int32_t>(6,8,10,12), openvdb::math::Vec4<int32_t>(-8,-6,-12,7), openvdb::math::Vec4<int32_t>(-1,2,-3,4), openvdb::math::Vec4<int32_t>(0,12,0,16) }); // expected } } }, { "vec4f", { [&](){ mHarness.addAttributes<openvdb::math::Vec4<float>>(names, { openvdb::math::Vec4<float>(1.1f,2.3f,4.3f,5.4f), openvdb::math::Vec4<float>(-1.1f,-2.3f,-4.3f,-5.4f), openvdb::math::Vec4<float>(0.0f,0.0f,0.0f,0.0f), openvdb::math::Vec4<float>(0.0f,0.0f,0.0f,0.0f), openvdb::math::Vec4<float>(0.0f,0.0f,0.0f,0.0f), openvdb::math::Vec4<float>(1.1f, 2.3f, 4.3f, 5.4f) + openvdb::math::Vec4<float>(5.1f, 6.3f, 7.3f, 8.4f), openvdb::math::Vec4<float>(0.0f,0.0f,0.0f,0.0f), openvdb::math::Vec4<float>(0.0f,0.0f,0.0f,0.0f), openvdb::math::Vec4<float>(5.1f, 6.3f, 7.3f, 8.4f) }); }, [&](){ mHarness.addAttributes<openvdb::math::Vec4<float>>(names, { openvdb::math::Vec4<float>(1.1f,2.2f,3.3f,4.4f), openvdb::math::Vec4<float>(3.3f,4.4f,5.5f,6.6f), openvdb::math::Vec4<float>(5.5f,6.6f,7.7f,8.8f), openvdb::math::Vec4<float>(7.7f,8.8f,9.9f,-1.1f), openvdb::math::Vec4<float>(7.7f,8.8f,9.9f,-1.1f), openvdb::math::Vec4<float>(9.9f,-1.1f,-2.2f,-3.3f), openvdb::math::Vec4<float>(-2.2f,-3.3f,-4.4f,-5.5f), openvdb::math::Vec4<float>(-4.3f,-5.5f,-6.6f,-7.7f), openvdb::math::Vec4<float>(-8.2f,-9.3f,0.6f,-1.7f) }, // in { openvdb::math::Vec4<float>(1.1f,2.2f,3.3f,4.4f) + openvdb::math::Vec4<float>(1.1f,2.3f,4.3f,5.4f), openvdb::math::Vec4<float>(3.3f,4.4f,5.5f,6.6f) - openvdb::math::Vec4<float>(1.1f,2.3f,4.3f,5.4f), openvdb::math::Vec4<float>(5.5f,6.6f,7.7f,8.8f) * openvdb::math::Vec4<float>(1.1f,2.3f,4.3f,5.4f), openvdb::math::Vec4<float>(7.7f,8.8f,9.9f,-1.1f) / openvdb::math::Vec4<float>(1.1f,2.3f,4.3f,5.4f), openvdb::math::Vec4<float>(std::fmod(7.7f,1.1f),std::fmod(8.8f,2.3f),std::fmod(9.9f,4.3f),std::fmod(-1.1f,5.4f)+5.4f), // floored mod openvdb::math::Vec4<float>(1.1f, 2.3f, 4.3f, 5.4f) + openvdb::math::Vec4<float>(5.1f, 6.3f, 7.3f, 8.4f), openvdb::math::Vec4<float>(-2.2f,-3.3f,-4.4f,-5.5f) + openvdb::math::Vec4<float>(-4.3f,-5.5f,-6.6f,-7.7f), openvdb::math::Vec4<float>(-4.3f,-5.5f,-6.6f,-7.7f), openvdb::math::Vec4<float>(-8.2f,-9.3f,0.6f,-1.7f) + openvdb::math::Vec4<float>(5.1f, 6.3f, 7.3f, 8.4f) }); // expected } } }, { "vec4d", { [&](){ mHarness.addAttributes<openvdb::math::Vec4<double>>(names, { openvdb::math::Vec4<double>(1.1,2.3,4.3,5.4), openvdb::math::Vec4<double>(-1.1,-2.3,-4.3,-5.4), openvdb::math::Vec4<double>(0.0,0.0,0.0,0.0), openvdb::math::Vec4<double>(0.0,0.0,0.0,0.0), openvdb::math::Vec4<double>(0.0,0.0,0.0,0.0), openvdb::math::Vec4<double>(1.1, 2.3, 4.3, 5.4) + openvdb::math::Vec4<double>(5.1, 6.3, 7.3, 8.4), openvdb::math::Vec4<double>(0.0,0.0,0.0,0.0), openvdb::math::Vec4<double>(0.0,0.0,0.0,0.0), openvdb::math::Vec4<double>(5.1, 6.3, 7.3, 8.4) }); }, [&](){ mHarness.addAttributes<openvdb::math::Vec4<double>>(names, { openvdb::math::Vec4<double>(1.1,2.2,3.3,4.4), openvdb::math::Vec4<double>(3.3,4.4,5.5,6.6), openvdb::math::Vec4<double>(5.5,6.6,7.7,8.8), openvdb::math::Vec4<double>(7.7,8.8,9.9,-1.1), openvdb::math::Vec4<double>(7.7,8.8,9.9,-1.1), openvdb::math::Vec4<double>(9.9,-1.1,-2.2,-3.3), openvdb::math::Vec4<double>(-2.2,-3.3,-4.4,-5.5), openvdb::math::Vec4<double>(-4.3,-5.5,-6.6,-7.7), openvdb::math::Vec4<double>(-8.2,-9.3,0.6,-1.7) }, // in { openvdb::math::Vec4<double>(1.1,2.2,3.3,4.4) + openvdb::math::Vec4<double>(1.1,2.3,4.3,5.4), openvdb::math::Vec4<double>(3.3,4.4,5.5,6.6) - openvdb::math::Vec4<double>(1.1,2.3,4.3,5.4), openvdb::math::Vec4<double>(5.5,6.6,7.7,8.8) * openvdb::math::Vec4<double>(1.1,2.3,4.3,5.4), openvdb::math::Vec4<double>(7.7,8.8,9.9,-1.1) / openvdb::math::Vec4<double>(1.1,2.3,4.3,5.4), openvdb::math::Vec4<double>(std::fmod(7.7,1.1),std::fmod(8.8,2.3),std::fmod(9.9,4.3),std::fmod(-1.1,5.4)+5.4), // floored mod openvdb::math::Vec4<double>(1.1, 2.3, 4.3, 5.4) + openvdb::math::Vec4<double>(5.1, 6.3, 7.3, 8.4), openvdb::math::Vec4<double>(-2.2,-3.3,-4.4,-5.5) + openvdb::math::Vec4<double>(-4.3,-5.5,-6.6,-7.7), openvdb::math::Vec4<double>(-4.3,-5.5,-6.6,-7.7), openvdb::math::Vec4<double>(-8.2,-9.3,0.6,-1.7) + openvdb::math::Vec4<double>(5.1, 6.3, 7.3, 8.4) }); // expected } } } }; for (const auto& expc : expected) { for (const auto& test : expc.second) { mHarness.reset(); test.operator()(); this->execute("assign_compound." + expc.first + ".ax"); } } } void TestAssign::compoundMatrixAssignment() { const std::string code = R"( _T1_@test1 += _l1_; _T1_@test2 -= _l1_; _T1_@test3 *= _l1_; _T1_ local1 = _l1_, local2 = _l2_; local1 += local2; _T1_@test4 = local1; _T1_@test5 += _T1_@test6; _T1_@test7 += local2; )"; auto generate = [&](const auto& map) { for (const auto& config : map) { std::string repl = code; unittest_util::replace(repl, "_T1_", config.first); // replace type // replace literal values for (const auto& settings : config.second) { unittest_util::replace(repl, settings.first, settings.second); } this->registerTest(repl, "assign_compound." + config.first + ".ax"); } }; generate(mat3); generate(mat4); const openvdb::math::Mat3<float> m3fl1(1.1f, 2.3f, 4.3f, 5.4f, 6.7f, 7.8f, 9.1f, 4.5f, 8.2f); const openvdb::math::Mat3<float> m3fl2(9.1f, 7.3f,-1.3f, 4.4f,-6.7f, 0.8f, 9.1f,-0.5f, 8.2f); const openvdb::math::Mat3<double> m3dl1(1.1, 2.3, 4.3, 5.4, 6.7, 7.8, 9.1, 4.5, 8.2); const openvdb::math::Mat3<double> m3dl2(9.1, 7.3,-1.3, 4.4,-6.7, 0.8, 9.1,-0.5, 8.2); const openvdb::math::Mat4<float> m4fl1(1.1f, 2.3f, 4.3f, 5.4f, 6.7f, 7.8f, 9.1f, 4.5f, 8.2f, 3.3f, 2.9f, 5.9f, 0.1f, 0.3f, 5.1f, 1.9f); const openvdb::math::Mat4<float> m4fl2(0.1f, 2.3f,-9.3f, 4.5f, -1.7f, 7.8f, 2.1f, 3.3f, 3.3f,-3.3f,-0.3f, 2.5f, 5.1f, 0.5f, 8.1f,-1.7f); const openvdb::math::Mat4<double> m4dl1(1.1, 2.3, 4.3, 5.4, 6.7, 7.8, 9.1, 4.5, 8.2, 3.3, 2.9, 5.9, 0.1, 0.3, 5.1, 1.9); const openvdb::math::Mat4<double> m4dl2(0.1, 2.3,-9.3, 4.5, -1.7, 7.8, 2.1, 3.3, 3.3,-3.3,-0.3, 2.5, 5.1, 0.5, 8.1,-1.7); const auto names = unittest_util::nameSequence("test", 7); const std::map<std::string, std::vector<std::function<void()>>> expected = { { "mat3f", { [&](){ mHarness.addAttributes<openvdb::math::Mat3<float>>(names, { m3fl1, -m3fl1, openvdb::math::Mat3<float>::zero(), m3fl1 + m3fl2, openvdb::math::Mat3<float>::zero(), openvdb::math::Mat3<float>::zero(), m3fl2 }); }, [&](){ mHarness.addAttributes<openvdb::math::Mat3<float>>(names, { openvdb::math::Mat3<float>(2.3f, 4.3f, 5.4f, 6.7f, 7.8f, 9.1f, 4.5f, 8.2f, 1.1f), openvdb::math::Mat3<float>(4.3f, 5.4f, 6.7f, 7.8f, 9.1f, 4.5f, 8.2f, 1.1f, 2.3f), openvdb::math::Mat3<float>(5.4f, 6.7f, 7.8f, 9.1f, 4.5f, 8.2f, 1.1f, 2.3f, 4.3f), openvdb::math::Mat3<float>(8.3f, 2.3f, 6.1f, 4.5f, 0.1f, 0.1f, 5.3f, 4.5f, 8.9f), openvdb::math::Mat3<float>(6.7f, 7.8f, 9.1f, 4.5f, 8.2f, 1.1f, 2.3f, 4.3f, 5.4f), openvdb::math::Mat3<float>(7.8f, 9.1f, 4.5f, 8.2f, 1.1f, 2.3f, 4.3f, 5.4f, 6.7f), openvdb::math::Mat3<float>(-6.8f,-8.1f,-4.5f, 5.2f,-1.1f, 2.3f, -0.3f, 5.4f,-3.7f) }, // in { openvdb::math::Mat3<float>(2.3f, 4.3f, 5.4f, 6.7f, 7.8f, 9.1f, 4.5f, 8.2f, 1.1f) + m3fl1, openvdb::math::Mat3<float>(4.3f, 5.4f, 6.7f, 7.8f, 9.1f, 4.5f, 8.2f, 1.1f, 2.3f) - m3fl1, openvdb::math::Mat3<float>(5.4f, 6.7f, 7.8f, 9.1f, 4.5f, 8.2f, 1.1f, 2.3f, 4.3f) * m3fl1, m3fl1 + m3fl2, openvdb::math::Mat3<float>(6.7f, 7.8f, 9.1f, 4.5f, 8.2f, 1.1f, 2.3f, 4.3f, 5.4f) + openvdb::math::Mat3<float>(7.8f, 9.1f, 4.5f, 8.2f, 1.1f, 2.3f, 4.3f, 5.4f, 6.7f), openvdb::math::Mat3<float>(7.8f, 9.1f, 4.5f, 8.2f, 1.1f, 2.3f, 4.3f, 5.4f, 6.7f), openvdb::math::Mat3<float>(-6.8f,-8.1f,-4.5f, 5.2f,-1.1f, 2.3f, -0.3f, 5.4f,-3.7f) + m3fl2 }); // expected } } }, { "mat3d", { [&](){ mHarness.addAttributes<openvdb::math::Mat3<double>>(names, { m3dl1, -m3dl1, openvdb::math::Mat3<double>::zero(), m3dl1 + m3dl2, openvdb::math::Mat3<double>::zero(), openvdb::math::Mat3<double>::zero(), m3dl2 }); }, [&](){ mHarness.addAttributes<openvdb::math::Mat3<double>>(names, { openvdb::math::Mat3<double>(2.3, 4.3, 5.4, 6.7, 7.8, 9.1, 4.5, 8.2, 1.1), openvdb::math::Mat3<double>(4.3, 5.4, 6.7, 7.8, 9.1, 4.5, 8.2, 1.1, 2.3), openvdb::math::Mat3<double>(5.4, 6.7, 7.8, 9.1, 4.5, 8.2, 1.1, 2.3, 4.3), openvdb::math::Mat3<double>(8.3, 2.3, 6.1, 4.5, 0.1, 0.1, 5.3, 4.5, 8.9), openvdb::math::Mat3<double>(6.7, 7.8, 9.1, 4.5, 8.2, 1.1, 2.3, 4.3, 5.4), openvdb::math::Mat3<double>(7.8, 9.1, 4.5, 8.2, 1.1, 2.3, 4.3, 5.4, 6.7), openvdb::math::Mat3<double>(-6.8,-8.1,-4.5, 5.2,-1.1, 2.3, -0.3, 5.4,-3.7) }, // in { openvdb::math::Mat3<double>(2.3, 4.3, 5.4, 6.7, 7.8, 9.1, 4.5, 8.2, 1.1) + m3dl1, openvdb::math::Mat3<double>(4.3, 5.4, 6.7, 7.8, 9.1, 4.5, 8.2, 1.1, 2.3) - m3dl1, openvdb::math::Mat3<double>(5.4, 6.7, 7.8, 9.1, 4.5, 8.2, 1.1, 2.3, 4.3) * m3dl1, m3dl1 + m3dl2, openvdb::math::Mat3<double>(6.7, 7.8, 9.1, 4.5, 8.2, 1.1, 2.3, 4.3, 5.4) + openvdb::math::Mat3<double>(7.8, 9.1, 4.5, 8.2, 1.1, 2.3, 4.3, 5.4, 6.7), openvdb::math::Mat3<double>(7.8, 9.1, 4.5, 8.2, 1.1, 2.3, 4.3, 5.4, 6.7), openvdb::math::Mat3<double>(-6.8,-8.1,-4.5, 5.2,-1.1, 2.3, -0.3, 5.4,-3.7) + m3dl2 }); // expected } } }, { "mat4f", { [&](){ mHarness.addAttributes<openvdb::math::Mat4<float>>(names, { m4fl1, -m4fl1, openvdb::math::Mat4<float>::zero(), m4fl1 + m4fl2, openvdb::math::Mat4<float>::zero(), openvdb::math::Mat4<float>::zero(), m4fl2 }); }, [&](){ mHarness.addAttributes<openvdb::math::Mat4<float>>(names, { openvdb::math::Mat4<float>(2.3f,-4.3f, 5.4f, 6.7f, 7.8f,-9.1f, 4.5f, 8.2f, 1.1f,-5.4f,-6.7f, 7.8f, 6.7f, 7.8f, 9.1f,-2.4f), openvdb::math::Mat4<float>(4.3f,-5.4f, 6.7f, 7.8f, 9.1f, 4.5f, 8.2f, 1.1f, 2.3f, 6.7f, 7.8f, 9.1f, -1.3f,-0.1f, 1.1f, 0.9f), openvdb::math::Mat4<float>(5.4f, 6.7f, 7.8f, 9.1f, -4.5f, 8.2f, 1.1f,-2.3f, -4.3f,-7.8f, 9.1f, 4.5f, -6.7f, 2.2f,-7.1f, 1.1f), openvdb::math::Mat4<float>(1.2f, 5.1f, 8.2f, 3.1f, -3.3f, -7.3f, 0.2f,-0.1f, 1.4f, 0.8f, 8.8f,-1.1f, -7.8f, 4.1f, 4.4f, -4.7f), openvdb::math::Mat4<float>(5.4f, 6.7f, 8.2f, 1.1f, -2.3f, -4.3f, 2.2f,-7.1f, 1.1f, 7.8f, 9.1f,-4.5f, -7.8f, 9.1f, 4.5f, -6.7f), openvdb::math::Mat4<float>(8.2f, 1.1f, 6.3f,-4.3f, 9.1f, -4.5f,-7.8f, 9.1f, 4.5f, 6.7f,-5.4f, 6.7f, 2.2f,-7.1f, 1.1f, 7.8f), openvdb::math::Mat4<float>(4.3f,-5.1f,-5.3f, 2.2f, 2.1f, -4.2f, 2.3f,-1.1f, 0.5f, 0.7f, 1.3f, 0.7f, -1.2f, 3.4f, 9.9f, 9.8f), }, // in { openvdb::math::Mat4<float>(2.3f,-4.3f, 5.4f, 6.7f, 7.8f,-9.1f, 4.5f, 8.2f, 1.1f,-5.4f,-6.7f, 7.8f, 6.7f, 7.8f, 9.1f,-2.4f) + m4fl1, openvdb::math::Mat4<float>(4.3f,-5.4f, 6.7f, 7.8f, 9.1f, 4.5f, 8.2f, 1.1f, 2.3f, 6.7f, 7.8f, 9.1f, -1.3f,-0.1f, 1.1f, 0.9f) - m4fl1, openvdb::math::Mat4<float>(5.4f, 6.7f, 7.8f, 9.1f, -4.5f, 8.2f, 1.1f,-2.3f, -4.3f,-7.8f, 9.1f, 4.5f, -6.7f, 2.2f,-7.1f, 1.1f) * m4fl1, m4fl1 + m4fl2, openvdb::math::Mat4<float>(5.4f, 6.7f, 8.2f, 1.1f, -2.3f, -4.3f, 2.2f,-7.1f, 1.1f, 7.8f, 9.1f,-4.5f, -7.8f, 9.1f, 4.5f, -6.7f) + openvdb::math::Mat4<float>(8.2f, 1.1f, 6.3f,-4.3f, 9.1f, -4.5f,-7.8f, 9.1f, 4.5f, 6.7f,-5.4f, 6.7f, 2.2f,-7.1f, 1.1f, 7.8f), openvdb::math::Mat4<float>(8.2f, 1.1f, 6.3f,-4.3f, 9.1f, -4.5f,-7.8f, 9.1f, 4.5f, 6.7f,-5.4f, 6.7f, 2.2f,-7.1f, 1.1f, 7.8f), openvdb::math::Mat4<float>(4.3f,-5.1f,-5.3f, 2.2f, 2.1f, -4.2f, 2.3f,-1.1f, 0.5f, 0.7f, 1.3f, 0.7f, -1.2f, 3.4f, 9.9f, 9.8f) + m4fl2 }); // expected } } }, { "mat4d", { [&](){ mHarness.addAttributes<openvdb::math::Mat4<double>>(names, { m4dl1, -m4dl1, openvdb::math::Mat4<double>::zero(), m4dl1 + m4dl2, openvdb::math::Mat4<double>::zero(), openvdb::math::Mat4<double>::zero(), m4dl2 }); }, [&](){ mHarness.addAttributes<openvdb::math::Mat4<double>>(names, { openvdb::math::Mat4<double>(2.3,-4.3, 5.4, 6.7, 7.8,-9.1, 4.5, 8.2, 1.1,-5.4,-6.7, 7.8, 6.7, 7.8, 9.1,-2.4), openvdb::math::Mat4<double>(4.3,-5.4, 6.7, 7.8, 9.1, 4.5, 8.2, 1.1, 2.3, 6.7, 7.8, 9.1, -1.3,-0.1, 1.1, 0.9), openvdb::math::Mat4<double>(5.4, 6.7, 7.8, 9.1, -4.5, 8.2, 1.1,-2.3, -4.3,-7.8, 9.1, 4.5, -6.7, 2.2,-7.1, 1.1), openvdb::math::Mat4<double>(1.2, 5.1, 8.2, 3.1, -3.3, -7.3, 0.2,-0.1, 1.4, 0.8, 8.8,-1.1, -7.8, 4.1, 4.4, -4.7), openvdb::math::Mat4<double>(5.4, 6.7, 8.2, 1.1, -2.3, -4.3, 2.2,-7.1, 1.1, 7.8, 9.1,-4.5, -7.8, 9.1, 4.5, -6.7), openvdb::math::Mat4<double>(8.2, 1.1, 6.3,-4.3, 9.1, -4.5,-7.8, 9.1, 4.5, 6.7,-5.4, 6.7, 2.2,-7.1, 1.1, 7.8), openvdb::math::Mat4<double>(4.3,-5.1,-5.3, 2.2, 2.1, -4.2, 2.3,-1.1, 0.5, 0.7, 1.3, 0.7, -1.2, 3.4, 9.9, 9.8), }, // in { openvdb::math::Mat4<double>(2.3,-4.3, 5.4, 6.7, 7.8,-9.1, 4.5, 8.2, 1.1,-5.4,-6.7, 7.8, 6.7, 7.8, 9.1,-2.4) + m4dl1, openvdb::math::Mat4<double>(4.3,-5.4, 6.7, 7.8, 9.1, 4.5, 8.2, 1.1, 2.3, 6.7, 7.8, 9.1, -1.3,-0.1, 1.1, 0.9) - m4dl1, openvdb::math::Mat4<double>(5.4, 6.7, 7.8, 9.1, -4.5, 8.2, 1.1,-2.3, -4.3,-7.8, 9.1, 4.5, -6.7, 2.2,-7.1, 1.1) * m4dl1, m4dl1 + m4dl2, openvdb::math::Mat4<double>(5.4, 6.7, 8.2, 1.1, -2.3, -4.3, 2.2,-7.1, 1.1, 7.8, 9.1,-4.5, -7.8, 9.1, 4.5, -6.7) + openvdb::math::Mat4<double>(8.2, 1.1, 6.3,-4.3, 9.1, -4.5,-7.8, 9.1, 4.5, 6.7,-5.4, 6.7, 2.2,-7.1, 1.1, 7.8), openvdb::math::Mat4<double>(8.2, 1.1, 6.3,-4.3, 9.1, -4.5,-7.8, 9.1, 4.5, 6.7,-5.4, 6.7, 2.2,-7.1, 1.1, 7.8), openvdb::math::Mat4<double>(4.3,-5.1,-5.3, 2.2, 2.1, -4.2, 2.3,-1.1, 0.5, 0.7, 1.3, 0.7, -1.2, 3.4, 9.9, 9.8) + m4dl2 }); // expected } } } }; for (const auto& expc : expected) { for (const auto& test : expc.second) { mHarness.reset(); test.operator()(); this->execute("assign_compound." + expc.first + ".ax"); } } } void TestAssign::compoundStringAssignment() { const std::string code = R"( _T1_@test1 += _l1_; _T1_ local1 = _l1_, local2 = _l2_; // test default init and empty string string empty = ""; string defaultstr; local1 += local2; defaultstr += local1; defaultstr += empty; _T1_@test2 = defaultstr; _T1_@test3 += _T1_@test4; _T1_@test5 += local2; )"; auto generate = [&](const auto& map) { for (const auto& config : map) { std::string repl = code; unittest_util::replace(repl, "_T1_", config.first); // replace type // replace literal values for (const auto& settings : config.second) { unittest_util::replace(repl, settings.first, settings.second); } this->registerTest(repl, "assign_compound." + config.first + ".ax"); } }; generate(string); const auto names = unittest_util::nameSequence("test", 5); const std::map<std::string, std::vector<std::function<void()>>> expected = { { "string", { [&](){ mHarness.addAttributes<std::string>(names, { "foo", "foobar", "", "", "bar" }); }, [&](){ mHarness.addAttributes<std::string>(names, { "abc ", "xyz", " 123", "4560", " " }, // in { "abc foo", "foobar", " 1234560", "4560", " bar" }); // expected }, } } }; for (const auto& expc : expected) { for (const auto& test : expc.second) { mHarness.reset(); test.operator()(); this->execute("assign_compound." + expc.first + ".ax"); } } } void TestAssign::implicitScalarAssignment() { auto generate = [this](const auto& source, const auto& targets) { for (const auto& t1 : source) { std::string code = "_T1_ local = _l1_;\n"; unittest_util::replace(code, "_T1_", t1.first); unittest_util::replace(code, "_l1_", t1.second.at("_l1_")); for (const auto& target : targets) { for (const auto& t2 : *target) { if (t1.first == t2.first) continue; std::string tmp = "_T2_@_A1_ = local;"; unittest_util::replace(tmp, "_A1_", "test" + t2.first); unittest_util::replace(tmp, "_T2_", t2.first); code += tmp + "\n"; } } this->registerTest(code, "assign_implicit_scalar." + t1.first + ".ax"); } }; // source -> dest generate(integral, std::vector<decltype(integral)*>{ &integral, &floating }); generate(floating, std::vector<decltype(integral)*>{ &integral, &floating }); // source -> dest const std::map<std::string, std::function<void()>> expected = { { "bool", [&](){ mHarness.addAttribute<int32_t>("testint32", 1); mHarness.addAttribute<int64_t>("testint64", 1); mHarness.addAttribute<float>("testfloat", 1.0f); mHarness.addAttribute<double>("testdouble", 1.0); } }, { "int32", [&](){ mHarness.addAttribute<bool>("testbool", true); mHarness.addAttribute<int64_t>("testint64", 2); mHarness.addAttribute<float>("testfloat", 2.0f); mHarness.addAttribute<double>("testdouble", 2.0); } }, { "int64", [&](){ mHarness.addAttribute<bool>("testbool", true); mHarness.addAttribute<int32_t>("testint32", 2); mHarness.addAttribute<float>("testfloat", 2.0f); mHarness.addAttribute<double>("testdouble", 2.0); } }, { "float", [&](){ mHarness.addAttribute<bool>("testbool", true); mHarness.addAttribute<int32_t>("testint32", 1); mHarness.addAttribute<int64_t>("testint64", 1); mHarness.addAttribute<double>("testdouble", double(1.1f)); } }, { "double", [&](){ mHarness.addAttribute<bool>("testbool", true); mHarness.addAttribute<int32_t>("testint32", 1); mHarness.addAttribute<int64_t>("testint64", 1); mHarness.addAttribute<float>("testfloat", float(1.1)); } } }; for (const auto& expc : expected) { mHarness.reset(); expc.second.operator()(); this->execute("assign_implicit_scalar." + expc.first + ".ax"); } } void TestAssign::implicitContainerAssignment() { auto generate = [this](const auto& source, const auto& target) { for (const auto& t1 : source) { std::string code = "_T1_ local = _l1_;\n"; unittest_util::replace(code, "_T1_", t1.first); unittest_util::replace(code, "_l1_", t1.second.at("_l1_")); for (const auto& t2 : target) { if (t1.first == t2.first) continue; std::string tmp = "_T2_@_A1_ = local;"; unittest_util::replace(tmp, "_A1_", "test" + t2.first); unittest_util::replace(tmp, "_T2_", t2.first); code += tmp + "\n"; } this->registerTest(code, "assign_implicit_container." + t1.first + ".ax"); } }; // source -> dest generate(vec2, vec2); generate(vec3, vec3); generate(vec4, vec4); generate(mat3, mat3); generate(mat4, mat4); // test name is the source type in use. source -> dest const std::map<std::string, std::function<void()>> expected = { { "vec2i", [&]() { mHarness.addAttribute<openvdb::math::Vec2<float>>("testvec2f", openvdb::math::Vec2<float>(1.0f,2.0f)); mHarness.addAttribute<openvdb::math::Vec2<double>>("testvec2d", openvdb::math::Vec2<double>(1.0,2.0)); } }, { "vec2f", [&]() { mHarness.addAttribute<openvdb::math::Vec2<int32_t>>("testvec2i", openvdb::math::Vec2<int32_t>(1,2)); mHarness.addAttribute<openvdb::math::Vec2<double>>("testvec2d", openvdb::math::Vec2<double>(double(1.1f),double(2.3f))); } }, { "vec2d", [&]() { mHarness.addAttribute<openvdb::math::Vec2<int32_t>>("testvec2i", openvdb::math::Vec2<int32_t>(1,2)); mHarness.addAttribute<openvdb::math::Vec2<float>>("testvec2f", openvdb::math::Vec2<float>(float(1.1),float(2.3))); } }, { "vec3i", [&]() { mHarness.addAttribute<openvdb::math::Vec3<float>>("testvec3f", openvdb::math::Vec3<float>(1.0f,2.0f,3.0f)); mHarness.addAttribute<openvdb::math::Vec3<double>>("testvec3d", openvdb::math::Vec3<double>(1.0,2.0,3.0)); } }, { "vec3f", [&]() { mHarness.addAttribute<openvdb::math::Vec3<int32_t>>("testvec3i", openvdb::math::Vec3<int32_t>(1,2,4)); mHarness.addAttribute<openvdb::math::Vec3<double>>("testvec3d", openvdb::math::Vec3<double>(double(1.1f),double(2.3f),double(4.3f))); } }, { "vec3d", [&]() { mHarness.addAttribute<openvdb::math::Vec3<int32_t>>("testvec3i", openvdb::math::Vec3<int32_t>(1,2,4)); mHarness.addAttribute<openvdb::math::Vec3<float>>("testvec3f", openvdb::math::Vec3<float>(float(1.1),float(2.3),float(4.3))); } }, { "vec4i", [&]() { mHarness.addAttribute<openvdb::math::Vec4<float>>("testvec4f", openvdb::math::Vec4<float>(1.0f,2.0f,3.0f,4.0f)); mHarness.addAttribute<openvdb::math::Vec4<double>>("testvec4d", openvdb::math::Vec4<double>(1.0,2.0,3.0,4.0)); } }, { "vec4f", [&]() { mHarness.addAttribute<openvdb::math::Vec4<int32_t>>("testvec4i", openvdb::math::Vec4<int32_t>(1,2,4,5)); mHarness.addAttribute<openvdb::math::Vec4<double>>("testvec4d", openvdb::math::Vec4<double>(double(1.1f),double(2.3f),double(4.3f),double(5.4f))); } }, { "vec4d", [&]() { mHarness.addAttribute<openvdb::math::Vec4<int32_t>>("testvec4i", openvdb::math::Vec4<int32_t>(1,2,4,5)); mHarness.addAttribute<openvdb::math::Vec4<float>>("testvec4f", openvdb::math::Vec4<float>(float(1.1),float(2.3),float(4.3),float(5.4))); } }, { "mat3f", [&](){ mHarness.addAttribute<openvdb::math::Mat3<double>>("testmat3d", openvdb::math::Mat3<double>( double(1.1f),double(2.3f),double(4.3f), double(5.4f),double(6.7f),double(7.8f), double(9.1f),double(4.5f),double(8.2f))); } }, { "mat3d", [&](){ mHarness.addAttribute<openvdb::math::Mat3<float>>("testmat3f", openvdb::math::Mat3<float>( float(1.1),float(2.3),float(4.3), float(5.4),float(6.7),float(7.8), float(9.1),float(4.5),float(8.2))); } }, { "mat4f", [&](){ mHarness.addAttribute<openvdb::math::Mat4<double>>("testmat4d", openvdb::math::Mat4<double>( double(1.1f),double(2.3f),double(4.3f),double(5.4f), double(6.7f),double(7.8f),double(9.1f),double(4.5f), double(8.2f),double(3.3f),double(2.9f),double(5.9f), double(0.1f),double(0.3f),double(5.1f),double(1.9f))); } }, { "mat4d", [&](){ mHarness.addAttribute<openvdb::math::Mat4<float>>("testmat4f", openvdb::math::Mat4<float>( float(1.1),float(2.3),float(4.3),float(5.4), float(6.7),float(7.8),float(9.1),float(4.5), float(8.2),float(3.3),float(2.9),float(5.9), float(0.1),float(0.3),float(5.1),float(1.9))); } } }; for (const auto& expc : expected) { mHarness.reset(); expc.second.operator()(); this->execute("assign_implicit_container." + expc.first + ".ax"); } } void TestAssign::implicitContainerScalarAssignment() { auto generate = [this](const auto& source, const auto& targets) { for (const auto& t1 : source) { std::string code = "_T1_ local = _l1_;\n"; unittest_util::replace(code, "_T1_", t1.first); unittest_util::replace(code, "_l1_", t1.second.at("_l1_")); for (const auto& target : targets) { for (const auto& t2 : *target) { if (t1.first == t2.first) continue; std::string tmp = "_T2_@_A1_ = local;"; unittest_util::replace(tmp, "_A1_", "test" + t2.first); unittest_util::replace(tmp, "_T2_", t2.first); code += tmp + "\n"; } } this->registerTest(code, "assign_implicit_container_scalar." + t1.first + ".ax"); } }; generate(integral, std::vector<decltype(integral)*>{ &vec2, &vec3, &vec4, &mat3, &mat4 }); generate(floating, std::vector<decltype(integral)*>{ &vec2, &vec3, &vec4, &mat3, &mat4 }); auto symmetric3 = [](auto val) -> openvdb::math::Mat3<decltype(val)> { openvdb::math::Mat3<decltype(val)> mat; mat.setZero(); mat(0,0) = val; mat(1,1) = val; mat(2,2) = val; return mat; }; auto symmetric4 = [](auto val) -> openvdb::math::Mat4<decltype(val)> { openvdb::math::Mat4<decltype(val)> mat; mat.setZero(); mat(0,0) = val; mat(1,1) = val; mat(2,2) = val; mat(3,3) = val; return mat; }; const std::map<std::string, std::function<void()>> expected = { { "bool", [&]() { mHarness.addAttribute<openvdb::math::Vec2<int32_t>>("testvec2i", openvdb::math::Vec2<int32_t>(1,1)); mHarness.addAttribute<openvdb::math::Vec2<float>>("testvec2f", openvdb::math::Vec2<float>(1.0f,1.0f)); mHarness.addAttribute<openvdb::math::Vec2<double>>("testvec2d", openvdb::math::Vec2<double>(1.0,1.0)); mHarness.addAttribute<openvdb::math::Vec3<int32_t>>("testvec3i", openvdb::math::Vec3<int32_t>(1,1,1)); mHarness.addAttribute<openvdb::math::Vec3<float>>("testvec3f", openvdb::math::Vec3<float>(1.0f,1.0f,1.0f)); mHarness.addAttribute<openvdb::math::Vec3<double>>("testvec3d", openvdb::math::Vec3<double>(1.0,1.0,1.0)); mHarness.addAttribute<openvdb::math::Vec4<int32_t>>("testvec4i", openvdb::math::Vec4<int32_t>(1,1,1,1)); mHarness.addAttribute<openvdb::math::Vec4<float>>("testvec4f", openvdb::math::Vec4<float>(1.0f,1.0f,1.0f,1.0f)); mHarness.addAttribute<openvdb::math::Vec4<double>>("testvec4d", openvdb::math::Vec4<double>(1.0,1.0,1.0,1.0)); mHarness.addAttribute<openvdb::math::Mat3<float>>("testmat3f", symmetric3(1.0f)); mHarness.addAttribute<openvdb::math::Mat3<double>>("testmat3d", symmetric3(1.0)); mHarness.addAttribute<openvdb::math::Mat4<float>>("testmat4f", symmetric4(1.0f)); mHarness.addAttribute<openvdb::math::Mat4<double>>("testmat4d", symmetric4(1.0)); } }, { "int32", [&](){ mHarness.addAttribute<openvdb::math::Vec2<int32_t>>("testvec2i", openvdb::math::Vec2<int32_t>(2,2)); mHarness.addAttribute<openvdb::math::Vec2<double>>("testvec2d", openvdb::math::Vec2<double>(2.0,2.0)); mHarness.addAttribute<openvdb::math::Vec2<float>>("testvec2f", openvdb::math::Vec2<float>(2.0f,2.0f)); mHarness.addAttribute<openvdb::math::Vec3<int32_t>>("testvec3i", openvdb::math::Vec3<int32_t>(2,2,2)); mHarness.addAttribute<openvdb::math::Vec3<double>>("testvec3d", openvdb::math::Vec3<double>(2.0,2.0,2.0)); mHarness.addAttribute<openvdb::math::Vec3<float>>("testvec3f", openvdb::math::Vec3<float>(2.0f,2.0f,2.0f)); mHarness.addAttribute<openvdb::math::Vec4<int32_t>>("testvec4i", openvdb::math::Vec4<int32_t>(2,2,2,2)); mHarness.addAttribute<openvdb::math::Vec4<double>>("testvec4d", openvdb::math::Vec4<double>(2.0,2.0,2.0,2.0)); mHarness.addAttribute<openvdb::math::Vec4<float>>("testvec4f", openvdb::math::Vec4<float>(2.0f,2.0f,2.0f,2.0f)); mHarness.addAttribute<openvdb::math::Mat3<float>>("testmat3f", symmetric3(2.0f)); mHarness.addAttribute<openvdb::math::Mat3<double>>("testmat3d", symmetric3(2.0)); mHarness.addAttribute<openvdb::math::Mat4<float>>("testmat4f", symmetric4(2.0f)); mHarness.addAttribute<openvdb::math::Mat4<double>>("testmat4d", symmetric4(2.0)); } }, { "int64", [&](){ mHarness.addAttribute<openvdb::math::Vec2<int32_t>>("testvec2i", openvdb::math::Vec2<int32_t>(2,2)); mHarness.addAttribute<openvdb::math::Vec2<double>>("testvec2d", openvdb::math::Vec2<double>(2.0,2.0)); mHarness.addAttribute<openvdb::math::Vec2<float>>("testvec2f", openvdb::math::Vec2<float>(2.0f,2.0f)); mHarness.addAttribute<openvdb::math::Vec3<int32_t>>("testvec3i", openvdb::math::Vec3<int32_t>(2,2,2)); mHarness.addAttribute<openvdb::math::Vec3<double>>("testvec3d", openvdb::math::Vec3<double>(2.0,2.0,2.0)); mHarness.addAttribute<openvdb::math::Vec3<float>>("testvec3f", openvdb::math::Vec3<float>(2.0f,2.0f,2.0f)); mHarness.addAttribute<openvdb::math::Vec4<int32_t>>("testvec4i", openvdb::math::Vec4<int32_t>(2,2,2,2)); mHarness.addAttribute<openvdb::math::Vec4<double>>("testvec4d", openvdb::math::Vec4<double>(2.0,2.0,2.0,2.0)); mHarness.addAttribute<openvdb::math::Vec4<float>>("testvec4f", openvdb::math::Vec4<float>(2.0f,2.0f,2.0f,2.0f)); mHarness.addAttribute<openvdb::math::Mat3<float>>("testmat3f", symmetric3(2.0f)); mHarness.addAttribute<openvdb::math::Mat3<double>>("testmat3d", symmetric3(2.0)); mHarness.addAttribute<openvdb::math::Mat4<float>>("testmat4f", symmetric4(2.0f)); mHarness.addAttribute<openvdb::math::Mat4<double>>("testmat4d", symmetric4(2.0)); } }, { "float", [&](){ mHarness.addAttribute<openvdb::math::Vec2<int32_t>>("testvec2i", openvdb::math::Vec2<int32_t>(1,1)); mHarness.addAttribute<openvdb::math::Vec2<double>>("testvec2d", openvdb::math::Vec2<double>(double(1.1f),double(1.1f))); mHarness.addAttribute<openvdb::math::Vec2<float>>("testvec2f", openvdb::math::Vec2<float>(1.1f,1.1f)); mHarness.addAttribute<openvdb::math::Vec3<int32_t>>("testvec3i", openvdb::math::Vec3<int32_t>(1,1,1)); mHarness.addAttribute<openvdb::math::Vec3<double>>("testvec3d", openvdb::math::Vec3<double>(double(1.1f),double(1.1f),double(1.1f))); mHarness.addAttribute<openvdb::math::Vec3<float>>("testvec3f", openvdb::math::Vec3<float>(1.1f,1.1f,1.1f)); mHarness.addAttribute<openvdb::math::Vec4<int32_t>>("testvec4i", openvdb::math::Vec4<int32_t>(1,1,1,1)); mHarness.addAttribute<openvdb::math::Vec4<double>>("testvec4d", openvdb::math::Vec4<double>(double(1.1f),double(1.1f),double(1.1f),double(1.1f))); mHarness.addAttribute<openvdb::math::Vec4<float>>("testvec4f", openvdb::math::Vec4<float>(1.1f,1.1f,1.1f,1.1f)); mHarness.addAttribute<openvdb::math::Mat3<float>>("testmat3f", symmetric3(1.1f)); mHarness.addAttribute<openvdb::math::Mat3<double>>("testmat3d", symmetric3(double(1.1f))); mHarness.addAttribute<openvdb::math::Mat4<float>>("testmat4f", symmetric4(1.1f)); mHarness.addAttribute<openvdb::math::Mat4<double>>("testmat4d", symmetric4(double(1.1f))); } }, { "double", [&](){ mHarness.addAttribute<openvdb::math::Vec2<int32_t>>("testvec2i", openvdb::math::Vec2<int32_t>(1,1)); mHarness.addAttribute<openvdb::math::Vec2<double>>("testvec2d", openvdb::math::Vec2<double>(1.1,1.1)); mHarness.addAttribute<openvdb::math::Vec2<float>>("testvec2f", openvdb::math::Vec2<float>(float(1.1),float(1.1))); mHarness.addAttribute<openvdb::math::Vec3<int32_t>>("testvec3i", openvdb::math::Vec3<int32_t>(1,1,1)); mHarness.addAttribute<openvdb::math::Vec3<double>>("testvec3d", openvdb::math::Vec3<double>(1.1,1.1,1.1)); mHarness.addAttribute<openvdb::math::Vec3<float>>("testvec3f", openvdb::math::Vec3<float>(float(1.1),float(1.1),float(1.1))); mHarness.addAttribute<openvdb::math::Vec4<int32_t>>("testvec4i", openvdb::math::Vec4<int32_t>(1,1,1,1)); mHarness.addAttribute<openvdb::math::Vec4<double>>("testvec4d", openvdb::math::Vec4<double>(1.1,1.1,1.1,1.1)); mHarness.addAttribute<openvdb::math::Vec4<float>>("testvec4f", openvdb::math::Vec4<float>(float(1.1),float(1.1),float(1.1),float(1.1))); mHarness.addAttribute<openvdb::math::Mat3<float>>("testmat3f", symmetric3(float(1.1))); mHarness.addAttribute<openvdb::math::Mat3<double>>("testmat3d", symmetric3(1.1)); mHarness.addAttribute<openvdb::math::Mat4<float>>("testmat4f", symmetric4(float(1.1))); mHarness.addAttribute<openvdb::math::Mat4<double>>("testmat4d", symmetric4(1.1)); } } }; for (const auto& expc : expected) { mHarness.reset(); expc.second.operator()(); this->execute("assign_implicit_container_scalar." + expc.first + ".ax"); } } void TestAssign::scopedAssign() { const std::string code = R"( float var = 30.0f; { float var = 3.0f; } { float var = 1.0f; float@test2 = var; { float var = -10.0f; float@test3 = var; } { float@test7 = var; } } { float var = -100.0f; } { float var = 50.0f; { float var = -15.0f; float@test4 = var; } { float var = -10.0f; } { float@test5 = var; } float@test6 = var; } float@test1 = var; )"; this->registerTest(code, "assign_scoped.float.ax"); const auto names = unittest_util::nameSequence("test", 7); mHarness.addAttributes<float>(names, {30.0f, 1.0f, -10.0f, -15.0f, 50.0f, 50.0f, 1.0f}); this->execute("assign_scoped.float.ax"); CPPUNIT_ASSERT(mHarness.mLogger.hasWarning()); }
NVIDIA-Omniverse/ext-openvdb/openvdb_ax/openvdb_ax/test/integration/TestKeyword.cc
// Copyright Contributors to the OpenVDB Project // SPDX-License-Identifier: MPL-2.0 #include "TestHarness.h" #include <cppunit/extensions/HelperMacros.h> using namespace openvdb::points; class TestKeyword : public unittest_util::AXTestCase { public: CPPUNIT_TEST_SUITE(TestKeyword); CPPUNIT_TEST(testKeywordSimpleReturn); CPPUNIT_TEST(testKeywordReturnBranchIf); CPPUNIT_TEST(testKeywordReturnBranchLoop); CPPUNIT_TEST(testKeywordConditionalReturn); CPPUNIT_TEST(testKeywordForLoopKeywords); CPPUNIT_TEST(testKeywordWhileLoopKeywords); CPPUNIT_TEST(testKeywordDoWhileLoopKeywords); CPPUNIT_TEST_SUITE_END(); void testKeywordSimpleReturn(); void testKeywordReturnBranchIf(); void testKeywordReturnBranchLoop(); void testKeywordConditionalReturn(); void testKeywordForLoopKeywords(); void testKeywordWhileLoopKeywords(); void testKeywordDoWhileLoopKeywords(); }; CPPUNIT_TEST_SUITE_REGISTRATION(TestKeyword); void TestKeyword::testKeywordSimpleReturn() { mHarness.addAttribute<int>("return_test0", 0); mHarness.executeCode("test/snippets/keyword/simpleReturn"); AXTESTS_STANDARD_ASSERT(); } void TestKeyword::testKeywordReturnBranchIf() { mHarness.addAttribute<int>("return_test1", 1); mHarness.executeCode("test/snippets/keyword/returnBranchIf"); AXTESTS_STANDARD_ASSERT(); } void TestKeyword::testKeywordReturnBranchLoop() { mHarness.addAttribute<int>("return_test2", 1); mHarness.executeCode("test/snippets/keyword/returnBranchLoop"); AXTESTS_STANDARD_ASSERT(); } void TestKeyword::testKeywordConditionalReturn() { mHarness.addAttribute<int>("return_test3", 3); mHarness.executeCode("test/snippets/keyword/conditionalReturn"); AXTESTS_STANDARD_ASSERT(); } void TestKeyword::testKeywordForLoopKeywords() { mHarness.addAttribute<openvdb::Vec3f>("loop_test4", openvdb::Vec3f(1.0,0.0,0.0)); mHarness.addAttribute<openvdb::Vec3f>("loop_test5", openvdb::Vec3f(1.0,0.0,3.0)); mHarness.addAttribute<openvdb::Vec3f>("loop_test6", openvdb::Vec3f(1.0,2.0,3.0)); mHarness.addAttribute<openvdb::Vec3f>("loop_test7", openvdb::Vec3f(1.0,2.0,3.0)); mHarness.addAttribute<openvdb::Vec3f>("loop_test8", openvdb::Vec3f(1.0,2.0,3.0)); mHarness.addAttribute<openvdb::math::Mat3s>("loop_test19", openvdb::math::Mat3s(1.0,2.0,3.0, 0.0,0.0,0.0, 7.0,8.0,9.0)); mHarness.addAttribute<openvdb::math::Mat3s>("loop_test20", openvdb::math::Mat3s(1.0,0.0,0.0, 0.0,0.0,0.0, 7.0,0.0,0.0)); mHarness.addAttribute<openvdb::math::Mat3s>("loop_test21", openvdb::math::Mat3s(1.0,0.0,3.0, 0.0,0.0,0.0, 7.0,0.0,9.0)); mHarness.addAttribute<openvdb::Vec3f>("return_test4", openvdb::Vec3f(10,10,10)); mHarness.executeCode("test/snippets/keyword/forLoopKeywords"); AXTESTS_STANDARD_ASSERT(); } void TestKeyword::testKeywordWhileLoopKeywords() { mHarness.addAttribute<openvdb::Vec3f>("loop_test10", openvdb::Vec3f(1.0,0.0,0.0)); mHarness.addAttribute<openvdb::Vec3f>("loop_test11", openvdb::Vec3f(0.0,0.0,2.0)); mHarness.addAttribute<openvdb::Vec3f>("return_test6", openvdb::Vec3f(100,100,100)); mHarness.executeCode("test/snippets/keyword/whileLoopKeywords"); AXTESTS_STANDARD_ASSERT(); } void TestKeyword::testKeywordDoWhileLoopKeywords() { mHarness.addAttribute<openvdb::Vec3f>("loop_test13", openvdb::Vec3f(1.0,0.0,0.0)); mHarness.addAttribute<openvdb::Vec3f>("loop_test14", openvdb::Vec3f(0.0,0.0,2.0)); mHarness.addAttribute<openvdb::Vec3f>("return_test7", openvdb::Vec3f(100,100,100)); mHarness.executeCode("test/snippets/keyword/doWhileLoopKeywords"); AXTESTS_STANDARD_ASSERT(); }
NVIDIA-Omniverse/ext-openvdb/openvdb_ax/openvdb_ax/test/integration/TestBinary.cc
// Copyright Contributors to the OpenVDB Project // SPDX-License-Identifier: MPL-2.0 #include "TestHarness.h" #include "../test/util.h" #include <cppunit/extensions/HelperMacros.h> using namespace openvdb::points; // Configuration values for binary code using ConfigMap = std::unordered_map<std::string, std::unordered_map<std::string, std::string>>; static const ConfigMap integral = { { "bool", { { "_L1_", "true" }, { "_L2_", "false" } } }, { "int16", { { "_L1_", "2" }, { "_L2_", "3" } } }, { "int32", { { "_L1_", "2" }, { "_L2_", "3" } } }, { "int64", { { "_L1_", "2l" }, { "_L2_", "3l" } } } }; static const ConfigMap floating = { { "float", { { "_L1_", "1.1f" }, { "_L2_", "2.3f" } } }, { "double", { { "_L1_", "1.1" }, { "_L2_", "2.3" } } } }; static const ConfigMap vec2 = { { "vec2i", { { "_L1_", "{1, 2}" }, { "_L2_", "{3, 4}" } } }, { "vec2f", { { "_L1_", "{1.1f, 2.3f}" }, { "_L2_", "{4.1f, 5.3f}" } } }, { "vec2d", { { "_L1_", "{1.1, 2.3}" }, { "_L2_", "{4.1, 5.3}" } } } }; static const ConfigMap vec3 = { { "vec3i", { { "_L1_", "{1, 2, 3}" }, { "_L2_", "{4, 5, 6}" } } }, { "vec3f", { { "_L1_", "{1.1f, 2.3f, 4.3f}" }, { "_L2_", "{4.1f, 5.3f, 6.3f}" } } }, { "vec3d", { { "_L1_", "{1.1, 2.3 , 4.3}" }, { "_L2_", "{4.1, 5.3, 6.3}" } } } }; static const ConfigMap vec4 = { { "vec4i", { { "_L1_", "{1, 2, 3, 4}" }, { "_L2_", "{5, 6, 7, 8}" } } }, { "vec4f", { { "_L1_", "{1.1f, 2.3f, 4.3f, 5.4f}" }, { "_L2_", "{5.1f, 6.3f, 7.3f, 8.4f}" } } }, { "vec4d", { { "_L1_", "{1.1, 2.3, 4.3, 5.4}" }, { "_L2_", "{5.1, 6.3, 7.3, 8.4}" } } } }; static const ConfigMap mat3 = { { "mat3f", { { "_L1_", "{1.1f, 2.3f, 4.3f, 5.4f, 6.7f, 7.8f, 9.1f, 4.5f, 8.2f }" }, { "_L2_", "{9.1f, 7.3f, -1.3f, 4.4f, -6.7f, 0.8f, 9.1f,-0.5f, 8.2f }" } } }, { "mat3d", { { "_L1_", "{1.1, 2.3, 4.3, 5.4, 6.7, 7.8, 9.1, 4.5, 8.2 }" }, { "_L2_", "{9.1, 7.3, -1.3, 4.4, -6.7, 0.8, 9.1,-0.5, 8.2 }" } } } }; static const ConfigMap mat4 = { { "mat4f", { { "_L1_", "{1.1f, 2.3f, 4.3f, 5.4f, 6.7f, 7.8f, 9.1f, 4.5f, 8.2f, 3.3f, 2.9f, 5.9f, 0.1f, 0.3f, 5.1f, 1.9f}" }, { "_L2_", "{0.1f, 2.3f,-9.3f, 4.5f, -1.7f, 7.8f, 2.1f, 3.3f, 3.3f,-3.3f,-0.3f, 2.5f, 5.1f, 0.5f, 8.1f,-1.7f}" } } }, { "mat4d", { { "_L1_", "{1.1, 2.3, 4.3, 5.4, 6.7, 7.8, 9.1, 4.5, 8.2, 3.3, 2.9, 5.9, 0.1, 0.3, 5.1, 1.9}" }, { "_L2_", "{0.1, 2.3,-9.3, 4.5, -1.7, 7.8, 2.1, 3.3, 3.3,-3.3,-0.3, 2.5, 5.1, 0.5, 8.1,-1.7}" } } } }; static const ConfigMap string = { { "string", { { "_L1_", "\"foo\"" }, { "_L2_", "\"bar\"" } } } }; class TestBinary : public unittest_util::AXTestCase { public: std::string dir() const override { return GET_TEST_DIRECTORY(); } CPPUNIT_TEST_SUITE(TestBinary); CPPUNIT_TEST(plus); CPPUNIT_TEST(minus); CPPUNIT_TEST(mult); CPPUNIT_TEST(div); CPPUNIT_TEST(mod); CPPUNIT_TEST(btand); CPPUNIT_TEST(btor); CPPUNIT_TEST(btxor); CPPUNIT_TEST(logicaland); CPPUNIT_TEST(logicalor); CPPUNIT_TEST(equalsequals); CPPUNIT_TEST(notequals); CPPUNIT_TEST(greaterthan); CPPUNIT_TEST(lessthan); CPPUNIT_TEST(greaterthanequals); CPPUNIT_TEST(lessthanequals); CPPUNIT_TEST(shiftleft); CPPUNIT_TEST(shiftright); CPPUNIT_TEST_SUITE_END(); void plus(); void minus(); void mult(); void div(); void mod(); void btand(); void btor(); void btxor(); void logicaland(); void logicalor(); void equalsequals(); void notequals(); void greaterthan(); void lessthan(); void greaterthanequals(); void lessthanequals(); void shiftleft(); void shiftright(); }; CPPUNIT_TEST_SUITE_REGISTRATION(TestBinary); void TestBinary::plus() { const std::string code = R"( _T1_@_A1_ = _L1_ + _L2_;)"; std::string repl; auto generate = [&](const auto& map) { for (const auto& config : map) { std::string tmp = code; unittest_util::replace(tmp, "_T1_", config.first); unittest_util::replace(tmp, "_A1_", "test" + config.first); for (const auto& settings : config.second) { unittest_util::replace(tmp, settings.first, settings.second); } repl += tmp; } }; generate(integral); generate(floating); generate(vec2); generate(vec3); generate(vec4); generate(mat3); generate(mat4); generate(string); this->registerTest(repl, "binary_plus.ax"); const std::map<std::string, std::function<void()>> expected = { { "bool", [&](){ mHarness.addAttribute<bool>("testbool", true); } }, { "int16", [&](){ mHarness.addAttribute<int16_t>("testint16", 5); } }, { "int32", [&](){ mHarness.addAttribute<int32_t>("testint32", 5); } }, { "int64", [&](){ mHarness.addAttribute<int64_t>("testint64", 5); } }, { "float", [&](){ mHarness.addAttribute<float>("testfloat", 1.1f + 2.3f); } }, { "double", [&](){ mHarness.addAttribute<double>("testdouble", 1.1 + 2.3); } }, { "vec2i", [&](){ mHarness.addAttribute<openvdb::math::Vec2<int32_t>>("testvec2i", openvdb::math::Vec2<int32_t>(4,6)); } }, { "vec2f", [&](){ mHarness.addAttribute<openvdb::math::Vec2<float>>("testvec2f", openvdb::math::Vec2<float>(1.1f+4.1f, 2.3f+5.3f)); } }, { "vec2d", [&](){ mHarness.addAttribute<openvdb::math::Vec2<double>>("testvec2d", openvdb::math::Vec2<double>(1.1+4.1, 2.3+5.3)); } }, { "vec3i", [&](){ mHarness.addAttribute<openvdb::math::Vec3<int32_t>>("testvec3i", openvdb::math::Vec3<int32_t>(5,7,9)); } }, { "vec3f", [&](){ mHarness.addAttribute<openvdb::math::Vec3<float>>("testvec3f", openvdb::math::Vec3<float>(1.1f+4.1f, 2.3f+5.3f, 4.3f+6.3f)); } }, { "vec3d", [&](){ mHarness.addAttribute<openvdb::math::Vec3<double>>("testvec3d", openvdb::math::Vec3<double>(1.1+4.1, 2.3+5.3, 4.3+6.3)); } }, { "vec4i", [&](){ mHarness.addAttribute<openvdb::math::Vec4<int32_t>>("testvec4i", openvdb::math::Vec4<int32_t>(6,8,10,12)); } }, { "vec4f", [&](){ mHarness.addAttribute<openvdb::math::Vec4<float>>("testvec4f", openvdb::math::Vec4<float>(1.1f+5.1f, 2.3f+6.3f, 4.3f+7.3f, 5.4f+8.4f)); } }, { "vec4d", [&](){ mHarness.addAttribute<openvdb::math::Vec4<double>>("testvec4d", openvdb::math::Vec4<double>(1.1+5.1, 2.3+6.3, 4.3+7.3, 5.4+8.4)); } }, { "mat3f", [&](){ mHarness.addAttribute<openvdb::math::Mat3<float>>("testmat3f", openvdb::math::Mat3<float>(1.1f, 2.3f, 4.3f, 5.4f, 6.7f, 7.8f, 9.1f, 4.5f, 8.2f) + openvdb::math::Mat3<float>(9.1f, 7.3f,-1.3f, 4.4f,-6.7f, 0.8f, 9.1f,-0.5f, 8.2f)); } }, { "mat3d", [&](){ mHarness.addAttribute<openvdb::math::Mat3<double>>("testmat3d", openvdb::math::Mat3<double>(1.1, 2.3, 4.3, 5.4, 6.7, 7.8, 9.1, 4.5, 8.2) + openvdb::math::Mat3<double>(9.1, 7.3,-1.3, 4.4,-6.7, 0.8, 9.1,-0.5, 8.2)); } }, { "mat4f", [&](){ mHarness.addAttribute<openvdb::math::Mat4<float>>("testmat4f", openvdb::math::Mat4<float>(1.1f, 2.3f, 4.3f, 5.4f, 6.7f, 7.8f, 9.1f, 4.5f, 8.2f, 3.3f, 2.9f, 5.9f, 0.1f, 0.3f, 5.1f, 1.9f) + openvdb::math::Mat4<float>(0.1f, 2.3f,-9.3f, 4.5f, -1.7f, 7.8f, 2.1f, 3.3f, 3.3f,-3.3f,-0.3f, 2.5f, 5.1f, 0.5f, 8.1f,-1.7f)); } }, { "mat4d", [&](){ mHarness.addAttribute<openvdb::math::Mat4<double>>("testmat4d", openvdb::math::Mat4<double>(1.1, 2.3, 4.3, 5.4, 6.7, 7.8, 9.1, 4.5, 8.2, 3.3, 2.9, 5.9, 0.1, 0.3, 5.1, 1.9) + openvdb::math::Mat4<double>(0.1, 2.3,-9.3, 4.5, -1.7, 7.8, 2.1, 3.3, 3.3,-3.3,-0.3, 2.5, 5.1, 0.5, 8.1,-1.7)); } }, { "string", [&](){ mHarness.addAttribute<std::string>("teststring", "foobar"); } } }; for (const auto& expc : expected) { expc.second.operator()(); } this->execute("binary_plus.ax"); } void TestBinary::minus() { const std::string code = R"( _T1_@_A1_ = _L1_ - _L2_;)"; std::string repl; auto generate = [&](const auto& map) { for (const auto& config : map) { std::string tmp = code; unittest_util::replace(tmp, "_T1_", config.first); unittest_util::replace(tmp, "_A1_", "test" + config.first); for (const auto& settings : config.second) { unittest_util::replace(tmp, settings.first, settings.second); } repl += tmp; } }; generate(integral); generate(floating); generate(vec2); generate(vec3); generate(vec4); generate(mat3); generate(mat4); this->registerTest(repl, "binary_minus.ax"); const std::map<std::string, std::function<void()>> expected = { { "bool", [&](){ mHarness.addAttribute<bool>("testbool", true); } }, { "int16", [&](){ mHarness.addAttribute<int16_t>("testint16", -1); } }, { "int32", [&](){ mHarness.addAttribute<int32_t>("testint32", -1); } }, { "int64", [&](){ mHarness.addAttribute<int64_t>("testint64", -1); } }, { "float", [&](){ mHarness.addAttribute<float>("testfloat", 1.1f - 2.3f); } }, { "double", [&](){ mHarness.addAttribute<double>("testdouble", 1.1 - 2.3); } }, { "vec2i", [&](){ mHarness.addAttribute<openvdb::math::Vec2<int32_t>>("testvec2i", openvdb::math::Vec2<int32_t>(-2,-2)); } }, { "vec2f", [&](){ mHarness.addAttribute<openvdb::math::Vec2<float>>("testvec2f", openvdb::math::Vec2<float>(1.1f-4.1f, 2.3f-5.3f)); } }, { "vec2d", [&](){ mHarness.addAttribute<openvdb::math::Vec2<double>>("testvec2d", openvdb::math::Vec2<double>(1.1-4.1, 2.3-5.3)); } }, { "vec3i", [&](){ mHarness.addAttribute<openvdb::math::Vec3<int32_t>>("testvec3i", openvdb::math::Vec3<int32_t>(-3,-3,-3)); } }, { "vec3f", [&](){ mHarness.addAttribute<openvdb::math::Vec3<float>>("testvec3f", openvdb::math::Vec3<float>(1.1f-4.1f, 2.3f-5.3f, 4.3f-6.3f)); } }, { "vec3d", [&](){ mHarness.addAttribute<openvdb::math::Vec3<double>>("testvec3d", openvdb::math::Vec3<double>(1.1-4.1, 2.3-5.3, 4.3-6.3)); } }, { "vec4i", [&](){ mHarness.addAttribute<openvdb::math::Vec4<int32_t>>("testvec4i", openvdb::math::Vec4<int32_t>(-4,-4,-4,-4)); } }, { "vec4f", [&](){ mHarness.addAttribute<openvdb::math::Vec4<float>>("testvec4f", openvdb::math::Vec4<float>(1.1f-5.1f, 2.3f-6.3f, 4.3f-7.3f, 5.4f-8.4f)); } }, { "vec4d", [&](){ mHarness.addAttribute<openvdb::math::Vec4<double>>("testvec4d", openvdb::math::Vec4<double>(1.1-5.1, 2.3-6.3, 4.3-7.3, 5.4-8.4)); } }, { "mat3f", [&](){ mHarness.addAttribute<openvdb::math::Mat3<float>>("testmat3f", openvdb::math::Mat3<float>(1.1f, 2.3f, 4.3f, 5.4f, 6.7f, 7.8f, 9.1f, 4.5f, 8.2f) - openvdb::math::Mat3<float>(9.1f, 7.3f,-1.3f, 4.4f,-6.7f, 0.8f, 9.1f,-0.5f, 8.2f)); } }, { "mat3d", [&](){ mHarness.addAttribute<openvdb::math::Mat3<double>>("testmat3d", openvdb::math::Mat3<double>(1.1, 2.3, 4.3, 5.4, 6.7, 7.8, 9.1, 4.5, 8.2) - openvdb::math::Mat3<double>(9.1, 7.3,-1.3, 4.4,-6.7, 0.8, 9.1,-0.5, 8.2)); } }, { "mat4f", [&](){ mHarness.addAttribute<openvdb::math::Mat4<float>>("testmat4f", openvdb::math::Mat4<float>(1.1f, 2.3f, 4.3f, 5.4f, 6.7f, 7.8f, 9.1f, 4.5f, 8.2f, 3.3f, 2.9f, 5.9f, 0.1f, 0.3f, 5.1f, 1.9f) - openvdb::math::Mat4<float>(0.1f, 2.3f,-9.3f, 4.5f, -1.7f, 7.8f, 2.1f, 3.3f, 3.3f,-3.3f,-0.3f, 2.5f, 5.1f, 0.5f, 8.1f,-1.7f)); } }, { "mat4d", [&](){ mHarness.addAttribute<openvdb::math::Mat4<double>>("testmat4d", openvdb::math::Mat4<double>(1.1, 2.3, 4.3, 5.4, 6.7, 7.8, 9.1, 4.5, 8.2, 3.3, 2.9, 5.9, 0.1, 0.3, 5.1, 1.9) - openvdb::math::Mat4<double>(0.1, 2.3,-9.3, 4.5, -1.7, 7.8, 2.1, 3.3, 3.3,-3.3,-0.3, 2.5, 5.1, 0.5, 8.1,-1.7)); } }, }; for (const auto& expc : expected) { expc.second.operator()(); } this->execute("binary_minus.ax"); } void TestBinary::mult() { const std::string code = R"( _T1_@_A1_ = _L1_ * _L2_;)"; std::string repl; auto generate = [&](const auto& map) { for (const auto& config : map) { std::string tmp = code; unittest_util::replace(tmp, "_T1_", config.first); unittest_util::replace(tmp, "_A1_", "test" + config.first); for (const auto& settings : config.second) { unittest_util::replace(tmp, settings.first, settings.second); } repl += tmp; } }; generate(integral); generate(floating); generate(vec2); generate(vec3); generate(vec4); generate(mat3); generate(mat4); this->registerTest(repl, "binary_mult.ax"); const std::map<std::string, std::function<void()>> expected = { { "bool", [&](){ mHarness.addAttribute<bool>("testbool", false); } }, { "int16", [&](){ mHarness.addAttribute<int16_t>("testint16", 6); } }, { "int32", [&](){ mHarness.addAttribute<int32_t>("testint32", 6); } }, { "int64", [&](){ mHarness.addAttribute<int64_t>("testint64", 6); } }, { "float", [&](){ mHarness.addAttribute<float>("testfloat", 1.1f * 2.3f); } }, { "double", [&](){ mHarness.addAttribute<double>("testdouble", 1.1 * 2.3); } }, { "vec2i", [&](){ mHarness.addAttribute<openvdb::math::Vec2<int32_t>>("testvec2i", openvdb::math::Vec2<int32_t>(3,8)); } }, { "vec2f", [&](){ mHarness.addAttribute<openvdb::math::Vec2<float>>("testvec2f", openvdb::math::Vec2<float>(1.1f*4.1f, 2.3f*5.3f)); } }, { "vec2d", [&](){ mHarness.addAttribute<openvdb::math::Vec2<double>>("testvec2d", openvdb::math::Vec2<double>(1.1*4.1, 2.3*5.3)); } }, { "vec3i", [&](){ mHarness.addAttribute<openvdb::math::Vec3<int32_t>>("testvec3i", openvdb::math::Vec3<int32_t>(4,10,18)); } }, { "vec3f", [&](){ mHarness.addAttribute<openvdb::math::Vec3<float>>("testvec3f", openvdb::math::Vec3<float>(1.1f*4.1f, 2.3f*5.3f, 4.3f*6.3f)); } }, { "vec3d", [&](){ mHarness.addAttribute<openvdb::math::Vec3<double>>("testvec3d", openvdb::math::Vec3<double>(1.1*4.1, 2.3*5.3, 4.3*6.3)); } }, { "vec4i", [&](){ mHarness.addAttribute<openvdb::math::Vec4<int32_t>>("testvec4i", openvdb::math::Vec4<int32_t>(5,12,21,32)); } }, { "vec4f", [&](){ mHarness.addAttribute<openvdb::math::Vec4<float>>("testvec4f", openvdb::math::Vec4<float>(1.1f*5.1f, 2.3f*6.3f, 4.3f*7.3f, 5.4f*8.4f)); } }, { "vec4d", [&](){ mHarness.addAttribute<openvdb::math::Vec4<double>>("testvec4d", openvdb::math::Vec4<double>(1.1*5.1, 2.3*6.3, 4.3*7.3, 5.4*8.4)); } }, { "mat3f", [&](){ mHarness.addAttribute<openvdb::math::Mat3<float>>("testmat3f", openvdb::math::Mat3<float>(1.1f, 2.3f, 4.3f, 5.4f, 6.7f, 7.8f, 9.1f, 4.5f, 8.2f) * openvdb::math::Mat3<float>(9.1f, 7.3f,-1.3f, 4.4f,-6.7f, 0.8f, 9.1f,-0.5f, 8.2f)); } }, { "mat3d", [&](){ mHarness.addAttribute<openvdb::math::Mat3<double>>("testmat3d", openvdb::math::Mat3<double>(1.1, 2.3, 4.3, 5.4, 6.7, 7.8, 9.1, 4.5, 8.2) * openvdb::math::Mat3<double>(9.1, 7.3,-1.3, 4.4,-6.7, 0.8, 9.1,-0.5, 8.2)); } }, { "mat4f", [&](){ mHarness.addAttribute<openvdb::math::Mat4<float>>("testmat4f", openvdb::math::Mat4<float>(1.1f, 2.3f, 4.3f, 5.4f, 6.7f, 7.8f, 9.1f, 4.5f, 8.2f, 3.3f, 2.9f, 5.9f, 0.1f, 0.3f, 5.1f, 1.9f) * openvdb::math::Mat4<float>(0.1f, 2.3f,-9.3f, 4.5f, -1.7f, 7.8f, 2.1f, 3.3f, 3.3f,-3.3f,-0.3f, 2.5f, 5.1f, 0.5f, 8.1f,-1.7f)); } }, { "mat4d", [&](){ mHarness.addAttribute<openvdb::math::Mat4<double>>("testmat4d", openvdb::math::Mat4<double>(1.1, 2.3, 4.3, 5.4, 6.7, 7.8, 9.1, 4.5, 8.2, 3.3, 2.9, 5.9, 0.1, 0.3, 5.1, 1.9) * openvdb::math::Mat4<double>(0.1, 2.3,-9.3, 4.5, -1.7, 7.8, 2.1, 3.3, 3.3,-3.3,-0.3, 2.5, 5.1, 0.5, 8.1,-1.7)); } } }; for (const auto& expc : expected) { expc.second.operator()(); } this->execute("binary_mult.ax"); } void TestBinary::div() { // @note reverses L1 and L2 as L2 is usually larger const std::string code = R"( _T1_@_A1_ = _L2_ / _L1_;)"; std::string repl; auto generate = [&](const auto& map) { for (const auto& config : map) { std::string tmp = code; unittest_util::replace(tmp, "_T1_", config.first); unittest_util::replace(tmp, "_A1_", "test" + config.first); for (const auto& settings : config.second) { unittest_util::replace(tmp, settings.first, settings.second); } repl += tmp; } }; generate(integral); generate(floating); generate(vec2); generate(vec3); generate(vec4); this->registerTest(repl, "binary_div.ax"); const std::map<std::string, std::function<void()>> expected = { { "bool", [&](){ mHarness.addAttribute<bool>("testbool", false); } }, { "int16", [&](){ mHarness.addAttribute<int16_t>("testint16", 1); } }, { "int32", [&](){ mHarness.addAttribute<int32_t>("testint32", 1); } }, { "int64", [&](){ mHarness.addAttribute<int64_t>("testint64", 1); } }, { "float", [&](){ mHarness.addAttribute<float>("testfloat", 2.3f/1.1f); } }, { "double", [&](){ mHarness.addAttribute<double>("testdouble", 2.3/1.1); } }, { "vec2i", [&](){ mHarness.addAttribute<openvdb::math::Vec2<int32_t>>("testvec2i", openvdb::math::Vec2<int32_t>(3,2)); } }, { "vec2f", [&](){ mHarness.addAttribute<openvdb::math::Vec2<float>>("testvec2f", openvdb::math::Vec2<float>(4.1f/1.1f, 5.3f/2.3f)); } }, { "vec2d", [&](){ mHarness.addAttribute<openvdb::math::Vec2<double>>("testvec2d", openvdb::math::Vec2<double>(4.1/1.1, 5.3/2.3)); } }, { "vec3i", [&](){ mHarness.addAttribute<openvdb::math::Vec3<int32_t>>("testvec3i", openvdb::math::Vec3<int32_t>(4,2,2)); } }, { "vec3f", [&](){ mHarness.addAttribute<openvdb::math::Vec3<float>>("testvec3f", openvdb::math::Vec3<float>(4.1f/1.1f, 5.3f/2.3f, 6.3f/4.3f)); } }, { "vec3d", [&](){ mHarness.addAttribute<openvdb::math::Vec3<double>>("testvec3d", openvdb::math::Vec3<double>(4.1/1.1, 5.3/2.3, 6.3/4.3)); } }, { "vec4i", [&](){ mHarness.addAttribute<openvdb::math::Vec4<int32_t>>("testvec4i", openvdb::math::Vec4<int32_t>(5,3,2,2)); } }, { "vec4f", [&](){ mHarness.addAttribute<openvdb::math::Vec4<float>>("testvec4f", openvdb::math::Vec4<float>(5.1f/1.1f, 6.3f/2.3f, 7.3f/4.3f, 8.4f/5.4f)); } }, { "vec4d", [&](){ mHarness.addAttribute<openvdb::math::Vec4<double>>("testvec4d", openvdb::math::Vec4<double>(5.1/1.1, 6.3/2.3, 7.3/4.3, 8.4/5.4)); } }, }; for (const auto& expc : expected) { expc.second.operator()(); } this->execute("binary_div.ax"); } void TestBinary::mod() { // @note reverses L1 and L2 as L2 is usually larger const std::string code = R"( _T1_@_A1_ = _L2_ % _L1_;)"; std::string repl; auto generate = [&](const auto& map) { for (const auto& config : map) { std::string tmp = code; unittest_util::replace(tmp, "_T1_", config.first); unittest_util::replace(tmp, "_A1_", "test" + config.first); for (const auto& settings : config.second) { unittest_util::replace(tmp, settings.first, settings.second); } repl += tmp; } }; generate(integral); generate(floating); generate(vec2); generate(vec3); generate(vec4); this->registerTest(repl, "binary_mod.ax"); const std::map<std::string, std::function<void()>> expected = { { "bool", [&](){ mHarness.addAttribute<bool>("testbool", false); } }, { "int16", [&](){ mHarness.addAttribute<int16_t>("testint16", 1); } }, { "int32", [&](){ mHarness.addAttribute<int32_t>("testint32", 1); } }, { "int64", [&](){ mHarness.addAttribute<int64_t>("testint64", 1); } }, { "float", [&](){ mHarness.addAttribute<float>("testfloat", std::fmod(2.3f,1.1f)); } }, { "double", [&](){ mHarness.addAttribute<double>("testdouble", std::fmod(2.3,1.1)); } }, { "vec2i", [&](){ mHarness.addAttribute<openvdb::math::Vec2<int32_t>>("testvec2i", openvdb::math::Vec2<int32_t>(0,0)); } }, { "vec2f", [&](){ mHarness.addAttribute<openvdb::math::Vec2<float>>("testvec2f", openvdb::math::Vec2<float>(std::fmod(4.1f,1.1f), std::fmod(5.3f,2.3f))); } }, { "vec2d", [&](){ mHarness.addAttribute<openvdb::math::Vec2<double>>("testvec2d", openvdb::math::Vec2<double>(std::fmod(4.1,1.1), std::fmod(5.3,2.3))); } }, { "vec3i", [&](){ mHarness.addAttribute<openvdb::math::Vec3<int32_t>>("testvec3i", openvdb::math::Vec3<int32_t>(0,1,0)); } }, { "vec3f", [&](){ mHarness.addAttribute<openvdb::math::Vec3<float>>("testvec3f", openvdb::math::Vec3<float>(std::fmod(4.1f,1.1f), std::fmod(5.3f,2.3f), std::fmod(6.3f,4.3f))); } }, { "vec3d", [&](){ mHarness.addAttribute<openvdb::math::Vec3<double>>("testvec3d", openvdb::math::Vec3<double>(std::fmod(4.1,1.1), std::fmod(5.3,2.3), std::fmod(6.3,4.3))); } }, { "vec4i", [&](){ mHarness.addAttribute<openvdb::math::Vec4<int32_t>>("testvec4i", openvdb::math::Vec4<int32_t>(0,0,1,0)); } }, { "vec4f", [&](){ mHarness.addAttribute<openvdb::math::Vec4<float>>("testvec4f", openvdb::math::Vec4<float>(std::fmod(5.1f,1.1f), std::fmod(6.3f,2.3f), std::fmod(7.3f,4.3f), std::fmod(8.4f,5.4f))); } }, { "vec4d", [&](){ mHarness.addAttribute<openvdb::math::Vec4<double>>("testvec4d", openvdb::math::Vec4<double>(std::fmod(5.1,1.1), std::fmod(6.3,2.3), std::fmod(7.3,4.3), std::fmod(8.4,5.4))); } }, }; for (const auto& expc : expected) { expc.second.operator()(); } this->execute("binary_mod.ax"); } void TestBinary::btand() { const std::string code = R"( _T1_@_A1_ = _L1_ & _L2_;)"; std::string repl; auto generate = [&](const auto& map) { for (const auto& config : map) { std::string tmp = code; unittest_util::replace(tmp, "_T1_", config.first); unittest_util::replace(tmp, "_A1_", "test" + config.first); for (const auto& settings : config.second) { unittest_util::replace(tmp, settings.first, settings.second); } repl += tmp; } }; generate(integral); this->registerTest(repl, "binary_bitand.ax"); const std::map<std::string, std::function<void()>> expected = { { "bool", [&](){ mHarness.addAttribute<bool>("testbool", false); } }, { "int16", [&](){ mHarness.addAttribute<int16_t>("testint16", 2); } }, { "int32", [&](){ mHarness.addAttribute<int32_t>("testint32", 2); } }, { "int64", [&](){ mHarness.addAttribute<int64_t>("testint64", 2); } }, }; for (const auto& expc : expected) { expc.second.operator()(); } this->execute("binary_bitand.ax"); } void TestBinary::btor() { const std::string code = R"( _T1_@_A1_ = _L1_ | _L2_;)"; std::string repl; auto generate = [&](const auto& map) { for (const auto& config : map) { std::string tmp = code; unittest_util::replace(tmp, "_T1_", config.first); unittest_util::replace(tmp, "_A1_", "test" + config.first); for (const auto& settings : config.second) { unittest_util::replace(tmp, settings.first, settings.second); } repl += tmp; } }; generate(integral); this->registerTest(repl, "binary_bitor.ax"); const std::map<std::string, std::function<void()>> expected = { { "bool", [&](){ mHarness.addAttribute<bool>("testbool", true); } }, { "int16", [&](){ mHarness.addAttribute<int16_t>("testint16", 3); } }, { "int32", [&](){ mHarness.addAttribute<int32_t>("testint32", 3); } }, { "int64", [&](){ mHarness.addAttribute<int64_t>("testint64", 3); } }, }; for (const auto& expc : expected) { expc.second.operator()(); } this->execute("binary_bitor.ax"); } void TestBinary::btxor() { const std::string code = R"( _T1_@_A1_ = _L1_ ^ _L2_;)"; std::string repl; auto generate = [&](const auto& map) { for (const auto& config : map) { std::string tmp = code; unittest_util::replace(tmp, "_T1_", config.first); unittest_util::replace(tmp, "_A1_", "test" + config.first); for (const auto& settings : config.second) { unittest_util::replace(tmp, settings.first, settings.second); } repl += tmp; } }; generate(integral); this->registerTest(repl, "binary_bitxor.ax"); const std::map<std::string, std::function<void()>> expected = { { "bool", [&](){ mHarness.addAttribute<bool>("testbool", true); } }, { "int16", [&](){ mHarness.addAttribute<int16_t>("testint16", 1); } }, { "int32", [&](){ mHarness.addAttribute<int32_t>("testint32", 1); } }, { "int64", [&](){ mHarness.addAttribute<int64_t>("testint64", 1); } }, }; for (const auto& expc : expected) { expc.second.operator()(); } this->execute("binary_bitxor.ax"); } void TestBinary::logicaland() { const std::string code = R"( _T1_@_A1_ = _L1_ && _L2_;)"; std::string repl; auto generate = [&](const auto& map) { for (const auto& config : map) { std::string tmp = code; unittest_util::replace(tmp, "_T1_", config.first); unittest_util::replace(tmp, "_A1_", "test" + config.first); for (const auto& settings : config.second) { unittest_util::replace(tmp, settings.first, settings.second); } repl += tmp; } }; generate(integral); generate(floating); this->registerTest(repl, "binary_logicaland.ax"); const std::map<std::string, std::function<void()>> expected = { { "bool", [&](){ mHarness.addAttribute<bool>("testbool", false); } }, { "int16", [&](){ mHarness.addAttribute<int16_t>("testint16", 1); } }, { "int32", [&](){ mHarness.addAttribute<int32_t>("testint32", 1); } }, { "int64", [&](){ mHarness.addAttribute<int64_t>("testint64", 1); } }, { "float", [&](){ mHarness.addAttribute<float>("testfloat", 1.0f); } }, { "double", [&](){ mHarness.addAttribute<double>("testdouble", 1.0); } }, }; for (const auto& expc : expected) { expc.second.operator()(); } this->execute("binary_logicaland.ax"); // Also test short circuiting logical op for && mHarness.reset(); this->registerTest(R"( int@scircuit1 = 0; int@scircuit2 = 1; int@scircuit3 = 2; int@scircuit1++ && ++int@scircuit2; ++int@scircuit1 && ++int@scircuit3; int@scircuit4 = 1; int@scircuit5 = 1; true && int@scircuit4 = 2; false && int@scircuit5 = 2;)", "binary_logicaland_scircuit.ax"); mHarness.addAttributes<int32_t>(unittest_util::nameSequence("scircuit", 5), { 2, 1, 3, 2, 1 }); this->execute("binary_logicaland_scircuit.ax"); } void TestBinary::logicalor() { const std::string code = R"( _T1_@_A1_ = _L1_ || _L2_;)"; std::string repl; auto generate = [&](const auto& map) { for (const auto& config : map) { std::string tmp = code; unittest_util::replace(tmp, "_T1_", config.first); unittest_util::replace(tmp, "_A1_", "test" + config.first); for (const auto& settings : config.second) { unittest_util::replace(tmp, settings.first, settings.second); } repl += tmp; } }; generate(integral); generate(floating); this->registerTest(repl, "binary_logicalor.ax"); const std::map<std::string, std::function<void()>> expected = { { "bool", [&](){ mHarness.addAttribute<bool>("testbool", true); } }, { "int16", [&](){ mHarness.addAttribute<int16_t>("testint16", 1); } }, { "int32", [&](){ mHarness.addAttribute<int32_t>("testint32", 1); } }, { "int64", [&](){ mHarness.addAttribute<int64_t>("testint64", 1); } }, { "float", [&](){ mHarness.addAttribute<float>("testfloat", 1.0f); } }, { "double", [&](){ mHarness.addAttribute<double>("testdouble", 1.0); } }, }; for (const auto& expc : expected) { expc.second.operator()(); } this->execute("binary_logicalor.ax"); // Also test short circuiting logical op for || mHarness.reset(); this->registerTest(R"( int@scircuit1 = 0; int@scircuit2 = 1; int@scircuit3 = 2; int@scircuit1++ || ++int@scircuit2; ++int@scircuit1 || ++int@scircuit3; int@scircuit4 = 1; int@scircuit5 = 1; true || int@scircuit4 = 2; false || int@scircuit5 = 2;)", "binary_logicalor_scircuit.ax"); mHarness.addAttributes<int32_t>(unittest_util::nameSequence("scircuit", 5), { 2, 2, 2, 1, 2 }); this->execute("binary_logicalor_scircuit.ax"); } void TestBinary::equalsequals() { const std::string code = R"( bool@_A1_ = _L1_ == _L2_; bool@_A2_ = _L2_ == _L2_;)"; size_t idx = 1; std::string repl; auto generate = [&](const auto& map) { for (const auto& config : map) { std::string tmp = code; unittest_util::replace(tmp, "_A1_", "test" + std::to_string(idx++)); unittest_util::replace(tmp, "_A2_", "test" + std::to_string(idx++)); for (const auto& settings : config.second) { unittest_util::replace(tmp, settings.first, settings.second); } repl += tmp; } }; generate(integral); generate(floating); generate(vec2); generate(vec3); generate(vec4); generate(mat3); generate(mat4); this->registerTest(repl, "binary_relational_equalsequals.ax"); CPPUNIT_ASSERT(idx != 0); const auto names = unittest_util::nameSequence("test", idx-1); std::vector<bool> results; for (size_t i = 0; i < idx-1; ++i) { results.emplace_back((i % 2 == 0) ? false : true); } mHarness.addAttributes<bool>(names, results); this->execute("binary_relational_equalsequals.ax"); } void TestBinary::notequals() { const std::string code = R"( bool@_A1_ = _L1_ != _L2_; bool@_A2_ = _L2_ != _L2_;)"; size_t idx = 1; std::string repl; auto generate = [&](const auto& map) { for (const auto& config : map) { std::string tmp = code; unittest_util::replace(tmp, "_A1_", "test" + std::to_string(idx++)); unittest_util::replace(tmp, "_A2_", "test" + std::to_string(idx++)); for (const auto& settings : config.second) { unittest_util::replace(tmp, settings.first, settings.second); } repl += tmp; } }; generate(integral); generate(floating); generate(vec2); generate(vec3); generate(vec4); generate(mat3); generate(mat4); this->registerTest(repl, "binary_relational_notequals.ax"); CPPUNIT_ASSERT(idx != 0); const auto names = unittest_util::nameSequence("test", idx-1); std::vector<bool> results; for (size_t i = 0; i < idx-1; ++i) { results.emplace_back((i % 2 == 1) ? false : true); } mHarness.addAttributes<bool>(names, results); this->execute("binary_relational_notequals.ax"); } void TestBinary::greaterthan() { const std::string code = R"( bool@_A1_ = _L1_ > _L2_; bool@_A2_ = _L2_ > _L1_; bool@_A3_ = _L2_ > _L2_;)"; size_t idx = 1; std::string repl; auto generate = [&](const auto& map) { for (const auto& config : map) { std::string tmp = code; unittest_util::replace(tmp, "_A1_", "test" + std::to_string(idx++)); unittest_util::replace(tmp, "_A2_", "test" + std::to_string(idx++)); unittest_util::replace(tmp, "_A3_", "test" + std::to_string(idx++)); for (const auto& settings : config.second) { unittest_util::replace(tmp, settings.first, settings.second); } repl += tmp; } }; generate(integral); generate(floating); this->registerTest(repl, "binary_relational_greaterthan.ax"); CPPUNIT_ASSERT(idx != 0); const auto names = unittest_util::nameSequence("test", idx-1); std::vector<bool> results; for (const auto& config : integral) { if (config.first == "bool") { // L1 and L2 for bools are swapped results.emplace_back(true); results.emplace_back(false); results.emplace_back(false); } else { results.emplace_back(false); results.emplace_back(true); results.emplace_back(false); } } const size_t typecount = floating.size(); for (size_t i = 0; i < typecount; ++i) { results.emplace_back(false); results.emplace_back(true); results.emplace_back(false); } mHarness.addAttributes<bool>(names, results); this->execute("binary_relational_greaterthan.ax"); } void TestBinary::lessthan() { const std::string code = R"( bool@_A1_ = _L1_ < _L2_; bool@_A2_ = _L2_ < _L1_; bool@_A3_ = _L2_ < _L2_;)"; size_t idx = 1; std::string repl; auto generate = [&](const auto& map) { for (const auto& config : map) { std::string tmp = code; unittest_util::replace(tmp, "_A1_", "test" + std::to_string(idx++)); unittest_util::replace(tmp, "_A2_", "test" + std::to_string(idx++)); unittest_util::replace(tmp, "_A3_", "test" + std::to_string(idx++)); for (const auto& settings : config.second) { unittest_util::replace(tmp, settings.first, settings.second); } repl += tmp; } }; generate(integral); generate(floating); this->registerTest(repl, "binary_relational_lessthan.ax"); CPPUNIT_ASSERT(idx != 0); const auto names = unittest_util::nameSequence("test", idx-1); std::vector<bool> results; for (const auto& config : integral) { if (config.first == "bool") { // L1 and L2 for bools are swapped results.emplace_back(false); results.emplace_back(true); results.emplace_back(false); } else { results.emplace_back(true); results.emplace_back(false); results.emplace_back(false); } } const size_t typecount = floating.size(); for (size_t i = 0; i < typecount; ++i) { results.emplace_back(true); results.emplace_back(false); results.emplace_back(false); } mHarness.addAttributes<bool>(names, results); this->execute("binary_relational_lessthan.ax"); } void TestBinary::greaterthanequals() { const std::string code = R"( bool@_A1_ = _L1_ >= _L2_; bool@_A2_ = _L2_ >= _L1_; bool@_A3_ = _L2_ >= _L2_;)"; size_t idx = 1; std::string repl; auto generate = [&](const auto& map) { for (const auto& config : map) { std::string tmp = code; unittest_util::replace(tmp, "_A1_", "test" + std::to_string(idx++)); unittest_util::replace(tmp, "_A2_", "test" + std::to_string(idx++)); unittest_util::replace(tmp, "_A3_", "test" + std::to_string(idx++)); for (const auto& settings : config.second) { unittest_util::replace(tmp, settings.first, settings.second); } repl += tmp; } }; generate(integral); generate(floating); this->registerTest(repl, "binary_relational_greaterthanequals.ax"); CPPUNIT_ASSERT(idx != 0); const auto names = unittest_util::nameSequence("test", idx-1); std::vector<bool> results; for (const auto& config : integral) { if (config.first == "bool") { // L1 and L2 for bools are swapped results.emplace_back(true); results.emplace_back(false); results.emplace_back(true); } else { results.emplace_back(false); results.emplace_back(true); results.emplace_back(true); } } const size_t typecount = floating.size(); for (size_t i = 0; i < typecount; ++i) { results.emplace_back(false); results.emplace_back(true); results.emplace_back(true); } mHarness.addAttributes<bool>(names, results); this->execute("binary_relational_greaterthanequals.ax"); } void TestBinary::lessthanequals() { const std::string code = R"( bool@_A1_ = _L1_ <= _L2_; bool@_A2_ = _L2_ <= _L1_; bool@_A3_ = _L2_ <= _L2_;)"; size_t idx = 1; std::string repl; auto generate = [&](const auto& map) { for (const auto& config : map) { std::string tmp = code; unittest_util::replace(tmp, "_A1_", "test" + std::to_string(idx++)); unittest_util::replace(tmp, "_A2_", "test" + std::to_string(idx++)); unittest_util::replace(tmp, "_A3_", "test" + std::to_string(idx++)); for (const auto& settings : config.second) { unittest_util::replace(tmp, settings.first, settings.second); } repl += tmp; } }; generate(integral); generate(floating); this->registerTest(repl, "binary_relational_lessthanequals.ax"); CPPUNIT_ASSERT(idx != 0); const auto names = unittest_util::nameSequence("test", idx-1); std::vector<bool> results; for (const auto& config : integral) { if (config.first == "bool") { // L1 and L2 for bools are swapped results.emplace_back(false); results.emplace_back(true); results.emplace_back(true); } else { results.emplace_back(true); results.emplace_back(false); results.emplace_back(true); } } const size_t typecount = floating.size(); for (size_t i = 0; i < typecount; ++i) { results.emplace_back(true); results.emplace_back(false); results.emplace_back(true); } mHarness.addAttributes<bool>(names, results); this->execute("binary_relational_lessthanequals.ax"); } void TestBinary::shiftleft() { const std::string code = R"( _T1_@_A1_ = _L1_ << _L2_; _T1_@_A2_ = _L2_ << _L1_;)"; std::string repl; auto generate = [&](const auto& map) { for (const auto& config : map) { std::string tmp = code; unittest_util::replace(tmp, "_T1_", config.first); unittest_util::replace(tmp, "_A1_", "test" + config.first + "1"); unittest_util::replace(tmp, "_A2_", "test" + config.first + "2"); for (const auto& settings : config.second) { unittest_util::replace(tmp, settings.first, settings.second); } repl += tmp; } }; generate(integral); this->registerTest(repl, "binary_shiftleft.ax"); const std::map<std::string, std::function<void()>> expected = { { "bool", [&](){ mHarness.addAttribute<bool>("testbool1", true); mHarness.addAttribute<bool>("testbool2", false); } }, { "int16", [&](){ mHarness.addAttribute<int16_t>("testint161", 16); mHarness.addAttribute<int16_t>("testint162", 12); } }, { "int32", [&](){ mHarness.addAttribute<int32_t>("testint321", 16); mHarness.addAttribute<int32_t>("testint322", 12); } }, { "int64", [&](){ mHarness.addAttribute<int64_t>("testint641", 16); mHarness.addAttribute<int64_t>("testint642", 12); } }, }; for (const auto& expc : expected) { expc.second.operator()(); } this->execute("binary_shiftleft.ax"); } void TestBinary::shiftright() { const std::string code = R"( _T1_@_A1_ = _L1_ >> _L2_; _T1_@_A2_ = _L2_ >> _L1_;)"; std::string repl; auto generate = [&](const auto& map) { for (const auto& config : map) { std::string tmp = code; unittest_util::replace(tmp, "_T1_", config.first); unittest_util::replace(tmp, "_A1_", "test" + config.first + "1"); unittest_util::replace(tmp, "_A2_", "test" + config.first + "2"); for (const auto& settings : config.second) { unittest_util::replace(tmp, settings.first, settings.second); } repl += tmp; } }; generate(integral); this->registerTest(repl, "binary_shiftright.ax"); const std::map<std::string, std::function<void()>> expected = { { "bool", [&](){ mHarness.addAttribute<bool>("testbool1", true); mHarness.addAttribute<bool>("testbool2", false); } }, { "int16", [&](){ mHarness.addAttribute<int16_t>("testint161", 0); mHarness.addAttribute<int16_t>("testint162", 0); } }, { "int", [&](){ mHarness.addAttribute<int32_t>("testint321", 0); mHarness.addAttribute<int32_t>("testint322", 0); } }, { "int64", [&](){ mHarness.addAttribute<int64_t>("testint641", 0); mHarness.addAttribute<int64_t>("testint642", 0); } }, }; for (const auto& expc : expected) { expc.second.operator()(); } this->execute("binary_shiftright.ax"); }
NVIDIA-Omniverse/ext-openvdb/openvdb_ax/openvdb_ax/test/integration/TestCrement.cc
// Copyright Contributors to the OpenVDB Project // SPDX-License-Identifier: MPL-2.0 #include "CompareGrids.h" #include "TestHarness.h" #include "../test/util.h" #include <openvdb_ax/compiler/CustomData.h> #include <openvdb_ax/Exceptions.h> #include <cppunit/extensions/HelperMacros.h> using namespace openvdb::points; class TestCrement : public unittest_util::AXTestCase { public: std::string dir() const override { return GET_TEST_DIRECTORY(); } CPPUNIT_TEST_SUITE(TestCrement); CPPUNIT_TEST(crementScalar); CPPUNIT_TEST(crementComponent); CPPUNIT_TEST_SUITE_END(); void crementScalar(); void crementComponent(); }; CPPUNIT_TEST_SUITE_REGISTRATION(TestCrement); void TestCrement::crementScalar() { const std::string code = R"( _T1_@test1 = ++_T1_@test2; _T1_@test3 = _T1_@test4++; _T1_@test5 = (_T1_@test6++, _T1_@test7++, ++_T1_@test6); _T1_@test8 = (++_T1_@test6, ++_T1_@test7, _T1_@test6++); ++_T1_@test9 = _T1_@test9; )"; auto generate = [&](const auto& types) { for (const auto& type : types) { std::string repl = code; unittest_util::replace(repl, "_T1_", type); this->registerTest(repl, "crement_inc." + type + ".ax"); unittest_util::replace(repl, "++", "--"); this->registerTest(repl, "crement_dec." + type + ".ax"); } }; generate(std::vector<std::string>{ "int16", "int32", "int64", "float", "double", }); const auto names = unittest_util::nameSequence("test", 9); const std::map<std::string, std::function<void(bool)>> expected = { { "int16", [&](bool inc){ if (inc) mHarness.addAttributes<int16_t>(names, { 0, 1, -1, 2, -3, 4, -3, 4, -4 }, { 2, 2, 2, 3, 6, 8, -1, 7, -3 }); else mHarness.addAttributes<int16_t>(names, { 0, 1, -1, 2, -3, 4, -3, 4, -4 }, { 0, 0, 2, 1, 2, 0, -5, 1, -5 }); }, }, { "int32", [&](bool inc){ if (inc) mHarness.addAttributes<int32_t>(names, { 0, 1, -1, 2, -3, 4, -3, 4, -4 }, { 2, 2, 2, 3, 6, 8, -1, 7, -3 }); else mHarness.addAttributes<int32_t>(names, { 0, 1, -1, 2, -3, 4, -3, 4, -4 }, { 0, 0, 2, 1, 2, 0, -5, 1, -5 }); }, }, { "int64", [&](bool inc){ if (inc) mHarness.addAttributes<int64_t>(names, { 0, 1, -1, 2, -3, 4, -3, 4, -4 }, { 2, 2, 2, 3, 6, 8, -1, 7, -3 }); else mHarness.addAttributes<int64_t>(names, { 0, 1, -1, 2, -3, 4, -3, 4, -4 }, { 0, 0, 2, 1, 2, 0, -5, 1, -5 }); }, }, { "float", [&](bool inc){ if (inc) mHarness.addAttributes<float>(names, { 0.1f, 1.4f, -1.9f, 2.5f, -3.3f, 4.5f, -3.3f, 4.7f, -4.8f }, { (1.4f+1.0f), (1.4f+1.0f), 2.5f, (2.5f+1.0f), (4.5f+1.0f+1.0f), (4.5f+1.0f+1.0f+1.0f+1.0f), (-3.3f+1.0f+1.0f), (4.5f+1.0f+1.0f+1.0f), (-4.8f+1.0f) }); else mHarness.addAttributes<float>(names, { 0.1f, 1.4f, -1.9f, 2.5f, -3.3f, 4.5f, -3.3f, 4.7f, -4.8f }, { (1.4f-1.0f), (1.4f-1.0f), 2.5f, (2.5f-1.0f), (4.5f-1.0f-1.0f), (4.5f-1.0f-1.0f-1.0f-1.0f), (-3.3f-1.0f-1.0f), (4.5f-1.0f-1.0f-1.0f), (-4.8f-1.0f) }); }, }, { "double", [&](bool inc){ if (inc) mHarness.addAttributes<double>(names, { 0.1, 1.4, -1.9, 2.5, -3.3, 4.5, -3.3, 4.7, -4.8 }, { (1.4+1.0), (1.4+1.0), 2.5, (2.5+1.0), (4.5+1.0+1.0), (4.5+1.0+1.0+1.0+1.0), (-3.3+1.0+1.0), (4.5+1.0+1.0+1.0), (-4.8+1.0) }); else mHarness.addAttributes<double>(names, { 0.1, 1.4, -1.9, 2.5, -3.3, 4.5, -3.3, 4.7, -4.8 }, { (1.4-1.0), (1.4-1.0), 2.5, (2.5-1.0), (4.5-1.0-1.0), (4.5-1.0-1.0-1.0-1.0), (-3.3-1.0-1.0), (4.5-1.0-1.0-1.0), (-4.8-1.0) }); }, }, }; for (const auto& expc : expected) { mHarness.reset(); expc.second.operator()(true); // increment this->execute("crement_inc." + expc.first + ".ax"); mHarness.reset(); expc.second.operator()(false); // decrement this->execute("crement_dec." + expc.first + ".ax"); } } void TestCrement::crementComponent() { // Just tests the first two components of every container const std::string code = R"( _T1_@_A1_[0] = ++_T1_@_A2_[0]; _T1_@_A1_[1] = _T1_@_A2_[1]++; )"; auto generate = [&](const auto& types) { std::string repl; for (const auto& type : types) { std::string tmp = code; unittest_util::replace(tmp, "_T1_", type); unittest_util::replace(tmp, "_A1_", "test" + type + "1"); unittest_util::replace(tmp, "_A2_", "test" + type + "2"); repl += tmp; } this->registerTest(repl, "crement_inc.component.ax"); unittest_util::replace(repl, "++", "--"); this->registerTest(repl, "crement_dec.component.ax"); }; generate(std::vector<std::string>{ "vec2i", "vec2f", "vec2d", "vec3i", "vec3f", "vec3d", "vec4i", "vec4f", "vec4d", "mat3f", "mat3d", "mat4f", "mat4d" }); const std::map<std::string, std::function<void()>> expected = { { "inc", [&](){ mHarness.addAttribute<openvdb::math::Vec2<int32_t>>("testvec2i1", openvdb::math::Vec2<int32_t>(0,1)); mHarness.addAttribute<openvdb::math::Vec2<int32_t>>("testvec2i2", openvdb::math::Vec2<int32_t>(-1,1), openvdb::math::Vec2<int32_t>(0,2)); mHarness.addAttribute<openvdb::math::Vec2<float>>("testvec2f1", openvdb::math::Vec2<float>(-1.1f+1.0f, 1.1f)); mHarness.addAttribute<openvdb::math::Vec2<float>>("testvec2f2", openvdb::math::Vec2<float>(-1.1f,1.1f), openvdb::math::Vec2<float>(-1.1f+1.0f, 1.1f+1.0f)); mHarness.addAttribute<openvdb::math::Vec2<double>>("testvec2d1", openvdb::math::Vec2<double>(-1.1+1.0, 1.1)); mHarness.addAttribute<openvdb::math::Vec2<double>>("testvec2d2", openvdb::math::Vec2<double>(-1.1,1.1), openvdb::math::Vec2<double>(-1.1+1.0, 1.1+1.0)); mHarness.addAttribute<openvdb::math::Vec3<int32_t>>("testvec3i1", openvdb::math::Vec3<int32_t>(0,1,0)); mHarness.addAttribute<openvdb::math::Vec3<int32_t>>("testvec3i2", openvdb::math::Vec3<int32_t>(-1,1,0), openvdb::math::Vec3<int32_t>(0,2,0)); mHarness.addAttribute<openvdb::math::Vec3<float>>("testvec3f1", openvdb::math::Vec3<float>(-1.1f+1.0f, 1.1f, 0.0f)); mHarness.addAttribute<openvdb::math::Vec3<float>>("testvec3f2", openvdb::math::Vec3<float>(-1.1f,1.1f,0.0f), openvdb::math::Vec3<float>(-1.1f+1.0f, 1.1f+1.0f, 0.0f)); mHarness.addAttribute<openvdb::math::Vec3<double>>("testvec3d1", openvdb::math::Vec3<double>(-1.1+1.0, 1.1, 0.0)); mHarness.addAttribute<openvdb::math::Vec3<double>>("testvec3d2", openvdb::math::Vec3<double>(-1.1,1.1,0.0), openvdb::math::Vec3<double>(-1.1+1.0, 1.1+1.0 ,0.0)); mHarness.addAttribute<openvdb::math::Vec4<int32_t>>("testvec4i1", openvdb::math::Vec4<int32_t>(0,1,0,0)); mHarness.addAttribute<openvdb::math::Vec4<int32_t>>("testvec4i2", openvdb::math::Vec4<int32_t>(-1,1,0,0), openvdb::math::Vec4<int32_t>(0,2,0,0)); mHarness.addAttribute<openvdb::math::Vec4<float>>("testvec4f1", openvdb::math::Vec4<float>(-1.1f+1.0f, 1.1f, 0.0f, 0.0f)); mHarness.addAttribute<openvdb::math::Vec4<float>>("testvec4f2", openvdb::math::Vec4<float>(-1.1f,1.1f,0.0f,0.0f), openvdb::math::Vec4<float>(-1.1f+1.0f, 1.1f+1.0f, 0.0f, 0.0f)); mHarness.addAttribute<openvdb::math::Vec4<double>>("testvec4d1", openvdb::math::Vec4<double>(-1.1+1.0, 1.1, 0.0, 0.0)); mHarness.addAttribute<openvdb::math::Vec4<double>>("testvec4d2", openvdb::math::Vec4<double>(-1.1,1.1,0.0,0.0), openvdb::math::Vec4<double>(-1.1+1.0, 1.1+1.0, 0.0, 0.0)); auto getmat = [](auto x, auto a, auto b) -> decltype(x) { x = decltype(x)::zero(); x(0,0) = a; x(0,1) = b; return x; }; mHarness.addAttribute<openvdb::math::Mat3<float>>("testmat3f1", getmat(openvdb::math::Mat3<float>(), -1.1f+1.0f, 1.1f)); mHarness.addAttribute<openvdb::math::Mat3<float>>("testmat3f2", getmat(openvdb::math::Mat3<float>(),-1.1f,1.1f), getmat(openvdb::math::Mat3<float>(),-1.1f+1.0f,1.1f+1.0f)); mHarness.addAttribute<openvdb::math::Mat3<double>>("testmat3d1", getmat(openvdb::math::Mat3<double>(), -1.1+1.0, 1.1)); mHarness.addAttribute<openvdb::math::Mat3<double>>("testmat3d2", getmat(openvdb::math::Mat3<double>(),-1.1,1.1), getmat(openvdb::math::Mat3<double>(),-1.1+1.0, 1.1+1.0)); mHarness.addAttribute<openvdb::math::Mat4<float>>("testmat4f1", getmat(openvdb::math::Mat4<float>(), -1.1f+1.0f, 1.1f)); mHarness.addAttribute<openvdb::math::Mat4<float>>("testmat4f2", getmat(openvdb::math::Mat4<float>(),-1.1f,1.1f), getmat(openvdb::math::Mat4<float>(),-1.1f+1.0f,1.1f+1.0f)); mHarness.addAttribute<openvdb::math::Mat4<double>>("testmat4d1", getmat(openvdb::math::Mat4<double>(), -1.1+1.0, 1.1)); mHarness.addAttribute<openvdb::math::Mat4<double>>("testmat4d2", getmat(openvdb::math::Mat4<double>(),-1.1,1.1), getmat(openvdb::math::Mat4<double>(),-1.1+1.0, 1.1+1.0)); } }, { "dec", [&](){ mHarness.addAttribute<openvdb::math::Vec2<int32_t>>("testvec2i1", openvdb::math::Vec2<int32_t>(-2,1)); mHarness.addAttribute<openvdb::math::Vec2<int32_t>>("testvec2i2", openvdb::math::Vec2<int32_t>(-1,1), openvdb::math::Vec2<int32_t>(-2,0)); mHarness.addAttribute<openvdb::math::Vec2<float>>("testvec2f1", openvdb::math::Vec2<float>(-1.1f-1.0f, 1.1f)); mHarness.addAttribute<openvdb::math::Vec2<float>>("testvec2f2", openvdb::math::Vec2<float>(-1.1f,1.1f), openvdb::math::Vec2<float>(-1.1f-1.0f, 1.1f-1.0f)); mHarness.addAttribute<openvdb::math::Vec2<double>>("testvec2d1", openvdb::math::Vec2<double>(-1.1-1.0, 1.1)); mHarness.addAttribute<openvdb::math::Vec2<double>>("testvec2d2", openvdb::math::Vec2<double>(-1.1,1.1), openvdb::math::Vec2<double>(-1.1-1.0, 1.1-1.0)); mHarness.addAttribute<openvdb::math::Vec3<int32_t>>("testvec3i1", openvdb::math::Vec3<int32_t>(-2,1,0)); mHarness.addAttribute<openvdb::math::Vec3<int32_t>>("testvec3i2", openvdb::math::Vec3<int32_t>(-1,1,0), openvdb::math::Vec3<int32_t>(-2,0,0)); mHarness.addAttribute<openvdb::math::Vec3<float>>("testvec3f1", openvdb::math::Vec3<float>(-1.1f-1.0f, 1.1f, 0.0f)); mHarness.addAttribute<openvdb::math::Vec3<float>>("testvec3f2", openvdb::math::Vec3<float>(-1.1f,1.1f,0.0f), openvdb::math::Vec3<float>(-1.1f-1.0f, 1.1f-1.0f, 0.0f)); mHarness.addAttribute<openvdb::math::Vec3<double>>("testvec3d1", openvdb::math::Vec3<double>(-1.1-1.0, 1.1, 0.0)); mHarness.addAttribute<openvdb::math::Vec3<double>>("testvec3d2", openvdb::math::Vec3<double>(-1.1,1.1,0.0), openvdb::math::Vec3<double>(-1.1-1.0, 1.1-1.0 ,0.0)); mHarness.addAttribute<openvdb::math::Vec4<int32_t>>("testvec4i1", openvdb::math::Vec4<int32_t>(-2,1,0,0)); mHarness.addAttribute<openvdb::math::Vec4<int32_t>>("testvec4i2", openvdb::math::Vec4<int32_t>(-1,1,0,0), openvdb::math::Vec4<int32_t>(-2,0,0,0)); mHarness.addAttribute<openvdb::math::Vec4<float>>("testvec4f1", openvdb::math::Vec4<float>(-1.1f-1.0f, 1.1f, 0.0f, 0.0f)); mHarness.addAttribute<openvdb::math::Vec4<float>>("testvec4f2", openvdb::math::Vec4<float>(-1.1f,1.1f,0.0f,0.0f), openvdb::math::Vec4<float>(-1.1f-1.0f, 1.1f-1.0f, 0.0f, 0.0f)); mHarness.addAttribute<openvdb::math::Vec4<double>>("testvec4d1", openvdb::math::Vec4<double>(-1.1-1.0, 1.1, 0.0, 0.0)); mHarness.addAttribute<openvdb::math::Vec4<double>>("testvec4d2", openvdb::math::Vec4<double>(-1.1,1.1,0.0,0.0), openvdb::math::Vec4<double>(-1.1-1.0, 1.1-1.0, 0.0, 0.0)); auto getmat = [](auto x, auto a, auto b) -> decltype(x) { x = decltype(x)::zero(); x(0,0) = a; x(0,1) = b; return x; }; mHarness.addAttribute<openvdb::math::Mat3<float>>("testmat3f1", getmat(openvdb::math::Mat3<float>(), -1.1f-1.0f, 1.1f)); mHarness.addAttribute<openvdb::math::Mat3<float>>("testmat3f2", getmat(openvdb::math::Mat3<float>(),-1.1f,1.1f), getmat(openvdb::math::Mat3<float>(),-1.1f-1.0f,1.1f-1.0f)); mHarness.addAttribute<openvdb::math::Mat3<double>>("testmat3d1", getmat(openvdb::math::Mat3<double>(), -1.1-1.0, 1.1)); mHarness.addAttribute<openvdb::math::Mat3<double>>("testmat3d2", getmat(openvdb::math::Mat3<double>(),-1.1,1.1), getmat(openvdb::math::Mat3<double>(),-1.1-1.0, 1.1-1.0)); mHarness.addAttribute<openvdb::math::Mat4<float>>("testmat4f1", getmat(openvdb::math::Mat4<float>(), -1.1f-1.0f, 1.1f)); mHarness.addAttribute<openvdb::math::Mat4<float>>("testmat4f2", getmat(openvdb::math::Mat4<float>(),-1.1f,1.1f), getmat(openvdb::math::Mat4<float>(),-1.1f-1.0f,1.1f-1.0f)); mHarness.addAttribute<openvdb::math::Mat4<double>>("testmat4d1", getmat(openvdb::math::Mat4<double>(), -1.1-1.0, 1.1)); mHarness.addAttribute<openvdb::math::Mat4<double>>("testmat4d2", getmat(openvdb::math::Mat4<double>(),-1.1,1.1), getmat(openvdb::math::Mat4<double>(),-1.1-1.0, 1.1-1.0)); } } }; for (const auto& expc : expected) { mHarness.reset(); expc.second.operator()(); this->execute("crement_" + expc.first + ".component.ax"); } }
NVIDIA-Omniverse/ext-openvdb/openvdb_ax/openvdb_ax/test/backend/TestLogger.cc
// Copyright Contributors to the OpenVDB Project // SPDX-License-Identifier: MPL-2.0 #include "util.h" #include <openvdb_ax/ast/Parse.h> #include <openvdb_ax/compiler/Logger.h> #include <cppunit/extensions/HelperMacros.h> class TestLogger : public CppUnit::TestCase { public: CPPUNIT_TEST_SUITE(TestLogger); //CPPUNIT_TEST(testParseNewNode); CPPUNIT_TEST(testParseSetsTree); CPPUNIT_TEST(testAddError); CPPUNIT_TEST(testAddWarning); CPPUNIT_TEST(testWarningsAsErrors); CPPUNIT_TEST(testMaxErrors); CPPUNIT_TEST_SUITE_END(); //void testParseNewNode(); void testParseSetsTree(); void testAddError(); void testAddWarning(); void testWarningsAsErrors(); void testMaxErrors(); }; CPPUNIT_TEST_SUITE_REGISTRATION(TestLogger); /* extern openvdb::ax::Logger* axlog; /// @note We don't deploy the grammar c files as part of the AX install. /// Because the unit tests are structured to be able to build against /// an existing version of AX we can't include the parser.cc here for /// access to newNode. It's tested through other methods, but we /// should restructure how this code is shared by perhaps moving it to /// a shared header (including the definition of AXLTYPE) void TestLogger::testParseNewNode() { openvdb::ax::Logger logger; axlog = &logger;// setting global Logger* used in parser AXLTYPE location; location.first_line = 100; location.first_column = 65; const auto& nodeToLineColMap = logger.mNodeToLineColMap; CPPUNIT_ASSERT(nodeToLineColMap.empty()); const openvdb::ax::ast::Local* testLocal = newNode<openvdb::ax::ast::Local>(&location, "test"); CPPUNIT_ASSERT_EQUAL(nodeToLineColMap.size(),static_cast<size_t>(1)); openvdb::ax::Logger::CodeLocation lineCol = nodeToLineColMap.at(testLocal); CPPUNIT_ASSERT_EQUAL(lineCol.first, static_cast<size_t>(100)); CPPUNIT_ASSERT_EQUAL(lineCol.second, static_cast<size_t>(65)); } */ void TestLogger::testParseSetsTree() { openvdb::ax::Logger logger; CPPUNIT_ASSERT(!logger.mTreePtr); std::string code(""); openvdb::ax::ast::Tree::ConstPtr tree = openvdb::ax::ast::parse(code.c_str(), logger); CPPUNIT_ASSERT(tree); CPPUNIT_ASSERT_EQUAL(tree, logger.mTreePtr); } void TestLogger::testAddError() { std::vector<std::string> messages; openvdb::ax::Logger logger([&messages](const std::string& message) { messages.emplace_back(message); }); CPPUNIT_ASSERT(!logger.hasError()); CPPUNIT_ASSERT_EQUAL(logger.errors(), messages.size()); openvdb::ax::Logger::CodeLocation codeLocation(1,1); std::string message("test"); logger.error(message, codeLocation); CPPUNIT_ASSERT(logger.hasError()); CPPUNIT_ASSERT_EQUAL(messages.size(), static_cast<size_t>(1)); CPPUNIT_ASSERT_EQUAL(logger.errors(), static_cast<size_t>(1)); CPPUNIT_ASSERT_EQUAL(strcmp(messages.back().c_str(), "[1] error: test 1:1"), 0); logger.error(message, codeLocation); CPPUNIT_ASSERT_EQUAL(messages.size(), static_cast<size_t>(2)); CPPUNIT_ASSERT_EQUAL(logger.errors(), static_cast<size_t>(2)); logger.clear(); CPPUNIT_ASSERT(!logger.hasError()); CPPUNIT_ASSERT_EQUAL(logger.errors(), static_cast<size_t>(0)); openvdb::ax::ast::Local testLocal("name"); logger.error(message, &testLocal); CPPUNIT_ASSERT(logger.hasError()); CPPUNIT_ASSERT_EQUAL(logger.errors(), static_cast<size_t>(1)); CPPUNIT_ASSERT_EQUAL(messages.size(), static_cast<size_t>(3)); CPPUNIT_ASSERT(!logger.mTreePtr); CPPUNIT_ASSERT_EQUAL(strcmp(messages.back().c_str(), "[1] error: test"), 0); logger.clear(); CPPUNIT_ASSERT(!logger.hasError()); // test that add error finds code location { openvdb::ax::ast::Tree::ConstPtr tree = openvdb::ax::ast::parse(" a;", logger); const openvdb::ax::ast::Node* local = tree->child(0)->child(0); CPPUNIT_ASSERT(local); logger.error(message, local); CPPUNIT_ASSERT(logger.hasError()); CPPUNIT_ASSERT_EQUAL(logger.errors(), static_cast<size_t>(1)); CPPUNIT_ASSERT(logger.mTreePtr); CPPUNIT_ASSERT_EQUAL(strcmp(messages.back().c_str(), "[1] error: test 1:2"), 0); } logger.clear(); CPPUNIT_ASSERT(!logger.hasError()); // test add error finds code location even when node is deep copy { openvdb::ax::ast::Tree::ConstPtr tree = openvdb::ax::ast::parse("a;", logger); openvdb::ax::ast::Tree::ConstPtr treeCopy(tree->copy()); const openvdb::ax::ast::Node* local = tree->child(0)->child(0); CPPUNIT_ASSERT(local); const openvdb::ax::ast::Node* localCopy = treeCopy->child(0)->child(0); CPPUNIT_ASSERT(localCopy); // add referring to copy logger.error(message, localCopy); CPPUNIT_ASSERT(logger.hasError()); CPPUNIT_ASSERT_EQUAL(logger.errors(), static_cast<size_t>(1)); CPPUNIT_ASSERT_EQUAL(messages.size(), static_cast<size_t>(5)); CPPUNIT_ASSERT(logger.mTreePtr); CPPUNIT_ASSERT_EQUAL(strcmp(messages.back().c_str(), "[1] error: test 1:1"), 0); } } void TestLogger::testAddWarning() { std::vector<std::string> messages; openvdb::ax::Logger logger([](const std::string&) {}, [&messages](const std::string& message) { messages.emplace_back(message); }); CPPUNIT_ASSERT(!logger.hasWarning()); CPPUNIT_ASSERT_EQUAL(logger.warnings(), messages.size()); openvdb::ax::Logger::CodeLocation codeLocation(1,1); std::string message("test"); logger.warning(message, codeLocation); CPPUNIT_ASSERT(logger.hasWarning()); CPPUNIT_ASSERT_EQUAL(messages.size(), static_cast<size_t>(1)); CPPUNIT_ASSERT_EQUAL(logger.warnings(), static_cast<size_t>(1)); CPPUNIT_ASSERT_EQUAL(strcmp(messages.back().c_str(), "[1] warning: test 1:1"), 0); logger.warning(message, codeLocation); CPPUNIT_ASSERT_EQUAL(messages.size(), static_cast<size_t>(2)); CPPUNIT_ASSERT_EQUAL(logger.warnings(), static_cast<size_t>(2)); logger.clear(); CPPUNIT_ASSERT(!logger.hasWarning()); CPPUNIT_ASSERT_EQUAL(logger.warnings(), static_cast<size_t>(0)); openvdb::ax::ast::Local testLocal("name"); logger.warning(message, &testLocal); CPPUNIT_ASSERT(logger.hasWarning()); CPPUNIT_ASSERT_EQUAL(logger.warnings(), static_cast<size_t>(1)); CPPUNIT_ASSERT_EQUAL(messages.size(), static_cast<size_t>(3)); CPPUNIT_ASSERT(!logger.mTreePtr); CPPUNIT_ASSERT_EQUAL(strcmp(messages.back().c_str(), "[1] warning: test"), 0); logger.clear(); CPPUNIT_ASSERT(!logger.hasWarning()); // test that add warning finds code location { openvdb::ax::ast::Tree::ConstPtr tree = openvdb::ax::ast::parse(" a;", logger); const openvdb::ax::ast::Node* local = tree->child(0)->child(0); CPPUNIT_ASSERT(local); logger.warning(message, local); CPPUNIT_ASSERT(logger.hasWarning()); CPPUNIT_ASSERT_EQUAL(logger.warnings(), static_cast<size_t>(1)); CPPUNIT_ASSERT(logger.mTreePtr); CPPUNIT_ASSERT_EQUAL(strcmp(messages.back().c_str(), "[1] warning: test 1:2"), 0); } logger.clear(); CPPUNIT_ASSERT(!logger.hasWarning()); // test add warning finds code location even when node is deep copy { openvdb::ax::ast::Tree::ConstPtr tree = openvdb::ax::ast::parse("a;", logger); openvdb::ax::ast::Tree::ConstPtr treeCopy(tree->copy()); const openvdb::ax::ast::Node* local = tree->child(0)->child(0); CPPUNIT_ASSERT(local); const openvdb::ax::ast::Node* localCopy = treeCopy->child(0)->child(0); CPPUNIT_ASSERT(localCopy); // add referring to copy logger.warning(message, localCopy); CPPUNIT_ASSERT(logger.hasWarning()); CPPUNIT_ASSERT_EQUAL(logger.warnings(), static_cast<size_t>(1)); CPPUNIT_ASSERT_EQUAL(messages.size(), static_cast<size_t>(5)); CPPUNIT_ASSERT(logger.mTreePtr); CPPUNIT_ASSERT_EQUAL(strcmp(messages.back().c_str(), "[1] warning: test 1:1"), 0); } } void TestLogger::testWarningsAsErrors() { openvdb::ax::Logger logger([](const std::string&) {}); const std::string message("test"); const openvdb::ax::Logger::CodeLocation location(10,20); logger.setWarningsAsErrors(true); CPPUNIT_ASSERT(!logger.hasError()); CPPUNIT_ASSERT(!logger.hasWarning()); logger.warning(message, location); CPPUNIT_ASSERT(logger.hasError()); CPPUNIT_ASSERT(!logger.hasWarning()); } void TestLogger::testMaxErrors() { openvdb::ax::Logger logger([](const std::string&) {}); const std::string message("test"); const openvdb::ax::Logger::CodeLocation location(10,20); CPPUNIT_ASSERT(logger.error(message, location)); CPPUNIT_ASSERT(logger.error(message, location)); CPPUNIT_ASSERT(logger.error(message, location)); logger.clear(); logger.setMaxErrors(2); CPPUNIT_ASSERT(logger.error(message, location)); CPPUNIT_ASSERT(!logger.error(message, location)); CPPUNIT_ASSERT(!logger.error(message, location)); }
NVIDIA-Omniverse/ext-openvdb/openvdb_ax/openvdb_ax/test/backend/TestFunctionGroup.cc
// Copyright Contributors to the OpenVDB Project // SPDX-License-Identifier: MPL-2.0 #include "util.h" #include <openvdb_ax/codegen/FunctionTypes.h> #include <cppunit/extensions/HelperMacros.h> #include <memory> #include <string> /////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////// // Framework methods for the subsequent unit tests /// @brief Dummy derived function which implemented types struct TestFunction : public openvdb::ax::codegen::Function { static_assert(std::has_virtual_destructor <openvdb::ax::codegen::Function>::value, "Base class destructor is not virtual"); TestFunction(const std::vector<llvm::Type*>& types, llvm::Type* ret, const std::string& symbol) : openvdb::ax::codegen::Function(types.size(), symbol) , mTypes(types), mRet(ret) {} ~TestFunction() override {} llvm::Type* types(std::vector<llvm::Type*>& types, llvm::LLVMContext&) const override { types = mTypes; return mRet; } const std::vector<llvm::Type*> mTypes; llvm::Type* mRet; }; inline openvdb::ax::codegen::FunctionGroup::Ptr axtestscalar(llvm::LLVMContext& C) { using openvdb::ax::codegen::Function; using openvdb::ax::codegen::FunctionGroup; llvm::Type* voidty = llvm::Type::getVoidTy(C); FunctionGroup::Ptr group(new FunctionGroup("test", "The documentation", { Function::Ptr(new TestFunction({llvm::Type::getDoubleTy(C)}, voidty, "ax.testd")), Function::Ptr(new TestFunction({llvm::Type::getFloatTy(C)}, voidty, "ax.testf")), Function::Ptr(new TestFunction({llvm::Type::getInt64Ty(C)}, voidty, "ax.testi64")), Function::Ptr(new TestFunction({llvm::Type::getInt32Ty(C)}, voidty, "ax.testi32")), Function::Ptr(new TestFunction({llvm::Type::getInt16Ty(C)}, voidty, "ax.testi16")), Function::Ptr(new TestFunction({llvm::Type::getInt1Ty(C)}, voidty, "ax.testi1")) })); return group; } inline openvdb::ax::codegen::FunctionGroup::Ptr axtestsize(llvm::LLVMContext& C) { using openvdb::ax::codegen::Function; using openvdb::ax::codegen::FunctionGroup; llvm::Type* voidty = llvm::Type::getVoidTy(C); FunctionGroup::Ptr group(new FunctionGroup("test", "The documentation", { Function::Ptr(new TestFunction({}, voidty, "ax.empty")), Function::Ptr(new TestFunction({llvm::Type::getDoubleTy(C)}, voidty, "ax.d")), Function::Ptr(new TestFunction({ llvm::Type::getDoubleTy(C), llvm::Type::getDoubleTy(C) }, voidty, "ax.dd")), })); return group; } inline openvdb::ax::codegen::FunctionGroup::Ptr axtestmulti(llvm::LLVMContext& C) { using openvdb::ax::codegen::Function; using openvdb::ax::codegen::FunctionGroup; llvm::Type* voidty = llvm::Type::getVoidTy(C); FunctionGroup::Ptr group(new FunctionGroup("test", "The documentation", { Function::Ptr(new TestFunction({}, voidty, "ax.empty")), Function::Ptr(new TestFunction({llvm::Type::getInt32Ty(C)}, voidty, "ax.i32")), Function::Ptr(new TestFunction({ llvm::Type::getDoubleTy(C), llvm::Type::getDoubleTy(C) }, voidty, "ax.dd")), Function::Ptr(new TestFunction({ llvm::Type::getInt32Ty(C), llvm::Type::getDoubleTy(C) }, voidty, "ax.i32d")), Function::Ptr(new TestFunction({ llvm::Type::getDoubleTy(C)->getPointerTo(), llvm::Type::getInt32Ty(C), llvm::Type::getDoubleTy(C) }, voidty, "ax.d*i32d")), Function::Ptr(new TestFunction({ llvm::ArrayType::get(llvm::Type::getInt32Ty(C), 1)->getPointerTo(), }, voidty, "ax.i32x1")), Function::Ptr(new TestFunction({ llvm::ArrayType::get(llvm::Type::getInt32Ty(C), 2)->getPointerTo(), }, voidty, "ax.i32x2")), })); return group; } /////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////// class TestFunctionGroup : public CppUnit::TestCase { public: // Test FunctionGroup signature matching and execution errors CPPUNIT_TEST_SUITE(TestFunctionGroup); CPPUNIT_TEST(testFunctionGroup); CPPUNIT_TEST(testMatch); CPPUNIT_TEST(testExecute); CPPUNIT_TEST_SUITE_END(); void testFunctionGroup(); void testMatch(); void testExecute(); }; CPPUNIT_TEST_SUITE_REGISTRATION(TestFunctionGroup); void TestFunctionGroup::testFunctionGroup() { using openvdb::ax::codegen::Function; using openvdb::ax::codegen::FunctionGroup; unittest_util::LLVMState state; llvm::LLVMContext& C = state.context(); llvm::Type* voidty = llvm::Type::getVoidTy(C); Function::Ptr decl1(new TestFunction({}, voidty, "ax.test1")); Function::Ptr decl2(new TestFunction({}, voidty, "ax.test2")); Function::Ptr decl3(new TestFunction({}, voidty, "ax.test3")); FunctionGroup::Ptr group(new FunctionGroup("test", "The documentation", { decl1, decl2, decl3 })); CPPUNIT_ASSERT_EQUAL(std::string("test"), std::string(group->name())); CPPUNIT_ASSERT_EQUAL(std::string("The documentation"), std::string(group->doc())); CPPUNIT_ASSERT_EQUAL(size_t(3), group->list().size()); CPPUNIT_ASSERT_EQUAL(decl1, group->list()[0]); CPPUNIT_ASSERT_EQUAL(decl2, group->list()[1]); CPPUNIT_ASSERT_EQUAL(decl3, group->list()[2]); } void TestFunctionGroup::testMatch() { using openvdb::ax::codegen::LLVMType; using openvdb::ax::codegen::Function; using openvdb::ax::codegen::FunctionGroup; unittest_util::LLVMState state; llvm::LLVMContext& C = state.context(); std::vector<llvm::Type*> types; Function::SignatureMatch match; Function::Ptr result; // FunctionGroup::Ptr group = axtestscalar(C); const std::vector<Function::Ptr>* list = &group->list(); // test explicit matching types.resize(1); types[0] = llvm::Type::getInt1Ty(C); result = group->match(types, C, &match); CPPUNIT_ASSERT(Function::SignatureMatch::Explicit == match); CPPUNIT_ASSERT(result); CPPUNIT_ASSERT_EQUAL((*list)[5], result); // types[0] = llvm::Type::getInt16Ty(C); result = group->match(types, C, &match); CPPUNIT_ASSERT(Function::SignatureMatch::Explicit == match); CPPUNIT_ASSERT(result); CPPUNIT_ASSERT_EQUAL((*list)[4], result); // types[0] = llvm::Type::getInt32Ty(C); result = group->match(types, C, &match); CPPUNIT_ASSERT(Function::SignatureMatch::Explicit == match); CPPUNIT_ASSERT(result); CPPUNIT_ASSERT_EQUAL((*list)[3], result); // types[0] = llvm::Type::getInt64Ty(C); result = group->match(types, C, &match); CPPUNIT_ASSERT(Function::SignatureMatch::Explicit == match); CPPUNIT_ASSERT(result); CPPUNIT_ASSERT_EQUAL((*list)[2], result); // types[0] = llvm::Type::getFloatTy(C); result = group->match(types, C, &match); CPPUNIT_ASSERT(Function::SignatureMatch::Explicit == match); CPPUNIT_ASSERT(result); CPPUNIT_ASSERT_EQUAL((*list)[1], result); // types[0] = llvm::Type::getDoubleTy(C); result = group->match(types, C, &match); CPPUNIT_ASSERT(Function::SignatureMatch::Explicit == match); CPPUNIT_ASSERT(result); CPPUNIT_ASSERT_EQUAL((*list)[0], result); // test unsigned integers automatic type creation - these are not supported in the // language however can be constructed from the API. The function framework does // not differentiate between signed and unsigned integers types[0] = LLVMType<uint64_t>::get(C); result = group->match(types, C, &match); CPPUNIT_ASSERT(Function::SignatureMatch::Explicit == match); CPPUNIT_ASSERT(result); CPPUNIT_ASSERT_EQUAL((*list)[2], result); // test implicit matching - types should match to the first available castable signature // which is always the void(double) "tsfd" function for all provided scalars types[0] = llvm::Type::getInt8Ty(C); result = group->match(types, C, &match); CPPUNIT_ASSERT(Function::SignatureMatch::Implicit == match); CPPUNIT_ASSERT(result); CPPUNIT_ASSERT_EQUAL((*list)[0], result); types.clear(); // test invalid matching - Size matching returns the first function which matched // the size result = group->match(types, C, &match); CPPUNIT_ASSERT_EQUAL(Function::SignatureMatch::None, match); CPPUNIT_ASSERT(!result); result = group->match(types, C, &match); CPPUNIT_ASSERT(Function::SignatureMatch::None == match); CPPUNIT_ASSERT(!result); // types.emplace_back(llvm::Type::getInt1Ty(C)->getPointerTo()); result = group->match(types, C, &match); CPPUNIT_ASSERT(Function::SignatureMatch::Size == match); CPPUNIT_ASSERT(!result); // types[0] = llvm::ArrayType::get(llvm::Type::getInt1Ty(C), 1); result = group->match(types, C, &match); CPPUNIT_ASSERT(Function::SignatureMatch::Size == match); CPPUNIT_ASSERT(!result); // types[0] = llvm::Type::getInt1Ty(C); types.emplace_back(llvm::Type::getInt1Ty(C)); result = group->match(types, C, &match); CPPUNIT_ASSERT(Function::SignatureMatch::None == match); CPPUNIT_ASSERT(!result); // // Test varying argument size function // test explicit matching group = axtestsize(C); list = &group->list(); types.resize(2); types[0] = llvm::Type::getDoubleTy(C); types[1] = llvm::Type::getDoubleTy(C); result = group->match(types, C, &match); CPPUNIT_ASSERT(Function::SignatureMatch::Explicit == match); CPPUNIT_ASSERT(result); CPPUNIT_ASSERT_EQUAL((*list)[2], result); // types.resize(1); types[0] = llvm::Type::getDoubleTy(C); result = group->match(types, C, &match); CPPUNIT_ASSERT(Function::SignatureMatch::Explicit == match); CPPUNIT_ASSERT(result); CPPUNIT_ASSERT_EQUAL((*list)[1], result); // types.clear(); result = group->match(types, C, &match); CPPUNIT_ASSERT(Function::SignatureMatch::Explicit == match); CPPUNIT_ASSERT(result); CPPUNIT_ASSERT_EQUAL((*list)[0], result); // Test implicit matching types.resize(2); types[0] = llvm::Type::getFloatTy(C); types[1] = llvm::Type::getInt32Ty(C); result = group->match(types, C, &match); CPPUNIT_ASSERT(Function::SignatureMatch::Implicit == match); CPPUNIT_ASSERT(result); CPPUNIT_ASSERT_EQUAL((*list)[2], result); // Test non matching types.resize(3); types[0] = llvm::Type::getDoubleTy(C); types[1] = llvm::Type::getDoubleTy(C); types[2] = llvm::Type::getDoubleTy(C); result = group->match(types, C, &match); CPPUNIT_ASSERT(Function::SignatureMatch::None == match); CPPUNIT_ASSERT(!result); // // Test multi function group = axtestmulti(C); list = &group->list(); // test explicit/implicit matching types.clear(); result = group->match(types, C, &match); CPPUNIT_ASSERT(Function::SignatureMatch::Explicit == match); CPPUNIT_ASSERT(result); CPPUNIT_ASSERT_EQUAL((*list)[0], result); // types.resize(2); types[0] = llvm::Type::getDoubleTy(C); types[1] = llvm::Type::getDoubleTy(C); result = group->match(types, C, &match); CPPUNIT_ASSERT(Function::SignatureMatch::Explicit == match); CPPUNIT_ASSERT(result); CPPUNIT_ASSERT_EQUAL((*list)[2], result); // types[0] = llvm::Type::getInt32Ty(C); types[1] = llvm::Type::getDoubleTy(C); result = group->match(types, C, &match); CPPUNIT_ASSERT(Function::SignatureMatch::Explicit == match); CPPUNIT_ASSERT(result); CPPUNIT_ASSERT_EQUAL((*list)[3], result); // types[0] = llvm::Type::getInt32Ty(C); types[1] = llvm::Type::getInt32Ty(C); result = group->match(types, C, &match); CPPUNIT_ASSERT(Function::SignatureMatch::Implicit == match); CPPUNIT_ASSERT(result); CPPUNIT_ASSERT_EQUAL((*list)[2], result); // types.resize(1); types[0] = llvm::ArrayType::get(llvm::Type::getInt32Ty(C), 1)->getPointerTo(); result = group->match(types, C, &match); CPPUNIT_ASSERT(Function::SignatureMatch::Explicit == match); CPPUNIT_ASSERT(result); CPPUNIT_ASSERT_EQUAL((*list)[5], result); // types[0] = llvm::ArrayType::get(llvm::Type::getInt32Ty(C), 2)->getPointerTo(); result = group->match(types, C, &match); CPPUNIT_ASSERT(Function::SignatureMatch::Explicit == match); CPPUNIT_ASSERT(result); CPPUNIT_ASSERT_EQUAL((*list)[6], result); } void TestFunctionGroup::testExecute() { using openvdb::ax::codegen::LLVMType; using openvdb::ax::codegen::Function; using openvdb::ax::codegen::FunctionGroup; unittest_util::LLVMState state; llvm::LLVMContext& C = state.context(); llvm::IRBuilder<> B(state.scratchBlock()); llvm::Value* result = nullptr; llvm::CallInst* call = nullptr; llvm::Function* target = nullptr; std::vector<llvm::Value*> args; // test execution // test invalid arguments throws FunctionGroup::Ptr group(new FunctionGroup("empty", "", {})); CPPUNIT_ASSERT(!group->execute(/*args*/{}, B)); group = axtestscalar(C); const std::vector<Function::Ptr>* list = &group->list(); CPPUNIT_ASSERT(!group->execute({}, B)); CPPUNIT_ASSERT(!group->execute({ B.getTrue(), B.getTrue() }, B)); args.resize(1); // test llvm function calls - execute and get the called function. // check this is already inserted into the module and is expected // llvm::Function using create on the expected function signature args[0] = B.getTrue(); result = group->execute(args, B); CPPUNIT_ASSERT(result); CPPUNIT_ASSERT(llvm::isa<llvm::CallInst>(result)); call = llvm::cast<llvm::CallInst>(result); CPPUNIT_ASSERT(call); target = call->getCalledFunction(); CPPUNIT_ASSERT(target); CPPUNIT_ASSERT_EQUAL((*list)[5]->create(state.module()), target); // args[0] = B.getInt16(1); result = group->execute(args, B); CPPUNIT_ASSERT(result); CPPUNIT_ASSERT(llvm::isa<llvm::CallInst>(result)); call = llvm::cast<llvm::CallInst>(result); CPPUNIT_ASSERT(call); target = call->getCalledFunction(); CPPUNIT_ASSERT(target); CPPUNIT_ASSERT_EQUAL((*list)[4]->create(state.module()), target); // args[0] = B.getInt32(1); result = group->execute(args, B); CPPUNIT_ASSERT(result); CPPUNIT_ASSERT(llvm::isa<llvm::CallInst>(result)); call = llvm::cast<llvm::CallInst>(result); CPPUNIT_ASSERT(call); target = call->getCalledFunction(); CPPUNIT_ASSERT(target); CPPUNIT_ASSERT_EQUAL((*list)[3]->create(state.module()), target); // args[0] = B.getInt64(1); result = group->execute(args, B); CPPUNIT_ASSERT(result); CPPUNIT_ASSERT(llvm::isa<llvm::CallInst>(result)); call = llvm::cast<llvm::CallInst>(result); CPPUNIT_ASSERT(call); target = call->getCalledFunction(); CPPUNIT_ASSERT(target); CPPUNIT_ASSERT_EQUAL((*list)[2]->create(state.module()), target); // args[0] = llvm::ConstantFP::get(llvm::Type::getFloatTy(C), 1.0f); result = group->execute(args, B); CPPUNIT_ASSERT(result); CPPUNIT_ASSERT(llvm::isa<llvm::CallInst>(result)); call = llvm::cast<llvm::CallInst>(result); CPPUNIT_ASSERT(call); target = call->getCalledFunction(); CPPUNIT_ASSERT(target); CPPUNIT_ASSERT_EQUAL((*list)[1]->create(state.module()), target); // args[0] = llvm::ConstantFP::get(llvm::Type::getDoubleTy(C), 1.0); result = group->execute(args, B); CPPUNIT_ASSERT(result); CPPUNIT_ASSERT(llvm::isa<llvm::CallInst>(result)); call = llvm::cast<llvm::CallInst>(result); CPPUNIT_ASSERT(call); target = call->getCalledFunction(); CPPUNIT_ASSERT(target); CPPUNIT_ASSERT_EQUAL((*list)[0]->create(state.module()), target); // // Test multi function group = axtestmulti(C); list = &group->list(); args.clear(); result = group->execute(args, B); CPPUNIT_ASSERT(result); CPPUNIT_ASSERT(llvm::isa<llvm::CallInst>(result)); call = llvm::cast<llvm::CallInst>(result); CPPUNIT_ASSERT(call); target = call->getCalledFunction(); CPPUNIT_ASSERT(target); CPPUNIT_ASSERT_EQUAL((*list)[0]->create(state.module()), target); // args.resize(1); args[0] = B.CreateAlloca(llvm::ArrayType::get(llvm::Type::getInt32Ty(C), 1)); result = group->execute(args, B); CPPUNIT_ASSERT(result); CPPUNIT_ASSERT(llvm::isa<llvm::CallInst>(result)); call = llvm::cast<llvm::CallInst>(result); CPPUNIT_ASSERT(call); target = call->getCalledFunction(); CPPUNIT_ASSERT(target); CPPUNIT_ASSERT_EQUAL((*list)[5]->create(state.module()), target); // args[0] = B.CreateAlloca(llvm::ArrayType::get(llvm::Type::getInt32Ty(C), 2)); result = group->execute(args, B); CPPUNIT_ASSERT(result); CPPUNIT_ASSERT(llvm::isa<llvm::CallInst>(result)); call = llvm::cast<llvm::CallInst>(result); CPPUNIT_ASSERT(call); target = call->getCalledFunction(); CPPUNIT_ASSERT(target); CPPUNIT_ASSERT_EQUAL((*list)[6]->create(state.module()), target); // args.resize(2); args[0] = llvm::ConstantFP::get(llvm::Type::getDoubleTy(C), 1.0); args[1] = llvm::ConstantFP::get(llvm::Type::getDoubleTy(C), 1.0); result = group->execute(args, B); CPPUNIT_ASSERT(result); CPPUNIT_ASSERT(llvm::isa<llvm::CallInst>(result)); call = llvm::cast<llvm::CallInst>(result); CPPUNIT_ASSERT(call); target = call->getCalledFunction(); CPPUNIT_ASSERT(target); CPPUNIT_ASSERT_EQUAL((*list)[2]->create(state.module()), target); }
NVIDIA-Omniverse/ext-openvdb/openvdb_ax/openvdb_ax/test/backend/TestFunctionRegistry.cc
// Copyright Contributors to the OpenVDB Project // SPDX-License-Identifier: MPL-2.0 #include <iostream> #include "util.h" #include <openvdb_ax/compiler/CompilerOptions.h> #include <openvdb_ax/codegen/Functions.h> #include <openvdb_ax/codegen/FunctionRegistry.h> #include <cppunit/extensions/HelperMacros.h> class TestFunctionRegistry : public CppUnit::TestCase { public: CPPUNIT_TEST_SUITE(TestFunctionRegistry); CPPUNIT_TEST(testCreateAllVerify); CPPUNIT_TEST_SUITE_END(); void testCreateAllVerify(); }; CPPUNIT_TEST_SUITE_REGISTRATION(TestFunctionRegistry); void TestFunctionRegistry::testCreateAllVerify() { openvdb::ax::codegen::FunctionRegistry::UniquePtr reg = openvdb::ax::codegen::createDefaultRegistry(); openvdb::ax::FunctionOptions opts; // check that no warnings are printed during registration // @todo Replace this with a better logger once AX has one! std::streambuf* sbuf = std::cerr.rdbuf(); try { // Redirect cerr std::stringstream buffer; std::cerr.rdbuf(buffer.rdbuf()); reg->createAll(opts, true); const std::string& result = buffer.str(); CPPUNIT_ASSERT_MESSAGE(result, result.empty()); } catch (...) { std::cerr.rdbuf(sbuf); throw; } std::cerr.rdbuf(sbuf); }
NVIDIA-Omniverse/ext-openvdb/openvdb_ax/openvdb_ax/test/backend/TestSymbolTable.cc
// Copyright Contributors to the OpenVDB Project // SPDX-License-Identifier: MPL-2.0 #include "util.h" #include <openvdb_ax/codegen/SymbolTable.h> #include <cppunit/extensions/HelperMacros.h> template <typename T> using LLVMType = openvdb::ax::codegen::LLVMType<T>; class TestSymbolTable : public CppUnit::TestCase { public: CPPUNIT_TEST_SUITE(TestSymbolTable); CPPUNIT_TEST(testSingleTable); CPPUNIT_TEST(testTableBlocks); CPPUNIT_TEST_SUITE_END(); void testSingleTable(); void testTableBlocks(); }; CPPUNIT_TEST_SUITE_REGISTRATION(TestSymbolTable); void TestSymbolTable::testSingleTable() { unittest_util::LLVMState state; llvm::IRBuilder<> builder(state.scratchBlock()); llvm::Type* type = LLVMType<float>::get(state.context()); llvm::Value* value1 = builder.CreateAlloca(type); llvm::Value* value2 = builder.CreateAlloca(type); CPPUNIT_ASSERT(value1); CPPUNIT_ASSERT(value2); openvdb::ax::codegen::SymbolTable table; CPPUNIT_ASSERT(table.map().empty()); CPPUNIT_ASSERT(table.insert("test", value1)); CPPUNIT_ASSERT(!table.insert("test", nullptr)); CPPUNIT_ASSERT(table.exists("test")); CPPUNIT_ASSERT_EQUAL(value1, table.get("test")); table.clear(); CPPUNIT_ASSERT(table.map().empty()); CPPUNIT_ASSERT(!table.exists("test")); CPPUNIT_ASSERT(table.insert("test", value1)); CPPUNIT_ASSERT(table.replace("test", value2)); CPPUNIT_ASSERT(!table.replace("other", value2)); CPPUNIT_ASSERT(table.exists("test")); CPPUNIT_ASSERT(table.exists("other")); CPPUNIT_ASSERT_EQUAL(value2, table.get("test")); CPPUNIT_ASSERT_EQUAL(value2, table.get("other")); } void TestSymbolTable::testTableBlocks() { unittest_util::LLVMState state; llvm::IRBuilder<> builder(state.scratchBlock()); llvm::Type* type = LLVMType<float>::get(state.context()); llvm::Value* value1 = builder.CreateAlloca(type); llvm::Value* value2 = builder.CreateAlloca(type); llvm::Value* value3 = builder.CreateAlloca(type); llvm::Value* value4 = builder.CreateAlloca(type); CPPUNIT_ASSERT(value1); CPPUNIT_ASSERT(value2); CPPUNIT_ASSERT(value3); CPPUNIT_ASSERT(value4); // test table insertion and erase openvdb::ax::codegen::SymbolTableBlocks tables; openvdb::ax::codegen::SymbolTable* table1 = &(tables.globals()); openvdb::ax::codegen::SymbolTable* table2 = tables.getOrInsert(0); CPPUNIT_ASSERT_EQUAL(table1, table2); table2 = &(tables.get(0)); CPPUNIT_ASSERT_EQUAL(table1, table2); CPPUNIT_ASSERT_THROW(tables.erase(0), std::runtime_error); tables.getOrInsert(1); tables.getOrInsert(2); tables.getOrInsert(4); CPPUNIT_ASSERT_THROW(tables.get(3), std::runtime_error); CPPUNIT_ASSERT(tables.erase(4)); CPPUNIT_ASSERT(tables.erase(2)); CPPUNIT_ASSERT(tables.erase(1)); tables.globals().insert("global1", value1); tables.globals().insert("global2", value2); // test find methods llvm::Value* result = tables.find("global1"); CPPUNIT_ASSERT_EQUAL(value1, result); result = tables.find("global2"); CPPUNIT_ASSERT_EQUAL(value2, result); table1 = tables.getOrInsert(2); table2 = tables.getOrInsert(4); tables.getOrInsert(5); // test multi table find methods table1->insert("table_level_2", value3); table2->insert("table_level_4", value4); // test find second nested value result = tables.find("table_level_2", 0); CPPUNIT_ASSERT(!result); result = tables.find("table_level_2", 1); CPPUNIT_ASSERT(!result); result = tables.find("table_level_2", 2); CPPUNIT_ASSERT_EQUAL(value3, result); // test find fourth nested value result = tables.find("table_level_4", 0); CPPUNIT_ASSERT(!result); result = tables.find("table_level_4", 3); CPPUNIT_ASSERT(!result); result = tables.find("table_level_4", 4); CPPUNIT_ASSERT_EQUAL(value4, result); result = tables.find("table_level_4", 10000); CPPUNIT_ASSERT_EQUAL(value4, result); // test find fourth nested value with matching global name tables.globals().insert("table_level_4", value1); result = tables.find("table_level_4"); CPPUNIT_ASSERT_EQUAL(value4, result); result = tables.find("table_level_4", 4); CPPUNIT_ASSERT_EQUAL(value4, result); result = tables.find("table_level_4", 3); CPPUNIT_ASSERT_EQUAL(value1, result); // test replace CPPUNIT_ASSERT(tables.replace("table_level_4", value2)); result = tables.find("table_level_4"); CPPUNIT_ASSERT_EQUAL(value2, result); // test global was not replaced result = tables.find("table_level_4", 0); CPPUNIT_ASSERT_EQUAL(value1, result); CPPUNIT_ASSERT(!tables.replace("empty", nullptr)); }
NVIDIA-Omniverse/ext-openvdb/openvdb_ax/openvdb_ax/test/backend/TestComputeGeneratorFailures.cc
// Copyright Contributors to the OpenVDB Project // SPDX-License-Identifier: MPL-2.0 #include "util.h" #include "../util.h" #include <openvdb_ax/compiler/CompilerOptions.h> #include <openvdb_ax/compiler/Logger.h> #include <openvdb_ax/codegen/FunctionRegistry.h> #include <openvdb_ax/codegen/ComputeGenerator.h> #include <openvdb_ax/ast/AST.h> #include <cppunit/extensions/HelperMacros.h> static const std::vector<std::string> tests { // codegen errors /// implicit narrow "int a; vec2i b; a=b;", "int a; vec3i b; a=b;", "int a; vec4i b; a=b;", "float a; vec2f b; a=b;", "float a; vec3f b; a=b;", "float a; vec4f b; a=b;", "float a; mat3f b; a=b;", "float a; mat4f b; a=b;", "double a; vec2d b; a=b;", "double a; vec3d b; a=b;", "double a; vec4d b; a=b;", "double a; mat3f b; a=b;", "double a; mat4f b; a=b;", /// unsupported bin ops "float a; a << 1;", "float a; a >> 1;", "float a; a | 1;", "float a; a ^ 1;", "float a; a & 1;", "double a; a << 1;", "double a; a >> 1;", "double a; a | 1;", "double a; a ^ 1;", "double a; a & 1;", "mat3d a,b; a % b;", "mat3d a,b; a & b;", "mat3d a,b; a && b;", "mat3d a,b; a << b;", "mat3d a,b; a >> b;", "mat3d a,b; a ^ b;", "mat3d a,b; a || b;", "mat3f a,b; a % b;", "mat3f a,b; a & b;", "mat3f a,b; a && b;", "mat3f a,b; a << b;", "mat3f a,b; a >> b;", "mat3f a,b; a ^ b;", "mat3f a,b; a || b;", "mat4d a,b; a % b;", "mat4d a,b; a & b;", "mat4d a,b; a && b;", "mat4d a,b; a << b;", "mat4d a,b; a >> b;", "mat4d a,b; a ^ b;", "mat4d a,b; a || b;", "string a,b; a & b;", "string a,b; a && b;", "string a,b; a - b;", "string a,b; a << b;", "string a,b; a >> b;", "string a,b; a ^ b;", "string a,b; a | b;", "string a,b; a || b;", "vec2d a,b; a & b;", "vec2d a,b; a && b;", "vec2d a,b; a << b;", "vec2d a,b; a >> b;", "vec2d a,b; a ^ b;", "vec2d a,b; a | b;", "vec2d a,b; a || b;", "vec2f a,b; a & b;", "vec2f a,b; a && b;", "vec2f a,b; a << b;", "vec2f a,b; a >> b;", "vec2f a,b; a ^ b;", "vec2f a,b; a | b;", "vec2f a,b; a || b;", "vec2i a,b; a & b;", "vec2i a,b; a && b;", "vec2i a,b; a << b;", "vec2i a,b; a >> b;", "vec2i a,b; a ^ b;", "vec2i a,b; a | b;", "vec2i a,b; a || b;", "vec3d a,b; a & b;", "vec3d a,b; a && b;", "vec3d a,b; a << b;", "vec3d a,b; a >> b;", "vec3d a,b; a ^ b;", "vec3d a,b; a | b;", "vec3d a,b; a || b;", "vec3f a,b; a & b;", "vec3f a,b; a && b;", "vec3f a,b; a << b;", "vec3f a,b; a >> b;", "vec3f a,b; a ^ b;", "vec3f a,b; a | b;", "vec3f a,b; a || b;", "vec3i a,b; a & b;", "vec3i a,b; a && b;", "vec3i a,b; a << b;", "vec3i a,b; a >> b;", "vec3i a,b; a ^ b;", "vec3i a,b; a | b;", "vec3i a,b; a || b;", "vec4d a,b; a & b;", "vec4d a,b; a && b;", "vec4d a,b; a << b;", "vec4d a,b; a >> b;", "vec4d a,b; a ^ b;", "vec4d a,b; a ^ b;", "vec4d a,b; a || b;", "vec4f a,b; a & b;", "vec4f a,b; a && b;", "vec4f a,b; a << b;", "vec4f a,b; a >> b;", "vec4f a,b; a ^ b;", "vec4f a,b; a | b;", "vec4f a,b; a || b;", "vec4i a,b; a & b;", "vec4i a,b; a && b;", "vec4i a,b; a << b;", "vec4i a,b; a >> b;", "vec4i a,b; a ^ b;", "vec4i a,b; a | b;", "vec4i a,b; a || b;", /// invalid unary ops "vec2f a; !a;", "vec2d a; !a;", "vec3d a; !a;", "vec3f a; !a;", "vec4f a; !a;", "vec4d a; !a;", "mat3f a; !a;", "mat3d a; !a;", "mat3f a; !a;", "mat4d a; !a;", "vec2f a; ~a;", "vec2d a; ~a;", "vec3d a; ~a;", "vec3f a; ~a;", "vec4f a; ~a;", "vec4d a; ~a;", "mat3f a; ~a;", "mat3d a; ~a;", "mat3f a; ~a;", "mat4d a; ~a;", /// missing function "nonexistent();", /// non/re declared "a;", "int a; int a;", "{ int a; int a; }", "int a, a;", "a ? b : c;", "a ? true : false;", "true ? a : c;", "true ? a : false;", "true ? true : c;", "a && b;", "a && true;", "true && b;", /// invalid crement "string a; ++a;", "vec2f a; ++a;", "vec3f a; ++a;", "vec4f a; ++a;", "mat3f a; ++a;", "mat4f a; ++a;", /// array size assignments "vec2f a; vec3f b; a=b;", "vec3f a; vec2f b; a=b;", "vec4f a; vec3f b; a=b;", "vec2d a; vec3d b; a=b;", "vec3d a; vec2d b; a=b;", "vec4d a; vec3d b; a=b;", "vec2i a; vec3i b; a=b;", "vec3i a; vec2i b; a=b;", "vec4i a; vec3i b; a=b;", "mat4f a; mat3f b; a=b;", "mat4d a; mat3d b; a=b;", /// string assignments "string a = 1;", "int a; string b; b=a;", "float a; string b; b=a;", "double a; string b; b=a;", "vec3f a; string b; b=a;", "mat3f a; string b; b=a;", /// array index "int a; a[0];", "vec3f a; string b; a[b];", "vec3f a; vec3f b; a[b];", "vec3f a; mat3f b; a[b];", "vec3f a; a[1,1];", "mat3f a; vec3f b; a[b,1];", "mat3f a; vec3f b; a[1,b];", /// unsupported implicit casts/ops "vec2f a; vec3f b; a*b;", "vec3f a; vec4f b; a*b;", "vec3f a; vec2f b; a*b;", "vec2i a; vec3f b; a*b;", "mat3f a; mat4f b; a*b;", "string a; mat4f b; a*b;", "int a; string b; a*b;", "string a; string b; a*b;", "string a; string b; a-b;", "string a; string b; a/b;", "~0.0f;", "vec3f a; ~a;" /// loops "break;", "continue;", // ternary "int a = true ? print(1) : print(2);", "true ? print(1) : 1;", "mat4d a; a ? 0 : 1;", "mat4f a; a ? 0 : 1;", "string a; a ? 0 : 1;", "vec2d a; a ? 0 : 1;", "vec2f a; a ? 0 : 1;", "vec2i a; a ? 0 : 1;", "vec3d a; a ? 0 : 1;", "vec3f a; a ? 0 : 1;", "vec3i a; a ? 0 : 1;", "vec4d a; a ? 0 : 1;", "vec4f a; a ? 0 : 1;", "vec4i a; a ? 0 : 1;", // "int a, b; (a ? b : 2) = 1;", "true ? {1,2} : {1,2,3};", "true ? \"foo\" : 1;", "true ? 1.0f : \"foo\";", "{1,1} && 1 ? true : false;", "{1,1} ? true : false;", "{1,1} && 1 ? \"foo\" : false;", "\"foo\" ? true : false;", "true ? {1,1} && 1: {1,1};", "true ? {1,1} : {1,1} && 1;", "string a; true ? a : 1;", "string a; true ? 1.0f : a;", // conditional "mat4d a; if (a) 1;", "mat4f a; if (a) 1;", "string a; if (a) 1;", "vec2d a; if (a) 1;", "vec2f a; if (a) 1;", "vec2i a; if (a) 1;", "vec3d a; if (a) 1;", "vec3f a; if (a) 1;", "vec3i a; if (a) 1;", "vec4d a; if (a) 1;", "vec4f a; if (a) 1;", "vec4i a; if (a) 1;", "if ({1,1} && 1) 1;", "if (true) {1,1} && 1;", // loops "mat4d a; for (;a;) 1;", "mat4f a; for (;a;) 1;", "string a; for (;a;) 1;", "vec2d a; for (;a;) 1;", "vec2f a; for (;a;) 1;", "vec2i a; for (;a;) 1;", "vec3d a; for (;a;) 1;", "vec3f a; for (;a;) 1;", "vec3i a; for (;a;) 1;", "vec4d a; for (;a;) 1;", "vec4f a; for (;a;) 1;", "vec4i a; for (;a;) 1;", "mat4d a; while (a) 1;", "mat4f a; while (a) 1;", "string a; while (a) 1;", "vec2d a; while (a) 1;", "vec2f a; while (a) 1;", "vec2i a; while (a) 1;", "vec3d a; while (a) 1;", "vec3f a; while (a) 1;", "vec3i a; while (a) 1;", "vec4d a; while (a) 1;", "vec4f a; while (a) 1;", "vec4i a; while (a) 1;", "mat4d a; do { 1; } while(a);", "mat4f a; do { 1; } while(a);", "string a; do { 1; } while(a);", "vec2d a; do { 1; } while(a);", "vec2f a; do { 1; } while(a);", "vec2i a; do { 1; } while(a);", "vec3d a; do { 1; } while(a);", "vec3f a; do { 1; } while(a);", "vec3i a; do { 1; } while(a);", "vec4d a; do { 1; } while(a);", "vec4f a; do { 1; } while(a);", "vec4i a; do { 1; } while(a);", // comma "vec2i v; v++, 1;", "vec2i v; 1, v++;" }; class TestComputeGeneratorFailures : public CppUnit::TestCase { public: CPPUNIT_TEST_SUITE(TestComputeGeneratorFailures); CPPUNIT_TEST(testFailures); CPPUNIT_TEST_SUITE_END(); void testFailures(); }; CPPUNIT_TEST_SUITE_REGISTRATION(TestComputeGeneratorFailures); void TestComputeGeneratorFailures::testFailures() { openvdb::ax::FunctionOptions opts; openvdb::ax::codegen::FunctionRegistry reg; // create logger that suppresses all messages, but still logs number of errors/warnings openvdb::ax::Logger logger([](const std::string&) {}); logger.setMaxErrors(1); for (const auto& code : tests) { const openvdb::ax::ast::Tree::ConstPtr ast = openvdb::ax::ast::parse(code.c_str(), logger); CPPUNIT_ASSERT_MESSAGE(ERROR_MSG("Unable to parse", code), ast.get()); unittest_util::LLVMState state; openvdb::ax::codegen::codegen_internal::ComputeGenerator gen(state.module(), opts, reg, logger); gen.generate(*ast); CPPUNIT_ASSERT_MESSAGE(ERROR_MSG("Expected Compiler Error", code), logger.hasError()); logger.clear(); } }
NVIDIA-Omniverse/ext-openvdb/openvdb_ax/openvdb_ax/test/backend/TestFunctionTypes.cc
// Copyright Contributors to the OpenVDB Project // SPDX-License-Identifier: MPL-2.0 #include "util.h" #include <openvdb_ax/codegen/FunctionTypes.h> #include <cppunit/extensions/HelperMacros.h> #include <llvm/IR/Verifier.h> #include <llvm/Support/raw_ostream.h> #include <sstream> /////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////// /// @brief Dummy derived function which implemented types struct TestFunction : public openvdb::ax::codegen::Function { static_assert(std::has_virtual_destructor <openvdb::ax::codegen::Function>::value, "Base class destructor is not virtual"); TestFunction(const std::vector<llvm::Type*>& types, llvm::Type* ret, const std::string& symbol) : openvdb::ax::codegen::Function(types.size(), symbol) , mTypes(types), mRet(ret) {} ~TestFunction() override {} llvm::Type* types(std::vector<llvm::Type*>& types, llvm::LLVMContext&) const override { types = mTypes; return mRet; } const std::vector<llvm::Type*> mTypes; llvm::Type* mRet; }; /// @brief Dummy derived IR function which implemented types and /// forwards on the generator struct TestIRFunction : public openvdb::ax::codegen::IRFunctionBase { static_assert(std::has_virtual_destructor <openvdb::ax::codegen::IRFunctionBase>::value, "Base class destructor is not virtual"); TestIRFunction(const std::vector<llvm::Type*>& types, llvm::Type* ret, const std::string& symbol, const openvdb::ax::codegen::IRFunctionBase::GeneratorCb& gen) : openvdb::ax::codegen::IRFunctionBase(symbol, gen, types.size()) , mTypes(types), mRet(ret) {} ~TestIRFunction() override {} llvm::Type* types(std::vector<llvm::Type*>& types, llvm::LLVMContext&) const override { types = mTypes; return mRet; } const std::vector<llvm::Type*> mTypes; llvm::Type* mRet; }; /// @brief static function to test c binding addresses struct CBindings { static void voidfunc() {} static int16_t scalarfunc(bool,int16_t,int32_t,int64_t,float,double) { return int16_t(); } static int32_t scalatptsfunc(bool*,int16_t*,int32_t*,int64_t*,float*,double*) { return int32_t(); } static int64_t arrayfunc(bool(*)[1],int16_t(*)[2],int32_t(*)[3],int64_t(*)[4],float(*)[5],double(*)[6]) { return int64_t(); } static void multiptrfunc(void*, void**, void***, float*, float**, float***) { } template <typename Type> static inline Type tmplfunc() { return Type(); } }; /// @brief Helper method to finalize a function (with a terminator) /// If F is nullptr, finalizes the current function inline llvm::Instruction* finalizeFunction(llvm::IRBuilder<>& B, llvm::Function* F = nullptr) { auto IP = B.saveIP(); if (F) { if (F->empty()) { B.SetInsertPoint(llvm::BasicBlock::Create(B.getContext(), "", F)); } else { B.SetInsertPoint(&(F->getEntryBlock())); } } llvm::Instruction* ret = B.CreateRetVoid(); B.restoreIP(IP); return ret; } /// @brief Defines to wrap the verification of IR #define VERIFY_FUNCTION_IR(Function) { \ std::string error; llvm::raw_string_ostream os(error); \ const bool valid = !llvm::verifyFunction(*Function, &os); \ CPPUNIT_ASSERT_MESSAGE(os.str(), valid); \ } #define VERIFY_MODULE_IR(Module) { \ std::string error; llvm::raw_string_ostream os(error); \ const bool valid = !llvm::verifyModule(*Module, &os); \ CPPUNIT_ASSERT_MESSAGE(os.str(), valid); \ } #define VERIFY_MODULE_IR_INVALID(Module) { \ const bool valid = llvm::verifyModule(*Module); \ CPPUNIT_ASSERT_MESSAGE("Expected IR to be invalid!", valid); \ } #define VERIFY_FUNCTION_IR_INVALID(Function) { \ const bool valid = llvm::verifyFunction(*Function); \ CPPUNIT_ASSERT_MESSAGE("Expected IR to be invalid!", valid); \ } /////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////// class TestFunctionTypes : public CppUnit::TestCase { public: CPPUNIT_TEST_SUITE(TestFunctionTypes); CPPUNIT_TEST(testLLVMTypesFromSignature); CPPUNIT_TEST(testLLVMFunctionTypeFromSignature); CPPUNIT_TEST(testPrintSignature); // Test Function::create, Function::types and other base methods CPPUNIT_TEST(testFunctionCreate); // Test Function::call CPPUNIT_TEST(testFunctionCall); // Test Function::match CPPUNIT_TEST(testFunctionMatch); // Test derived CFunctions, mainly CFunction::create and CFunction::types CPPUNIT_TEST(testCFunctions); // Test C constant folding CPPUNIT_TEST(testCFunctionCF); // Test derived IR Function, IRFunctionBase::create and IRFunctionBase::call CPPUNIT_TEST(testIRFunctions); // Test SRET methods for both C and IR functions CPPUNIT_TEST(testSRETFunctions); CPPUNIT_TEST_SUITE_END(); void testLLVMTypesFromSignature(); void testLLVMFunctionTypeFromSignature(); void testPrintSignature(); void testFunctionCreate(); void testFunctionCall(); void testFunctionMatch(); void testCFunctions(); void testCFunctionCF(); void testIRFunctions(); void testSRETFunctions(); }; CPPUNIT_TEST_SUITE_REGISTRATION(TestFunctionTypes); void TestFunctionTypes::testLLVMTypesFromSignature() { using openvdb::ax::codegen::llvmTypesFromSignature; unittest_util::LLVMState state; llvm::Type* type = nullptr; std::vector<llvm::Type*> types; type = llvmTypesFromSignature<void()>(state.context()); CPPUNIT_ASSERT(type); CPPUNIT_ASSERT(type->isVoidTy()); type = llvmTypesFromSignature<void()>(state.context(), &types); CPPUNIT_ASSERT(type); CPPUNIT_ASSERT(type->isVoidTy()); CPPUNIT_ASSERT(types.empty()); type = llvmTypesFromSignature<float()>(state.context(), &types); CPPUNIT_ASSERT(type); CPPUNIT_ASSERT(type->isFloatTy()); CPPUNIT_ASSERT(types.empty()); type = llvmTypesFromSignature<float(double, int64_t, float(*)[3])>(state.context(), &types); CPPUNIT_ASSERT(type); CPPUNIT_ASSERT(type->isFloatTy()); CPPUNIT_ASSERT_EQUAL(size_t(3), types.size()); CPPUNIT_ASSERT(types[0]->isDoubleTy()); CPPUNIT_ASSERT(types[1]->isIntegerTy(64)); CPPUNIT_ASSERT(types[2]->isPointerTy()); type = types[2]->getPointerElementType(); CPPUNIT_ASSERT(type); CPPUNIT_ASSERT(type->isArrayTy()); type = type->getArrayElementType(); CPPUNIT_ASSERT(type); CPPUNIT_ASSERT(type->isFloatTy()); } void TestFunctionTypes::testLLVMFunctionTypeFromSignature() { using openvdb::ax::codegen::llvmFunctionTypeFromSignature; unittest_util::LLVMState state; llvm::FunctionType* ftype = nullptr; std::vector<llvm::Type*> types; ftype = llvmFunctionTypeFromSignature<void()>(state.context()); CPPUNIT_ASSERT(ftype); CPPUNIT_ASSERT(ftype->getReturnType()->isVoidTy()); CPPUNIT_ASSERT_EQUAL(0u, ftype->getNumParams()); ftype = llvmFunctionTypeFromSignature<float(double, int64_t, float(*)[3])>(state.context()); CPPUNIT_ASSERT(ftype); CPPUNIT_ASSERT(ftype->getReturnType()->isFloatTy()); CPPUNIT_ASSERT_EQUAL(3u, ftype->getNumParams()); CPPUNIT_ASSERT(ftype->getParamType(0)->isDoubleTy()); CPPUNIT_ASSERT(ftype->getParamType(1)->isIntegerTy(64)); CPPUNIT_ASSERT(ftype->getParamType(2)->isPointerTy()); llvm::Type* type = ftype->getParamType(2)->getPointerElementType(); CPPUNIT_ASSERT(type); CPPUNIT_ASSERT(type->isArrayTy()); type = type->getArrayElementType(); CPPUNIT_ASSERT(type); CPPUNIT_ASSERT(type->isFloatTy()); } void TestFunctionTypes::testPrintSignature() { using openvdb::ax::codegen::printSignature; unittest_util::LLVMState state; llvm::LLVMContext& C = state.context(); std::vector<llvm::Type*> types; const llvm::Type* vt = llvm::Type::getVoidTy(C); std::ostringstream os; printSignature(os, types, vt); CPPUNIT_ASSERT(os.str() == "void()"); os.str(""); types.emplace_back(llvm::Type::getInt32Ty(C)); types.emplace_back(llvm::Type::getInt64Ty(C)); printSignature(os, types, vt); CPPUNIT_ASSERT_EQUAL(std::string("void(i32; i64)"), os.str()); os.str(""); printSignature(os, types, vt, "test"); CPPUNIT_ASSERT_EQUAL(std::string("void test(i32; i64)"), os.str()); os.str(""); printSignature(os, types, vt, "", {"one"}, true); CPPUNIT_ASSERT_EQUAL(std::string("void(int32 one; int64)"), os.str()); os.str(""); printSignature(os, types, vt, "", {"one", "two"}, true); CPPUNIT_ASSERT_EQUAL(std::string("void(int32 one; int64 two)"), os.str()); os.str(""); printSignature(os, types, vt, "1", {"one", "two", "three"}, true); CPPUNIT_ASSERT_EQUAL(std::string("void 1(int32 one; int64 two)"), os.str()); os.str(""); printSignature(os, types, vt, "1", {"", "two"}, false); CPPUNIT_ASSERT_EQUAL(std::string("void 1(i32; i64 two)"), os.str()); os.str(""); printSignature(os, types, vt, "1", {"", "two"}, false); CPPUNIT_ASSERT_EQUAL(std::string("void 1(i32; i64 two)"), os.str()); os.str(""); types.emplace_back(llvm::Type::getInt8PtrTy(C)); types.emplace_back(llvm::ArrayType::get(llvm::Type::getInt32Ty(C), 3)); printSignature(os, types, llvm::Type::getInt64Ty(C), "test", {"", "two"}, true); CPPUNIT_ASSERT_EQUAL(std::string("int64 test(int32; int64 two; i8*; vec3i)"), os.str()); os.str(""); types.clear(); printSignature(os, types, llvm::Type::getInt64Ty(C), "test", {"", "two"}); CPPUNIT_ASSERT_EQUAL(std::string("i64 test()"), os.str()); os.str(""); } void TestFunctionTypes::testFunctionCreate() { using openvdb::ax::codegen::Function; unittest_util::LLVMState state; llvm::LLVMContext& C = state.context(); llvm::Module& M = state.module(); std::vector<llvm::Type*> types; llvm::Type* type = nullptr; std::ostringstream os; Function::Ptr test(new TestFunction({llvm::Type::getInt32Ty(C)}, llvm::Type::getVoidTy(C), "ax.test")); // test types type = test->types(types, C); CPPUNIT_ASSERT_EQUAL(size_t(1), types.size()); CPPUNIT_ASSERT(types[0]->isIntegerTy(32)); CPPUNIT_ASSERT(type); CPPUNIT_ASSERT(type->isVoidTy()); // test various getters CPPUNIT_ASSERT_EQUAL(std::string("ax.test"), std::string(test->symbol())); CPPUNIT_ASSERT_EQUAL(size_t(1), test->size()); CPPUNIT_ASSERT_EQUAL(std::string(""), std::string(test->argName(0))); CPPUNIT_ASSERT_EQUAL(std::string(""), std::string(test->argName(1))); // test create llvm::Function* function = test->create(C); // additional create call should create a new function CPPUNIT_ASSERT(function != test->create(C)); CPPUNIT_ASSERT(function); CPPUNIT_ASSERT(!function->isVarArg()); CPPUNIT_ASSERT(function->empty()); CPPUNIT_ASSERT_EQUAL(size_t(1), function->arg_size()); llvm::FunctionType* ftype = function->getFunctionType(); CPPUNIT_ASSERT(ftype); CPPUNIT_ASSERT(ftype->getReturnType()->isVoidTy()); CPPUNIT_ASSERT_EQUAL(1u, ftype->getNumParams()); CPPUNIT_ASSERT(ftype->getParamType(0)->isIntegerTy(32)); CPPUNIT_ASSERT(function->getAttributes().isEmpty()); // test create with a module (same as above, but check inserted into M) CPPUNIT_ASSERT(!M.getFunction("ax.test")); function = test->create(M); // additional call should match CPPUNIT_ASSERT_EQUAL(function, test->create(M)); CPPUNIT_ASSERT(function); CPPUNIT_ASSERT(M.getFunction("ax.test")); CPPUNIT_ASSERT_EQUAL(function, M.getFunction("ax.test")); CPPUNIT_ASSERT(!function->isVarArg()); CPPUNIT_ASSERT(function->empty()); CPPUNIT_ASSERT_EQUAL(size_t(1), function->arg_size()); ftype = function->getFunctionType(); CPPUNIT_ASSERT(ftype); CPPUNIT_ASSERT(ftype->getReturnType()->isVoidTy()); CPPUNIT_ASSERT_EQUAL(1u, ftype->getNumParams()); CPPUNIT_ASSERT(ftype->getParamType(0)->isIntegerTy(32)); CPPUNIT_ASSERT(function->getAttributes().isEmpty()); // test print os.str(""); test->print(C, os, "name", /*axtypes=*/true); CPPUNIT_ASSERT_EQUAL(std::string("void name(int32)"), os.str()); // // Test empty signature test.reset(new TestFunction({}, llvm::Type::getInt32Ty(C), "ax.empty.test")); types.clear(); // test types type = test->types(types, C); CPPUNIT_ASSERT_EQUAL(size_t(0), types.size()); CPPUNIT_ASSERT(type); CPPUNIT_ASSERT(type->isIntegerTy(32)); // test various getters CPPUNIT_ASSERT_EQUAL(std::string("ax.empty.test"), std::string(test->symbol())); CPPUNIT_ASSERT_EQUAL(size_t(0), test->size()); CPPUNIT_ASSERT_EQUAL(std::string(""), std::string(test->argName(0))); // test create function = test->create(C); CPPUNIT_ASSERT(function); CPPUNIT_ASSERT(!function->isVarArg()); CPPUNIT_ASSERT(function->empty()); CPPUNIT_ASSERT_EQUAL(size_t(0), function->arg_size()); ftype = function->getFunctionType(); CPPUNIT_ASSERT(ftype); CPPUNIT_ASSERT(ftype->getReturnType()->isIntegerTy(32)); CPPUNIT_ASSERT_EQUAL(0u, ftype->getNumParams()); CPPUNIT_ASSERT(function->getAttributes().isEmpty()); // test create with a module (same as above, but check inserted into M) CPPUNIT_ASSERT(!M.getFunction("ax.empty.test")); function = test->create(M); CPPUNIT_ASSERT(function); CPPUNIT_ASSERT(M.getFunction("ax.empty.test")); CPPUNIT_ASSERT_EQUAL(function, M.getFunction("ax.empty.test")); CPPUNIT_ASSERT_EQUAL(function, test->create(M)); // test print os.str(""); test->print(C, os, "name", /*axtypes=*/true); CPPUNIT_ASSERT_EQUAL(std::string("int32 name()"), os.str()); // // Test scalar types test.reset(new TestFunction({ llvm::Type::getInt1Ty(C), llvm::Type::getInt16Ty(C), llvm::Type::getInt32Ty(C), llvm::Type::getInt64Ty(C), llvm::Type::getFloatTy(C), llvm::Type::getDoubleTy(C), }, llvm::Type::getInt16Ty(C), "ax.scalars.test")); types.clear(); CPPUNIT_ASSERT_EQUAL(std::string("ax.scalars.test"), std::string(test->symbol())); type = test->types(types, state.context()); CPPUNIT_ASSERT(type); CPPUNIT_ASSERT(type->isIntegerTy(16)); CPPUNIT_ASSERT_EQUAL(size_t(6), types.size()); CPPUNIT_ASSERT(types[0]->isIntegerTy(1)); CPPUNIT_ASSERT(types[1]->isIntegerTy(16)); CPPUNIT_ASSERT(types[2]->isIntegerTy(32)); CPPUNIT_ASSERT(types[3]->isIntegerTy(64)); CPPUNIT_ASSERT(types[4]->isFloatTy()); CPPUNIT_ASSERT(types[5]->isDoubleTy()); // test create function = test->create(C); CPPUNIT_ASSERT(function); CPPUNIT_ASSERT(!function->isVarArg()); CPPUNIT_ASSERT(function->empty()); CPPUNIT_ASSERT_EQUAL(size_t(6), function->arg_size()); ftype = function->getFunctionType(); CPPUNIT_ASSERT(ftype); CPPUNIT_ASSERT(ftype->getReturnType()->isIntegerTy(16)); CPPUNIT_ASSERT_EQUAL(6u, ftype->getNumParams()); CPPUNIT_ASSERT(ftype->getParamType(0)->isIntegerTy(1)); CPPUNIT_ASSERT(ftype->getParamType(1)->isIntegerTy(16)); CPPUNIT_ASSERT(ftype->getParamType(2)->isIntegerTy(32)); CPPUNIT_ASSERT(ftype->getParamType(3)->isIntegerTy(64)); CPPUNIT_ASSERT(ftype->getParamType(4)->isFloatTy()); CPPUNIT_ASSERT(ftype->getParamType(5)->isDoubleTy()); CPPUNIT_ASSERT(function->getAttributes().isEmpty()); // test create with a module (same as above, but check inserted into M) CPPUNIT_ASSERT(!M.getFunction("ax.scalars.test")); function = test->create(M); CPPUNIT_ASSERT(function); CPPUNIT_ASSERT(M.getFunction("ax.scalars.test")); CPPUNIT_ASSERT_EQUAL(function, M.getFunction("ax.scalars.test")); CPPUNIT_ASSERT_EQUAL(function, test->create(M)); // test print os.str(""); test->print(C, os, "name", /*axtypes=*/true); CPPUNIT_ASSERT_EQUAL(std::string("int16 name(bool; int16; int32; int64; float; double)"), os.str()); // // Test scalar ptrs types test.reset(new TestFunction({ llvm::Type::getInt1Ty(C)->getPointerTo(), llvm::Type::getInt16Ty(C)->getPointerTo(), llvm::Type::getInt32Ty(C)->getPointerTo(), llvm::Type::getInt64Ty(C)->getPointerTo(), llvm::Type::getFloatTy(C)->getPointerTo(), llvm::Type::getDoubleTy(C)->getPointerTo() }, llvm::Type::getInt32Ty(C), "ax.scalarptrs.test")); types.clear(); CPPUNIT_ASSERT_EQUAL(std::string("ax.scalarptrs.test"), std::string(test->symbol())); type = test->types(types, C); CPPUNIT_ASSERT(type->isIntegerTy(32)); CPPUNIT_ASSERT_EQUAL(size_t(6), types.size()); CPPUNIT_ASSERT(types[0] == llvm::Type::getInt1Ty(C)->getPointerTo()); CPPUNIT_ASSERT(types[1] == llvm::Type::getInt16Ty(C)->getPointerTo()); CPPUNIT_ASSERT(types[2] == llvm::Type::getInt32Ty(C)->getPointerTo()); CPPUNIT_ASSERT(types[3] == llvm::Type::getInt64Ty(C)->getPointerTo()); CPPUNIT_ASSERT(types[4] == llvm::Type::getFloatTy(C)->getPointerTo()); CPPUNIT_ASSERT(types[5] == llvm::Type::getDoubleTy(C)->getPointerTo()); // test create function = test->create(C); CPPUNIT_ASSERT(function); CPPUNIT_ASSERT(!function->isVarArg()); CPPUNIT_ASSERT(function->empty()); CPPUNIT_ASSERT_EQUAL(size_t(6), function->arg_size()); ftype = function->getFunctionType(); CPPUNIT_ASSERT(ftype); CPPUNIT_ASSERT(ftype->getReturnType()->isIntegerTy(32)); CPPUNIT_ASSERT_EQUAL(6u, ftype->getNumParams()); CPPUNIT_ASSERT(ftype->getParamType(0) == llvm::Type::getInt1Ty(C)->getPointerTo()); CPPUNIT_ASSERT(ftype->getParamType(1) == llvm::Type::getInt16Ty(C)->getPointerTo()); CPPUNIT_ASSERT(ftype->getParamType(2) == llvm::Type::getInt32Ty(C)->getPointerTo()); CPPUNIT_ASSERT(ftype->getParamType(3) == llvm::Type::getInt64Ty(C)->getPointerTo()); CPPUNIT_ASSERT(ftype->getParamType(4) == llvm::Type::getFloatTy(C)->getPointerTo()); CPPUNIT_ASSERT(ftype->getParamType(5) == llvm::Type::getDoubleTy(C)->getPointerTo()); CPPUNIT_ASSERT(function->getAttributes().isEmpty()); // test create with a module (same as above, but check inserted into M) CPPUNIT_ASSERT(!M.getFunction("ax.scalarptrs.test")); function = test->create(M); CPPUNIT_ASSERT(function); CPPUNIT_ASSERT(M.getFunction("ax.scalarptrs.test")); CPPUNIT_ASSERT_EQUAL(function, M.getFunction("ax.scalarptrs.test")); CPPUNIT_ASSERT_EQUAL(function, test->create(M)); // // Test array ptrs types test.reset(new TestFunction({ llvm::ArrayType::get(llvm::Type::getInt32Ty(C), 2)->getPointerTo(), // vec2i llvm::ArrayType::get(llvm::Type::getFloatTy(C), 2)->getPointerTo(), // vec2f llvm::ArrayType::get(llvm::Type::getDoubleTy(C), 2)->getPointerTo(), // vec2d llvm::ArrayType::get(llvm::Type::getInt32Ty(C), 3)->getPointerTo(), // vec3i llvm::ArrayType::get(llvm::Type::getFloatTy(C), 3)->getPointerTo(), // vec3f llvm::ArrayType::get(llvm::Type::getDoubleTy(C), 3)->getPointerTo(), // vec3d llvm::ArrayType::get(llvm::Type::getInt32Ty(C), 4)->getPointerTo(), // vec4i llvm::ArrayType::get(llvm::Type::getFloatTy(C), 4)->getPointerTo(), // vec4f llvm::ArrayType::get(llvm::Type::getDoubleTy(C), 4)->getPointerTo(), // vec4d llvm::ArrayType::get(llvm::Type::getInt32Ty(C), 9)->getPointerTo(), // ix9 (not supported by ax) llvm::ArrayType::get(llvm::Type::getFloatTy(C), 9)->getPointerTo(), // mat3f llvm::ArrayType::get(llvm::Type::getDoubleTy(C), 9)->getPointerTo(), // mat3d llvm::ArrayType::get(llvm::Type::getInt32Ty(C), 16)->getPointerTo(), // ix16 (not supported by ax) llvm::ArrayType::get(llvm::Type::getFloatTy(C), 16)->getPointerTo(), // mat3f llvm::ArrayType::get(llvm::Type::getDoubleTy(C), 16)->getPointerTo() // mat3d }, llvm::Type::getInt64Ty(C), "ax.arrayptrs.test")); types.clear(); type = test->types(types, C); CPPUNIT_ASSERT(type->isIntegerTy(64)); CPPUNIT_ASSERT_EQUAL(size_t(15), types.size()); CPPUNIT_ASSERT(types[0] == llvm::ArrayType::get(llvm::Type::getInt32Ty(C), 2)->getPointerTo()); CPPUNIT_ASSERT(types[1] == llvm::ArrayType::get(llvm::Type::getFloatTy(C), 2)->getPointerTo()); CPPUNIT_ASSERT(types[2] == llvm::ArrayType::get(llvm::Type::getDoubleTy(C), 2)->getPointerTo()); CPPUNIT_ASSERT(types[3] == llvm::ArrayType::get(llvm::Type::getInt32Ty(C), 3)->getPointerTo()); CPPUNIT_ASSERT(types[4] == llvm::ArrayType::get(llvm::Type::getFloatTy(C), 3)->getPointerTo()); CPPUNIT_ASSERT(types[5] == llvm::ArrayType::get(llvm::Type::getDoubleTy(C), 3)->getPointerTo()); CPPUNIT_ASSERT(types[6] == llvm::ArrayType::get(llvm::Type::getInt32Ty(C), 4)->getPointerTo()); CPPUNIT_ASSERT(types[7] == llvm::ArrayType::get(llvm::Type::getFloatTy(C), 4)->getPointerTo()); CPPUNIT_ASSERT(types[8] == llvm::ArrayType::get(llvm::Type::getDoubleTy(C), 4)->getPointerTo()); CPPUNIT_ASSERT(types[9] == llvm::ArrayType::get(llvm::Type::getInt32Ty(C), 9)->getPointerTo()); CPPUNIT_ASSERT(types[10] == llvm::ArrayType::get(llvm::Type::getFloatTy(C), 9)->getPointerTo()); CPPUNIT_ASSERT(types[11] == llvm::ArrayType::get(llvm::Type::getDoubleTy(C), 9)->getPointerTo()); CPPUNIT_ASSERT(types[12] == llvm::ArrayType::get(llvm::Type::getInt32Ty(C), 16)->getPointerTo()); CPPUNIT_ASSERT(types[13] == llvm::ArrayType::get(llvm::Type::getFloatTy(C), 16)->getPointerTo()); CPPUNIT_ASSERT(types[14] == llvm::ArrayType::get(llvm::Type::getDoubleTy(C), 16)->getPointerTo()); // test create function = test->create(C); CPPUNIT_ASSERT(function); CPPUNIT_ASSERT(!function->isVarArg()); CPPUNIT_ASSERT(function->empty()); CPPUNIT_ASSERT_EQUAL(size_t(15), function->arg_size()); ftype = function->getFunctionType(); CPPUNIT_ASSERT(ftype); CPPUNIT_ASSERT(ftype->getReturnType()->isIntegerTy(64)); CPPUNIT_ASSERT_EQUAL(15u, ftype->getNumParams()); CPPUNIT_ASSERT(ftype->getParamType(0) == llvm::ArrayType::get(llvm::Type::getInt32Ty(C), 2)->getPointerTo()); CPPUNIT_ASSERT(ftype->getParamType(1) == llvm::ArrayType::get(llvm::Type::getFloatTy(C), 2)->getPointerTo()); CPPUNIT_ASSERT(ftype->getParamType(2) == llvm::ArrayType::get(llvm::Type::getDoubleTy(C), 2)->getPointerTo()); CPPUNIT_ASSERT(ftype->getParamType(3) == llvm::ArrayType::get(llvm::Type::getInt32Ty(C), 3)->getPointerTo()); CPPUNIT_ASSERT(ftype->getParamType(4) == llvm::ArrayType::get(llvm::Type::getFloatTy(C), 3)->getPointerTo()); CPPUNIT_ASSERT(ftype->getParamType(5) == llvm::ArrayType::get(llvm::Type::getDoubleTy(C), 3)->getPointerTo()); CPPUNIT_ASSERT(ftype->getParamType(6) == llvm::ArrayType::get(llvm::Type::getInt32Ty(C), 4)->getPointerTo()); CPPUNIT_ASSERT(ftype->getParamType(7) == llvm::ArrayType::get(llvm::Type::getFloatTy(C), 4)->getPointerTo()); CPPUNIT_ASSERT(ftype->getParamType(8) == llvm::ArrayType::get(llvm::Type::getDoubleTy(C), 4)->getPointerTo()); CPPUNIT_ASSERT(ftype->getParamType(9) == llvm::ArrayType::get(llvm::Type::getInt32Ty(C), 9)->getPointerTo()); CPPUNIT_ASSERT(ftype->getParamType(10) == llvm::ArrayType::get(llvm::Type::getFloatTy(C), 9)->getPointerTo()); CPPUNIT_ASSERT(ftype->getParamType(11) == llvm::ArrayType::get(llvm::Type::getDoubleTy(C), 9)->getPointerTo()); CPPUNIT_ASSERT(ftype->getParamType(12) == llvm::ArrayType::get(llvm::Type::getInt32Ty(C), 16)->getPointerTo()); CPPUNIT_ASSERT(ftype->getParamType(13) == llvm::ArrayType::get(llvm::Type::getFloatTy(C), 16)->getPointerTo()); CPPUNIT_ASSERT(ftype->getParamType(14) == llvm::ArrayType::get(llvm::Type::getDoubleTy(C), 16)->getPointerTo()); CPPUNIT_ASSERT(function->getAttributes().isEmpty()); // test create with a module (same as above, but check inserted into M) CPPUNIT_ASSERT(!M.getFunction("ax.arrayptrs.test")); function = test->create(M); CPPUNIT_ASSERT(function); CPPUNIT_ASSERT(M.getFunction("ax.arrayptrs.test")); CPPUNIT_ASSERT_EQUAL(function, M.getFunction("ax.arrayptrs.test")); CPPUNIT_ASSERT_EQUAL(function, test->create(M)); // test print - note mat/i types are not ax types os.str(""); test->print(C, os, "name", /*axtypes=*/true); CPPUNIT_ASSERT_EQUAL(std::string("int64 name(vec2i; vec2f; vec2d; vec3i; vec3f; vec3d;" " vec4i; vec4f; vec4d; [9 x i32]*; mat3f; mat3d; [16 x i32]*; mat4f; mat4d)"), os.str()); // // Test void ptr arguments test.reset(new TestFunction({ llvm::Type::getVoidTy(C)->getPointerTo(), llvm::Type::getVoidTy(C)->getPointerTo()->getPointerTo(), llvm::Type::getVoidTy(C)->getPointerTo()->getPointerTo()->getPointerTo(), llvm::Type::getFloatTy(C)->getPointerTo(), llvm::Type::getFloatTy(C)->getPointerTo()->getPointerTo(), llvm::Type::getFloatTy(C)->getPointerTo()->getPointerTo()->getPointerTo() }, llvm::Type::getVoidTy(C), "ax.vptrs.test")); types.clear(); // Note that C++ bindings will convert void* to i8* but they should be // unmodified in this example where we use the derived TestFunction type = test->types(types, C); CPPUNIT_ASSERT(type->isVoidTy()); CPPUNIT_ASSERT_EQUAL(size_t(6), types.size()); CPPUNIT_ASSERT(types[0] == llvm::Type::getVoidTy(C)->getPointerTo()); CPPUNIT_ASSERT(types[1] == llvm::Type::getVoidTy(C)->getPointerTo()->getPointerTo()); CPPUNIT_ASSERT(types[2] == llvm::Type::getVoidTy(C)->getPointerTo()->getPointerTo()->getPointerTo()); CPPUNIT_ASSERT(types[3] == llvm::Type::getFloatTy(C)->getPointerTo()); CPPUNIT_ASSERT(types[4] == llvm::Type::getFloatTy(C)->getPointerTo()->getPointerTo()); CPPUNIT_ASSERT(types[5] == llvm::Type::getFloatTy(C)->getPointerTo()->getPointerTo()->getPointerTo()); // test create function = test->create(C); CPPUNIT_ASSERT(function); CPPUNIT_ASSERT(!function->isVarArg()); CPPUNIT_ASSERT(function->empty()); CPPUNIT_ASSERT_EQUAL(size_t(6), function->arg_size()); ftype = function->getFunctionType(); CPPUNIT_ASSERT(ftype); CPPUNIT_ASSERT(ftype->getReturnType()->isVoidTy()); CPPUNIT_ASSERT_EQUAL(6u, ftype->getNumParams()); CPPUNIT_ASSERT(ftype->getParamType(0) == llvm::Type::getVoidTy(C)->getPointerTo()); CPPUNIT_ASSERT(ftype->getParamType(1) == llvm::Type::getVoidTy(C)->getPointerTo()->getPointerTo()); CPPUNIT_ASSERT(ftype->getParamType(2) == llvm::Type::getVoidTy(C)->getPointerTo()->getPointerTo()->getPointerTo()); CPPUNIT_ASSERT(ftype->getParamType(3) == llvm::Type::getFloatTy(C)->getPointerTo()); CPPUNIT_ASSERT(ftype->getParamType(4) == llvm::Type::getFloatTy(C)->getPointerTo()->getPointerTo()); CPPUNIT_ASSERT(ftype->getParamType(5) == llvm::Type::getFloatTy(C)->getPointerTo()->getPointerTo()->getPointerTo()); CPPUNIT_ASSERT(function->getAttributes().isEmpty()); // test create with a module (same as above, but check inserted into M) CPPUNIT_ASSERT(!M.getFunction("ax.vptrs.test")); function = test->create(M); CPPUNIT_ASSERT(function); CPPUNIT_ASSERT(M.getFunction("ax.vptrs.test")); CPPUNIT_ASSERT_EQUAL(function, M.getFunction("ax.vptrs.test")); CPPUNIT_ASSERT_EQUAL(function, test->create(M)); // // Test creation with builder methods // @note These methods may be moved to the constructor in the future CPPUNIT_ASSERT(test->dependencies().empty()); CPPUNIT_ASSERT(!test->hasParamAttribute(0, llvm::Attribute::ReadOnly)); CPPUNIT_ASSERT(!test->hasParamAttribute(-1, llvm::Attribute::ReadOnly)); test->setDependencies({"dep"}); CPPUNIT_ASSERT_EQUAL(size_t(1), test->dependencies().size()); CPPUNIT_ASSERT_EQUAL(std::string("dep"), std::string(test->dependencies().front())); test->setDependencies({}); CPPUNIT_ASSERT(test->dependencies().empty()); test->setFnAttributes({llvm::Attribute::ReadOnly}); test->setRetAttributes({llvm::Attribute::NoAlias}); test->setParamAttributes(1, {llvm::Attribute::WriteOnly}); test->setParamAttributes(-1, {llvm::Attribute::WriteOnly}); CPPUNIT_ASSERT(!test->hasParamAttribute(0, llvm::Attribute::WriteOnly)); CPPUNIT_ASSERT(!test->hasParamAttribute(2, llvm::Attribute::WriteOnly)); CPPUNIT_ASSERT(test->hasParamAttribute(1, llvm::Attribute::WriteOnly)); CPPUNIT_ASSERT(test->hasParamAttribute(-1, llvm::Attribute::WriteOnly)); function = test->create(C); CPPUNIT_ASSERT(function); llvm::AttributeList list = function->getAttributes(); CPPUNIT_ASSERT(!list.isEmpty()); CPPUNIT_ASSERT(!list.hasParamAttrs(0)); CPPUNIT_ASSERT(!list.hasParamAttrs(2)); CPPUNIT_ASSERT(list.hasParamAttr(1, llvm::Attribute::WriteOnly)); CPPUNIT_ASSERT(list.hasFnAttribute(llvm::Attribute::ReadOnly)); CPPUNIT_ASSERT(list.hasAttribute(llvm::AttributeList::ReturnIndex, llvm::Attribute::NoAlias)); } void TestFunctionTypes::testFunctionCall() { using openvdb::ax::codegen::Function; using openvdb::ax::codegen::LLVMType; using openvdb::ax::AXString; // { unittest_util::LLVMState state; llvm::LLVMContext& C = state.context(); llvm::Module& M = state.module(); llvm::IRBuilder<> B(state.scratchBlock()); llvm::Function* BaseFunction = B.GetInsertBlock()->getParent(); Function::Ptr test(new TestFunction({llvm::Type::getInt32Ty(C)}, llvm::Type::getVoidTy(C), "ax.test")); llvm::Function* function = test->create(M); llvm::Value* arg = B.getInt32(1); llvm::Value* result = test->call({arg}, B, /*cast*/false); CPPUNIT_ASSERT(result); llvm::CallInst* call = llvm::dyn_cast<llvm::CallInst>(result); CPPUNIT_ASSERT(call); CPPUNIT_ASSERT_EQUAL(function, call->getCalledFunction()); CPPUNIT_ASSERT_EQUAL(1u, call->getNumArgOperands()); CPPUNIT_ASSERT_EQUAL(arg, call->getArgOperand(0)); // Test the builder is pointing to the correct location CPPUNIT_ASSERT_EQUAL(&(BaseFunction->getEntryBlock()), B.GetInsertBlock()); // add a ret void to the current function and to the created function, // then check the IR is valid (this will check the function arguments // and creation are all correct) finalizeFunction(B); finalizeFunction(B, function); VERIFY_FUNCTION_IR(function); VERIFY_MODULE_IR(&M); } { unittest_util::LLVMState state; llvm::LLVMContext& C = state.context(); llvm::Module& M = state.module(); llvm::IRBuilder<> B(state.scratchBlock()); llvm::Function* BaseFunction = B.GetInsertBlock()->getParent(); Function::Ptr test(new TestFunction({llvm::Type::getInt32Ty(C)}, llvm::Type::getVoidTy(C), "ax.test")); // call first, then create llvm::Value* arg = B.getInt32(1); llvm::Value* result = test->call({arg}, B, /*cast*/false); llvm::Function* function = test->create(M); CPPUNIT_ASSERT(result); llvm::CallInst* call = llvm::dyn_cast<llvm::CallInst>(result); CPPUNIT_ASSERT(call); CPPUNIT_ASSERT_EQUAL(function, call->getCalledFunction()); CPPUNIT_ASSERT_EQUAL(1u, call->getNumArgOperands()); CPPUNIT_ASSERT_EQUAL(arg, call->getArgOperand(0)); // Test the builder is pointing to the correct location CPPUNIT_ASSERT_EQUAL(&(BaseFunction->getEntryBlock()), B.GetInsertBlock()); // add a ret void to the current function and to the created function, // then check the IR is valid (this will check the function arguments // and creation are all correct) finalizeFunction(B); finalizeFunction(B, function); VERIFY_FUNCTION_IR(function); VERIFY_MODULE_IR(&M); } // Now test casting/argument mismatching for most argument types unittest_util::LLVMState state; llvm::LLVMContext& C = state.context(); llvm::Module& M = state.module(); llvm::IRBuilder<> B(state.scratchBlock()); Function::Ptr test(new TestFunction({ llvm::ArrayType::get(llvm::Type::getInt32Ty(C), 3)->getPointerTo(), // vec3i llvm::ArrayType::get(llvm::Type::getDoubleTy(C), 2)->getPointerTo(), // vec2d llvm::ArrayType::get(llvm::Type::getDoubleTy(C), 9)->getPointerTo(), // mat3d llvm::Type::getInt32Ty(C), // int llvm::Type::getInt64Ty(C), // int64 llvm::Type::getFloatTy(C) // float }, llvm::Type::getVoidTy(C), "ax.test")); std::vector<llvm::Type*> expected; test->types(expected, C); // default args llvm::Value* f32c0 = LLVMType<float>::get(C, 0.0f); // float llvm::Value* d64c0 = LLVMType<double>::get(C, 0.0); // double llvm::Value* i32c1 = B.getInt32(1); // int llvm::Value* i64c1 = B.getInt64(1); // int64 llvm::Value* vec3i = openvdb::ax::codegen::arrayPack({i32c1,i32c1,i32c1}, B); // vec3i llvm::Value* vec2d = openvdb::ax::codegen::arrayPack({d64c0,d64c0},B); // vec2d llvm::Value* mat3d = openvdb::ax::codegen::arrayPack({ d64c0,d64c0,d64c0, d64c0,d64c0,d64c0, d64c0,d64c0,d64c0 }, B); // mat3d std::vector<llvm::Value*> args{vec3i, vec2d, mat3d, i32c1, i64c1, f32c0}; llvm::Function* function = test->create(M); finalizeFunction(B, function); VERIFY_FUNCTION_IR(function); // also finalize the current module function, but set the inset point // just above it so we can continue to verify IR during this test llvm::Value* inst = B.CreateRetVoid(); // This specifies that created instructions should be inserted before // the specified instruction. B.SetInsertPoint(llvm::cast<llvm::Instruction>(inst)); // test no casting needed for valid IR llvm::Value* result = test->call(args, B, /*cast*/false); CPPUNIT_ASSERT(result); llvm::CallInst* call = llvm::dyn_cast<llvm::CallInst>(result); CPPUNIT_ASSERT(call); CPPUNIT_ASSERT_EQUAL(function, call->getCalledFunction()); CPPUNIT_ASSERT_EQUAL(6u, call->getNumArgOperands()); CPPUNIT_ASSERT_EQUAL(args[0], call->getArgOperand(0)); CPPUNIT_ASSERT_EQUAL(args[1], call->getArgOperand(1)); CPPUNIT_ASSERT_EQUAL(args[2], call->getArgOperand(2)); CPPUNIT_ASSERT_EQUAL(args[3], call->getArgOperand(3)); CPPUNIT_ASSERT_EQUAL(args[4], call->getArgOperand(4)); CPPUNIT_ASSERT_EQUAL(args[5], call->getArgOperand(5)); VERIFY_MODULE_IR(&M); // test no casting needed for valid IR, even with cast=true result = test->call(args, B, /*cast*/true); CPPUNIT_ASSERT(result); call = llvm::dyn_cast<llvm::CallInst>(result); CPPUNIT_ASSERT(call); CPPUNIT_ASSERT_EQUAL(function, call->getCalledFunction()); CPPUNIT_ASSERT_EQUAL(6u, call->getNumArgOperands()); CPPUNIT_ASSERT_EQUAL(args[0], call->getArgOperand(0)); CPPUNIT_ASSERT_EQUAL(args[1], call->getArgOperand(1)); CPPUNIT_ASSERT_EQUAL(args[2], call->getArgOperand(2)); CPPUNIT_ASSERT_EQUAL(args[3], call->getArgOperand(3)); CPPUNIT_ASSERT_EQUAL(args[4], call->getArgOperand(4)); CPPUNIT_ASSERT_EQUAL(args[5], call->getArgOperand(5)); VERIFY_MODULE_IR(&M); // // Test different types of valid casting llvm::Value* i1c0 = LLVMType<bool>::get(C, true); // bool llvm::Value* vec3f = openvdb::ax::codegen::arrayPack({f32c0,f32c0,f32c0}, B); // vec3f llvm::Value* vec3d = openvdb::ax::codegen::arrayPack({d64c0,d64c0,d64c0}, B); // vec3d llvm::Value* vec2f = openvdb::ax::codegen::arrayPack({f32c0,f32c0},B); // vec2f llvm::Value* vec2i = openvdb::ax::codegen::arrayPack({i32c1,i32c1},B); // vecid llvm::Value* mat3f = openvdb::ax::codegen::arrayPack({ f32c0,f32c0,f32c0, f32c0,f32c0,f32c0, f32c0,f32c0,f32c0 }, B); // mat3f // std::vector<llvm::Value*> argsToCast; argsToCast.emplace_back(vec3f); // vec3f argsToCast.emplace_back(vec2f); // vec2f argsToCast.emplace_back(mat3f); // mat3f argsToCast.emplace_back(i1c0); // bool argsToCast.emplace_back(i1c0); // bool argsToCast.emplace_back(i1c0); // bool result = test->call(argsToCast, B, /*cast*/true); CPPUNIT_ASSERT(result); call = llvm::dyn_cast<llvm::CallInst>(result); CPPUNIT_ASSERT(call); CPPUNIT_ASSERT_EQUAL(function, call->getCalledFunction()); CPPUNIT_ASSERT_EQUAL(6u, call->getNumArgOperands()); CPPUNIT_ASSERT(argsToCast[0] != call->getArgOperand(0)); CPPUNIT_ASSERT(argsToCast[1] != call->getArgOperand(1)); CPPUNIT_ASSERT(argsToCast[2] != call->getArgOperand(2)); CPPUNIT_ASSERT(argsToCast[3] != call->getArgOperand(3)); CPPUNIT_ASSERT(argsToCast[4] != call->getArgOperand(4)); CPPUNIT_ASSERT(argsToCast[5] != call->getArgOperand(5)); CPPUNIT_ASSERT(expected[0] == call->getArgOperand(0)->getType()); CPPUNIT_ASSERT(expected[1] == call->getArgOperand(1)->getType()); CPPUNIT_ASSERT(expected[2] == call->getArgOperand(2)->getType()); CPPUNIT_ASSERT(expected[3] == call->getArgOperand(3)->getType()); CPPUNIT_ASSERT(expected[4] == call->getArgOperand(4)->getType()); CPPUNIT_ASSERT(expected[5] == call->getArgOperand(5)->getType()); VERIFY_MODULE_IR(&M); // argsToCast.clear(); argsToCast.emplace_back(vec3d); // vec3d argsToCast.emplace_back(vec2i); // vec2i argsToCast.emplace_back(mat3d); // mat3d - no cast required argsToCast.emplace_back(f32c0); // float argsToCast.emplace_back(f32c0); // float argsToCast.emplace_back(f32c0); // float - no cast required result = test->call(argsToCast, B, /*cast*/true); CPPUNIT_ASSERT(result); call = llvm::dyn_cast<llvm::CallInst>(result); CPPUNIT_ASSERT(call); CPPUNIT_ASSERT_EQUAL(function, call->getCalledFunction()); CPPUNIT_ASSERT_EQUAL(6u, call->getNumArgOperands()); CPPUNIT_ASSERT(argsToCast[0] != call->getArgOperand(0)); CPPUNIT_ASSERT(argsToCast[1] != call->getArgOperand(1)); CPPUNIT_ASSERT_EQUAL(args[2], call->getArgOperand(2)); CPPUNIT_ASSERT(argsToCast[3] != call->getArgOperand(3)); CPPUNIT_ASSERT(argsToCast[4] != call->getArgOperand(4)); CPPUNIT_ASSERT_EQUAL(args[5], call->getArgOperand(5)); CPPUNIT_ASSERT(expected[0] == call->getArgOperand(0)->getType()); CPPUNIT_ASSERT(expected[1] == call->getArgOperand(1)->getType()); CPPUNIT_ASSERT(expected[3] == call->getArgOperand(3)->getType()); CPPUNIT_ASSERT(expected[4] == call->getArgOperand(4)->getType()); VERIFY_MODULE_IR(&M); // argsToCast.clear(); argsToCast.emplace_back(vec3i); // vec3i - no cast required argsToCast.emplace_back(vec2d); // vec2d - no cast required argsToCast.emplace_back(mat3d); // mat3d - no cast required argsToCast.emplace_back(i64c1); // int64 argsToCast.emplace_back(i64c1); // int64 - no cast required argsToCast.emplace_back(i64c1); // int64 result = test->call(argsToCast, B, /*cast*/true); CPPUNIT_ASSERT(result); call = llvm::dyn_cast<llvm::CallInst>(result); CPPUNIT_ASSERT(call); CPPUNIT_ASSERT_EQUAL(function, call->getCalledFunction()); CPPUNIT_ASSERT_EQUAL(6u, call->getNumArgOperands()); CPPUNIT_ASSERT_EQUAL(args[0], call->getArgOperand(0)); CPPUNIT_ASSERT_EQUAL(args[1], call->getArgOperand(1)); CPPUNIT_ASSERT_EQUAL(args[2], call->getArgOperand(2)); CPPUNIT_ASSERT(argsToCast[3] != call->getArgOperand(3)); CPPUNIT_ASSERT_EQUAL(args[4], call->getArgOperand(4)); CPPUNIT_ASSERT(argsToCast[5] != call->getArgOperand(5)); CPPUNIT_ASSERT(expected[3] == call->getArgOperand(3)->getType()); CPPUNIT_ASSERT(expected[5] == call->getArgOperand(5)->getType()); VERIFY_MODULE_IR(&M); // // Test that invalid IR is generated if casting cannot be performed. // This is just to test that call doesn't error or behave unexpectedly // Test called with castable arg but cast is false. Test arg is left // unchanged and IR is invalid due to signature size result = test->call({vec3f}, B, /*cast*/false); CPPUNIT_ASSERT(result); call = llvm::dyn_cast<llvm::CallInst>(result); CPPUNIT_ASSERT(call); CPPUNIT_ASSERT_EQUAL(function, call->getCalledFunction()); CPPUNIT_ASSERT_EQUAL(1u, call->getNumArgOperands()); // should be the same as cast is false CPPUNIT_ASSERT(vec3f == call->getArgOperand(0)); VERIFY_MODULE_IR_INVALID(&M); // Remove the bad instruction (and re-verify to double check) call->eraseFromParent(); VERIFY_MODULE_IR(&M); // Test called with castable arg with cast true. Test IR is invalid // due to signature size result = test->call({vec3f}, B, /*cast*/true); CPPUNIT_ASSERT(result); call = llvm::dyn_cast<llvm::CallInst>(result); CPPUNIT_ASSERT(call); CPPUNIT_ASSERT_EQUAL(function, call->getCalledFunction()); CPPUNIT_ASSERT_EQUAL(1u, call->getNumArgOperands()); // shouldn't be the same as it should have been cast CPPUNIT_ASSERT(vec3f != call->getArgOperand(0)); CPPUNIT_ASSERT(expected[0] == call->getArgOperand(0)->getType()); VERIFY_MODULE_IR_INVALID(&M); // Remove the bad instruction (and re-verify to double check) call->eraseFromParent(); VERIFY_MODULE_IR(&M); // Test called with non castable args, but matchign signature size. // Test IR is invalid due to cast being off result = test->call(argsToCast, B, /*cast*/false); CPPUNIT_ASSERT(result); call = llvm::dyn_cast<llvm::CallInst>(result); CPPUNIT_ASSERT(call); CPPUNIT_ASSERT_EQUAL(function, call->getCalledFunction()); CPPUNIT_ASSERT_EQUAL(6u, call->getNumArgOperands()); // no casting, args should match operands CPPUNIT_ASSERT(argsToCast[0] == call->getArgOperand(0)); CPPUNIT_ASSERT(argsToCast[1] == call->getArgOperand(1)); CPPUNIT_ASSERT(argsToCast[2] == call->getArgOperand(2)); CPPUNIT_ASSERT(argsToCast[3] == call->getArgOperand(3)); CPPUNIT_ASSERT(argsToCast[4] == call->getArgOperand(4)); CPPUNIT_ASSERT(argsToCast[5] == call->getArgOperand(5)); VERIFY_MODULE_IR_INVALID(&M); // Remove the bad instruction (and re-verify to double check) call->eraseFromParent(); VERIFY_MODULE_IR(&M); // // Test strings llvm::Type* axstr = LLVMType<AXString*>::get(C); // str* llvm::Type* chars = LLVMType<char*>::get(C); // char* // build values llvm::Value* chararray = B.CreateGlobalStringPtr("tmp"); // char* llvm::Constant* constLoc = llvm::cast<llvm::Constant>(chararray); llvm::Constant* size = LLVMType<AXString::SizeType>::get(C, static_cast<AXString::SizeType>(3)); llvm::Value* constStr = LLVMType<AXString>::get(C, constLoc, size); llvm::Value* strptr = B.CreateAlloca(LLVMType<AXString>::get(C)); B.CreateStore(constStr, strptr); // void ax.str.test(AXString*, char*) test.reset(new TestFunction({axstr, chars}, llvm::Type::getVoidTy(C), "ax.str.test")); std::vector<llvm::Value*> stringArgs{strptr, chararray}; function = test->create(M); finalizeFunction(B, function); VERIFY_FUNCTION_IR(function); result = test->call(stringArgs, B, /*cast*/false); CPPUNIT_ASSERT(result); call = llvm::dyn_cast<llvm::CallInst>(result); CPPUNIT_ASSERT(call); CPPUNIT_ASSERT_EQUAL(function, call->getCalledFunction()); CPPUNIT_ASSERT_EQUAL(2u, call->getNumArgOperands()); CPPUNIT_ASSERT(stringArgs[0] == call->getArgOperand(0)); CPPUNIT_ASSERT(stringArgs[1] == call->getArgOperand(1)); // result = test->call(stringArgs, B, /*cast*/true); CPPUNIT_ASSERT(result); call = llvm::dyn_cast<llvm::CallInst>(result); CPPUNIT_ASSERT(call); CPPUNIT_ASSERT_EQUAL(function, call->getCalledFunction()); CPPUNIT_ASSERT_EQUAL(2u, call->getNumArgOperands()); CPPUNIT_ASSERT(stringArgs[0] == call->getArgOperand(0)); CPPUNIT_ASSERT(stringArgs[1] == call->getArgOperand(1)); // Test AXString -> char* stringArgs[0] = strptr; stringArgs[1] = strptr; result = test->call(stringArgs, B, /*cast*/true); CPPUNIT_ASSERT(result); call = llvm::dyn_cast<llvm::CallInst>(result); CPPUNIT_ASSERT(call); CPPUNIT_ASSERT_EQUAL(function, call->getCalledFunction()); CPPUNIT_ASSERT_EQUAL(2u, call->getNumArgOperands()); CPPUNIT_ASSERT(stringArgs[0] == call->getArgOperand(0)); CPPUNIT_ASSERT(stringArgs[1] != call->getArgOperand(1)); CPPUNIT_ASSERT(chars == call->getArgOperand(1)->getType()); VERIFY_MODULE_IR(&M); // Test char* does not catch to AXString stringArgs[0] = chararray; stringArgs[1] = chararray; result = test->call(stringArgs, B, /*cast*/true); CPPUNIT_ASSERT(result); call = llvm::dyn_cast<llvm::CallInst>(result); CPPUNIT_ASSERT(call); CPPUNIT_ASSERT_EQUAL(function, call->getCalledFunction()); CPPUNIT_ASSERT_EQUAL(2u, call->getNumArgOperands()); // no valid casting CPPUNIT_ASSERT(stringArgs[0] == call->getArgOperand(0)); CPPUNIT_ASSERT(stringArgs[1] == call->getArgOperand(1)); VERIFY_MODULE_IR_INVALID(&M); // Remove the bad instruction (and re-verify to double check) call->eraseFromParent(); VERIFY_MODULE_IR(&M); // // Test ** pointers test.reset(new TestFunction({ llvm::Type::getFloatTy(C)->getPointerTo()->getPointerTo(), llvm::Type::getDoubleTy(C)->getPointerTo()->getPointerTo() }, llvm::Type::getVoidTy(C), "ax.ptrs.test")); function = test->create(M); finalizeFunction(B, function); VERIFY_FUNCTION_IR(function); llvm::Value* fptr = B.CreateAlloca(llvm::Type::getFloatTy(C)->getPointerTo()); llvm::Value* dptr = B.CreateAlloca(llvm::Type::getDoubleTy(C)->getPointerTo()); result = test->call({fptr, dptr}, B, /*cast*/false); CPPUNIT_ASSERT(result); call = llvm::dyn_cast<llvm::CallInst>(result); CPPUNIT_ASSERT(call); CPPUNIT_ASSERT_EQUAL(function, call->getCalledFunction()); CPPUNIT_ASSERT_EQUAL(2u, call->getNumArgOperands()); CPPUNIT_ASSERT(fptr == call->getArgOperand(0)); CPPUNIT_ASSERT(dptr == call->getArgOperand(1)); VERIFY_MODULE_IR(&M); // result = test->call({fptr, dptr}, B, /*cast*/true); CPPUNIT_ASSERT(result); call = llvm::dyn_cast<llvm::CallInst>(result); CPPUNIT_ASSERT(call); CPPUNIT_ASSERT_EQUAL(function, call->getCalledFunction()); CPPUNIT_ASSERT_EQUAL(2u, call->getNumArgOperands()); CPPUNIT_ASSERT(fptr == call->getArgOperand(0)); CPPUNIT_ASSERT(dptr == call->getArgOperand(1)); VERIFY_MODULE_IR(&M); // switch the points, check no valid casting result = test->call({dptr, fptr}, B, /*cast*/true); CPPUNIT_ASSERT(result); call = llvm::dyn_cast<llvm::CallInst>(result); CPPUNIT_ASSERT(call); CPPUNIT_ASSERT_EQUAL(function, call->getCalledFunction()); CPPUNIT_ASSERT_EQUAL(2u, call->getNumArgOperands()); // args unaltered as casting is invalid CPPUNIT_ASSERT(dptr == call->getArgOperand(0)); CPPUNIT_ASSERT(fptr == call->getArgOperand(1)); VERIFY_MODULE_IR_INVALID(&M); // Remove the bad instruction (and re-verify to double check) call->eraseFromParent(); VERIFY_MODULE_IR(&M); // // Test void pointers test.reset(new TestFunction({ LLVMType<void*>::get(C), }, llvm::Type::getVoidTy(C), "ax.void.test")); function = test->create(M); finalizeFunction(B, function); VERIFY_FUNCTION_IR(function); llvm::Value* vptrptr = B.CreateAlloca(LLVMType<void*>::get(C)); llvm::Value* vptr = B.CreateLoad(vptrptr); result = test->call({vptr}, B, /*cast*/false); CPPUNIT_ASSERT(result); call = llvm::dyn_cast<llvm::CallInst>(result); CPPUNIT_ASSERT(call); CPPUNIT_ASSERT_EQUAL(function, call->getCalledFunction()); CPPUNIT_ASSERT_EQUAL(1u, call->getNumArgOperands()); CPPUNIT_ASSERT(vptr == call->getArgOperand(0)); VERIFY_MODULE_IR(&M); // result = test->call({vptr}, B, /*cast*/true); CPPUNIT_ASSERT(result); call = llvm::dyn_cast<llvm::CallInst>(result); CPPUNIT_ASSERT(call); CPPUNIT_ASSERT_EQUAL(function, call->getCalledFunction()); CPPUNIT_ASSERT_EQUAL(1u, call->getNumArgOperands()); CPPUNIT_ASSERT(vptr == call->getArgOperand(0)); VERIFY_MODULE_IR(&M); // verify no cast from other pointers to void* result = test->call({fptr}, B, /*cast*/true); CPPUNIT_ASSERT(result); call = llvm::dyn_cast<llvm::CallInst>(result); CPPUNIT_ASSERT(call); CPPUNIT_ASSERT_EQUAL(function, call->getCalledFunction()); CPPUNIT_ASSERT_EQUAL(1u, call->getNumArgOperands()); CPPUNIT_ASSERT(fptr == call->getArgOperand(0)); VERIFY_MODULE_IR_INVALID(&M); // Remove the bad instruction (and re-verify to double check) call->eraseFromParent(); VERIFY_MODULE_IR(&M); } void TestFunctionTypes::testFunctionMatch() { using openvdb::ax::codegen::Function; using openvdb::ax::codegen::LLVMType; unittest_util::LLVMState state; llvm::LLVMContext& C = state.context(); Function::SignatureMatch match; const std::vector<llvm::Type*> scalars { llvm::Type::getInt1Ty(C), // bool llvm::Type::getInt16Ty(C), // int16 llvm::Type::getInt32Ty(C), // int llvm::Type::getInt64Ty(C), // int64 llvm::Type::getFloatTy(C), // float llvm::Type::getDoubleTy(C) // double }; const std::vector<llvm::Type*> array2 { llvm::ArrayType::get(llvm::Type::getInt32Ty(C), 2)->getPointerTo(), // vec2i llvm::ArrayType::get(llvm::Type::getFloatTy(C), 2)->getPointerTo(), // vec2f llvm::ArrayType::get(llvm::Type::getDoubleTy(C), 2)->getPointerTo() // vec2d }; const std::vector<llvm::Type*> array3 { llvm::ArrayType::get(llvm::Type::getInt32Ty(C), 3)->getPointerTo(), // vec3i llvm::ArrayType::get(llvm::Type::getFloatTy(C), 3)->getPointerTo(), // vec3f llvm::ArrayType::get(llvm::Type::getDoubleTy(C), 3)->getPointerTo() // vec3d }; const std::vector<llvm::Type*> array4 { llvm::ArrayType::get(llvm::Type::getInt32Ty(C), 4)->getPointerTo(), // vec3i llvm::ArrayType::get(llvm::Type::getFloatTy(C), 4)->getPointerTo(), // vec3f llvm::ArrayType::get(llvm::Type::getDoubleTy(C), 4)->getPointerTo() // vec3d }; const std::vector<llvm::Type*> array9 { llvm::ArrayType::get(llvm::Type::getInt32Ty(C), 9)->getPointerTo(), // ix9 (not supported by ax) llvm::ArrayType::get(llvm::Type::getFloatTy(C), 9)->getPointerTo(), // mat3f llvm::ArrayType::get(llvm::Type::getDoubleTy(C), 9)->getPointerTo() // mat3d }; const std::vector<llvm::Type*> array16 { llvm::ArrayType::get(llvm::Type::getInt32Ty(C), 16)->getPointerTo(), // ix16 (not supported by ax) llvm::ArrayType::get(llvm::Type::getFloatTy(C), 16)->getPointerTo(), // mat3f llvm::ArrayType::get(llvm::Type::getDoubleTy(C), 16)->getPointerTo() // mat3d }; const std::vector<std::vector<llvm::Type*>> arrays { array2, array3, array4, array9, array16, }; // test empty explicit match Function::Ptr test(new TestFunction({}, llvm::Type::getVoidTy(C), "ax.test")); match = test->match({}, C); CPPUNIT_ASSERT_EQUAL(match, Function::Explicit); // std::vector<llvm::Type*> types; types.insert(types.end(), scalars.begin(), scalars.end()); types.insert(types.end(), array2.begin(), array2.end()); types.insert(types.end(), array3.begin(), array3.end()); types.insert(types.end(), array4.begin(), array4.end()); types.insert(types.end(), array9.begin(), array9.end()); types.insert(types.end(), array16.begin(), array16.end()); types.insert(types.end(), LLVMType<openvdb::ax::AXString*>::get(C)); // check types are unique CPPUNIT_ASSERT_EQUAL(std::set<llvm::Type*>(types.begin(), types.end()).size(), types.size()); // test.reset(new TestFunction({ llvm::Type::getInt1Ty(C), // bool llvm::Type::getInt16Ty(C), // int16 llvm::Type::getInt32Ty(C), // int32 llvm::Type::getInt64Ty(C), // int64 llvm::Type::getFloatTy(C), // float llvm::Type::getDoubleTy(C), // double llvm::ArrayType::get(llvm::Type::getInt32Ty(C), 2)->getPointerTo(), // vec2i llvm::ArrayType::get(llvm::Type::getFloatTy(C), 2)->getPointerTo(), // vec2f llvm::ArrayType::get(llvm::Type::getDoubleTy(C), 2)->getPointerTo(), // vec2d llvm::ArrayType::get(llvm::Type::getInt32Ty(C), 3)->getPointerTo(), // vec3i llvm::ArrayType::get(llvm::Type::getFloatTy(C), 3)->getPointerTo(), // vec3f llvm::ArrayType::get(llvm::Type::getDoubleTy(C), 3)->getPointerTo(), // vec3d llvm::ArrayType::get(llvm::Type::getInt32Ty(C), 4)->getPointerTo(), // vec4i llvm::ArrayType::get(llvm::Type::getFloatTy(C), 4)->getPointerTo(), // vec4f llvm::ArrayType::get(llvm::Type::getDoubleTy(C), 4)->getPointerTo(), // vec4d llvm::ArrayType::get(llvm::Type::getInt32Ty(C), 9)->getPointerTo(), // ix9 (not supported by ax) llvm::ArrayType::get(llvm::Type::getFloatTy(C), 9)->getPointerTo(), // mat3f llvm::ArrayType::get(llvm::Type::getDoubleTy(C), 9)->getPointerTo(), // mat3d llvm::ArrayType::get(llvm::Type::getInt32Ty(C), 16)->getPointerTo(), // ix16 (not supported by ax) llvm::ArrayType::get(llvm::Type::getFloatTy(C), 16)->getPointerTo(), // mat4f llvm::ArrayType::get(llvm::Type::getDoubleTy(C), 16)->getPointerTo(), // mat4d LLVMType<openvdb::ax::AXString*>::get(C) // string }, llvm::Type::getVoidTy(C), "ax.test")); match = test->match(types, C); CPPUNIT_ASSERT_EQUAL(match, Function::Explicit); // test size match llvm::Type* i32t = llvm::Type::getInt32Ty(C); test.reset(new TestFunction({i32t}, llvm::Type::getVoidTy(C), "ax.test")); match = test->match({llvm::ArrayType::get(i32t, 1)->getPointerTo()}, C); CPPUNIT_ASSERT_EQUAL(match, Function::Size); match = test->match({i32t->getPointerTo()}, C); CPPUNIT_ASSERT_EQUAL(match, Function::Size); // test no match match = test->match({}, C); CPPUNIT_ASSERT_EQUAL(Function::None, match); match = test->match({i32t, i32t}, C); CPPUNIT_ASSERT_EQUAL(Function::None, match); // test scalar matches for (size_t i = 0; i < scalars.size(); ++i) { test.reset(new TestFunction({scalars[i]}, llvm::Type::getVoidTy(C), "ax.test")); std::vector<llvm::Type*> copy(scalars); std::swap(copy[i], copy.back()); copy.pop_back(); CPPUNIT_ASSERT_EQUAL(size_t(5), copy.size()); CPPUNIT_ASSERT_EQUAL(Function::Explicit, test->match({scalars[i]}, C)); CPPUNIT_ASSERT_EQUAL(Function::Implicit, test->match({copy[0]}, C)); CPPUNIT_ASSERT_EQUAL(Function::Implicit, test->match({copy[1]}, C)); CPPUNIT_ASSERT_EQUAL(Function::Implicit, test->match({copy[2]}, C)); CPPUNIT_ASSERT_EQUAL(Function::Implicit, test->match({copy[3]}, C)); CPPUNIT_ASSERT_EQUAL(Function::Implicit, test->match({copy[4]}, C)); } // // Test array matches - no implicit cast as operands are not marked as readonly for (const std::vector<llvm::Type*>& types : arrays) { // test these array types for (size_t i = 0; i < types.size(); ++i) { test.reset(new TestFunction({types[i]}, llvm::Type::getVoidTy(C), "ax.test")); std::vector<llvm::Type*> copy(types); std::swap(copy[i], copy.back()); copy.pop_back(); CPPUNIT_ASSERT_EQUAL(size_t(2), copy.size()); CPPUNIT_ASSERT_EQUAL(Function::Explicit, test->match({types[i]}, C)); CPPUNIT_ASSERT_EQUAL(Function::Size, test->match({copy[0]}, C)); CPPUNIT_ASSERT_EQUAL(Function::Size, test->match({copy[1]}, C)); // test non matching size arrays for (const std::vector<llvm::Type*>& inputs : arrays) { if (&types == &inputs) continue; for (size_t i = 0; i < inputs.size(); ++i) { CPPUNIT_ASSERT_EQUAL(Function::Size, test->match({inputs[i]}, C)); } } } } // // Test array matches with readonly marking for (const std::vector<llvm::Type*>& types : arrays) { // test these array types for (size_t i = 0; i < types.size(); ++i) { test.reset(new TestFunction({types[i]}, llvm::Type::getVoidTy(C), "ax.test")); test->setParamAttributes(0, {llvm::Attribute::ReadOnly}); std::vector<llvm::Type*> copy(types); std::swap(copy[i], copy.back()); copy.pop_back(); CPPUNIT_ASSERT_EQUAL(size_t(2), copy.size()); CPPUNIT_ASSERT_EQUAL(Function::Explicit, test->match({types[i]}, C)); CPPUNIT_ASSERT_EQUAL(Function::Implicit, test->match({copy[0]}, C)); CPPUNIT_ASSERT_EQUAL(Function::Implicit, test->match({copy[1]}, C)); // test non matching size arrays for (const std::vector<llvm::Type*>& inputs : arrays) { if (&types == &inputs) continue; for (size_t i = 0; i < inputs.size(); ++i) { CPPUNIT_ASSERT_EQUAL(Function::Size, test->match({inputs[i]}, C)); } } } } // test strings test.reset(new TestFunction({LLVMType<char*>::get(C)}, llvm::Type::getVoidTy(C), "ax.test")); CPPUNIT_ASSERT_EQUAL(Function::Size, test->match({LLVMType<openvdb::ax::AXString*>::get(C)}, C)); CPPUNIT_ASSERT_EQUAL(Function::Explicit, test->match({LLVMType<char*>::get(C)}, C)); test->setParamAttributes(0, {llvm::Attribute::ReadOnly}); CPPUNIT_ASSERT_EQUAL(Function::Implicit, test->match({LLVMType<openvdb::ax::AXString*>::get(C)}, C)); test.reset(new TestFunction({LLVMType<openvdb::ax::AXString*>::get(C)}, llvm::Type::getVoidTy(C), "ax.test")); CPPUNIT_ASSERT_EQUAL(Function::Size, test->match({LLVMType<char*>::get(C)}, C)); // test pointers llvm::Type* fss = llvm::Type::getFloatTy(C)->getPointerTo()->getPointerTo(); llvm::Type* dss = llvm::Type::getDoubleTy(C)->getPointerTo()->getPointerTo(); test.reset(new TestFunction({fss, dss}, llvm::Type::getVoidTy(C), "ax.ptrs.test")); CPPUNIT_ASSERT_EQUAL(Function::Explicit, test->match({fss, dss}, C)); CPPUNIT_ASSERT_EQUAL(Function::Size, test->match({fss, fss}, C)); // Even if pointers are marked as readonly, casting is not supported test->setParamAttributes(0, {llvm::Attribute::ReadOnly}); test->setParamAttributes(1, {llvm::Attribute::ReadOnly}); CPPUNIT_ASSERT_EQUAL(Function::Size, test->match({fss, fss}, C)); } void TestFunctionTypes::testCFunctions() { using openvdb::ax::codegen::CFunction; unittest_util::LLVMState state; llvm::LLVMContext& C = state.context(); llvm::Type* returnType = nullptr; std::vector<llvm::Type*> types; // test basic creation CFunction<void()> voidfunc("voidfunc", &CBindings::voidfunc); CFunction<int16_t(bool,int16_t,int32_t,int64_t,float,double)> scalars("scalarfunc", &CBindings::scalarfunc); CFunction<int32_t(bool*,int16_t*,int32_t*,int64_t*,float*,double*)> scalarptrs("scalatptsfunc", &CBindings::scalatptsfunc); CFunction<int64_t(bool(*)[1],int16_t(*)[2],int32_t(*)[3],int64_t(*)[4],float(*)[5],double(*)[6])> arrayptrs("arrayfunc", &CBindings::arrayfunc); CFunction<float()> select("tmplfunc", (float(*)())(CBindings::tmplfunc)); CFunction<void(void*, void**, void***, float*, float**, float***)> mindirect("multiptrfunc", &CBindings::multiptrfunc); // test static void function CPPUNIT_ASSERT_EQUAL(size_t(0), voidfunc.size()); CPPUNIT_ASSERT_EQUAL(reinterpret_cast<uint64_t>(&CBindings::voidfunc), voidfunc.address()); CPPUNIT_ASSERT_EQUAL(std::string("voidfunc"), std::string(voidfunc.symbol())); // test scalar arguments CPPUNIT_ASSERT_EQUAL(size_t(6), scalars.size()); CPPUNIT_ASSERT_EQUAL(reinterpret_cast<uint64_t>(&CBindings::scalarfunc), scalars.address()); CPPUNIT_ASSERT_EQUAL(std::string("scalarfunc"), std::string(scalars.symbol())); // test scalar ptr arguments CPPUNIT_ASSERT_EQUAL(size_t(6), scalarptrs.size()); CPPUNIT_ASSERT_EQUAL(reinterpret_cast<uint64_t>(&CBindings::scalatptsfunc), scalarptrs.address()); CPPUNIT_ASSERT_EQUAL(std::string("scalatptsfunc"), std::string(scalarptrs.symbol())); // test array ptr arguments CPPUNIT_ASSERT_EQUAL(size_t(6), arrayptrs.size()); CPPUNIT_ASSERT_EQUAL(reinterpret_cast<uint64_t>(&CBindings::arrayfunc), arrayptrs.address()); CPPUNIT_ASSERT_EQUAL(std::string("arrayfunc"), std::string(arrayptrs.symbol())); // test selected template functions CPPUNIT_ASSERT_EQUAL(size_t(0), select.size()); CPPUNIT_ASSERT_EQUAL(reinterpret_cast<uint64_t>(&CBindings::tmplfunc<float>), select.address()); CPPUNIT_ASSERT_EQUAL(std::string("tmplfunc"), std::string(select.symbol())); // test multiple indirection layers CPPUNIT_ASSERT_EQUAL(size_t(6), mindirect.size()); CPPUNIT_ASSERT_EQUAL(reinterpret_cast<uint64_t>(&CBindings::multiptrfunc), mindirect.address()); CPPUNIT_ASSERT_EQUAL(std::string("multiptrfunc"), std::string(mindirect.symbol())); // // Test types // test scalar arguments returnType = scalars.types(types, C); CPPUNIT_ASSERT(returnType->isIntegerTy(16)); CPPUNIT_ASSERT_EQUAL(size_t(6), types.size()); CPPUNIT_ASSERT(types[0]->isIntegerTy(1)); CPPUNIT_ASSERT(types[1]->isIntegerTy(16)); CPPUNIT_ASSERT(types[2]->isIntegerTy(32)); CPPUNIT_ASSERT(types[3]->isIntegerTy(64)); CPPUNIT_ASSERT(types[4]->isFloatTy()); CPPUNIT_ASSERT(types[5]->isDoubleTy()); types.clear(); // test scalar ptr arguments returnType = scalarptrs.types(types, C); CPPUNIT_ASSERT(returnType->isIntegerTy(32)); CPPUNIT_ASSERT_EQUAL(size_t(6), types.size()); CPPUNIT_ASSERT(types[0] == llvm::Type::getInt1Ty(C)->getPointerTo()); CPPUNIT_ASSERT(types[1] == llvm::Type::getInt16Ty(C)->getPointerTo()); CPPUNIT_ASSERT(types[2] == llvm::Type::getInt32Ty(C)->getPointerTo()); CPPUNIT_ASSERT(types[3] == llvm::Type::getInt64Ty(C)->getPointerTo()); CPPUNIT_ASSERT(types[4] == llvm::Type::getFloatTy(C)->getPointerTo()); CPPUNIT_ASSERT(types[5] == llvm::Type::getDoubleTy(C)->getPointerTo()); types.clear(); // test array ptr arguments returnType = arrayptrs.types(types, C); CPPUNIT_ASSERT(returnType->isIntegerTy(64)); CPPUNIT_ASSERT_EQUAL(size_t(6), types.size()); CPPUNIT_ASSERT(types[0] == llvm::ArrayType::get(llvm::Type::getInt1Ty(C), 1)->getPointerTo()); CPPUNIT_ASSERT(types[1] == llvm::ArrayType::get(llvm::Type::getInt16Ty(C), 2)->getPointerTo()); CPPUNIT_ASSERT(types[2] == llvm::ArrayType::get(llvm::Type::getInt32Ty(C), 3)->getPointerTo()); CPPUNIT_ASSERT(types[3] == llvm::ArrayType::get(llvm::Type::getInt64Ty(C), 4)->getPointerTo()); CPPUNIT_ASSERT(types[4] == llvm::ArrayType::get(llvm::Type::getFloatTy(C), 5)->getPointerTo()); CPPUNIT_ASSERT(types[5] == llvm::ArrayType::get(llvm::Type::getDoubleTy(C), 6)->getPointerTo()); types.clear(); // test void ptr arguments // void* are inferred as int8_t* types returnType = mindirect.types(types, C); CPPUNIT_ASSERT(returnType->isVoidTy()); CPPUNIT_ASSERT_EQUAL(size_t(6), types.size()); CPPUNIT_ASSERT(types[0] == llvm::Type::getInt8PtrTy(C)); CPPUNIT_ASSERT(types[1] == llvm::Type::getInt8PtrTy(C)->getPointerTo()); CPPUNIT_ASSERT(types[2] == llvm::Type::getInt8PtrTy(C)->getPointerTo()->getPointerTo()); CPPUNIT_ASSERT(types[3] == llvm::Type::getFloatTy(C)->getPointerTo()); CPPUNIT_ASSERT(types[4] == llvm::Type::getFloatTy(C)->getPointerTo()->getPointerTo()); CPPUNIT_ASSERT(types[5] == llvm::Type::getFloatTy(C)->getPointerTo()->getPointerTo()->getPointerTo()); } void TestFunctionTypes::testCFunctionCF() { using openvdb::ax::codegen::CFunction; using openvdb::ax::codegen::LLVMType; static auto cftest1 = []() -> int32_t { return 10; }; static auto cftest2 = [](float a) -> float { return a; }; // currently unsupported for arrays static auto cftest3 = [](float(*a)[3]) -> float { return (*a)[0]; }; // currently unsupported for return voids static auto cftest4 = [](float* a) -> void { (*a)*=5.0f; }; unittest_util::LLVMState state; llvm::LLVMContext& C = state.context(); llvm::IRBuilder<> B(state.scratchBlock()); // test with no args CFunction<int32_t()> test1("ax.test1", cftest1); // off by default CPPUNIT_ASSERT(!test1.hasConstantFold()); CPPUNIT_ASSERT(test1.fold({B.getInt32(1)}, C) == nullptr); test1.setConstantFold(true); llvm::Value* result = test1.fold({B.getInt32(1)}, C); CPPUNIT_ASSERT(result); llvm::ConstantInt* constant = llvm::dyn_cast<llvm::ConstantInt>(result); CPPUNIT_ASSERT(constant); CPPUNIT_ASSERT_EQUAL(uint64_t(10), constant->getLimitedValue()); // test with scalar arg CFunction<float(float)> test2("ax.test2", cftest2); test2.setConstantFold(true); result = test2.fold({LLVMType<float>::get(C, -3.2f)}, C); CPPUNIT_ASSERT(result); llvm::ConstantFP* constantfp = llvm::dyn_cast<llvm::ConstantFP>(result); CPPUNIT_ASSERT(constantfp); const llvm::APFloat& apf = constantfp->getValueAPF(); CPPUNIT_ASSERT_EQUAL(-3.2f, apf.convertToFloat()); // test unsupported CFunction<float(float(*)[3])> test3("ax.test3", cftest3); test3.setConstantFold(true); // constant arg (verify it would 100% match) // note that this arg is fundamentally the wrong type for this function // and the way in which we support vector types anyway (by ptr) - but because // its impossible to have a constant ptr, use this for now as this will most // likely be the way we support folding for arrays in the future llvm::Value* arg = LLVMType<float[3]>::get(C, {1,2,3}); CPPUNIT_ASSERT(llvm::isa<llvm::Constant>(arg)); // check fold fails CPPUNIT_ASSERT(test3.fold({arg}, C) == nullptr); // CFunction<void(float*)> test4("ax.test4", cftest4); test4.setConstantFold(true); // constant arg (verify it would 100% match) llvm::Value* nullfloat = llvm::ConstantPointerNull::get(LLVMType<float*>::get(C)); std::vector<llvm::Type*> types; test4.types(types, C); CPPUNIT_ASSERT_EQUAL(size_t(1), types.size()); CPPUNIT_ASSERT(nullfloat->getType() == types.front()); CPPUNIT_ASSERT(test4.fold({nullfloat}, C) == nullptr); } void TestFunctionTypes::testIRFunctions() { using openvdb::ax::codegen::LLVMType; using openvdb::ax::codegen::Function; using openvdb::ax::codegen::IRFunctionBase; unittest_util::LLVMState state; llvm::LLVMContext& C = state.context(); // Small test to check the templated version of IRFunction::types. // All other checks work with the IRFunctionBase class { using openvdb::ax::codegen::IRFunction; static auto generate = [](const std::vector<llvm::Value*>&, llvm::IRBuilder<>&) -> llvm::Value* { return nullptr; }; IRFunction<double(bool, int16_t*, int32_t(*)[1], int64_t, float*, double(*)[2])> mix("mix", generate); CPPUNIT_ASSERT_EQUAL(std::string("mix"), std::string(mix.symbol())); std::vector<llvm::Type*> types; llvm::Type* returnType = mix.types(types, C); CPPUNIT_ASSERT(returnType->isDoubleTy()); CPPUNIT_ASSERT_EQUAL(size_t(6), types.size()); CPPUNIT_ASSERT(types[0] == llvm::Type::getInt1Ty(C)); CPPUNIT_ASSERT(types[1] == llvm::Type::getInt16Ty(C)->getPointerTo()); CPPUNIT_ASSERT(types[2] == llvm::ArrayType::get(llvm::Type::getInt32Ty(C), 1)->getPointerTo()); CPPUNIT_ASSERT(types[3] == llvm::Type::getInt64Ty(C)); CPPUNIT_ASSERT(types[4] == llvm::Type::getFloatTy(C)->getPointerTo()); CPPUNIT_ASSERT(types[5] == llvm::ArrayType::get(llvm::Type::getDoubleTy(C), 2)->getPointerTo()); } llvm::Module& M = state.module(); llvm::IRBuilder<> B(state.scratchBlock("TestFunction")); llvm::Function* BaseFunction = B.GetInsertBlock()->getParent(); B.SetInsertPoint(finalizeFunction(B)); // Build the following function: // float test(float a, float b) { // float c = a + b; // return c; // } // how to handle the terminating instruction int termMode = 0; std::string expectedName; auto generate = [&B, &M, &termMode, &expectedName] (const std::vector<llvm::Value*>& args, llvm::IRBuilder<>& _B) -> llvm::Value* { // test the builder is pointing to the correct location CPPUNIT_ASSERT(&B != &_B); llvm::BasicBlock* Block = _B.GetInsertBlock(); CPPUNIT_ASSERT(Block); CPPUNIT_ASSERT(Block->empty()); llvm::Function* F = Block->getParent(); CPPUNIT_ASSERT(F); CPPUNIT_ASSERT_EQUAL(expectedName, std::string(F->getName())); llvm::Module* _M = F->getParent(); CPPUNIT_ASSERT_EQUAL(&M, _M); CPPUNIT_ASSERT_EQUAL(size_t(2), args.size()); CPPUNIT_ASSERT(args[0] == llvm::cast<llvm::Value>(F->arg_begin())); CPPUNIT_ASSERT(args[1] == llvm::cast<llvm::Value>(F->arg_begin()+1)); CPPUNIT_ASSERT(args[0]->getType()->isFloatTy()); CPPUNIT_ASSERT(args[1]->getType()->isFloatTy()); llvm::Value* result = _B.CreateFAdd(args[0], args[1]); if (termMode == 0) return _B.CreateRet(result); if (termMode == 1) return result; if (termMode == 2) return nullptr; CPPUNIT_ASSERT(false); return nullptr; }; llvm::Function* function = nullptr; expectedName = "ax.ir.test"; Function::Ptr test(new TestIRFunction({ llvm::Type::getFloatTy(C), llvm::Type::getFloatTy(C) }, llvm::Type::getFloatTy(C), expectedName, generate)); // Test function prototype creation CPPUNIT_ASSERT(!M.getFunction("ax.ir.test")); function = test->create(C); CPPUNIT_ASSERT(!M.getFunction("ax.ir.test")); CPPUNIT_ASSERT(function); CPPUNIT_ASSERT(function->empty()); CPPUNIT_ASSERT(function != test->create(C)); CPPUNIT_ASSERT(!function->isVarArg()); CPPUNIT_ASSERT_EQUAL(size_t(2), function->arg_size()); llvm::FunctionType* ftype = function->getFunctionType(); CPPUNIT_ASSERT(ftype); CPPUNIT_ASSERT(ftype->getReturnType()->isFloatTy()); CPPUNIT_ASSERT_EQUAL(2u, ftype->getNumParams()); CPPUNIT_ASSERT(ftype->getParamType(0)->isFloatTy()); CPPUNIT_ASSERT(ftype->getParamType(1)->isFloatTy()); CPPUNIT_ASSERT(function->getAttributes().isEmpty()); // Test function creation with module and IR generation CPPUNIT_ASSERT(!M.getFunction("ax.ir.test")); function = test->create(M); CPPUNIT_ASSERT(function); CPPUNIT_ASSERT_EQUAL(function, M.getFunction("ax.ir.test")); CPPUNIT_ASSERT(!function->empty()); llvm::BasicBlock* BB = &(function->getEntryBlock()); // two instructions - the add and return CPPUNIT_ASSERT_EQUAL(size_t(2), BB->size()); auto iter = BB->begin(); llvm::BinaryOperator* binary = llvm::dyn_cast<llvm::BinaryOperator>(iter); CPPUNIT_ASSERT(binary); CPPUNIT_ASSERT_EQUAL(llvm::Instruction::FAdd, binary->getOpcode()); CPPUNIT_ASSERT_EQUAL(llvm::cast<llvm::Value>(function->arg_begin()), binary->getOperand(0)); CPPUNIT_ASSERT_EQUAL(llvm::cast<llvm::Value>(function->arg_begin()+1), binary->getOperand(1)); ++iter; llvm::ReturnInst* ret = llvm::dyn_cast<llvm::ReturnInst>(iter); CPPUNIT_ASSERT(ret); llvm::Value* rvalue = ret->getReturnValue(); CPPUNIT_ASSERT(rvalue); CPPUNIT_ASSERT(rvalue->getType()->isFloatTy()); // the return is the result of the bin op CPPUNIT_ASSERT_EQUAL(rvalue, llvm::cast<llvm::Value>(binary)); ++iter; CPPUNIT_ASSERT(BB->end() == iter); // additional call should match CPPUNIT_ASSERT_EQUAL(function, test->create(M)); // verify IR VERIFY_FUNCTION_IR(function); // Test call llvm::Value* fp1 = LLVMType<float>::get(C, 1.0f); llvm::Value* fp2 = LLVMType<float>::get(C, 2.0f); llvm::Value* result = test->call({fp1, fp2}, B, /*cast*/false); CPPUNIT_ASSERT(result); llvm::CallInst* call = llvm::dyn_cast<llvm::CallInst>(result); CPPUNIT_ASSERT(call); CPPUNIT_ASSERT_EQUAL(function, call->getCalledFunction()); CPPUNIT_ASSERT_EQUAL(2u, call->getNumArgOperands()); CPPUNIT_ASSERT_EQUAL(fp1, call->getArgOperand(0)); CPPUNIT_ASSERT_EQUAL(fp2, call->getArgOperand(1)); // Test the builder is pointing to the correct location CPPUNIT_ASSERT_EQUAL(&(BaseFunction->getEntryBlock()), B.GetInsertBlock()); CPPUNIT_ASSERT_EQUAL(llvm::cast<llvm::Value>(call), llvm::cast<llvm::Value>(--B.GetInsertPoint())); // verify IR VERIFY_FUNCTION_IR(function); VERIFY_FUNCTION_IR(BaseFunction); VERIFY_MODULE_IR(&M); // // Test auto return - the IRFunctionBase should handle the return // also test that calling Function::call correctly creates the // function in the module expectedName = "ax.ir.autoret.test"; termMode = 1; test.reset(new TestIRFunction({ llvm::Type::getFloatTy(C), llvm::Type::getFloatTy(C) }, llvm::Type::getFloatTy(C), expectedName, generate)); CPPUNIT_ASSERT(!M.getFunction("ax.ir.autoret.test")); result = test->call({fp1, fp2}, B, /*cast*/false); CPPUNIT_ASSERT(result); call = llvm::dyn_cast<llvm::CallInst>(result); CPPUNIT_ASSERT(call); function = M.getFunction("ax.ir.autoret.test"); CPPUNIT_ASSERT_EQUAL(function, call->getCalledFunction()); CPPUNIT_ASSERT_EQUAL(2u, call->getNumArgOperands()); CPPUNIT_ASSERT_EQUAL(fp1, call->getArgOperand(0)); CPPUNIT_ASSERT_EQUAL(fp2, call->getArgOperand(1)); CPPUNIT_ASSERT(!function->empty()); BB = &(function->getEntryBlock()); // two instructions - the add and return CPPUNIT_ASSERT_EQUAL(size_t(2), BB->size()); iter = BB->begin(); binary = llvm::dyn_cast<llvm::BinaryOperator>(iter); CPPUNIT_ASSERT(binary); CPPUNIT_ASSERT_EQUAL(llvm::Instruction::FAdd, binary->getOpcode()); CPPUNIT_ASSERT_EQUAL(llvm::cast<llvm::Value>(function->arg_begin()), binary->getOperand(0)); CPPUNIT_ASSERT_EQUAL(llvm::cast<llvm::Value>(function->arg_begin()+1), binary->getOperand(1)); ++iter; ret = llvm::dyn_cast<llvm::ReturnInst>(iter); CPPUNIT_ASSERT(ret); rvalue = ret->getReturnValue(); CPPUNIT_ASSERT(rvalue); CPPUNIT_ASSERT(rvalue->getType()->isFloatTy()); // the return is the result of the bin op CPPUNIT_ASSERT_EQUAL(rvalue, llvm::cast<llvm::Value>(binary)); ++iter; CPPUNIT_ASSERT(BB->end() == iter); // Test the builder is pointing to the correct location CPPUNIT_ASSERT_EQUAL(&(BaseFunction->getEntryBlock()), B.GetInsertBlock()); CPPUNIT_ASSERT_EQUAL(llvm::cast<llvm::Value>(call), llvm::cast<llvm::Value>(--B.GetInsertPoint())); // verify VERIFY_FUNCTION_IR(function); VERIFY_FUNCTION_IR(BaseFunction); VERIFY_MODULE_IR(&M); // Test invalid return expectedName = "ax.ir.retnull.test"; termMode = 2; test.reset(new TestIRFunction({ llvm::Type::getFloatTy(C), llvm::Type::getFloatTy(C) }, llvm::Type::getFloatTy(C), expectedName, generate)); CPPUNIT_ASSERT(!M.getFunction("ax.ir.retnull.test")); // will throw as the function expects a float ret, not void or null // NOTE: The function will still be created, but be in an invaid state CPPUNIT_ASSERT_THROW(test->create(M), openvdb::AXCodeGenError); function = M.getFunction("ax.ir.retnull.test"); CPPUNIT_ASSERT(function); result = test->call({fp1, fp2}, B, /*cast*/false); CPPUNIT_ASSERT(result); call = llvm::dyn_cast<llvm::CallInst>(result); CPPUNIT_ASSERT(call); CPPUNIT_ASSERT_EQUAL(function, call->getCalledFunction()); CPPUNIT_ASSERT_EQUAL(2u, call->getNumArgOperands()); CPPUNIT_ASSERT_EQUAL(fp1, call->getArgOperand(0)); CPPUNIT_ASSERT_EQUAL(fp2, call->getArgOperand(1)); BB = &(function->getEntryBlock()); // two instructions - the add and return CPPUNIT_ASSERT_EQUAL(size_t(2), BB->size()); iter = BB->begin(); binary = llvm::dyn_cast<llvm::BinaryOperator>(iter); CPPUNIT_ASSERT(binary); CPPUNIT_ASSERT_EQUAL(llvm::Instruction::FAdd, binary->getOpcode()); CPPUNIT_ASSERT_EQUAL(llvm::cast<llvm::Value>(function->arg_begin()), binary->getOperand(0)); CPPUNIT_ASSERT_EQUAL(llvm::cast<llvm::Value>(function->arg_begin()+1), binary->getOperand(1)); ++iter; ret = llvm::dyn_cast<llvm::ReturnInst>(iter); CPPUNIT_ASSERT(ret); CPPUNIT_ASSERT(!ret->getReturnValue()); ++iter; CPPUNIT_ASSERT(BB->end() == iter); // Test the builder is pointing to the correct location CPPUNIT_ASSERT_EQUAL(&(BaseFunction->getEntryBlock()), B.GetInsertBlock()); CPPUNIT_ASSERT_EQUAL(llvm::cast<llvm::Value>(call), llvm::cast<llvm::Value>(--B.GetInsertPoint())); // verify - function is invalid as it returns void but the // prototype wants a float VERIFY_FUNCTION_IR_INVALID(function); VERIFY_FUNCTION_IR(BaseFunction); VERIFY_MODULE_IR_INVALID(&M); // // Test embedded IR auto embdedGen = [&B, &M] (const std::vector<llvm::Value*>& args, llvm::IRBuilder<>& _B) -> llvm::Value* { // test the builder is pointing to the correct location // note, for embedded IR, the same builder will be used CPPUNIT_ASSERT_EQUAL(&B, &_B); llvm::BasicBlock* Block = _B.GetInsertBlock(); CPPUNIT_ASSERT(Block); CPPUNIT_ASSERT(!Block->empty()); llvm::Function* F = Block->getParent(); CPPUNIT_ASSERT(F); CPPUNIT_ASSERT_EQUAL(std::string("TestFunction"), std::string(F->getName())); CPPUNIT_ASSERT_EQUAL(&M, F->getParent()); CPPUNIT_ASSERT_EQUAL(size_t(2), args.size()); CPPUNIT_ASSERT(args[0]->getType()->isFloatTy()); CPPUNIT_ASSERT(args[1]->getType()->isFloatTy()); // Can't just do a CreateFAdd as the IR builder won't actually even // write the instruction as its const and unused - so store in a new // alloc llvm::Value* alloc = _B.CreateAlloca(args[0]->getType()); _B.CreateStore(args[0], alloc); return _B.CreateLoad(alloc); }; test.reset(new TestIRFunction({ llvm::Type::getFloatTy(C), llvm::Type::getFloatTy(C) }, llvm::Type::getFloatTy(C), "ax.ir.embed.test", embdedGen)); static_cast<IRFunctionBase&>(*test).setEmbedIR(true); // test create does nothing CPPUNIT_ASSERT(test->create(C) == nullptr); CPPUNIT_ASSERT(test->create(M) == nullptr); // test call CPPUNIT_ASSERT(!M.getFunction("ax.ir.embed.test")); result = test->call({fp1, fp2}, B, /*cast*/false); CPPUNIT_ASSERT(result); CPPUNIT_ASSERT(!M.getFunction("ax.ir.embed.test")); auto IP = B.GetInsertPoint(); // check the prev instructions are as expected CPPUNIT_ASSERT(llvm::isa<llvm::LoadInst>(--IP)); CPPUNIT_ASSERT(llvm::isa<llvm::StoreInst>(--IP)); CPPUNIT_ASSERT(llvm::isa<llvm::AllocaInst>(--IP)); // Test the builder is pointing to the correct location CPPUNIT_ASSERT_EQUAL(&(BaseFunction->getEntryBlock()), B.GetInsertBlock()); } void TestFunctionTypes::testSRETFunctions() { using openvdb::ax::codegen::LLVMType; using openvdb::ax::codegen::Function; using openvdb::ax::codegen::CFunctionSRet; using openvdb::ax::codegen::IRFunctionSRet; unittest_util::LLVMState state; llvm::LLVMContext& C = state.context(); llvm::Module& M = state.module(); llvm::IRBuilder<> B(state.scratchBlock()); std::vector<llvm::Type*> types; llvm::Type* type = nullptr; llvm::Value* result = nullptr; llvm::Function* function = nullptr; llvm::FunctionType* ftype = nullptr; Function::SignatureMatch match; std::ostringstream os; B.SetInsertPoint(finalizeFunction(B)); llvm::Function* BaseFunction = B.GetInsertBlock()->getParent(); // test C SRET static auto csret = [](float(*output)[3]) { (*output)[0] = 1.0f; }; Function::Ptr test(new CFunctionSRet<void(float(*)[3])> ("ax.c.test", (void(*)(float(*)[3]))(csret))); // test types llvm::Type* vec3f = llvm::ArrayType::get(llvm::Type::getFloatTy(C), 3); type = test->types(types, C); CPPUNIT_ASSERT_EQUAL(size_t(1), types.size()); CPPUNIT_ASSERT(types[0] == vec3f->getPointerTo(0)); CPPUNIT_ASSERT(type); CPPUNIT_ASSERT(type->isVoidTy()); // test various getters CPPUNIT_ASSERT_EQUAL(std::string("ax.c.test"), std::string(test->symbol())); CPPUNIT_ASSERT_EQUAL(size_t(1), test->size()); CPPUNIT_ASSERT_EQUAL(std::string(""), std::string(test->argName(0))); // test printing os.str(""); test->print(C, os, "name", /*axtypes=*/true); CPPUNIT_ASSERT_EQUAL(std::string("vec3f name()"), os.str()); // test match match = test->match({vec3f->getPointerTo()}, C); CPPUNIT_ASSERT_EQUAL(match, Function::None); match = test->match({}, C); CPPUNIT_ASSERT_EQUAL(match, Function::Explicit); match = test->Function::match({vec3f->getPointerTo()}, C); CPPUNIT_ASSERT_EQUAL(match, Function::Explicit); // test create CPPUNIT_ASSERT(!M.getFunction("ax.c.test")); function = test->create(M); CPPUNIT_ASSERT(function); CPPUNIT_ASSERT(M.getFunction("ax.c.test")); CPPUNIT_ASSERT_EQUAL(function, test->create(M)); CPPUNIT_ASSERT(function->empty()); CPPUNIT_ASSERT_EQUAL(size_t(1), function->arg_size()); CPPUNIT_ASSERT(function->getAttributes().isEmpty()); ftype = function->getFunctionType(); CPPUNIT_ASSERT(ftype); CPPUNIT_ASSERT(ftype->getReturnType()->isVoidTy()); CPPUNIT_ASSERT_EQUAL(1u, ftype->getNumParams()); CPPUNIT_ASSERT(ftype->getParamType(0) == vec3f->getPointerTo()); // test call - sret function do not return the CallInst as the value result = test->call({}, B, /*cast*/false); CPPUNIT_ASSERT(result); CPPUNIT_ASSERT(!llvm::dyn_cast<llvm::CallInst>(result)); CPPUNIT_ASSERT(result->getType() == vec3f->getPointerTo()); CPPUNIT_ASSERT_EQUAL(&(BaseFunction->getEntryBlock()), B.GetInsertBlock()); VERIFY_FUNCTION_IR(function); VERIFY_MODULE_IR(&M); // // test sret with two arguments static auto csret2 = [](float(*output)[3], float(*input)[3]) { (*output)[0] = (*input)[0]; }; test.reset(new CFunctionSRet<void(float(*)[3],float(*)[3])> ("ax.c2.test", (void(*)(float(*)[3],float(*)[3]))(csret2))); types.clear(); // test types type = test->types(types, C); CPPUNIT_ASSERT_EQUAL(size_t(2), types.size()); CPPUNIT_ASSERT(types[0] == vec3f->getPointerTo(0)); CPPUNIT_ASSERT(types[1] == vec3f->getPointerTo(0)); CPPUNIT_ASSERT(type); CPPUNIT_ASSERT(type->isVoidTy()); // test various getters CPPUNIT_ASSERT_EQUAL(std::string("ax.c2.test"), std::string(test->symbol())); CPPUNIT_ASSERT_EQUAL(size_t(2), test->size()); CPPUNIT_ASSERT_EQUAL(std::string(""), std::string(test->argName(0))); CPPUNIT_ASSERT_EQUAL(std::string(""), std::string(test->argName(1))); // test printing os.str(""); test->print(C, os, "name", /*axtypes=*/true); CPPUNIT_ASSERT_EQUAL(std::string("vec3f name(vec3f)"), os.str()); // test match match = test->match({vec3f->getPointerTo(),vec3f->getPointerTo()}, C); CPPUNIT_ASSERT_EQUAL(match, Function::None); match = test->match({vec3f->getPointerTo()}, C); CPPUNIT_ASSERT_EQUAL(match, Function::Explicit); match = test->match({}, C); CPPUNIT_ASSERT_EQUAL(match, Function::None); match = test->Function::match({vec3f->getPointerTo(),vec3f->getPointerTo()}, C); CPPUNIT_ASSERT_EQUAL(match, Function::Explicit); // test create CPPUNIT_ASSERT(!M.getFunction("ax.c2.test")); function = test->create(M); CPPUNIT_ASSERT(function); CPPUNIT_ASSERT(M.getFunction("ax.c2.test")); CPPUNIT_ASSERT_EQUAL(function, test->create(M)); CPPUNIT_ASSERT(function->empty()); CPPUNIT_ASSERT_EQUAL(size_t(2), function->arg_size()); CPPUNIT_ASSERT(function->getAttributes().isEmpty()); ftype = function->getFunctionType(); CPPUNIT_ASSERT(ftype); CPPUNIT_ASSERT(ftype->getReturnType()->isVoidTy()); CPPUNIT_ASSERT_EQUAL(2u, ftype->getNumParams()); CPPUNIT_ASSERT(ftype->getParamType(0) == vec3f->getPointerTo()); CPPUNIT_ASSERT(ftype->getParamType(1) == vec3f->getPointerTo()); // test call - sret function do not return the CallInst as the value llvm::Value* f32c0 = LLVMType<float>::get(C, 0.0f); // float llvm::Value* vec3fv = openvdb::ax::codegen::arrayPack({f32c0,f32c0,f32c0}, B); // vec3f result = test->call({vec3fv}, B, /*cast*/false); CPPUNIT_ASSERT(result); CPPUNIT_ASSERT(!llvm::dyn_cast<llvm::CallInst>(result)); CPPUNIT_ASSERT(result->getType() == vec3f->getPointerTo()); CPPUNIT_ASSERT_EQUAL(&(BaseFunction->getEntryBlock()), B.GetInsertBlock()); VERIFY_FUNCTION_IR(function); VERIFY_MODULE_IR(&M); // // test IR SRET // Build the following function: // void test(vec3f* a) { // a[0] = 1.0f; // } // which has a front interface of: // vec3f test() { vec3f a; a[0] = 1; return a;}; // auto generate = [&B, &M] (const std::vector<llvm::Value*>& args, llvm::IRBuilder<>& _B) -> llvm::Value* { // test the builder is pointing to the correct location CPPUNIT_ASSERT(&B != &_B); llvm::BasicBlock* Block = _B.GetInsertBlock(); CPPUNIT_ASSERT(Block); CPPUNIT_ASSERT(Block->empty()); llvm::Function* F = Block->getParent(); CPPUNIT_ASSERT(F); CPPUNIT_ASSERT_EQUAL(std::string("ax.ir.test"), std::string(F->getName())); llvm::Module* _M = F->getParent(); CPPUNIT_ASSERT_EQUAL(&M, _M); CPPUNIT_ASSERT_EQUAL(size_t(1), args.size()); CPPUNIT_ASSERT(args[0] == llvm::cast<llvm::Value>(F->arg_begin())); CPPUNIT_ASSERT(args[0]->getType() == llvm::ArrayType::get(llvm::Type::getFloatTy(_B.getContext()), 3)->getPointerTo()); llvm::Value* e0 = _B.CreateConstGEP2_64(args[0], 0, 0); _B.CreateStore(LLVMType<float>::get(_B.getContext(), 1.0f), e0); return nullptr; }; test.reset(new IRFunctionSRet<void(float(*)[3])>("ax.ir.test", generate)); types.clear(); // test types type = test->types(types, C); CPPUNIT_ASSERT_EQUAL(size_t(1), types.size()); CPPUNIT_ASSERT(types[0] == vec3f->getPointerTo(0)); CPPUNIT_ASSERT(type); CPPUNIT_ASSERT(type->isVoidTy()); // test various getters CPPUNIT_ASSERT_EQUAL(std::string("ax.ir.test"), std::string(test->symbol())); CPPUNIT_ASSERT_EQUAL(size_t(1), test->size()); CPPUNIT_ASSERT_EQUAL(std::string(""), std::string(test->argName(0))); // test printing os.str(""); test->print(C, os, "name", /*axtypes=*/true); CPPUNIT_ASSERT_EQUAL(std::string("vec3f name()"), os.str()); // test match match = test->match({vec3f->getPointerTo()}, C); CPPUNIT_ASSERT_EQUAL(match, Function::None); match = test->match({}, C); CPPUNIT_ASSERT_EQUAL(match, Function::Explicit); match = test->Function::match({vec3f->getPointerTo()}, C); CPPUNIT_ASSERT_EQUAL(match, Function::Explicit); // test create CPPUNIT_ASSERT(!M.getFunction("ax.ir.test")); function = test->create(M); CPPUNIT_ASSERT(function); CPPUNIT_ASSERT_EQUAL(function, M.getFunction("ax.ir.test")); CPPUNIT_ASSERT(!function->empty()); // test instructions llvm::BasicBlock* BB = &(function->getEntryBlock()); CPPUNIT_ASSERT_EQUAL(size_t(3), BB->size()); auto iter = BB->begin(); CPPUNIT_ASSERT(llvm::isa<llvm::GetElementPtrInst>(iter++)); CPPUNIT_ASSERT(llvm::isa<llvm::StoreInst>(iter++)); CPPUNIT_ASSERT(llvm::isa<llvm::ReturnInst>(iter++)); CPPUNIT_ASSERT(BB->end() == iter); // additional call should match CPPUNIT_ASSERT_EQUAL(function, test->create(M)); CPPUNIT_ASSERT_EQUAL(size_t(1), function->arg_size()); CPPUNIT_ASSERT(function->getAttributes().isEmpty()); // check function type ftype = function->getFunctionType(); CPPUNIT_ASSERT(ftype); CPPUNIT_ASSERT(ftype->getReturnType()->isVoidTy()); CPPUNIT_ASSERT_EQUAL(1u, ftype->getNumParams()); CPPUNIT_ASSERT(ftype->getParamType(0) == vec3f->getPointerTo()); // test call - sret function do not return the CallInst as the value result = test->call({}, B, /*cast*/false); CPPUNIT_ASSERT(result); CPPUNIT_ASSERT(!llvm::dyn_cast<llvm::CallInst>(result)); CPPUNIT_ASSERT(result->getType() == vec3f->getPointerTo()); CPPUNIT_ASSERT_EQUAL(&(BaseFunction->getEntryBlock()), B.GetInsertBlock()); VERIFY_FUNCTION_IR(function); VERIFY_MODULE_IR(&M); }
NVIDIA-Omniverse/ext-openvdb/openvdb_ax/openvdb_ax/test/backend/TestTypes.cc
// Copyright Contributors to the OpenVDB Project // SPDX-License-Identifier: MPL-2.0 #include "util.h" #include <openvdb_ax/codegen/Types.h> #include <openvdb/math/Vec2.h> #include <openvdb/math/Vec3.h> #include <openvdb/math/Vec4.h> #include <openvdb/math/Mat3.h> #include <openvdb/math/Mat4.h> #include <cppunit/extensions/HelperMacros.h> class TestTypes : public CppUnit::TestCase { public: CPPUNIT_TEST_SUITE(TestTypes); CPPUNIT_TEST(testTypes); CPPUNIT_TEST(testVDBTypes); CPPUNIT_TEST_SUITE_END(); void testTypes(); void testVDBTypes(); }; CPPUNIT_TEST_SUITE_REGISTRATION(TestTypes); void TestTypes::testTypes() { using openvdb::ax::codegen::LLVMType; unittest_util::LLVMState state; llvm::LLVMContext& C = state.context(); // scalar types CPPUNIT_ASSERT_EQUAL(llvm::cast<llvm::Type>(llvm::Type::getInt1Ty(C)), LLVMType<bool>::get(C)); CPPUNIT_ASSERT_EQUAL(llvm::cast<llvm::Type>(llvm::Type::getInt8Ty(C)), LLVMType<int8_t>::get(C)); CPPUNIT_ASSERT_EQUAL(llvm::cast<llvm::Type>(llvm::Type::getInt16Ty(C)), LLVMType<int16_t>::get(C)); CPPUNIT_ASSERT_EQUAL(llvm::cast<llvm::Type>(llvm::Type::getInt32Ty(C)), LLVMType<int32_t>::get(C)); CPPUNIT_ASSERT_EQUAL(llvm::cast<llvm::Type>(llvm::Type::getInt64Ty(C)), LLVMType<int64_t>::get(C)); CPPUNIT_ASSERT_EQUAL(llvm::cast<llvm::Type>(llvm::Type::getFloatTy(C)), LLVMType<float>::get(C)); CPPUNIT_ASSERT_EQUAL(llvm::cast<llvm::Type>(llvm::Type::getDoubleTy(C)), LLVMType<double>::get(C)); // scalar values CPPUNIT_ASSERT_EQUAL(llvm::cast<llvm::Constant>(llvm::ConstantInt::get(llvm::Type::getInt1Ty(C), true)), LLVMType<bool>::get(C, true)); CPPUNIT_ASSERT_EQUAL(llvm::cast<llvm::Constant>(llvm::ConstantInt::get(llvm::Type::getInt8Ty(C), int8_t(1))), LLVMType<int8_t>::get(C, int8_t(1))); CPPUNIT_ASSERT_EQUAL(llvm::cast<llvm::Constant>(llvm::ConstantInt::get(llvm::Type::getInt16Ty(C), int16_t(2))), LLVMType<int16_t>::get(C, int16_t(2))); CPPUNIT_ASSERT_EQUAL(llvm::cast<llvm::Constant>(llvm::ConstantInt::get(llvm::Type::getInt32Ty(C), int32_t(3))), LLVMType<int32_t>::get(C, int32_t(3))); CPPUNIT_ASSERT_EQUAL(llvm::cast<llvm::Constant>(llvm::ConstantInt::get(llvm::Type::getInt64Ty(C), int64_t(4))), LLVMType<int64_t>::get(C, int64_t(4))); // array types #if LLVM_VERSION_MAJOR > 6 CPPUNIT_ASSERT_EQUAL(llvm::cast<llvm::Type>(llvm::ArrayType::get(llvm::Type::getInt1Ty(C), 1)), LLVMType<bool[1]>::get(C)); #endif CPPUNIT_ASSERT_EQUAL(llvm::cast<llvm::Type>(llvm::ArrayType::get(llvm::Type::getInt8Ty(C), 2)), LLVMType<int8_t[2]>::get(C)); CPPUNIT_ASSERT_EQUAL(llvm::cast<llvm::Type>(llvm::ArrayType::get(llvm::Type::getInt16Ty(C), 3)), LLVMType<int16_t[3]>::get(C)); CPPUNIT_ASSERT_EQUAL(llvm::cast<llvm::Type>(llvm::ArrayType::get(llvm::Type::getInt32Ty(C), 4)), LLVMType<int32_t[4]>::get(C)); CPPUNIT_ASSERT_EQUAL(llvm::cast<llvm::Type>(llvm::ArrayType::get(llvm::Type::getInt64Ty(C), 5)), LLVMType<int64_t[5]>::get(C)); CPPUNIT_ASSERT_EQUAL(llvm::cast<llvm::Type>(llvm::ArrayType::get(llvm::Type::getFloatTy(C), 6)), LLVMType<float[6]>::get(C)); CPPUNIT_ASSERT_EQUAL(llvm::cast<llvm::Type>(llvm::ArrayType::get(llvm::Type::getDoubleTy(C), 7)), LLVMType<double[7]>::get(C)); // array values #if LLVM_VERSION_MAJOR > 6 CPPUNIT_ASSERT_EQUAL(llvm::cast<llvm::Constant>(llvm::ConstantDataArray::get<bool>(C, {true})), LLVMType<bool[1]>::get(C, {true})); #endif const std::vector<uint8_t> veci8{1,2}; CPPUNIT_ASSERT_EQUAL(llvm::cast<llvm::Constant>(llvm::ConstantDataArray::get(C, veci8)), LLVMType<uint8_t[2]>::get(C, {1,2})); const std::vector<uint16_t> veci16{1,2,3}; CPPUNIT_ASSERT_EQUAL(llvm::cast<llvm::Constant>(llvm::ConstantDataArray::get(C, veci16)), LLVMType<uint16_t[3]>::get(C, {1,2,3})); const std::vector<uint32_t> veci32{1,2,3,4}; CPPUNIT_ASSERT_EQUAL(llvm::cast<llvm::Constant>(llvm::ConstantDataArray::get(C, veci32)), LLVMType<uint32_t[4]>::get(C, {1,2,3,4})); const std::vector<uint64_t> veci64{1,2,3,4,5}; CPPUNIT_ASSERT_EQUAL(llvm::cast<llvm::Constant>(llvm::ConstantDataArray::get(C, veci64)), LLVMType<uint64_t[5]>::get(C, {1,2,3,4,5})); const std::vector<float> vecf{.0f,.1f,.2f,.3f,.4f,.5f}; CPPUNIT_ASSERT_EQUAL(llvm::cast<llvm::Constant>(llvm::ConstantDataArray::get(C, vecf)), LLVMType<float[6]>::get(C, {.0f,.1f,.2f,.3f,.4f,.5f})); const std::vector<double> vecd{.0,.1,.2,.3,.4,.5,.6}; CPPUNIT_ASSERT_EQUAL(llvm::cast<llvm::Constant>(llvm::ConstantDataArray::get(C, vecd)), LLVMType<double[7]>::get(C, {.0,.1,.2,.3,.4,.5,.6})); // void CPPUNIT_ASSERT_EQUAL(llvm::cast<llvm::Type>(llvm::Type::getVoidTy(C)), LLVMType<void>::get(C)); // some special cases we alias CPPUNIT_ASSERT_EQUAL(llvm::Type::getInt8PtrTy(C), LLVMType<void*>::get(C)); CPPUNIT_ASSERT_EQUAL(llvm::cast<llvm::Type>(llvm::Type::getInt8Ty(C)), LLVMType<char>::get(C)); } void TestTypes::testVDBTypes() { using openvdb::ax::codegen::LLVMType; unittest_util::LLVMState state; llvm::LLVMContext& C = state.context(); CPPUNIT_ASSERT_EQUAL(llvm::cast<llvm::Type>(llvm::ArrayType::get(llvm::Type::getInt32Ty(C), 2)), LLVMType<openvdb::math::Vec2<int32_t>>::get(C)); CPPUNIT_ASSERT_EQUAL(llvm::cast<llvm::Type>(llvm::ArrayType::get(llvm::Type::getFloatTy(C), 2)), LLVMType<openvdb::math::Vec2<float>>::get(C)); CPPUNIT_ASSERT_EQUAL(llvm::cast<llvm::Type>(llvm::ArrayType::get(llvm::Type::getDoubleTy(C), 2)), LLVMType<openvdb::math::Vec2<double>>::get(C)); CPPUNIT_ASSERT_EQUAL(llvm::cast<llvm::Type>(llvm::ArrayType::get(llvm::Type::getInt32Ty(C), 3)), LLVMType<openvdb::math::Vec3<int32_t>>::get(C)); CPPUNIT_ASSERT_EQUAL(llvm::cast<llvm::Type>(llvm::ArrayType::get(llvm::Type::getFloatTy(C), 3)), LLVMType<openvdb::math::Vec3<float>>::get(C)); CPPUNIT_ASSERT_EQUAL(llvm::cast<llvm::Type>(llvm::ArrayType::get(llvm::Type::getDoubleTy(C), 3)), LLVMType<openvdb::math::Vec3<double>>::get(C)); CPPUNIT_ASSERT_EQUAL(llvm::cast<llvm::Type>(llvm::ArrayType::get(llvm::Type::getInt32Ty(C), 4)), LLVMType<openvdb::math::Vec4<int32_t>>::get(C)); CPPUNIT_ASSERT_EQUAL(llvm::cast<llvm::Type>(llvm::ArrayType::get(llvm::Type::getFloatTy(C), 4)), LLVMType<openvdb::math::Vec4<float>>::get(C)); CPPUNIT_ASSERT_EQUAL(llvm::cast<llvm::Type>(llvm::ArrayType::get(llvm::Type::getDoubleTy(C), 4)), LLVMType<openvdb::math::Vec4<double>>::get(C)); CPPUNIT_ASSERT_EQUAL(llvm::cast<llvm::Type>(llvm::ArrayType::get(llvm::Type::getFloatTy(C), 9)), LLVMType<openvdb::math::Mat3<float>>::get(C)); CPPUNIT_ASSERT_EQUAL(llvm::cast<llvm::Type>(llvm::ArrayType::get(llvm::Type::getDoubleTy(C), 9)), LLVMType<openvdb::math::Mat3<double>>::get(C)); CPPUNIT_ASSERT_EQUAL(llvm::cast<llvm::Type>(llvm::ArrayType::get(llvm::Type::getFloatTy(C), 16)), LLVMType<openvdb::math::Mat4<float>>::get(C)); CPPUNIT_ASSERT_EQUAL(llvm::cast<llvm::Type>(llvm::ArrayType::get(llvm::Type::getDoubleTy(C), 16)), LLVMType<openvdb::math::Mat4<double>>::get(C)); }
NVIDIA-Omniverse/ext-openvdb/openvdb_ax/openvdb_ax/test/backend/util.h
// Copyright Contributors to the OpenVDB Project // SPDX-License-Identifier: MPL-2.0 #ifndef OPENVDB_AX_UNITTEST_BACKEND_UTIL_HAS_BEEN_INCLUDED #define OPENVDB_AX_UNITTEST_BACKEND_UTIL_HAS_BEEN_INCLUDED #include <openvdb_ax/codegen/Types.h> #include <llvm/IR/LLVMContext.h> #include <llvm/IR/Module.h> #include <llvm/IR/IRBuilder.h> #include <memory> #include <string> namespace unittest_util { struct LLVMState { LLVMState(const std::string& name = "__test_module") : mCtx(new llvm::LLVMContext), mModule(new llvm::Module(name, *mCtx)) {} llvm::LLVMContext& context() { return *mCtx; } llvm::Module& module() { return *mModule; } inline llvm::BasicBlock* scratchBlock(const std::string& functionName = "TestFunction", const std::string& blockName = "TestEntry") { llvm::FunctionType* type = llvm::FunctionType::get(openvdb::ax::codegen::LLVMType<void>::get(this->context()), /**var-args*/false); llvm::Function* dummyFunction = llvm::Function::Create(type, llvm::Function::ExternalLinkage, functionName, &this->module()); return llvm::BasicBlock::Create(this->context(), blockName, dummyFunction); } private: std::unique_ptr<llvm::LLVMContext> mCtx; std::unique_ptr<llvm::Module> mModule; }; } #endif // OPENVDB_AX_UNITTEST_BACKEND_UTIL_HAS_BEEN_INCLUDED
NVIDIA-Omniverse/ext-openvdb/openvdb_ax/openvdb_ax/test/frontend/TestUnaryOperatorNode.cc
// Copyright Contributors to the OpenVDB Project // SPDX-License-Identifier: MPL-2.0 #include <openvdb_ax/ast/AST.h> #include <openvdb_ax/ast/Scanners.h> #include <openvdb_ax/ast/PrintTree.h> #include <openvdb_ax/Exceptions.h> #include <openvdb_ax/test/util.h> #include <cppunit/extensions/HelperMacros.h> #include <string> using namespace openvdb::ax::ast; using namespace openvdb::ax::ast::tokens; namespace { static const unittest_util::CodeTests tests = { { "-a;", Node::Ptr(new UnaryOperator(new Local("a"), OperatorToken::MINUS)) }, { "+a;", Node::Ptr(new UnaryOperator(new Local("a"), OperatorToken::PLUS)) }, { "!a;", Node::Ptr(new UnaryOperator(new Local("a"), OperatorToken::NOT)) }, { "~a;", Node::Ptr(new UnaryOperator(new Local("a"), OperatorToken::BITNOT)) }, { "~~a;", Node::Ptr(new UnaryOperator(new UnaryOperator(new Local("a"), OperatorToken::BITNOT), OperatorToken::BITNOT)) }, { "!~a;", Node::Ptr(new UnaryOperator(new UnaryOperator(new Local("a"), OperatorToken::BITNOT), OperatorToken::NOT)) }, { "+-a;", Node::Ptr(new UnaryOperator(new UnaryOperator(new Local("a"), OperatorToken::MINUS), OperatorToken::PLUS)) }, { "-+a;", Node::Ptr(new UnaryOperator(new UnaryOperator(new Local("a"), OperatorToken::PLUS), OperatorToken::MINUS)) }, { "!!!a;", Node::Ptr(new UnaryOperator( new UnaryOperator( new UnaryOperator(new Local("a"), OperatorToken::NOT), OperatorToken::NOT ), OperatorToken::NOT )) }, { "~~~a;", Node::Ptr(new UnaryOperator( new UnaryOperator( new UnaryOperator(new Local("a"), OperatorToken::BITNOT), OperatorToken::BITNOT ), OperatorToken::BITNOT )) }, { "-(a+b);", Node::Ptr(new UnaryOperator( new BinaryOperator( new Local("a"), new Local("b"), OperatorToken::PLUS ), OperatorToken::MINUS )) }, { "!func();", Node::Ptr(new UnaryOperator(new FunctionCall("func"), OperatorToken::NOT)) }, { "-@a;", Node::Ptr(new UnaryOperator(new Attribute("a", CoreType::FLOAT, true), OperatorToken::MINUS)) }, { "!v@a;", Node::Ptr(new UnaryOperator(new Attribute("a", CoreType::VEC3F), OperatorToken::NOT)) }, { "~v@a;", Node::Ptr(new UnaryOperator(new Attribute("a", CoreType::VEC3F), OperatorToken::BITNOT)) }, { "+int(a);", Node::Ptr(new UnaryOperator(new Cast(new Local("a"), CoreType::INT32), OperatorToken::PLUS)) }, { "-(float(a));", Node::Ptr(new UnaryOperator(new Cast(new Local("a"), CoreType::FLOAT), OperatorToken::MINUS)) }, { "!a.x;", Node::Ptr(new UnaryOperator(new ArrayUnpack(new Local("a"), new Value<int32_t>(0)), OperatorToken::NOT)) }, { "-a[0];", Node::Ptr(new UnaryOperator(new ArrayUnpack(new Local("a"), new Value<int32_t>(0)), OperatorToken::MINUS)) }, { "-++a;", Node::Ptr(new UnaryOperator(new Crement(new Local("a"), Crement::Operation::Increment, false), OperatorToken::MINUS)) }, { "!{a,b,c};", Node::Ptr(new UnaryOperator( new ArrayPack({ new Local("a"), new Local("b"), new Local("c") }), OperatorToken::NOT )) }, { "!(a,b,c);", Node::Ptr(new UnaryOperator( new CommaOperator({ new Local("a"), new Local("b"), new Local("c") }), OperatorToken::NOT )) }, // This is a bit of a weird one - should perhaps look to making this a syntax error // (it will fail at compilation with an lvalue error) { "-a=a;", Node::Ptr(new UnaryOperator( new AssignExpression(new Local("a"), new Local("a")), OperatorToken::MINUS )) } }; } class TestUnaryOperatorNode : public CppUnit::TestCase { public: CPPUNIT_TEST_SUITE(TestUnaryOperatorNode); CPPUNIT_TEST(testSyntax); CPPUNIT_TEST(testASTNode); CPPUNIT_TEST_SUITE_END(); void testSyntax() { TEST_SYNTAX_PASSES(tests); } void testASTNode(); }; CPPUNIT_TEST_SUITE_REGISTRATION(TestUnaryOperatorNode); void TestUnaryOperatorNode::testASTNode() { for (const auto& test : tests) { const std::string& code = test.first; const Node* expected = test.second.get(); const Tree::ConstPtr tree = parse(code.c_str()); CPPUNIT_ASSERT_MESSAGE(ERROR_MSG("No AST returned", code), static_cast<bool>(tree)); // get the first statement const Node* result = tree->child(0)->child(0); CPPUNIT_ASSERT(result); CPPUNIT_ASSERT_MESSAGE(ERROR_MSG("Invalid AST node", code), Node::UnaryOperatorNode == result->nodetype()); std::vector<const Node*> resultList, expectedList; linearize(*result, resultList); linearize(*expected, expectedList); if (!unittest_util::compareLinearTrees(expectedList, resultList)) { std::ostringstream os; os << "\nExpected:\n"; openvdb::ax::ast::print(*expected, true, os); os << "Result:\n"; openvdb::ax::ast::print(*result, true, os); CPPUNIT_FAIL(ERROR_MSG("Mismatching Trees for Unary Operator code", code) + os.str()); } } }
NVIDIA-Omniverse/ext-openvdb/openvdb_ax/openvdb_ax/test/frontend/TestCastNode.cc
// Copyright Contributors to the OpenVDB Project // SPDX-License-Identifier: MPL-2.0 #include <openvdb_ax/ast/AST.h> #include <openvdb_ax/ast/Scanners.h> #include <openvdb_ax/ast/PrintTree.h> #include <openvdb_ax/Exceptions.h> #include <openvdb_ax/test/util.h> #include <cppunit/extensions/HelperMacros.h> #include <string> using namespace openvdb::ax::ast; using namespace openvdb::ax::ast::tokens; namespace { static const unittest_util::CodeTests tests = { { "bool(a);", Node::Ptr(new Cast(new Local("a"), CoreType::BOOL)) }, { "int(a);", Node::Ptr(new Cast(new Local("a"), CoreType::INT32)) }, { "int32(a);", Node::Ptr(new Cast(new Local("a"), CoreType::INT32)) }, { "int64(a);", Node::Ptr(new Cast(new Local("a"), CoreType::INT64)) }, { "float(a);", Node::Ptr(new Cast(new Local("a"), CoreType::FLOAT)) }, { "double(a);", Node::Ptr(new Cast(new Local("a"), CoreType::DOUBLE)) }, { "int32((a));", Node::Ptr(new Cast(new Local("a"), CoreType::INT32)) }, { "int32(1l);", Node::Ptr(new Cast(new Value<int64_t>(1), CoreType::INT32)) }, { "int32(1);", Node::Ptr(new Cast(new Value<int32_t>(1), CoreType::INT32)) }, { "int32(0);", Node::Ptr(new Cast(new Value<int32_t>(0), CoreType::INT32)) }, { "int32(@a);", Node::Ptr(new Cast(new Attribute("a", CoreType::FLOAT, true), CoreType::INT32)) }, { "double(true);", Node::Ptr(new Cast(new Value<bool>(true), CoreType::DOUBLE)) }, { "double(false);", Node::Ptr(new Cast(new Value<bool>(false), CoreType::DOUBLE)) }, { "int32(1.0f);", Node::Ptr(new Cast(new Value<float>(1.0f), CoreType::INT32)) }, { "int64(1.0);", Node::Ptr(new Cast(new Value<double>(1.0), CoreType::INT64)) }, { "float(true);", Node::Ptr(new Cast(new Value<bool>(true), CoreType::FLOAT)) }, { "int32(func());", Node::Ptr(new Cast(new FunctionCall("func"), CoreType::INT32)) }, { "bool(a+b);", Node::Ptr(new Cast(new BinaryOperator(new Local("a"), new Local("b"), OperatorToken::PLUS), CoreType::BOOL)) }, { "int32(~a);", Node::Ptr(new Cast(new UnaryOperator(new Local("a"), OperatorToken::BITNOT), CoreType::INT32)) }, { "int64(~a);", Node::Ptr(new Cast(new UnaryOperator(new Local("a"), OperatorToken::BITNOT), CoreType::INT64)) }, { "float(a = b);", Node::Ptr(new Cast(new AssignExpression(new Local("a"), new Local("b")), CoreType::FLOAT)) }, { "double(a.x);", Node::Ptr(new Cast(new ArrayUnpack(new Local("a"), new Value<int32_t>(0)), CoreType::DOUBLE)) }, { "int32(a++);", Node::Ptr(new Cast(new Crement(new Local("a"), Crement::Operation::Increment, true), CoreType::INT32)) }, { "int32({a,b,c});", Node::Ptr(new Cast(new ArrayPack({new Local("a"), new Local("b"), new Local("c")}), CoreType::INT32)) }, { "int32((a,b,c));", Node::Ptr(new Cast(new CommaOperator({new Local("a"), new Local("b"), new Local("c")}), CoreType::INT32)) }, { "float(double(0));", Node::Ptr(new Cast(new Cast(new Value<int32_t>(0), CoreType::DOUBLE), CoreType::FLOAT)) }, }; } class TestCastNode : public CppUnit::TestCase { public: CPPUNIT_TEST_SUITE(TestCastNode); CPPUNIT_TEST(testSyntax); CPPUNIT_TEST(testASTNode); CPPUNIT_TEST_SUITE_END(); void testSyntax() { TEST_SYNTAX_PASSES(tests); } void testASTNode(); }; CPPUNIT_TEST_SUITE_REGISTRATION(TestCastNode); void TestCastNode::testASTNode() { for (const auto& test : tests) { const std::string& code = test.first; const Node* expected = test.second.get(); const Tree::ConstPtr tree = parse(code.c_str()); CPPUNIT_ASSERT_MESSAGE(ERROR_MSG("No AST returned", code), static_cast<bool>(tree)); // get the first statement const Node* result = tree->child(0)->child(0); CPPUNIT_ASSERT(result); CPPUNIT_ASSERT_MESSAGE(ERROR_MSG("Invalid AST node", code), Node::CastNode == result->nodetype()); std::vector<const Node*> resultList, expectedList; linearize(*result, resultList); linearize(*expected, expectedList); if (!unittest_util::compareLinearTrees(expectedList, resultList)) { std::ostringstream os; os << "\nExpected:\n"; openvdb::ax::ast::print(*expected, true, os); os << "Result:\n"; openvdb::ax::ast::print(*result, true, os); CPPUNIT_FAIL(ERROR_MSG("Mismatching Trees for Cast code", code) + os.str()); } } }
NVIDIA-Omniverse/ext-openvdb/openvdb_ax/openvdb_ax/test/frontend/TestCommaOperator.cc
// Copyright Contributors to the OpenVDB Project // SPDX-License-Identifier: MPL-2.0 #include <openvdb_ax/ast/AST.h> #include <openvdb_ax/ast/Scanners.h> #include <openvdb_ax/ast/PrintTree.h> #include <openvdb_ax/Exceptions.h> #include <openvdb_ax/test/util.h> #include <cppunit/extensions/HelperMacros.h> #include <string> using namespace openvdb::ax::ast; using namespace openvdb::ax::ast::tokens; namespace { static const unittest_util::CodeTests tests = { { "(1, 2, (1,2,3));", Node::Ptr( new CommaOperator({ new Value<int32_t>(1), new Value<int32_t>(2), new CommaOperator({ new Value<int32_t>(1), new Value<int32_t>(2), new Value<int32_t>(3) }) })) }, { "(1.f,2.0,3l);" , Node::Ptr( new CommaOperator({ new Value<float>(1.0f), new Value<double>(2.0), new Value<int64_t>(3) })) }, { "((a,b,c), (d,e,f), (g,h,i));", Node::Ptr( new CommaOperator({ new CommaOperator({ new Local("a"), new Local("b"), new Local("c") }), new CommaOperator({ new Local("d"), new Local("e"), new Local("f") }), new CommaOperator({ new Local("g"), new Local("h"), new Local("i") }) })) }, { "((a),b+1,-c);", Node::Ptr( new CommaOperator({ new Local("a"), new BinaryOperator(new Local("b"), new Value<int32_t>(1), OperatorToken::PLUS), new UnaryOperator(new Local("c"), OperatorToken::MINUS) })) }, { "(@x,++z,true);", Node::Ptr( new CommaOperator({ new Attribute("x", CoreType::FLOAT, true), new Crement(new Local("z"), Crement::Operation::Increment, false), new Value<bool>(true) })) }, { "(@x,z++,\"bar\");", Node::Ptr( new CommaOperator({ new Attribute("x", CoreType::FLOAT, true), new Crement(new Local("z"), Crement::Operation::Increment, true), new Value<std::string>("bar") })) }, { "(float(x),b=c,c.z);", Node::Ptr( new CommaOperator({ new Cast(new Local("x"), CoreType::FLOAT), new AssignExpression(new Local("b"), new Local("c")), new ArrayUnpack(new Local("c"), new Value<int32_t>(2)) })) }, { "(test(),a[0],b[1,2]);", Node::Ptr( new CommaOperator({ new FunctionCall("test"), new ArrayUnpack(new Local("a"), new Value<int32_t>(0)), new ArrayUnpack(new Local("b"), new Value<int32_t>(1), new Value<int32_t>(2)) })) }, { "(1,2,3,4,5,6,7,8,9);", Node::Ptr( new CommaOperator({ new Value<int32_t>(1), new Value<int32_t>(2), new Value<int32_t>(3), new Value<int32_t>(4), new Value<int32_t>(5), new Value<int32_t>(6), new Value<int32_t>(7), new Value<int32_t>(8), new Value<int32_t>(9) })) }, { "( 1, 2, 3, 4, \ 5, 6, 7, 8, \ 9,10,11,12, \ 13,14,15,16 );", Node::Ptr( new CommaOperator({ new Value<int32_t>(1), new Value<int32_t>(2), new Value<int32_t>(3), new Value<int32_t>(4), new Value<int32_t>(5), new Value<int32_t>(6), new Value<int32_t>(7), new Value<int32_t>(8), new Value<int32_t>(9), new Value<int32_t>(10), new Value<int32_t>(11), new Value<int32_t>(12), new Value<int32_t>(13), new Value<int32_t>(14), new Value<int32_t>(15), new Value<int32_t>(16) })) }, }; } class TestCommaOperator : public CppUnit::TestCase { public: CPPUNIT_TEST_SUITE(TestCommaOperator); CPPUNIT_TEST(testSyntax); CPPUNIT_TEST(testASTNode); CPPUNIT_TEST_SUITE_END(); void testSyntax() { TEST_SYNTAX_PASSES(tests); } void testASTNode(); }; CPPUNIT_TEST_SUITE_REGISTRATION(TestCommaOperator); void TestCommaOperator::testASTNode() { for (const auto& test : tests) { const std::string& code = test.first; const Node* expected = test.second.get(); const Tree::ConstPtr tree = parse(code.c_str()); CPPUNIT_ASSERT_MESSAGE(ERROR_MSG("No AST returned", code), static_cast<bool>(tree)); // get the first statement const Node* result = tree->child(0)->child(0); CPPUNIT_ASSERT(result); CPPUNIT_ASSERT_MESSAGE(ERROR_MSG("Invalid AST node", code), Node::CommaOperatorNode == result->nodetype()); std::vector<const Node*> resultList, expectedList; linearize(*result, resultList); linearize(*expected, expectedList); if (!unittest_util::compareLinearTrees(expectedList, resultList)) { std::ostringstream os; os << "\nExpected:\n"; openvdb::ax::ast::print(*expected, true, os); os << "Result:\n"; openvdb::ax::ast::print(*result, true, os); CPPUNIT_FAIL(ERROR_MSG("Mismatching Trees for Comma Operator code", code) + os.str()); } } }
NVIDIA-Omniverse/ext-openvdb/openvdb_ax/openvdb_ax/test/frontend/TestStatementListNode.cc
// Copyright Contributors to the OpenVDB Project // SPDX-License-Identifier: MPL-2.0 #include <openvdb_ax/ast/AST.h> #include <openvdb_ax/ast/Scanners.h> #include <openvdb_ax/ast/PrintTree.h> #include <openvdb_ax/Exceptions.h> #include <openvdb_ax/test/util.h> #include <cppunit/extensions/HelperMacros.h> #include <string> using namespace openvdb::ax::ast; using namespace openvdb::ax::ast::tokens; namespace { static const unittest_util::CodeTests tests = { { "int32 a = (1,2,3), b=1, c=(b=1);", Node::Ptr(new StatementList({ new DeclareLocal(CoreType::INT32, new Local("a"), new CommaOperator({ new Value<int32_t>(1), new Value<int32_t>(2), new Value<int32_t>(3), })), new DeclareLocal(CoreType::INT32, new Local("b"), new Value<int32_t>(1)), new DeclareLocal(CoreType::INT32, new Local("c"), new AssignExpression( new Local("b"), new Value<int32_t>(1))), })) }, { "int32 a, b;", Node::Ptr(new StatementList({ new DeclareLocal(CoreType::INT32, new Local("a")), new DeclareLocal(CoreType::INT32, new Local("b")) })) }, { "int32 a, b = 1;", Node::Ptr(new StatementList({ new DeclareLocal(CoreType::INT32, new Local("a")), new DeclareLocal(CoreType::INT32, new Local("b"), new Value<int32_t>(1)) })) }, { "int32 a, b = 1, c = 1;", Node::Ptr(new StatementList({ new DeclareLocal(CoreType::INT32, new Local("a")), new DeclareLocal(CoreType::INT32, new Local("b"), new Value<int32_t>(1)), new DeclareLocal(CoreType::INT32, new Local("c"), new Value<int32_t>(1)) })) }, { "int32 a, b = 1, c;", Node::Ptr(new StatementList({ new DeclareLocal(CoreType::INT32, new Local("a")), new DeclareLocal(CoreType::INT32, new Local("b"), new Value<int32_t>(1)), new DeclareLocal(CoreType::INT32, new Local("c")) })) }, { "int32 a, b = 1, c, d = 1;", Node::Ptr(new StatementList({ new DeclareLocal(CoreType::INT32, new Local("a")), new DeclareLocal(CoreType::INT32, new Local("b"), new Value<int32_t>(1)), new DeclareLocal(CoreType::INT32, new Local("c")), new DeclareLocal(CoreType::INT32, new Local("d"), new Value<int32_t>(1)) })) } }; } class TestStatementList : public CppUnit::TestCase { public: CPPUNIT_TEST_SUITE(TestStatementList); CPPUNIT_TEST(testSyntax); CPPUNIT_TEST(testASTNode); CPPUNIT_TEST_SUITE_END(); void testSyntax() { TEST_SYNTAX_PASSES(tests); } void testASTNode(); }; CPPUNIT_TEST_SUITE_REGISTRATION(TestStatementList); void TestStatementList::testASTNode() { for (const auto& test : tests) { const std::string& code = test.first; const Node* expected = test.second.get(); const Tree::ConstPtr tree = parse(code.c_str()); CPPUNIT_ASSERT_MESSAGE(ERROR_MSG("No AST returned", code), static_cast<bool>(tree)); // get the first statement const Node* result = tree->child(0)->child(0); CPPUNIT_ASSERT(result); CPPUNIT_ASSERT_MESSAGE(ERROR_MSG("Invalid AST node", code), Node::StatementListNode == result->nodetype()); std::vector<const Node*> resultList, expectedList; linearize(*result, resultList); linearize(*expected, expectedList); if (!unittest_util::compareLinearTrees(expectedList, resultList)) { std::ostringstream os; os << "\nExpected:\n"; openvdb::ax::ast::print(*expected, true, os); os << "Result:\n"; openvdb::ax::ast::print(*result, true, os); CPPUNIT_FAIL(ERROR_MSG("Mismatching Trees for Statement List code", code) + os.str()); } } }
NVIDIA-Omniverse/ext-openvdb/openvdb_ax/openvdb_ax/test/frontend/TestCrementNode.cc
// Copyright Contributors to the OpenVDB Project // SPDX-License-Identifier: MPL-2.0 #include <openvdb_ax/ast/AST.h> #include <openvdb_ax/ast/Scanners.h> #include <openvdb_ax/ast/PrintTree.h> #include <openvdb_ax/Exceptions.h> #include <openvdb_ax/test/util.h> #include <cppunit/extensions/HelperMacros.h> #include <string> using namespace openvdb::ax::ast; using namespace openvdb::ax::ast::tokens; namespace { static const unittest_util::CodeTests tests = { { "a++;", Node::Ptr(new Crement(new Local("a"), Crement::Operation::Increment, /*post*/true)) }, { "++a;", Node::Ptr(new Crement(new Local("a"), Crement::Operation::Increment, /*post*/false)) }, { "a--;", Node::Ptr(new Crement(new Local("a"), Crement::Operation::Decrement, /*post*/true)) }, { "--a;", Node::Ptr(new Crement(new Local("a"), Crement::Operation::Decrement, /*post*/false)) }, { "s@a--;", Node::Ptr(new Crement(new Attribute("a", CoreType::STRING), Crement::Operation::Decrement, /*post*/true)) }, { "f@a++;", Node::Ptr(new Crement(new Attribute("a", CoreType::FLOAT), Crement::Operation::Increment, /*post*/true)) }, { "++f@a;", Node::Ptr(new Crement(new Attribute("a", CoreType::FLOAT), Crement::Operation::Increment, /*post*/false)) }, { "++mat3f@a;", Node::Ptr(new Crement(new Attribute("a", CoreType::MAT3F), Crement::Operation::Increment, /*post*/false)) } }; } class TestCrementNode : public CppUnit::TestCase { public: CPPUNIT_TEST_SUITE(TestCrementNode); CPPUNIT_TEST(testSyntax); CPPUNIT_TEST(testASTNode); CPPUNIT_TEST_SUITE_END(); void testSyntax() { TEST_SYNTAX_PASSES(tests) }; void testASTNode(); }; CPPUNIT_TEST_SUITE_REGISTRATION(TestCrementNode); void TestCrementNode::testASTNode() { for (const auto& test : tests) { const std::string& code = test.first; const Node* expected = test.second.get(); const Tree::ConstPtr tree = parse(code.c_str()); CPPUNIT_ASSERT_MESSAGE(ERROR_MSG("No AST returned", code), static_cast<bool>(tree)); // get the first statement const Node* result = tree->child(0)->child(0); CPPUNIT_ASSERT(result); CPPUNIT_ASSERT_MESSAGE(ERROR_MSG("Invalid AST node", code), Node::CrementNode == result->nodetype()); std::vector<const Node*> resultList, expectedList; linearize(*result, resultList); linearize(*expected, expectedList); if (!unittest_util::compareLinearTrees(expectedList, resultList)) { std::ostringstream os; os << "\nExpected:\n"; openvdb::ax::ast::print(*expected, true, os); os << "Result:\n"; openvdb::ax::ast::print(*result, true, os); CPPUNIT_FAIL(ERROR_MSG("Mismatching Trees for Crement code", code) + os.str()); } } }
NVIDIA-Omniverse/ext-openvdb/openvdb_ax/openvdb_ax/test/frontend/TestArrayUnpackNode.cc
// Copyright Contributors to the OpenVDB Project // SPDX-License-Identifier: MPL-2.0 #include <openvdb_ax/ast/AST.h> #include <openvdb_ax/ast/Scanners.h> #include <openvdb_ax/ast/PrintTree.h> #include <openvdb_ax/Exceptions.h> #include <openvdb_ax/test/util.h> #include <cppunit/extensions/HelperMacros.h> #include <string> using namespace openvdb::ax::ast; using namespace openvdb::ax::ast::tokens; namespace { static const unittest_util::CodeTests tests = { { "a.x;", Node::Ptr(new ArrayUnpack(new Local("a"), new Value<int32_t>(0))) }, { "a.y;", Node::Ptr(new ArrayUnpack(new Local("a"), new Value<int32_t>(1))) }, { "a.z;", Node::Ptr(new ArrayUnpack(new Local("a"), new Value<int32_t>(2))) }, { "a.r;", Node::Ptr(new ArrayUnpack(new Local("a"), new Value<int32_t>(0))) }, { "a.g;", Node::Ptr(new ArrayUnpack(new Local("a"), new Value<int32_t>(1))) }, { "a.b;", Node::Ptr(new ArrayUnpack(new Local("a"), new Value<int32_t>(2))) }, { "x.x;", Node::Ptr(new ArrayUnpack(new Local("x"), new Value<int32_t>(0))) }, { "@x.x;", Node::Ptr(new ArrayUnpack(new Attribute("x", CoreType::FLOAT, true), new Value<int32_t>(0))) }, { "@a.x;", Node::Ptr(new ArrayUnpack(new Attribute("a", CoreType::FLOAT, true), new Value<int32_t>(0))) }, { "@b.y;", Node::Ptr(new ArrayUnpack(new Attribute("b", CoreType::FLOAT, true), new Value<int32_t>(1))) }, { "@c.z;", Node::Ptr(new ArrayUnpack(new Attribute("c", CoreType::FLOAT, true), new Value<int32_t>(2))) }, { "@a.r;", Node::Ptr(new ArrayUnpack(new Attribute("a", CoreType::FLOAT, true), new Value<int32_t>(0))) }, { "@a.g;", Node::Ptr(new ArrayUnpack(new Attribute("a", CoreType::FLOAT, true), new Value<int32_t>(1))) }, { "@a.b;", Node::Ptr(new ArrayUnpack(new Attribute("a", CoreType::FLOAT, true), new Value<int32_t>(2))) }, { "@a[0l];", Node::Ptr(new ArrayUnpack(new Attribute("a", CoreType::FLOAT, true), new Value<int64_t>(0))) }, { "@a[0];", Node::Ptr(new ArrayUnpack(new Attribute("a", CoreType::FLOAT, true), new Value<int32_t>(0))) }, { "@a[1];", Node::Ptr(new ArrayUnpack(new Attribute("a", CoreType::FLOAT, true), new Value<int32_t>(1))) }, { "@a[2];", Node::Ptr(new ArrayUnpack(new Attribute("a", CoreType::FLOAT, true), new Value<int32_t>(2))) }, { "@a[0.0f];", Node::Ptr(new ArrayUnpack(new Attribute("a", CoreType::FLOAT, true), new Value<float>(0.0f))) }, { "@a[0.0];", Node::Ptr(new ArrayUnpack(new Attribute("a", CoreType::FLOAT, true), new Value<double>(0.0))) }, { "@a[\"str\"];", Node::Ptr(new ArrayUnpack(new Attribute("a", CoreType::FLOAT, true), new Value<std::string>("str"))) }, { "@a[true];", Node::Ptr(new ArrayUnpack(new Attribute("a", CoreType::FLOAT, true), new Value<bool>(true))) }, { "@a[false];", Node::Ptr(new ArrayUnpack(new Attribute("a", CoreType::FLOAT, true), new Value<bool>(false))) }, { "@a[a];", Node::Ptr(new ArrayUnpack(new Attribute("a", CoreType::FLOAT, true), new Local("a"))) }, { "@a[0,0];", Node::Ptr(new ArrayUnpack(new Attribute("a", CoreType::FLOAT, true), new Value<int32_t>(0), new Value<int32_t>(0))) }, { "@a[1,0];", Node::Ptr(new ArrayUnpack(new Attribute("a", CoreType::FLOAT, true), new Value<int32_t>(1), new Value<int32_t>(0))) }, { "@a[2,0];", Node::Ptr(new ArrayUnpack(new Attribute("a", CoreType::FLOAT, true), new Value<int32_t>(2), new Value<int32_t>(0))) }, { "a[0,0];", Node::Ptr(new ArrayUnpack(new Local("a"), new Value<int32_t>(0), new Value<int32_t>(0))) }, { "a[1,0];", Node::Ptr(new ArrayUnpack(new Local("a"), new Value<int32_t>(1), new Value<int32_t>(0))) }, { "a[2,0];", Node::Ptr(new ArrayUnpack(new Local("a"), new Value<int32_t>(2), new Value<int32_t>(0))) }, { "@a[a,0];", Node::Ptr(new ArrayUnpack(new Attribute("a", CoreType::FLOAT, true), new Local("a"), new Value<int32_t>(0))) }, { "@a[b,1];", Node::Ptr(new ArrayUnpack(new Attribute("a", CoreType::FLOAT, true), new Local("b"), new Value<int32_t>(1))) }, { "@a[c,2];", Node::Ptr(new ArrayUnpack(new Attribute("a", CoreType::FLOAT, true), new Local("c"), new Value<int32_t>(2))) }, { "@a[a,d];", Node::Ptr(new ArrayUnpack(new Attribute("a", CoreType::FLOAT, true), new Local("a"), new Local("d"))) }, { "@a[b,e];", Node::Ptr(new ArrayUnpack(new Attribute("a", CoreType::FLOAT, true), new Local("b"), new Local("e"))) }, { "@a[c,f];", Node::Ptr(new ArrayUnpack(new Attribute("a", CoreType::FLOAT, true), new Local("c"), new Local("f"))) }, // { "a[(a),1+1];", Node::Ptr(new ArrayUnpack(new Local("a"), new Local("a"), new BinaryOperator(new Value<int32_t>(1), new Value<int32_t>(1), OperatorToken::PLUS))) }, { "a[!0,a=b];", Node::Ptr(new ArrayUnpack(new Local("a"), new UnaryOperator(new Value<int32_t>(0), OperatorToken::NOT), new AssignExpression(new Local("a"), new Local("b")))) }, { "a[test(),$A];", Node::Ptr(new ArrayUnpack(new Local("a"), new FunctionCall("test"), new ExternalVariable("A", CoreType::FLOAT))) }, { "a[a++,++a];", Node::Ptr(new ArrayUnpack(new Local("a"), new Crement(new Local("a"), Crement::Operation::Increment, true), new Crement(new Local("a"), Crement::Operation::Increment, false))) }, { "a[a[0,0],0];", Node::Ptr(new ArrayUnpack(new Local("a"), new ArrayUnpack(new Local("a"), new Value<int32_t>(0), new Value<int32_t>(0)), new Value<int32_t>(0))) }, { "a[(1,2,3)];", Node::Ptr(new ArrayUnpack(new Local("a"), new CommaOperator({ new Value<int32_t>(1), new Value<int32_t>(2), new Value<int32_t>(3) }) )) }, { "a[(1,2,3),(4,5,6)];", Node::Ptr(new ArrayUnpack(new Local("a"), new CommaOperator({ new Value<int32_t>(1), new Value<int32_t>(2), new Value<int32_t>(3), }), new CommaOperator({ new Value<int32_t>(4), new Value<int32_t>(5), new Value<int32_t>(6), }) )) }, { "a[a[0,0],a[0]];", Node::Ptr(new ArrayUnpack(new Local("a"), new ArrayUnpack(new Local("a"), new Value<int32_t>(0), new Value<int32_t>(0)), new ArrayUnpack(new Local("a"), new Value<int32_t>(0)))) } // @todo should this be a syntax error // { "@a[{1,2,3},{1,2,3,4}];", } }; } class TestArrayUnpackNode : public CppUnit::TestCase { public: CPPUNIT_TEST_SUITE(TestArrayUnpackNode); CPPUNIT_TEST(testSyntax); CPPUNIT_TEST(testASTNode); CPPUNIT_TEST_SUITE_END(); void testSyntax() { TEST_SYNTAX_PASSES(tests); } void testASTNode(); }; CPPUNIT_TEST_SUITE_REGISTRATION(TestArrayUnpackNode); void TestArrayUnpackNode::testASTNode() { for (const auto& test : tests) { const std::string& code = test.first; const Node* expected = test.second.get(); const Tree::ConstPtr tree = parse(code.c_str()); CPPUNIT_ASSERT_MESSAGE(ERROR_MSG("No AST returned", code), static_cast<bool>(tree)); // get the first statement const Node* result = tree->child(0)->child(0); CPPUNIT_ASSERT(result); CPPUNIT_ASSERT_MESSAGE(ERROR_MSG("Invalid AST node", code), Node::ArrayUnpackNode == result->nodetype()); std::vector<const Node*> resultList, expectedList; linearize(*result, resultList); linearize(*expected, expectedList); if (!unittest_util::compareLinearTrees(expectedList, resultList)) { std::ostringstream os; os << "\nExpected:\n"; openvdb::ax::ast::print(*expected, true, os); os << "Result:\n"; openvdb::ax::ast::print(*result, true, os); CPPUNIT_FAIL(ERROR_MSG("Mismatching Trees for Array Unpack code", code) + os.str()); } } }
NVIDIA-Omniverse/ext-openvdb/openvdb_ax/openvdb_ax/test/frontend/TestAssignExpressionNode.cc
// Copyright Contributors to the OpenVDB Project // SPDX-License-Identifier: MPL-2.0 #include <openvdb_ax/ast/AST.h> #include <openvdb_ax/ast/Scanners.h> #include <openvdb_ax/ast/PrintTree.h> #include <openvdb_ax/Exceptions.h> #include <openvdb_ax/test/util.h> #include <cppunit/extensions/HelperMacros.h> #include <string> using namespace openvdb::ax::ast; using namespace openvdb::ax::ast::tokens; namespace { unittest_util::CodeTests tests = { // test an attribute type passes for all expression types { "@a = (true);", Node::Ptr(new AssignExpression(new Attribute("a", CoreType::FLOAT, true), new Value<bool>(true))) }, { "@a = (1,2,3);", Node::Ptr(new AssignExpression( new Attribute("a", CoreType::FLOAT, true), new CommaOperator({ new Value<int32_t>(1), new Value<int32_t>(2), new Value<int32_t>(3), }) )) }, { "@a = test();", Node::Ptr(new AssignExpression(new Attribute("a", CoreType::FLOAT, true), new FunctionCall("test"))) }, { "@a = 1 + i@b;", Node::Ptr(new AssignExpression( new Attribute("a", CoreType::FLOAT, true), new BinaryOperator(new Value<int32_t>(1), new Attribute("b", CoreType::INT32), OperatorToken::PLUS) )) }, { "@a = -int@b;", Node::Ptr(new AssignExpression( new Attribute("a", CoreType::FLOAT, true), new UnaryOperator(new Attribute("b", CoreType::INT32), OperatorToken::MINUS) )) }, { "@a = ++float@b;", Node::Ptr(new AssignExpression( new Attribute("a", CoreType::FLOAT, true), new Crement(new Attribute("b", CoreType::FLOAT), Crement::Operation::Increment, false) )) }, { "@a = bool(2);", Node::Ptr(new AssignExpression( new Attribute("a", CoreType::FLOAT, true), new Cast(new Value<int32_t>(2), CoreType::BOOL) )) }, { "@a = {1, 2, 3};", Node::Ptr(new AssignExpression( new Attribute("a", CoreType::FLOAT, true), new ArrayPack({ new Value<int32_t>(1), new Value<int32_t>(2), new Value<int32_t>(3) }) )) }, { "@a = [email protected];", Node::Ptr(new AssignExpression( new Attribute("a", CoreType::FLOAT, true), new ArrayUnpack(new Attribute("b", CoreType::VEC3F), new Value<int32_t>(0)) )) }, { "@a = \"b\";", Node::Ptr(new AssignExpression(new Attribute("a", CoreType::FLOAT, true), new Value<std::string>("b"))) }, { "@a = b;", Node::Ptr(new AssignExpression(new Attribute("a", CoreType::FLOAT, true), new Local("b"))) }, // test all attribute { "bool@a = true;", Node::Ptr(new AssignExpression(new Attribute("a", CoreType::BOOL), new Value<bool>(true))) }, { "int16@a = true;", Node::Ptr(new AssignExpression(new Attribute("a", CoreType::INT16), new Value<bool>(true))) }, { "i@a = true;", Node::Ptr(new AssignExpression(new Attribute("a", CoreType::INT32), new Value<bool>(true))) }, { "int@a = true;", Node::Ptr(new AssignExpression(new Attribute("a", CoreType::INT32), new Value<bool>(true))) }, { "int32@a = true;", Node::Ptr(new AssignExpression(new Attribute("a", CoreType::INT32), new Value<bool>(true))) }, { "int64@a = true;", Node::Ptr(new AssignExpression(new Attribute("a", CoreType::INT64), new Value<bool>(true))) }, { "f@a = true;", Node::Ptr(new AssignExpression(new Attribute("a", CoreType::FLOAT), new Value<bool>(true))) }, { "float@a = true;", Node::Ptr(new AssignExpression(new Attribute("a", CoreType::FLOAT), new Value<bool>(true))) }, { "double@a = true;", Node::Ptr(new AssignExpression(new Attribute("a", CoreType::DOUBLE), new Value<bool>(true))) }, { "vec3i@a = true;", Node::Ptr(new AssignExpression(new Attribute("a", CoreType::VEC3I), new Value<bool>(true))) }, { "v@a = true;", Node::Ptr(new AssignExpression(new Attribute("a", CoreType::VEC3F), new Value<bool>(true))) }, { "vec3f@a = true;", Node::Ptr(new AssignExpression(new Attribute("a", CoreType::VEC3F), new Value<bool>(true))) }, { "vec3d@a = true;", Node::Ptr(new AssignExpression(new Attribute("a", CoreType::VEC3D), new Value<bool>(true))) }, { "s@a = true;", Node::Ptr(new AssignExpression(new Attribute("a", CoreType::STRING), new Value<bool>(true))) }, { "string@a = true;", Node::Ptr(new AssignExpression(new Attribute("a", CoreType::STRING), new Value<bool>(true))) }, // compound assignments (operation is stored implicitly) { "@a += true;", Node::Ptr(new AssignExpression( new Attribute("a", CoreType::FLOAT, true), new Value<bool>(true), OperatorToken::PLUS )) }, { "@a -= true;", Node::Ptr(new AssignExpression( new Attribute("a", CoreType::FLOAT, true), new Value<bool>(true), OperatorToken::MINUS )) }, { "@a *= true;", Node::Ptr(new AssignExpression( new Attribute("a", CoreType::FLOAT, true), new Value<bool>(true), OperatorToken::MULTIPLY )) }, { "@a /= true;", Node::Ptr(new AssignExpression( new Attribute("a", CoreType::FLOAT, true), new Value<bool>(true), OperatorToken::DIVIDE )) }, { "@a &= true;", Node::Ptr(new AssignExpression( new Attribute("a", CoreType::FLOAT, true), new Value<bool>(true), OperatorToken::BITAND )) }, { "@a |= true;", Node::Ptr(new AssignExpression( new Attribute("a", CoreType::FLOAT, true), new Value<bool>(true), OperatorToken::BITOR )) }, { "@a ^= true;", Node::Ptr(new AssignExpression( new Attribute("a", CoreType::FLOAT, true), new Value<bool>(true), OperatorToken::BITXOR )) }, { "@a %= true;", Node::Ptr(new AssignExpression( new Attribute("a", CoreType::FLOAT, true), new Value<bool>(true), OperatorToken::MODULO )) }, { "@a <<= true;", Node::Ptr(new AssignExpression( new Attribute("a", CoreType::FLOAT, true), new Value<bool>(true), OperatorToken::SHIFTLEFT )) }, { "@a >>= true;", Node::Ptr(new AssignExpression( new Attribute("a", CoreType::FLOAT, true), new Value<bool>(true), OperatorToken::SHIFTRIGHT )) }, // test component assignment { "[email protected] = true;", Node::Ptr(new AssignExpression( new ArrayUnpack( new Attribute("a", CoreType::VEC3I), new Value<int32_t>(0) ), new Value<bool>(true) )) }, { "vec3i@a[1] = true;", Node::Ptr(new AssignExpression( new ArrayUnpack( new Attribute("a", CoreType::VEC3I), new Value<int32_t>(1) ), new Value<bool>(true) )) }, { "[email protected] = true;", Node::Ptr(new AssignExpression( new ArrayUnpack( new Attribute("a", CoreType::VEC3I), new Value<int32_t>(2) ), new Value<bool>(true) )) }, { "[email protected] += true;", Node::Ptr(new AssignExpression( new ArrayUnpack( new Attribute("a", CoreType::VEC3I), new Value<int32_t>(0) ), new Value<bool>(true), OperatorToken::PLUS )) }, // test other lhs { "a = true;", Node::Ptr(new AssignExpression(new Local("a"), new Value<bool>(true))) }, { "++a = true;", Node::Ptr(new AssignExpression( new Crement(new Local("a"), Crement::Operation::Increment, false), new Value<bool>(true) )) }, { "++@a = true;", Node::Ptr(new AssignExpression( new Crement(new Attribute("a", CoreType::FLOAT, true), Crement::Operation::Increment, false), new Value<bool>(true) )) }, // chains { "@a = @b += 1;", Node::Ptr(new AssignExpression( new Attribute("a", CoreType::FLOAT, true), new AssignExpression( new Attribute("b", CoreType::FLOAT, true), new Value<int32_t>(1), OperatorToken::PLUS) )) }, { "@a = [email protected] = 1;", Node::Ptr(new AssignExpression( new Attribute("a", CoreType::FLOAT, true), new AssignExpression( new ArrayUnpack(new Attribute("b", CoreType::VEC3F), new Value<int32_t>(0)), new Value<int32_t>(1) ) )) }, { "@a += [email protected] = x %= 1;", Node::Ptr(new AssignExpression( new Attribute("a", CoreType::FLOAT, true), new AssignExpression( new ArrayUnpack(new Attribute("b", CoreType::VEC3F), new Value<int32_t>(0)), new AssignExpression( new Local("x"), new Value<int32_t>(1), OperatorToken::MODULO ) ), OperatorToken::PLUS )) } }; } class TestAssignExpressionNode : public CppUnit::TestCase { public: CPPUNIT_TEST_SUITE(TestAssignExpressionNode); CPPUNIT_TEST(testSyntax); CPPUNIT_TEST(testASTNode); CPPUNIT_TEST_SUITE_END(); void testSyntax() { TEST_SYNTAX_PASSES(tests); } void testASTNode(); }; CPPUNIT_TEST_SUITE_REGISTRATION(TestAssignExpressionNode); void TestAssignExpressionNode::testASTNode() { for (const auto& test : tests) { const std::string& code = test.first; const Node* expected = test.second.get(); const Tree::ConstPtr tree = parse(code.c_str()); CPPUNIT_ASSERT_MESSAGE(ERROR_MSG("No AST returned", code), static_cast<bool>(tree)); // get the first statement const Node* result = tree->child(0)->child(0); CPPUNIT_ASSERT(result); CPPUNIT_ASSERT_MESSAGE(ERROR_MSG("Invalid AST node", code), Node::AssignExpressionNode == result->nodetype()); std::vector<const Node*> resultList, expectedList; linearize(*result, resultList); linearize(*expected, expectedList); if (!unittest_util::compareLinearTrees(expectedList, resultList)) { std::ostringstream os; os << "\nExpected:\n"; openvdb::ax::ast::print(*expected, true, os); os << "Result:\n"; openvdb::ax::ast::print(*result, true, os); CPPUNIT_FAIL(ERROR_MSG("Mismatching Trees for Assign Expression code", code) + os.str()); } } }
NVIDIA-Omniverse/ext-openvdb/openvdb_ax/openvdb_ax/test/frontend/TestFunctionCallNode.cc
// Copyright Contributors to the OpenVDB Project // SPDX-License-Identifier: MPL-2.0 #include <openvdb_ax/ast/AST.h> #include <openvdb_ax/ast/Scanners.h> #include <openvdb_ax/ast/PrintTree.h> #include <openvdb_ax/Exceptions.h> #include <openvdb_ax/test/util.h> #include <cppunit/extensions/HelperMacros.h> #include <string> using namespace openvdb::ax::ast; using namespace openvdb::ax::ast::tokens; namespace { static const unittest_util::CodeTests tests = { { "func();", Node::Ptr(new FunctionCall("func")) }, { "_();", Node::Ptr(new FunctionCall("_")) }, { "_1();", Node::Ptr(new FunctionCall("_1")) }, { "a_();", Node::Ptr(new FunctionCall("a_")) }, { "_a();", Node::Ptr(new FunctionCall("_a")) }, { "A();", Node::Ptr(new FunctionCall("A")) }, { "D1f();", Node::Ptr(new FunctionCall("D1f")) }, { "f(a);", Node::Ptr(new FunctionCall("f", new Local("a"))) }, { "a(a,1);", Node::Ptr(new FunctionCall("a", { new Local("a"), new Value<int32_t>(1) })) }, { "func(1);", Node::Ptr(new FunctionCall("func", new Value<int32_t>(1) )) }, { "func(\"string\");", Node::Ptr(new FunctionCall("func", new Value<std::string>("string") )) }, { "func(true);", Node::Ptr(new FunctionCall("func", new Value<bool>(true) )) }, { "func({a,b,c});", Node::Ptr(new FunctionCall("func", new ArrayPack({ new Local("a"), new Local("b"), new Local("c") }) )) }, { "func((a,b,c));", Node::Ptr(new FunctionCall("func", new CommaOperator({ new Local("a"), new Local("b"), new Local("c") }) )) }, { "func(@a);", Node::Ptr(new FunctionCall("func", new Attribute("a", CoreType::FLOAT, true) )) }, { "func(++a);", Node::Ptr(new FunctionCall("func", new Crement(new Local("a"), Crement::Operation::Increment, false) )) }, { "func(~a);", Node::Ptr(new FunctionCall("func", new UnaryOperator(new Local("a"), OperatorToken::BITNOT) )) }, { "func((a));", Node::Ptr(new FunctionCall("func", new Local("a") )) }, { "func1(func2());", Node::Ptr(new FunctionCall("func1", new FunctionCall("func2") )) }, { "func(a=b);", Node::Ptr(new FunctionCall("func", new AssignExpression(new Local("a"), new Local("b")) )) }, { "func(a==b);", Node::Ptr(new FunctionCall("func", new BinaryOperator(new Local("a"), new Local("b"), OperatorToken::EQUALSEQUALS) )) }, { "func(a.x);", Node::Ptr(new FunctionCall("func", new ArrayUnpack(new Local("a"), new Value<int32_t>(0)) )) }, { "func(bool(a));", Node::Ptr(new FunctionCall("func", new Cast(new Local("a"), CoreType::BOOL) )) }, { "func(a,b,c,d,e,f);", Node::Ptr(new FunctionCall("func", { new Local("a"), new Local("b"), new Local("c"), new Local("d"), new Local("e"), new Local("f") } )) }, { "func((a, b), c);", Node::Ptr(new FunctionCall("func", { new CommaOperator({ new Local("a"), new Local("b") }), new Local("c") })) } }; } class TestFunctionCallNode : public CppUnit::TestCase { public: CPPUNIT_TEST_SUITE(TestFunctionCallNode); CPPUNIT_TEST(testSyntax); CPPUNIT_TEST(testASTNode); CPPUNIT_TEST_SUITE_END(); void testSyntax() { TEST_SYNTAX_PASSES(tests); } void testASTNode(); }; CPPUNIT_TEST_SUITE_REGISTRATION(TestFunctionCallNode); void TestFunctionCallNode::testASTNode() { for (const auto& test : tests) { const std::string& code = test.first; const Node* expected = test.second.get(); const Tree::ConstPtr tree = parse(code.c_str()); CPPUNIT_ASSERT_MESSAGE(ERROR_MSG("No AST returned", code), static_cast<bool>(tree)); // get the first statement const Node* result = tree->child(0)->child(0); CPPUNIT_ASSERT(result); CPPUNIT_ASSERT_MESSAGE(ERROR_MSG("Invalid AST node", code), Node::FunctionCallNode == result->nodetype()); std::vector<const Node*> resultList, expectedList; linearize(*result, resultList); linearize(*expected, expectedList); if (!unittest_util::compareLinearTrees(expectedList, resultList)) { std::ostringstream os; os << "\nExpected:\n"; openvdb::ax::ast::print(*expected, true, os); os << "Result:\n"; openvdb::ax::ast::print(*result, true, os); CPPUNIT_FAIL(ERROR_MSG("Mismatching Trees for Function Call code", code) + os.str()); } } }
NVIDIA-Omniverse/ext-openvdb/openvdb_ax/openvdb_ax/test/frontend/TestSyntaxFailures.cc
// Copyright Contributors to the OpenVDB Project // SPDX-License-Identifier: MPL-2.0 #include "test/util.h" #include <openvdb_ax/compiler/Compiler.h> #include <openvdb_ax/Exceptions.h> #include <string> #include <vector> #include <unordered_map> #include <functional> #include <cppunit/extensions/HelperMacros.h> namespace { // mimics std::pair<std::string, null> struct StrWrapper { StrWrapper(const char* str) : first(str) {} const std::string first; }; static const std::vector<StrWrapper> tests { // invalid r-value syntax "@a = @;", "@a = =;", "@a = +;", "@a = -;", "@a = *;", "@a = /;", "@a = %;", "@a = |;", "@a = &;", "@a = ^;", "@a = ~;", "@a = ==;", "@a = !=;", "@a = >;", "@a = <;", "@a = >=;", "@a = <=;", "@a = +=;", "@a = -=;", "@a = *=;", "@a = /=;", "@a = ++;", "@a = --;", "@a = &&;", "@a = ||;", "@a = !;", "@a = ,;", "@a = (;", "@a = );", "@a = {;", "@a =};", "@a = .x;", "@a = .y;", "@a = .z;", "@a = .r;", "@a = .g;", "@a = .b;", "@a = f@;", "@a = i@;", "@a = v@;", "@a = s@;", "@a = if;", "@a = else;", "@a = return;", "@a = ;", "@a = {};", "@a = \"a;", "[email protected] = 0;", "$a = $;", "$a = =;", "$a = +;", "$a = -;", "$a = *;", "$a = /;", "$a = %;", "$a = |;", "$a = &;", "$a = ^;", "$a = ~;", "$a = ==;", "$a = !=;", "$a = >;", "$a = <;", "$a = >=;", "$a = <=;", "$a = +=;", "$a = -=;", "$a = *=;", "$a = /=;", "$a = ++;", "$a = --;", "$a = &&;", "$a = ||;", "$a = !;", "$a = ,;", "$a = (;", "$a = );", "$a = {;", "$a =};", "$a = .x;", "$a = .y;", "$a = .z;", "$a = .r;", "$a = .g;", "$a = .b;", "$a = f$;", "$a = i$;", "$a = v$;", "$a = s$;", "$a = if;", "$a = else;", "$a = return;", "$a = ;", "$a = {};", "$a = {1};", "$a = \"a;", "v$a[0] = 0;", "v$a.a = 0;", // @todo these should probably be valid syntax and the code // generators should handle assignments based on the current // r/lvalues "5 = 5;", "$a = 5;", // invalid l-value // TODO: these should fail syntax tests // {"+@a = 0;", }, // {"-@a = 0;", }, // {"~@a = 0;", }, // {"!@a = 0;", }, // "++@a = 0;", // "--@a = 0;", "=@a;", "*@a;", "/@a;", "%@a;", "|@a;", "&@a;", "^@a;", "==@a;", "!=@a;", ">@a;", "<@a;", ">=@a;", "<=@a;", "+=@a;", "-=@a;", "*=@a;", "/=@a;", "&&@a;", "||@a;", ",@a;", "(@a;", ")@a;", "{@a;", "}@a;", ".x@a;", ".y@a;", ".z@a;", ".r@a;", ".g@a;", ".b@a;", "@@a;", "f@@a;", "i@@a;", "v@@a;", "s@@a;", "if@a;", "else@a;", "return@a;", "{1}@a;", "\"a\"@a;", "b@a;", "sht@a;", "it@a;", "l@a;", "flt@a;", "dbl@a;", "vecint@a;", "vint@a;", "vfloat@a;", "vecflt@a;", "vflt@a;", "vdouble@a;", "vecdbl@a;", "vdbl@a;", "str@a;", "++$a = 0;", "--$a = 0;", "=$a;", "*$a;", "/$a;", "%$a;", "|$a;", "&$a;", "^$a;", "==$a;", "!=$a;", ">$a;", "<$a;", ">=$a;", "<=$a;", "+=$a;", "-=$a;", "*=$a;", "/=$a;", "&&$a;", "||$a;", ",$a;", "($a;", ")$a;", "{$a;", "}$a;", ".x$a;", ".y$a;", ".z$a;", ".r$a;", ".g$a;", ".b$a;", "$$a;", "f$$a;", "i$$a;", "v$$a;", "s$$a;", "if$a;", "else$a;", "return$a;", "{1}$a;", "\"a\"$a;", "b$a;", "sht$a;", "it$a;", "l$a;", "flt$a;", "dbl$a;", "vecint$a;", "vint$a;", "vfloat$a;", "vecflt$a;", "vflt$a;", "vdouble$a;", "vecdbl$a;", "vdbl$a;", "str$a;", "a ! a;", "a ~ a;", "a \\ a;", "a ? a;", "bool + a;", "bool a + a;", "return + a;", "if + a;", "a + if(true) {};", "{} + {};", "~ + !;", "+ + -;", "; + ;", "int();", "int(return);", "int(if(true) {});", "int(;);", "int(bool a;);", "int(bool a);", "int{a};", "int[a];", "string(a);", "vector(a);", "vec3i(a);", "vec3f(a);", "vec3d(a);", // invalid if block "if (a) {b}", "if (a) else ();", "if (); else (a);", "if (a) if(b) {if (c)} else {}", "if (if(a));", "if ();", "if (); else ;", "if (); else ();", "if (); else () {}", "if (); elf {}", "if (a) {} elif (b) {}", "else {}", "else ;", "if a;", "if a {} elif b {}", "if (a); else ; else ;", "else (a); ", "if (a) {}; else {};", "if (a) {b = 1} else {};", "if (a) {} ; else {}", "if () {}; else (a);", // invalid ternary "?;", ":;", "? :;", "? : false;", "true ? :;", "true ? false;", "true ? false :;", "true : 1 ? 2;", "true ? 1 ? 2;", "true : 1 : 2;", "true ?? 1 : 2;", "true (? 1 :) 2;", "true (?:) 2;", "true (? false ? 1 : 2): 3;", "true ? (false ? 1 : 2:) 3;", "(true ? false ? 1 : 2): 3;", // invalid crement "++5;", "5++;", "--5;", "5--;", "++5--;", "++5++;", "--5++;", "--5--;", "{ 1, 1, 1}++;", "++{ 1, 1, 1};", "--{ 1, 1, 1};", "{ 1, 1, 1}--;", "++{ 1, 1, 1}++;", "++{ 1, 1, 1}--;", "--{ 1, 1, 1}--;", "++a-;", //"++a--;", //"++a++;", //"--a++;", //"--a--;", //"----a;", //"++++a;", //"a.x--;", //"-a.y--;", //"++a.z;", //"++@a--;", //"@a.x--;", //"[email protected];", //"[email protected];", "++$a--;", "$a.x--;", "-$a.y--;", "++$a.z;", "--f();", "f()++;", "return++;", "--return;", "true++;", "--false;", "--if;", "if++;", "else++;", "--else;", "--bool;", "short++;", "--int;", "long++;", "--float;", "++double;", "--vector;", "matrix--;", "--();", "()++;", "{}++;", "--{};", "--,;", ",--;", // invalid declare "int;", "int 1;", "string int;", "int bool a;", "int a", "vector a", "vector float a", // invalid function "function(;", "function);", "return();", "function(bool);", "function(bool a);", "function(+);", "function(!);", "function(~);", "function(-);", "function(&&);", "function{};" , "function(,);" , "function(, a);", "function(a, );", "function({,});", "function({});", "function({)};", "function{()};", "function{(});", "function{,};", "function(if(true) {});", "function(return);", "function(return;);", "function(while(true) a);", "function(while(true) {});", "\"function\"();" , "();", "+();", "10();", // invalid keyword return "return", "int return;", "return return;", "return max(1, 2);", "return 1 + a;", "return !a;", "return a = 1;", "return a.x = 1;", "return ++a;", "return int(a);", "return {1, 2, 3};", "return a[1];", "return true;", "return 0;", "return (1);", "return \"a\";", "return int a;", "return a;", "return @a;", // invalid unary "+bool;" , "+bool a;" , "bool -a;" , "-return;" , "!return;" , "+return;" , "~return;" , "~if(a) {};" , "if(a) -{};" , "if(a) {} !else {};", // @todo unary crementation expressions should be parsable but perhaps // not compilable "---a;" , "+++a;" , // invalid value ".0.0;", ".0.0f;", ".f;", "0..0;", "0.0l;", "0.0ls;", "0.0s;", "0.0sf;", "0.a", "0.af", "00ls;", "0ef;", "0f0;", "1.0f.0;", "1.\"1\";", "1.e6f;", "10000000.00000001s;", "1e.6f;", "1Ee6;", "1ee6;", "1eE6f;", "1ee6f;", "1l.0;", "1s.0;", "\"1.\"2;", "a.0", "a.0f", "false.0;", "true.;", // invalid vector "{1,2,3];", "[1,2,3};", "{,,};", "{,2,3};", "{()};", "{(1,)};", "{(,1)};", "{(1});", "({1)};", "{1,};", "{,1};", // invalid vector unpack "5.x;", "foo.2;", "a.w;", "a.X;", "a.Y;", "a.Z;", "@a.X;", "@a.Y;", "@a.Z;", "$a.X;", "$a.Y;", "$a.Z;", "a.xx;", "a++.x", "++a.x", "func().x", "int(y).x", "vector .", "vector .x", "vector foo.x", "(a + b).x", "(a).x;", "(@a).x;", "@.x;", "($a).x;", "$.x;", "true.x;", "a.rx;", "a.rgb;", // other failures (which may be used in the future) "function<>();", "function<true>();", "a[1:1];", "a.a;", "a->a;", "&a;", "a . a;", "a .* a;", "@a();", "$a();", "@a.function();", "@a.member;", "/**/;", "(a,a,a) = (b,b,b);", "(a,a,a) = 1;", "(a) = 1;", "a = (a=a) = a;", // invalid lone characters "£;", "`;", "¬;", "@;", "~;", "+;", "-;", "*;", "/;", "<<;", ">>;", ">;", "<;", "[];", "|;", ",;", "!;", "\\;" }; } class TestSyntaxFailures : public CppUnit::TestCase { public: CPPUNIT_TEST_SUITE(TestSyntaxFailures); CPPUNIT_TEST(testSyntax); CPPUNIT_TEST_SUITE_END(); void testSyntax(); }; CPPUNIT_TEST_SUITE_REGISTRATION(TestSyntaxFailures); void TestSyntaxFailures::testSyntax() { // Quickly check the above doesn't have multiple occurance // store multiple in a hash map const auto hash = [](const StrWrapper* s) { return std::hash<std::string>()(s->first); }; const auto equal = [](const StrWrapper* s1, const StrWrapper* s2) { return s1->first.compare(s2->first) == 0; }; std::unordered_map<const StrWrapper*, size_t, decltype(hash), decltype(equal)> map(tests.size(), hash, equal); for (const auto& test : tests) { ++map[&test]; } // Print strings that occur more than once for (auto iter : map) { if (iter.second > 1) { std::cout << iter.first->first << " printed x" << iter.second << std::endl; } } TEST_SYNTAX_FAILS(tests); }
NVIDIA-Omniverse/ext-openvdb/openvdb_ax/openvdb_ax/test/frontend/TestTernaryOperatorNode.cc
// Copyright Contributors to the OpenVDB Project // SPDX-License-Identifier: MPL-2.0 #include <openvdb_ax/ast/AST.h> #include <openvdb_ax/ast/Scanners.h> #include <openvdb_ax/ast/PrintTree.h> #include <openvdb_ax/Exceptions.h> #include <openvdb_ax/test/util.h> #include <cppunit/extensions/HelperMacros.h> #include <string> using namespace openvdb::ax::ast; using namespace openvdb::ax::ast::tokens; namespace { static const unittest_util::CodeTests tests = { { "true ? 1 : 0;", Node::Ptr(new TernaryOperator(new Value<bool>(true), new Value<int32_t>(1), new Value<int32_t>(0)))}, { "true ? a : 1.5f;", Node::Ptr(new TernaryOperator(new Value<bool>(true), new Local("a"), new Value<float>(1.5f)))}, { "false ? true : false;", Node::Ptr(new TernaryOperator(new Value<bool>(false), new Value<bool>(true), new Value<bool>(false)))}, { "a == b ? 1 : 0;", Node::Ptr(new TernaryOperator( new BinaryOperator( new Local("a"), new Local("b"), OperatorToken::EQUALSEQUALS), new Value<int32_t>(1), new Value<int32_t>(0)))}, { "a++ ? 1 : 0;", Node::Ptr(new TernaryOperator( new Crement(new Local("a"), Crement::Operation::Increment, true), new Value<int32_t>(1), new Value<int32_t>(0)))}, { "@a ? 1 : 0;", Node::Ptr(new TernaryOperator(new Attribute("a", CoreType::FLOAT, true), new Value<int32_t>(1), new Value<int32_t>(0)))}, { "func() ? 1 : 0;", Node::Ptr(new TernaryOperator(new FunctionCall("func"), new Value<int32_t>(1), new Value<int32_t>(0)))}, { "(true) ? 1 : 0;", Node::Ptr(new TernaryOperator(new Value<bool>(true), new Value<int32_t>(1), new Value<int32_t>(0)))}, { "true ? 3 : 2 ? 1 : 0;", Node::Ptr(new TernaryOperator( new Value<bool>(true), new Value<int32_t>(3), new TernaryOperator(new Value<int32_t>(2), new Value<int32_t>(1), new Value<int32_t>(0))))}, { "(true ? 3 : 2) ? 1 : 0;", Node::Ptr(new TernaryOperator( new TernaryOperator(new Value<bool>(true), new Value<int32_t>(3), new Value<int32_t>(2)), new Value<int32_t>(1), new Value<int32_t>(0)))}, { "true ? \"foo\" : \"bar\";", Node::Ptr(new TernaryOperator(new Value<bool>(true), new Value<std::string>("foo"), new Value<std::string>("bar")))}, { "true ? voidfunc1() : voidfunc2();", Node::Ptr(new TernaryOperator(new Value<bool>(true), new FunctionCall("voidfunc1"), new FunctionCall("voidfunc2")))}, { "true ? {1,1,1} : {0,0,0};", Node::Ptr(new TernaryOperator( new Value<bool>(true), new ArrayPack({ new Value<int32_t>(1), new Value<int32_t>(1), new Value<int32_t>(1) }) , new ArrayPack({ new Value<int32_t>(0), new Value<int32_t>(0), new Value<int32_t>(0) }) ))}, { "true ? false ? 3 : 2 : 1;" , Node::Ptr(new TernaryOperator( new Value<bool>(true), new TernaryOperator( new Value<bool>(false), new Value<int32_t>(3), new Value<int32_t>(2)), new Value<int32_t>(1)))}, { "true ? false ? 3 : 2 : (true ? 4 : 5);" , Node::Ptr(new TernaryOperator( new Value<bool>(true), new TernaryOperator( new Value<bool>(false), new Value<int32_t>(3), new Value<int32_t>(2)), new TernaryOperator( new Value<bool>(true), new Value<int32_t>(4), new Value<int32_t>(5))))}, { "true ? : 0;", Node::Ptr(new TernaryOperator(new Value<bool>(true), nullptr, new Value<int32_t>(0)))}, }; } class TestTernaryOperatorNode : public CppUnit::TestCase { public: CPPUNIT_TEST_SUITE(TestTernaryOperatorNode); CPPUNIT_TEST(testSyntax); CPPUNIT_TEST(testASTNode); CPPUNIT_TEST_SUITE_END(); void testSyntax() { TEST_SYNTAX_PASSES(tests); } void testASTNode(); }; CPPUNIT_TEST_SUITE_REGISTRATION(TestTernaryOperatorNode); void TestTernaryOperatorNode::testASTNode() { for (const auto& test : tests) { const std::string& code = test.first; const Node* expected = test.second.get(); const Tree::ConstPtr tree = parse(code.c_str()); CPPUNIT_ASSERT_MESSAGE(ERROR_MSG("No AST returned", code), static_cast<bool>(tree)); // get the first statement const Node* result = tree->child(0)->child(0); CPPUNIT_ASSERT(result); CPPUNIT_ASSERT_MESSAGE(ERROR_MSG("Invalid AST node", code), Node::TernaryOperatorNode == result->nodetype()); std::vector<const Node*> resultList, expectedList; linearize(*result, resultList); linearize(*expected, expectedList); if (!unittest_util::compareLinearTrees(expectedList, resultList)) { std::ostringstream os; os << "\nExpected:\n"; openvdb::ax::ast::print(*expected, true, os); os << "Result:\n"; openvdb::ax::ast::print(*result, true, os); CPPUNIT_FAIL(ERROR_MSG("Mismatching Trees for Ternary Operator code", code) + os.str()); } } }
NVIDIA-Omniverse/ext-openvdb/openvdb_ax/openvdb_ax/test/frontend/TestLoopNode.cc
// Copyright Contributors to the OpenVDB Project // SPDX-License-Identifier: MPL-2.0 #include <openvdb_ax/ast/AST.h> #include <openvdb_ax/ast/Scanners.h> #include <openvdb_ax/ast/PrintTree.h> #include <openvdb_ax/Exceptions.h> #include <openvdb_ax/test/util.h> #include <cppunit/extensions/HelperMacros.h> #include <string> using namespace openvdb::ax::ast; using namespace openvdb::ax::ast::tokens; namespace { static const unittest_util::CodeTests tests = { { "for (int32 i = 0; i < 10; ++i) {}", Node::Ptr(new Loop(tokens::LoopToken::FOR, new BinaryOperator(new Local("i"), new Value<int32_t>(10), OperatorToken::LESSTHAN), new Block(), new DeclareLocal(CoreType::INT32, new Local("i"), new Value<int32_t>(0)), new Crement(new Local("i"), Crement::Operation::Increment, /*post*/false))) }, { "for(int32 i = 0; i < 10; ++i) {}", Node::Ptr(new Loop(tokens::LoopToken::FOR, new BinaryOperator(new Local("i"), new Value<int32_t>(10), OperatorToken::LESSTHAN), new Block(), new DeclareLocal(CoreType::INT32, new Local("i"), new Value<int32_t>(0)), new Crement(new Local("i"), Crement::Operation::Increment, /*post*/false))) }, { "for (int32 i = 0;i < 10;++i) ;", Node::Ptr(new Loop(tokens::LoopToken::FOR, new BinaryOperator(new Local("i"), new Value<int32_t>(10), OperatorToken::LESSTHAN), new Block(), new DeclareLocal(CoreType::INT32, new Local("i"), new Value<int32_t>(0)), new Crement(new Local("i"), Crement::Operation::Increment, /*post*/false))) }, { "for (i; i < 10; ++i) {}", Node::Ptr(new Loop(tokens::LoopToken::FOR, new BinaryOperator(new Local("i"), new Value<int32_t>(10), OperatorToken::LESSTHAN), new Block(), new Local("i"), new Crement(new Local("i"), Crement::Operation::Increment, false))) }, { "for (@i; i < 10; ++i) {}", Node::Ptr(new Loop(tokens::LoopToken::FOR, new BinaryOperator(new Local("i"), new Value<int32_t>(10), OperatorToken::LESSTHAN), new Block(), new Attribute("i", CoreType::FLOAT, true), new Crement(new Local("i"), Crement::Operation::Increment, false))) }, { "for (!i; i < 10; ++i) {}", Node::Ptr(new Loop(tokens::LoopToken::FOR, new BinaryOperator(new Local("i"), new Value<int32_t>(10), OperatorToken::LESSTHAN), new Block(), new UnaryOperator(new Local("i"), OperatorToken::NOT), new Crement(new Local("i"), Crement::Operation::Increment, false))) }, { "for (i = 0; i < 10; ++i) {}", Node::Ptr(new Loop(tokens::LoopToken::FOR, new BinaryOperator(new Local("i"), new Value<int32_t>(10), OperatorToken::LESSTHAN), new Block(), new AssignExpression(new Local("i"), new Value<int32_t>(0)), new Crement(new Local("i"), Crement::Operation::Increment, false))) }, { "for (i+j; i < 10; ++i) {}", Node::Ptr(new Loop(tokens::LoopToken::FOR, new BinaryOperator(new Local("i"), new Value<int32_t>(10), OperatorToken::LESSTHAN), new Block(), new BinaryOperator(new Local("i"), new Local("j"), OperatorToken::PLUS), new Crement(new Local("i"), Crement::Operation::Increment, false))) }, { "for (func(i); i < 10; ++i) {}", Node::Ptr(new Loop(tokens::LoopToken::FOR, new BinaryOperator(new Local("i"), new Value<int32_t>(10), OperatorToken::LESSTHAN), new Block(), new FunctionCall("func", new Local("i")), new Crement(new Local("i"), Crement::Operation::Increment, false))) }, { "for (1; i < 10; ++i) {}", Node::Ptr(new Loop(tokens::LoopToken::FOR, new BinaryOperator(new Local("i"), new Value<int32_t>(10), OperatorToken::LESSTHAN), new Block(), new Value<int32_t>(1), new Crement(new Local("i"), Crement::Operation::Increment, false))) }, { "for (float$ext; i < 10; ++i) {}", Node::Ptr(new Loop(tokens::LoopToken::FOR, new BinaryOperator(new Local("i"), new Value<int32_t>(10), OperatorToken::LESSTHAN), new Block(), new ExternalVariable("ext", CoreType::FLOAT), new Crement(new Local("i"), Crement::Operation::Increment, false))) }, { "for (i++; i < 10; ++i) {}", Node::Ptr(new Loop(tokens::LoopToken::FOR, new BinaryOperator(new Local("i"), new Value<int32_t>(10), OperatorToken::LESSTHAN), new Block(), new Crement(new Local("i"), Crement::Operation::Increment, true), new Crement(new Local("i"), Crement::Operation::Increment, false))) }, { "for ({1,2.0,3.0f}; i < 10; ++i) {}", Node::Ptr(new Loop(tokens::LoopToken::FOR, new BinaryOperator(new Local("i"), new Value<int32_t>(10), OperatorToken::LESSTHAN), new Block(), new ArrayPack({new Value<int32_t>(1), new Value<double>(2.0), new Value<float>(3.0f)}), new Crement(new Local("i"), Crement::Operation::Increment, false))) }, { "for (1,2.0,3.0f; (i < 10, i > 10); (++i, --i)) {}", Node::Ptr(new Loop(tokens::LoopToken::FOR, new CommaOperator({ new BinaryOperator(new Local("i"), new Value<int32_t>(10), OperatorToken::LESSTHAN), new BinaryOperator(new Local("i"), new Value<int32_t>(10), OperatorToken::MORETHAN) }), new Block(), new CommaOperator({ new Value<int32_t>(1), new Value<double>(2.0), new Value<float>(3.0f) }), new CommaOperator({ new Crement(new Local("i"), Crement::Operation::Increment, false), new Crement(new Local("i"), Crement::Operation::Decrement, false), }) )) }, { "for (++i; i < 10; ++i) {}", Node::Ptr(new Loop(tokens::LoopToken::FOR, new BinaryOperator(new Local("i"), new Value<int32_t>(10), OperatorToken::LESSTHAN), new Block(), new Crement(new Local("i"), Crement::Operation::Increment, false), new Crement(new Local("i"), Crement::Operation::Increment, false))) }, { "for (x[2]; i < 10; ++i) {}", Node::Ptr(new Loop(tokens::LoopToken::FOR, new BinaryOperator(new Local("i"), new Value<int32_t>(10), OperatorToken::LESSTHAN), new Block(), new ArrayUnpack(new Local("x"), new Value<int32_t>(2)), new Crement(new Local("i"), Crement::Operation::Increment, false))) }, { "for ((x[2]); i < 10; ++i) {}", Node::Ptr(new Loop(tokens::LoopToken::FOR, new BinaryOperator(new Local("i"), new Value<int32_t>(10), OperatorToken::LESSTHAN), new Block(), new ArrayUnpack(new Local("x"), new Value<int32_t>(2)), new Crement(new Local("i"), Crement::Operation::Increment, false))) }, { "for (; i < 10; ++i) {}", Node::Ptr(new Loop(tokens::LoopToken::FOR, new BinaryOperator(new Local("i"), new Value<int32_t>(10), OperatorToken::LESSTHAN), new Block(), nullptr, new Crement(new Local("i"), Crement::Operation::Increment, /*post*/false))) }, { "for (int32 i = 0; i < 10; ++i, ++j) {}", Node::Ptr(new Loop(tokens::LoopToken::FOR, new BinaryOperator(new Local("i"), new Value<int32_t>(10), OperatorToken::LESSTHAN), new Block(), new DeclareLocal(CoreType::INT32, new Local("i"), new Value<int32_t>(0)), new CommaOperator({ new Crement(new Local("i"), Crement::Operation::Increment, /*post*/false), new Crement(new Local("j"), Crement::Operation::Increment, /*post*/false) }))) }, { "for (i = 0; i < 10; ++i, ++j) {}", Node::Ptr(new Loop(tokens::LoopToken::FOR, new BinaryOperator(new Local("i"), new Value<int32_t>(10), OperatorToken::LESSTHAN), new Block(), new AssignExpression(new Local("i"), new Value<int32_t>(0)), new CommaOperator({ new Crement(new Local("i"), Crement::Operation::Increment, /*post*/false), new Crement(new Local("j"), Crement::Operation::Increment, /*post*/false) }))) }, { "for (int32 i = 0; i; ++i) {}", Node::Ptr(new Loop(tokens::LoopToken::FOR, new Local("i"), new Block(), new DeclareLocal(CoreType::INT32, new Local("i"), new Value<int32_t>(0)), new Crement(new Local("i"), Crement::Operation::Increment, /*post*/false))) }, { "for (int32 i = 0; func(i); ++i) {}", Node::Ptr(new Loop(tokens::LoopToken::FOR, new FunctionCall("func", new Local("i")), new Block(), new DeclareLocal(CoreType::INT32, new Local("i"), new Value<int32_t>(0)), new Crement(new Local("i"), Crement::Operation::Increment, /*post*/false))) }, { "for (int32 i = 0; int32 j = func(i); ++i) {}", Node::Ptr(new Loop(tokens::LoopToken::FOR, new DeclareLocal(CoreType::INT32, new Local("j"),new FunctionCall("func", new Local("i"))), new Block(), new DeclareLocal(CoreType::INT32, new Local("i"), new Value<int32_t>(0)), new Crement(new Local("i"), Crement::Operation::Increment, /*post*/false))) }, { "for (; i < 10;) {}", Node::Ptr(new Loop(tokens::LoopToken::FOR, new BinaryOperator(new Local("i"), new Value<int32_t>(10), OperatorToken::LESSTHAN), new Block())) }, { "for (;;) {}", Node::Ptr(new Loop(tokens::LoopToken::FOR, new Value<bool>(true), new Block())) }, { "for (;;) { 1,2,3 };", Node::Ptr(new Loop(tokens::LoopToken::FOR, new Value<bool>(true), new Block(new ArrayPack({ new Value<int32_t>(1), new Value<int32_t>(2), new Value<int32_t>(3) })))) }, { "for (;;) { 1,2,3; }", Node::Ptr(new Loop(tokens::LoopToken::FOR, new Value<bool>(true), new Block(new CommaOperator({ new Value<int32_t>(1), new Value<int32_t>(2), new Value<int32_t>(3) })))) }, { "for (int32 i = 0, j = 0, k; i < 10; ++i) {}", Node::Ptr(new Loop(tokens::LoopToken::FOR, new BinaryOperator(new Local("i"), new Value<int32_t>(10), OperatorToken::LESSTHAN), new Block(), new StatementList({new DeclareLocal(CoreType::INT32, new Local("i"), new Value<int32_t>(0)), new DeclareLocal(CoreType::INT32, new Local("j"), new Value<int32_t>(0)), new DeclareLocal( CoreType::INT32, new Local("k"))}), new Crement(new Local("i"), Crement::Operation::Increment, /*post*/false))) }, { "for (i = 0, j = 0; i < 10; ++i) {}", Node::Ptr(new Loop(tokens::LoopToken::FOR, new BinaryOperator(new Local("i"), new Value<int32_t>(10), OperatorToken::LESSTHAN), new Block(), new CommaOperator({ new AssignExpression(new Local("i"), new Value<int32_t>(0)), new AssignExpression(new Local("j"), new Value<int32_t>(0)) }), new Crement(new Local("i"), Crement::Operation::Increment, /*post*/false))) }, { "for (int32 i = 0; i < 10, j < 10; ++i) {}", Node::Ptr(new Loop(tokens::LoopToken::FOR, new CommaOperator({ new BinaryOperator(new Local("i"), new Value<int32_t>(10), OperatorToken::LESSTHAN), new BinaryOperator(new Local("j"), new Value<int32_t>(10), OperatorToken::LESSTHAN) }), new Block(), new DeclareLocal(CoreType::INT32, new Local("i"), new Value<int32_t>(0)), new Crement(new Local("i"), Crement::Operation::Increment, /*post*/false))) }, { "while (int32 i = 0) {}", Node::Ptr(new Loop(tokens::LoopToken::WHILE, new DeclareLocal(CoreType::INT32, new Local("i"), new Value<int32_t>(0)), new Block())) }, { "while (i = 0) {}", Node::Ptr(new Loop(tokens::LoopToken::WHILE, new AssignExpression(new Local("i"), new Value<int32_t>(0)), new Block())) }, { "while ((a,b,c)) {}", Node::Ptr(new Loop(tokens::LoopToken::WHILE, new CommaOperator({ new Local("a"), new Local("b"), new Local("c") }), new Block())) }, { "while (i < 0, j = 10) ;", Node::Ptr(new Loop(tokens::LoopToken::WHILE, new CommaOperator({ new BinaryOperator(new Local("i"), new Value<int32_t>(0), OperatorToken::LESSTHAN), new AssignExpression(new Local("j"), new Value<int32_t>(10)) }), new Block())) }, { "while (i) { 1,2,3 };", Node::Ptr(new Loop(tokens::LoopToken::WHILE, new Local("i"), new Block(new ArrayPack({ new Value<int32_t>(1), new Value<int32_t>(2), new Value<int32_t>(3) })))) }, { "while (i) { 1,2,3; }", Node::Ptr(new Loop(tokens::LoopToken::WHILE, new Local("i"), new Block(new CommaOperator({ new Value<int32_t>(1), new Value<int32_t>(2), new Value<int32_t>(3) })))) }, { "do {} while (i < 0, j = 10)", Node::Ptr(new Loop(tokens::LoopToken::DO, new CommaOperator({ new BinaryOperator(new Local("i"), new Value<int32_t>(0), OperatorToken::LESSTHAN), new AssignExpression(new Local("j"), new Value<int32_t>(10)) }), new Block())) }, { "do ; while (int32 i = 0)", Node::Ptr(new Loop(tokens::LoopToken::DO, new DeclareLocal(CoreType::INT32, new Local("i"), new Value<int32_t>(0)), new Block())) }, { "do ; while ((a,b,c))", Node::Ptr(new Loop(tokens::LoopToken::DO, new CommaOperator({ new Local("a"), new Local("b"), new Local("c") }), new Block())) }, { "do ; while (a,b,c)", Node::Ptr(new Loop(tokens::LoopToken::DO, new CommaOperator({ new Local("a"), new Local("b"), new Local("c") }), new Block())) }, { "do { 1,2,3 }; while (i) ", Node::Ptr(new Loop(tokens::LoopToken::DO, new Local("i"), new Block(new ArrayPack({ new Value<int32_t>(1), new Value<int32_t>(2), new Value<int32_t>(3) })))) }, { "do { 1,2,3; } while (i) ", Node::Ptr(new Loop(tokens::LoopToken::DO, new Local("i"), new Block(new CommaOperator({ new Value<int32_t>(1), new Value<int32_t>(2), new Value<int32_t>(3) })))) } }; } class TestLoopNode : public CppUnit::TestCase { public: CPPUNIT_TEST_SUITE(TestLoopNode); CPPUNIT_TEST(testSyntax); CPPUNIT_TEST(testASTNode); CPPUNIT_TEST_SUITE_END(); void testSyntax() { TEST_SYNTAX_PASSES(tests); } void testASTNode(); }; CPPUNIT_TEST_SUITE_REGISTRATION(TestLoopNode); void TestLoopNode::testASTNode() { for (const auto& test : tests) { const std::string& code = test.first; const Node* expected = test.second.get(); const Tree::ConstPtr tree = parse(code.c_str()); CPPUNIT_ASSERT_MESSAGE(ERROR_MSG("No AST returned", code), static_cast<bool>(tree)); // get the first statement const Node* result = tree->child(0)->child(0); CPPUNIT_ASSERT(result); CPPUNIT_ASSERT_MESSAGE(ERROR_MSG("Invalid AST node", code), Node::LoopNode == result->nodetype()); std::vector<const Node*> resultList, expectedList; linearize(*result, resultList); linearize(*expected, expectedList); if (!unittest_util::compareLinearTrees(expectedList, resultList)) { std::ostringstream os; os << "\nExpected:\n"; openvdb::ax::ast::print(*expected, true, os); os << "Result:\n"; openvdb::ax::ast::print(*result, true, os); CPPUNIT_FAIL(ERROR_MSG("Mismatching Trees for Loop code", code) + os.str()); } } }
NVIDIA-Omniverse/ext-openvdb/openvdb_ax/openvdb_ax/test/frontend/TestAttributeNode.cc
// Copyright Contributors to the OpenVDB Project // SPDX-License-Identifier: MPL-2.0 #include <openvdb_ax/ast/AST.h> #include <openvdb_ax/ast/Scanners.h> #include <openvdb_ax/ast/PrintTree.h> #include <openvdb_ax/Exceptions.h> #include <openvdb_ax/test/util.h> #include <cppunit/extensions/HelperMacros.h> #include <string> using namespace openvdb::ax::ast; using namespace openvdb::ax::ast::tokens; namespace { static const unittest_util::CodeTests tests = { { "bool@_a;", Node::Ptr(new Attribute("_a", CoreType::BOOL)) }, { "int16@a_;", Node::Ptr(new Attribute("a_", CoreType::INT16)) }, { "i@a1;", Node::Ptr(new Attribute("a1", CoreType::INT32)) }, { "int@abc;", Node::Ptr(new Attribute("abc", CoreType::INT32)) }, { "int32@abc;", Node::Ptr(new Attribute("abc", CoreType::INT32)) }, { "int64@a;", Node::Ptr(new Attribute("a", CoreType::INT64)) }, { "@a;", Node::Ptr(new Attribute("a", CoreType::FLOAT, true)) }, { "f@a;", Node::Ptr(new Attribute("a", CoreType::FLOAT)) }, { "float@a;", Node::Ptr(new Attribute("a", CoreType::FLOAT)) }, { "double@a;", Node::Ptr(new Attribute("a", CoreType::DOUBLE)) }, { "vec2i@a;", Node::Ptr(new Attribute("a", CoreType::VEC2I)) }, { "vec2f@a;", Node::Ptr(new Attribute("a", CoreType::VEC2F)) }, { "vec2d@a;", Node::Ptr(new Attribute("a", CoreType::VEC2D)) }, { "vec3i@a;", Node::Ptr(new Attribute("a", CoreType::VEC3I)) }, { "v@a;", Node::Ptr(new Attribute("a", CoreType::VEC3F)) }, { "vec3f@a;", Node::Ptr(new Attribute("a", CoreType::VEC3F)) }, { "vec3d@a;", Node::Ptr(new Attribute("a", CoreType::VEC3D)) }, { "vec4i@a;", Node::Ptr(new Attribute("a", CoreType::VEC4I)) }, { "vec4f@a;", Node::Ptr(new Attribute("a", CoreType::VEC4F)) }, { "vec4d@a;", Node::Ptr(new Attribute("a", CoreType::VEC4D)) }, { "mat3f@a;", Node::Ptr(new Attribute("a", CoreType::MAT3F)) }, { "mat3d@a;", Node::Ptr(new Attribute("a", CoreType::MAT3D)) }, { "mat4f@a;", Node::Ptr(new Attribute("a", CoreType::MAT4F)) }, { "mat4d@a;", Node::Ptr(new Attribute("a", CoreType::MAT4D)) }, { "string@a;", Node::Ptr(new Attribute("a", CoreType::STRING)) }, { "s@a;", Node::Ptr(new Attribute("a", CoreType::STRING)) }, }; } class TestAttributeNode : public CppUnit::TestCase { public: CPPUNIT_TEST_SUITE(TestAttributeNode); CPPUNIT_TEST(testSyntax); CPPUNIT_TEST(testASTNode); CPPUNIT_TEST_SUITE_END(); void testSyntax() { TEST_SYNTAX_PASSES(tests); } void testASTNode(); }; CPPUNIT_TEST_SUITE_REGISTRATION(TestAttributeNode); void TestAttributeNode::testASTNode() { for (const auto& test : tests) { const std::string& code = test.first; const Node* expected = test.second.get(); const Tree::ConstPtr tree = parse(code.c_str()); CPPUNIT_ASSERT_MESSAGE(ERROR_MSG("No AST returned", code), static_cast<bool>(tree)); // get the first statement const Node* result = tree->child(0)->child(0); CPPUNIT_ASSERT(result); CPPUNIT_ASSERT_MESSAGE(ERROR_MSG("Invalid AST node", code), Node::AttributeNode == result->nodetype()); std::vector<const Node*> resultList, expectedList; linearize(*result, resultList); linearize(*expected, expectedList); if (!unittest_util::compareLinearTrees(expectedList, resultList)) { std::ostringstream os; os << "\nExpected:\n"; openvdb::ax::ast::print(*expected, true, os); os << "Result:\n"; openvdb::ax::ast::print(*result, true, os); CPPUNIT_FAIL(ERROR_MSG("Mismatching Trees for Attribute code", code) + os.str()); } } }
NVIDIA-Omniverse/ext-openvdb/openvdb_ax/openvdb_ax/test/frontend/TestValueNode.cc
// Copyright Contributors to the OpenVDB Project // SPDX-License-Identifier: MPL-2.0 #include <openvdb_ax/ast/AST.h> #include <openvdb_ax/ast/Scanners.h> #include <openvdb_ax/ast/PrintTree.h> #include <openvdb_ax/Exceptions.h> #include <openvdb_ax/test/util.h> #include <cppunit/extensions/HelperMacros.h> #include <string> #include <cstdlib> using namespace openvdb::ax::ast; using namespace openvdb::ax::ast::tokens; namespace { using CodeTestMap = std::map<Node::NodeType, unittest_util::CodeTests>; auto converti(const char* c) -> uint64_t { return std::strtoull(c, /*end*/nullptr, /*base*/10); } auto convertf(const char* c) -> float { return std::strtof(c, /*end*/nullptr); } auto convertd(const char* c) -> double { return std::strtod(c, /*end*/nullptr); } template <typename T> std::string fullDecimalValue(const T t) { // 767 is max number of digits necessary to accurately represent base 2 doubles std::ostringstream os; os << std::setprecision(767) << t; return os.str(); } static const CodeTestMap value_tests = { // No limits::lowest, negative values are a unary operator { Node::NodeType::ValueBoolNode, { { "false;", Node::Ptr(new Value<bool>(false)) }, { "true;", Node::Ptr(new Value<bool>(true)) }, } }, { Node::NodeType::ValueInt32Node, { { "00;", Node::Ptr(new Value<int32_t>(converti("0"))) }, { "1000000000000000;", Node::Ptr(new Value<int32_t>(converti("1000000000000000"))) }, // signed int wrap { "0;", Node::Ptr(new Value<int32_t>(converti("0"))) }, { "1234567890;", Node::Ptr(new Value<int32_t>(converti("1234567890"))) }, { "1;", Node::Ptr(new Value<int32_t>(converti("1"))) }, // signed int wrap { std::to_string(std::numeric_limits<int64_t>::max()) + ";", Node::Ptr(new Value<int32_t>(std::numeric_limits<int64_t>::max())) }, // signed int wrap { std::to_string(std::numeric_limits<uint64_t>::max()) + ";", Node::Ptr(new Value<int32_t>(std::numeric_limits<uint64_t>::max())) }, // signed int wrap { std::to_string(std::numeric_limits<int32_t>::max()) + "0;", Node::Ptr(new Value<int32_t>(uint64_t(std::numeric_limits<int32_t>::max()) * 10ul)) } } }, { Node::NodeType::ValueInt64Node, { { "01l;", Node::Ptr(new Value<int64_t>(converti("1"))) }, { "0l;", Node::Ptr(new Value<int64_t>(converti("0"))) }, { "1234567890l;", Node::Ptr(new Value<int64_t>(converti("1234567890l"))) }, // signed int wrap { std::to_string(uint64_t(std::numeric_limits<int64_t>::max()) + 1) + "l;", Node::Ptr(new Value<int64_t>(uint64_t(std::numeric_limits<int64_t>::max()) + 1ul)) } } }, { Node::NodeType::ValueFloatNode, { { ".123456789f;", Node::Ptr(new Value<float>(convertf(".123456789f"))) }, { "0.0f;", Node::Ptr(new Value<float>(convertf("0.0f"))) }, { "00.f;", Node::Ptr(new Value<float>(convertf("0.0f"))) }, { "0e+0f;", Node::Ptr(new Value<float>(convertf("0.0f"))) }, { "0e-0f;", Node::Ptr(new Value<float>(convertf("0.0f"))) }, { "0e0f;", Node::Ptr(new Value<float>(convertf("0.0f"))) }, { "1234567890.0987654321f;", Node::Ptr(new Value<float>(convertf("1234567890.0987654321f"))) }, { "1e+6f;", Node::Ptr(new Value<float>(convertf("1e+6f"))) }, { "1E+6f;", Node::Ptr(new Value<float>(convertf("1E+6f"))) }, { "1e-6f;", Node::Ptr(new Value<float>(convertf("1e-6f"))) }, { "1E-6f;", Node::Ptr(new Value<float>(convertf("1E-6f"))) }, { "1e6f;", Node::Ptr(new Value<float>(convertf("1e6f"))) }, { "1E6f;", Node::Ptr(new Value<float>(convertf("1E6f"))) } } }, { Node::NodeType::ValueDoubleNode, { { ".123456789;", Node::Ptr(new Value<double>(convertd(".123456789"))) }, { "0.0;", Node::Ptr(new Value<double>(convertd("0.0"))) }, { "0e0;", Node::Ptr(new Value<double>(convertd("0.0f"))) }, { "1.0;", Node::Ptr(new Value<double>(convertd("1.0"))) }, { "1234567890.00000000;", Node::Ptr(new Value<double>(convertd("1234567890.0"))) }, { "1234567890.0987654321;", Node::Ptr(new Value<double>(convertd("1234567890.0987654321"))) }, { "1234567890.10000000;", Node::Ptr(new Value<double>(convertd("1234567890.1"))) }, { "1234567890e-0;", Node::Ptr(new Value<double>(convertd("1234567890e-0"))) }, { "1e+6;", Node::Ptr(new Value<double>(convertd("1e+6"))) }, { "1e-6;", Node::Ptr(new Value<double>(convertd("1e-6"))) }, { "1e01;", Node::Ptr(new Value<double>(convertd("1e01"))) }, { "1e6;", Node::Ptr(new Value<double>(convertd("1e6"))) }, { "1E6;", Node::Ptr(new Value<double>(convertd("1E6"))) }, { std::to_string(std::numeric_limits<double>::max()) + ";", Node::Ptr(new Value<double>(std::numeric_limits<double>::max())) }, { fullDecimalValue(std::numeric_limits<double>::max()) + ".0;", Node::Ptr(new Value<double>(std::numeric_limits<double>::max())) }, { fullDecimalValue(std::numeric_limits<double>::min()) + ";", Node::Ptr(new Value<double>(std::numeric_limits<double>::min())) } } }, { Node::NodeType::ValueStrNode, { { "\"0.0\";", Node::Ptr(new Value<std::string>("0.0")) }, { "\"0.0f\";", Node::Ptr(new Value<std::string>("0.0f")) }, { "\"0\";", Node::Ptr(new Value<std::string>("0")) }, { "\"1234567890.0987654321\";", Node::Ptr(new Value<std::string>("1234567890.0987654321")) }, { "\"1234567890\";", Node::Ptr(new Value<std::string>("1234567890")) }, { "\"a1b2c3d4.e5f6g7.0\";", Node::Ptr(new Value<std::string>("a1b2c3d4.e5f6g7.0")) }, { "\"literal\";", Node::Ptr(new Value<std::string>("literal")) }, { "\"\";", Node::Ptr(new Value<std::string>("")) }, { "\"" + std::to_string(std::numeric_limits<double>::lowest()) + "\";", Node::Ptr(new Value<std::string>(std::to_string(std::numeric_limits<double>::lowest()))) }, { "\"" + std::to_string(std::numeric_limits<double>::max()) + "\";", Node::Ptr(new Value<std::string>(std::to_string(std::numeric_limits<double>::max()))) }, { "\"" + std::to_string(std::numeric_limits<int64_t>::lowest()) + "\";", Node::Ptr(new Value<std::string>(std::to_string(std::numeric_limits<int64_t>::lowest()))) }, { "\"" + std::to_string(std::numeric_limits<int64_t>::max()) + "\";", Node::Ptr(new Value<std::string>(std::to_string(std::numeric_limits<int64_t>::max()))) } } } }; } class TestValueNode : public CppUnit::TestCase { public: CPPUNIT_TEST_SUITE(TestValueNode); CPPUNIT_TEST(testSyntax); CPPUNIT_TEST(testASTNode); CPPUNIT_TEST_SUITE_END(); void testSyntax() { for (const auto& tests : value_tests) { TEST_SYNTAX_PASSES(tests.second); } } void testASTNode(); }; CPPUNIT_TEST_SUITE_REGISTRATION(TestValueNode); void TestValueNode::testASTNode() { for (const auto& tests : value_tests) { const Node::NodeType nodeType = tests.first; for (const auto& test : tests.second) { const std::string& code = test.first; const Node* expected = test.second.get(); const Tree::ConstPtr tree = parse(code.c_str()); CPPUNIT_ASSERT_MESSAGE(ERROR_MSG("No AST returned", code), static_cast<bool>(tree)); // get the first statement const Node* result = tree->child(0)->child(0); CPPUNIT_ASSERT(result); CPPUNIT_ASSERT_MESSAGE(ERROR_MSG("Invalid AST node", code), nodeType == result->nodetype()); std::vector<const Node*> resultList, expectedList; linearize(*result, resultList); linearize(*expected, expectedList); if (!unittest_util::compareLinearTrees(expectedList, resultList)) { std::ostringstream os; os << "\nExpected:\n"; openvdb::ax::ast::print(*expected, true, os); os << "Result:\n"; openvdb::ax::ast::print(*result, true, os); CPPUNIT_FAIL(ERROR_MSG("Mismatching Trees for Value (literal) code", code) + os.str()); } } } }
NVIDIA-Omniverse/ext-openvdb/openvdb_ax/openvdb_ax/test/frontend/TestLocalNode.cc
// Copyright Contributors to the OpenVDB Project // SPDX-License-Identifier: MPL-2.0 #include <openvdb_ax/ast/AST.h> #include <openvdb_ax/ast/Scanners.h> #include <openvdb_ax/ast/PrintTree.h> #include <openvdb_ax/Exceptions.h> #include <openvdb_ax/test/util.h> #include <cppunit/extensions/HelperMacros.h> #include <string> using namespace openvdb::ax::ast; using namespace openvdb::ax::ast::tokens; namespace { static const unittest_util::CodeTests tests = { { "a_;", Node::Ptr(new Local("a_")) }, { "_a;", Node::Ptr(new Local("_a")) }, { "_;", Node::Ptr(new Local("_")) }, { "aa;", Node::Ptr(new Local("aa")) }, { "A;", Node::Ptr(new Local("A")) }, { "_A;", Node::Ptr(new Local("_A")) }, { "a1;", Node::Ptr(new Local("a1")) }, { "_1;", Node::Ptr(new Local("_1")) }, { "abc;", Node::Ptr(new Local("abc")) }, { "D1f;", Node::Ptr(new Local("D1f")) }, { "var;", Node::Ptr(new Local("var")) } }; } class TestLocalNode : public CppUnit::TestCase { public: CPPUNIT_TEST_SUITE(TestLocalNode); CPPUNIT_TEST(testSyntax); CPPUNIT_TEST(testASTNode); CPPUNIT_TEST_SUITE_END(); void testSyntax() { TEST_SYNTAX_PASSES(tests); } void testASTNode(); }; CPPUNIT_TEST_SUITE_REGISTRATION(TestLocalNode); void TestLocalNode::testASTNode() { for (const auto& test : tests) { const std::string& code = test.first; const Node* expected = test.second.get(); const Tree::ConstPtr tree = parse(code.c_str()); CPPUNIT_ASSERT_MESSAGE(ERROR_MSG("No AST returned", code), static_cast<bool>(tree)); // get the first statement const Node* result = tree->child(0)->child(0); CPPUNIT_ASSERT(result); CPPUNIT_ASSERT_MESSAGE(ERROR_MSG("Invalid AST node", code), Node::LocalNode == result->nodetype()); std::vector<const Node*> resultList, expectedList; linearize(*result, resultList); linearize(*expected, expectedList); if (!unittest_util::compareLinearTrees(expectedList, resultList)) { std::ostringstream os; os << "\nExpected:\n"; openvdb::ax::ast::print(*expected, true, os); os << "Result:\n"; openvdb::ax::ast::print(*result, true, os); CPPUNIT_FAIL(ERROR_MSG("Mismatching Trees for Local code", code) + os.str()); } } }
NVIDIA-Omniverse/ext-openvdb/openvdb_ax/openvdb_ax/test/frontend/TestKeywordNode.cc
// Copyright Contributors to the OpenVDB Project // SPDX-License-Identifier: MPL-2.0 #include <openvdb_ax/ast/AST.h> #include <openvdb_ax/ast/Scanners.h> #include <openvdb_ax/ast/PrintTree.h> #include <openvdb_ax/Exceptions.h> #include <openvdb_ax/test/util.h> #include <cppunit/extensions/HelperMacros.h> #include <string> using namespace openvdb::ax::ast; using namespace openvdb::ax::ast::tokens; namespace { static const unittest_util::CodeTests tests = { { "return;", Node::Ptr(new Keyword(KeywordToken::RETURN)) }, { "break;", Node::Ptr(new Keyword(KeywordToken::BREAK)) }, { "continue;", Node::Ptr(new Keyword(KeywordToken::CONTINUE)) } }; } class TestKeywordNode : public CppUnit::TestCase { public: CPPUNIT_TEST_SUITE(TestKeywordNode); CPPUNIT_TEST(testSyntax); CPPUNIT_TEST(testASTNode); CPPUNIT_TEST_SUITE_END(); void testSyntax() { TEST_SYNTAX_PASSES(tests); } void testASTNode(); }; CPPUNIT_TEST_SUITE_REGISTRATION(TestKeywordNode); void TestKeywordNode::testASTNode() { for (const auto& test : tests) { const std::string& code = test.first; const Node* expected = test.second.get(); const Tree::ConstPtr tree = parse(code.c_str()); CPPUNIT_ASSERT_MESSAGE(ERROR_MSG("No AST returned", code), static_cast<bool>(tree)); // get the first statement const Node* result = tree->child(0)->child(0); CPPUNIT_ASSERT(result); const Keyword* resultAsKeyword = static_cast<const Keyword*>(result); CPPUNIT_ASSERT(resultAsKeyword); CPPUNIT_ASSERT_MESSAGE(ERROR_MSG("Invalid AST node", code), Node::KeywordNode == result->nodetype()); std::vector<const Node*> resultList, expectedList; linearize(*result, resultList); linearize(*expected, expectedList); if (!unittest_util::compareLinearTrees(expectedList, resultList)) { std::ostringstream os; os << "\nExpected:\n"; openvdb::ax::ast::print(*expected, true, os); os << "Result:\n"; openvdb::ax::ast::print(*result, true, os); CPPUNIT_FAIL(ERROR_MSG("Mismatching Trees for Return code", code) + os.str()); } } }
NVIDIA-Omniverse/ext-openvdb/openvdb_ax/openvdb_ax/test/frontend/TestExternalVariableNode.cc
// Copyright Contributors to the OpenVDB Project // SPDX-License-Identifier: MPL-2.0 #include <openvdb_ax/ast/AST.h> #include <openvdb_ax/ast/Scanners.h> #include <openvdb_ax/ast/PrintTree.h> #include <openvdb_ax/Exceptions.h> #include <openvdb_ax/test/util.h> #include <cppunit/extensions/HelperMacros.h> #include <string> using namespace openvdb::ax::ast; using namespace openvdb::ax::ast::tokens; namespace { static const unittest_util::CodeTests tests = { { "$a;", Node::Ptr(new ExternalVariable("a", CoreType::FLOAT)) }, { "bool$_a;", Node::Ptr(new ExternalVariable("_a", CoreType::BOOL)) }, { "i$a1;", Node::Ptr(new ExternalVariable("a1", CoreType::INT32)) }, { "int$abc;", Node::Ptr(new ExternalVariable("abc", CoreType::INT32)) }, { "int32$abc;", Node::Ptr(new ExternalVariable("abc", CoreType::INT32)) }, { "int64$a;", Node::Ptr(new ExternalVariable("a", CoreType::INT64)) }, { "f$a;", Node::Ptr(new ExternalVariable("a", CoreType::FLOAT)) }, { "float$a;", Node::Ptr(new ExternalVariable("a", CoreType::FLOAT)) }, { "double$a;", Node::Ptr(new ExternalVariable("a", CoreType::DOUBLE)) }, { "vec3i$a;", Node::Ptr(new ExternalVariable("a", CoreType::VEC3I)) }, { "v$a;", Node::Ptr(new ExternalVariable("a", CoreType::VEC3F)) }, { "vec3f$a;", Node::Ptr(new ExternalVariable("a", CoreType::VEC3F)) }, { "vec3d$a;", Node::Ptr(new ExternalVariable("a", CoreType::VEC3D)) }, { "string$a;", Node::Ptr(new ExternalVariable("a", CoreType::STRING)) }, { "s$a;", Node::Ptr(new ExternalVariable("a", CoreType::STRING)) }, }; } class TestExternalVariableNode : public CppUnit::TestCase { public: CPPUNIT_TEST_SUITE(TestExternalVariableNode); CPPUNIT_TEST(testSyntax); CPPUNIT_TEST(testASTNode); CPPUNIT_TEST_SUITE_END(); void testSyntax() { TEST_SYNTAX_PASSES(tests); } void testASTNode(); }; CPPUNIT_TEST_SUITE_REGISTRATION(TestExternalVariableNode); void TestExternalVariableNode::testASTNode() { for (const auto& test : tests) { const std::string& code = test.first; const Node* expected = test.second.get(); const Tree::ConstPtr tree = parse(code.c_str()); CPPUNIT_ASSERT_MESSAGE(ERROR_MSG("No AST returned", code), static_cast<bool>(tree)); // get the first statement const Node* result = tree->child(0)->child(0); CPPUNIT_ASSERT(result); CPPUNIT_ASSERT_MESSAGE(ERROR_MSG("Invalid AST node", code), Node::ExternalVariableNode == result->nodetype()); std::vector<const Node*> resultList, expectedList; linearize(*result, resultList); linearize(*expected, expectedList); if (!unittest_util::compareLinearTrees(expectedList, resultList)) { std::ostringstream os; os << "\nExpected:\n"; openvdb::ax::ast::print(*expected, true, os); os << "Result:\n"; openvdb::ax::ast::print(*result, true, os); CPPUNIT_FAIL(ERROR_MSG("Mismatching Trees for External Variable code", code) + os.str()); } } }
NVIDIA-Omniverse/ext-openvdb/openvdb_ax/openvdb_ax/test/frontend/TestConditionalStatementNode.cc
// Copyright Contributors to the OpenVDB Project // SPDX-License-Identifier: MPL-2.0 #include <openvdb_ax/ast/AST.h> #include <openvdb_ax/ast/Scanners.h> #include <openvdb_ax/ast/PrintTree.h> #include <openvdb_ax/Exceptions.h> #include <openvdb_ax/test/util.h> #include <cppunit/extensions/HelperMacros.h> #include <string> using namespace openvdb::ax::ast; using namespace openvdb::ax::ast::tokens; namespace { static const unittest_util::CodeTests tests = { { "if ((a));", Node::Ptr(new ConditionalStatement(new Local("a"), new Block())) }, { "if ((a,b));", Node::Ptr(new ConditionalStatement( new CommaOperator({ new Local("a"), new Local("b") }), new Block() )) }, { "if (a);", Node::Ptr(new ConditionalStatement(new Local("a"), new Block())) }, { "if(a);", Node::Ptr(new ConditionalStatement(new Local("a"), new Block())) }, { "if (@a);", Node::Ptr(new ConditionalStatement(new Attribute("a", CoreType::FLOAT, true), new Block())) }, { "if (1.0f);", Node::Ptr(new ConditionalStatement(new Value<float>(1.0f), new Block())) }, { "if (func());", Node::Ptr(new ConditionalStatement(new FunctionCall("func"), new Block())) }, { "if (a+b);", Node::Ptr(new ConditionalStatement( new BinaryOperator( new Local("a"), new Local("b"), OperatorToken::PLUS ), new Block()) ) }, { "if (-a);", Node::Ptr(new ConditionalStatement( new UnaryOperator( new Local("a"), OperatorToken::MINUS ), new Block()) ) }, { "if (a = 1);", Node::Ptr(new ConditionalStatement( new AssignExpression( new Local("a"), new Value<int32_t>(1) ), new Block()) ) }, { "if (a.x);", Node::Ptr(new ConditionalStatement( new ArrayUnpack( new Local("a"), new Value<int32_t>(0) ), new Block()) ) }, { "if (a++);", Node::Ptr(new ConditionalStatement( new Crement( new Local("a"), Crement::Operation::Increment, true ), new Block()) ) }, { "if (float(a));", Node::Ptr(new ConditionalStatement( new Cast( new Local("a"), CoreType::FLOAT ), new Block()) ) }, { "if ({1.0, 2.0, 3.0});", Node::Ptr(new ConditionalStatement( new ArrayPack({ new Value<double>(1.0), new Value<double>(2.0), new Value<double>(3.0) }), new Block()) ) }, { "if (a, b);", Node::Ptr(new ConditionalStatement( new CommaOperator({ new Local("a"), new Local("b") }), new Block())) }, { "if (a, b, true, c = 1);", Node::Ptr(new ConditionalStatement( new CommaOperator({ new Local("a"), new Local("b"), new Value<bool>(true), new AssignExpression( new Local("c"), new Value<int32_t>(1) ), }), new Block())) }, { "if (a) {b;}", Node::Ptr(new ConditionalStatement( new Local("a"), new Block(new Local("b")))) }, { "if (a); else ;", Node::Ptr(new ConditionalStatement(new Local("a"), new Block(), new Block())) }, { "if (a) {} else ;", Node::Ptr(new ConditionalStatement(new Local("a"), new Block(), new Block())) }, { "if (a); else {}", Node::Ptr(new ConditionalStatement(new Local("a"), new Block(), new Block())) }, { "if (a); else (b);", Node::Ptr(new ConditionalStatement( new Local("a"), new Block(), new Block(new Local("b")))) }, { "if (a); else {};", Node::Ptr(new ConditionalStatement(new Local("a"), new Block(), new Block())) }, { "if (a) {} else {}", Node::Ptr(new ConditionalStatement(new Local("a"), new Block(), new Block())) }, { "if (a) b = 1; else {}", Node::Ptr(new ConditionalStatement(new Local("a"), new Block( new AssignExpression( new Local("b"), new Value<int32_t>(1) ) ), new Block())) }, { "if (a) {b = 1;} else {}", Node::Ptr(new ConditionalStatement(new Local("a"), new Block( new AssignExpression( new Local("b"), new Value<int32_t>(1) ) ), new Block())) }, { "if (a); else if(b) ;", Node::Ptr(new ConditionalStatement( new Local("a"), new Block(), new Block( new ConditionalStatement( new Local("b"), new Block() ) ) )) }, { "if (a); else if((a,b)) ;", Node::Ptr(new ConditionalStatement( new Local("a"), new Block(), new Block( new ConditionalStatement( new CommaOperator({ new Local("a"), new Local("b") }), new Block() ) ) )) }, { "if (a) if(b) ; else ;", Node::Ptr(new ConditionalStatement( new Local("a"), new Block( new ConditionalStatement( new Local("b"), new Block(), new Block() ) ) )) }, { "if (a) if(b) {} else {} else ;", Node::Ptr(new ConditionalStatement( new Local("a"), new Block( new ConditionalStatement( new Local("b"), new Block(), new Block() ) ), new Block() )) }, { "if (a) if(b) {if (c) ; else ;} else {} else ;", Node::Ptr(new ConditionalStatement( new Local("a"), new Block( new ConditionalStatement( new Local("b"), new Block( new ConditionalStatement( new Local("c"), new Block(), new Block() ) ), new Block() ) ), new Block() )) }, { "if (a) if(b) {if (c) ;} else {}", Node::Ptr(new ConditionalStatement( new Local("a"), new Block( new ConditionalStatement( new Local("b"), new Block( new ConditionalStatement( new Local("c"), new Block() ) ), new Block() ) ) )) }, { "if (a) {} else if(b) {if (c) ;} else {}", Node::Ptr(new ConditionalStatement( new Local("a"), new Block(), new Block( new ConditionalStatement( new Local("b"), new Block( new ConditionalStatement( new Local("c"), new Block() ) ), new Block() ) ) )) }, { "if (a) { a,a; }", Node::Ptr(new ConditionalStatement(new Local("a"), new Block( new CommaOperator({ new Local("a"), new Local("a") }) ))) }, { "if (a) { a,a };", Node::Ptr(new ConditionalStatement(new Local("a"), new Block( new ArrayPack({ new Local("a"), new Local("a") }) ))) }, { "if (a) { a,a }; else { a,a; }", Node::Ptr(new ConditionalStatement(new Local("a"), new Block( new ArrayPack({ new Local("a"), new Local("a") }) ), new Block( new CommaOperator({ new Local("a"), new Local("a") }) ))) }, { "if (a) { a,a }; else { a,a };", Node::Ptr(new ConditionalStatement(new Local("a"), new Block( new ArrayPack({ new Local("a"), new Local("a") }) ), new Block( new ArrayPack({ new Local("a"), new Local("a") }) ) )) }, { "if (a) { { a,a; } }", Node::Ptr(new ConditionalStatement(new Local("a"), new Block( new Block( new CommaOperator({ new Local("a"), new Local("a") }) ) ) )) }, { "if (a) { { a,a }; };", Node::Ptr(new ConditionalStatement(new Local("a"), new Block( new ArrayPack({ new Local("a"), new Local("a") }) ) )) } }; } class TestConditionalStatementNode : public CppUnit::TestCase { public: CPPUNIT_TEST_SUITE(TestConditionalStatementNode); CPPUNIT_TEST(testSyntax); CPPUNIT_TEST(testASTNode); CPPUNIT_TEST_SUITE_END(); void testSyntax() { TEST_SYNTAX_PASSES(tests); } void testASTNode(); }; CPPUNIT_TEST_SUITE_REGISTRATION(TestConditionalStatementNode); void TestConditionalStatementNode::testASTNode() { for (const auto& test : tests) { const std::string& code = test.first; const Node* expected = test.second.get(); const Tree::ConstPtr tree = parse(code.c_str()); CPPUNIT_ASSERT_MESSAGE(ERROR_MSG("No AST returned", code), static_cast<bool>(tree)); // get the first statement const Node* result = tree->child(0)->child(0); CPPUNIT_ASSERT(result); CPPUNIT_ASSERT_MESSAGE(ERROR_MSG("Invalid AST node", code), Node::ConditionalStatementNode == result->nodetype()); std::vector<const Node*> resultList, expectedList; linearize(*result, resultList); linearize(*expected, expectedList); if (!unittest_util::compareLinearTrees(expectedList, resultList)) { std::ostringstream os; os << "\nExpected:\n"; openvdb::ax::ast::print(*expected, true, os); os << "Result:\n"; openvdb::ax::ast::print(*result, true, os); CPPUNIT_FAIL(ERROR_MSG("Mismatching Trees for Conditional Statement code", code) + os.str()); } } }
NVIDIA-Omniverse/ext-openvdb/openvdb_ax/openvdb_ax/test/frontend/TestBinaryOperatorNode.cc
// Copyright Contributors to the OpenVDB Project // SPDX-License-Identifier: MPL-2.0 #include <openvdb_ax/ast/AST.h> #include <openvdb_ax/ast/Scanners.h> #include <openvdb_ax/ast/PrintTree.h> #include <openvdb_ax/Exceptions.h> #include <openvdb_ax/test/util.h> #include <cppunit/extensions/HelperMacros.h> #include <string> using namespace openvdb::ax::ast; using namespace openvdb::ax::ast::tokens; namespace { static const unittest_util::CodeTests tests = { { "a + b;", Node::Ptr( new BinaryOperator( new Local("a"), new Local("b"), OperatorToken::PLUS ) ) }, { "a - b;", Node::Ptr( new BinaryOperator( new Local("a"), new Local("b"), OperatorToken::MINUS ) ) }, { "a * b;", Node::Ptr( new BinaryOperator( new Local("a"), new Local("b"), OperatorToken::MULTIPLY ) ) }, { "a / b;", Node::Ptr( new BinaryOperator( new Local("a"), new Local("b"), OperatorToken::DIVIDE ) ) }, { "a % b;", Node::Ptr( new BinaryOperator( new Local("a"), new Local("b"), OperatorToken::MODULO ) ) }, { "a << b;", Node::Ptr( new BinaryOperator( new Local("a"), new Local("b"), OperatorToken::SHIFTLEFT ) ) }, { "a >> b;", Node::Ptr( new BinaryOperator( new Local("a"), new Local("b"), OperatorToken::SHIFTRIGHT ) ) }, { "a & b;", Node::Ptr( new BinaryOperator( new Local("a"), new Local("b"), OperatorToken::BITAND ) ) }, { "a | b;", Node::Ptr( new BinaryOperator( new Local("a"), new Local("b"), OperatorToken::BITOR ) ) }, { "a ^ b;", Node::Ptr( new BinaryOperator( new Local("a"), new Local("b"), OperatorToken::BITXOR ) ) }, { "a && b;", Node::Ptr( new BinaryOperator( new Local("a"), new Local("b"), OperatorToken::AND ) ) }, { "a || b;", Node::Ptr( new BinaryOperator( new Local("a"), new Local("b"), OperatorToken::OR ) ) }, { "a == b;", Node::Ptr( new BinaryOperator( new Local("a"), new Local("b"), OperatorToken::EQUALSEQUALS ) ) }, { "a != b;", Node::Ptr( new BinaryOperator( new Local("a"), new Local("b"), OperatorToken::NOTEQUALS ) ) }, { "a > b;", Node::Ptr( new BinaryOperator( new Local("a"), new Local("b"), OperatorToken::MORETHAN ) ) }, { "a < b;", Node::Ptr( new BinaryOperator( new Local("a"), new Local("b"), OperatorToken::LESSTHAN ) ) }, { "a >= b;", Node::Ptr( new BinaryOperator( new Local("a"), new Local("b"), OperatorToken::MORETHANOREQUAL ) ) }, { "a <= b;", Node::Ptr( new BinaryOperator( new Local("a"), new Local("b"), OperatorToken::LESSTHANOREQUAL ) ) }, { "(a) + (a);", Node::Ptr( new BinaryOperator( new Local("a"), new Local("a"), OperatorToken::PLUS ) ) }, { "(a,b,c) + (d,e,f);", Node::Ptr( new BinaryOperator( new CommaOperator({ new Local("a"), new Local("b"), new Local("c") }), new CommaOperator({ new Local("d"), new Local("e"), new Local("f") }), OperatorToken::PLUS ) ) }, { "func1() + func2();", Node::Ptr( new BinaryOperator( new FunctionCall("func1"), new FunctionCall("func2"), OperatorToken::PLUS ) ) }, { "a + b - c;", Node::Ptr( new BinaryOperator( new BinaryOperator( new Local("a"), new Local("b"), OperatorToken::PLUS ), new Local("c"), OperatorToken::MINUS ) ) }, { "~a + !b;", Node::Ptr( new BinaryOperator( new UnaryOperator(new Local("a"), OperatorToken::BITNOT), new UnaryOperator(new Local("b"), OperatorToken::NOT), OperatorToken::PLUS ) ) }, { "++a - --b;", Node::Ptr( new BinaryOperator( new Crement(new Local("a"), Crement::Operation::Increment, false), new Crement(new Local("b"), Crement::Operation::Decrement, false), OperatorToken::MINUS ) ) }, { "a-- + b++;", Node::Ptr( new BinaryOperator( new Crement(new Local("a"), Crement::Operation::Decrement, true), new Crement(new Local("b"), Crement::Operation::Increment, true), OperatorToken::PLUS ) ) }, { "int(a) + float(b);", Node::Ptr( new BinaryOperator( new Cast(new Local("a"), CoreType::INT32), new Cast(new Local("b"), CoreType::FLOAT), OperatorToken::PLUS ) ) }, { "{a,b,c} + {d,e,f};", Node::Ptr( new BinaryOperator( new ArrayPack({ new Local("a"), new Local("b"), new Local("c") }), new ArrayPack({ new Local("d"), new Local("e"), new Local("f") }), OperatorToken::PLUS ) ) }, { "a.x + b.y;", Node::Ptr( new BinaryOperator( new ArrayUnpack(new Local("a"), new Value<int32_t>(0)), new ArrayUnpack(new Local("b"), new Value<int32_t>(1)), OperatorToken::PLUS ) ) }, { "0 + 1;", Node::Ptr( new BinaryOperator( new Value<int32_t>(0), new Value<int32_t>(1), OperatorToken::PLUS ) ) }, { "0.0f + 1.0;", Node::Ptr( new BinaryOperator( new Value<float>(0.0), new Value<double>(1.0), OperatorToken::PLUS ) ) }, { "@a + @b;", Node::Ptr( new BinaryOperator( new Attribute("a", CoreType::FLOAT, true), new Attribute("b", CoreType::FLOAT, true), OperatorToken::PLUS ) ) }, { "\"a\" + \"b\";", Node::Ptr( new BinaryOperator( new Value<std::string>("a"), new Value<std::string>("b"), OperatorToken::PLUS ) ) }, }; } class TestBinaryOperatorNode : public CppUnit::TestCase { public: CPPUNIT_TEST_SUITE(TestBinaryOperatorNode); CPPUNIT_TEST(testSyntax); CPPUNIT_TEST(testASTNode); CPPUNIT_TEST_SUITE_END(); void testSyntax() { TEST_SYNTAX_PASSES(tests); } void testASTNode(); }; CPPUNIT_TEST_SUITE_REGISTRATION(TestBinaryOperatorNode); void TestBinaryOperatorNode::testASTNode() { for (const auto& test : tests) { const std::string& code = test.first; const Node* expected = test.second.get(); const Tree::ConstPtr tree = parse(code.c_str()); CPPUNIT_ASSERT_MESSAGE(ERROR_MSG("No AST returned", code), static_cast<bool>(tree)); // get the first statement const Node* result = tree->child(0)->child(0); CPPUNIT_ASSERT(result); CPPUNIT_ASSERT_MESSAGE(ERROR_MSG("Invalid AST node", code), Node::BinaryOperatorNode == result->nodetype()); std::vector<const Node*> resultList, expectedList; linearize(*result, resultList); linearize(*expected, expectedList); if (!unittest_util::compareLinearTrees(expectedList, resultList)) { std::ostringstream os; os << "\nExpected:\n"; openvdb::ax::ast::print(*expected, true, os); os << "Result:\n"; openvdb::ax::ast::print(*result, true, os); CPPUNIT_FAIL(ERROR_MSG("Mismatching Trees for Binary Operator code", code) + os.str()); } } }
NVIDIA-Omniverse/ext-openvdb/openvdb_ax/openvdb_ax/test/frontend/TestDeclareLocalNode.cc
// Copyright Contributors to the OpenVDB Project // SPDX-License-Identifier: MPL-2.0 #include <openvdb_ax/ast/AST.h> #include <openvdb_ax/ast/Scanners.h> #include <openvdb_ax/ast/PrintTree.h> #include <openvdb_ax/Exceptions.h> #include <openvdb_ax/test/util.h> #include <cppunit/extensions/HelperMacros.h> #include <string> using namespace openvdb::ax::ast; using namespace openvdb::ax::ast::tokens; namespace { static const unittest_util::CodeTests tests = { { "bool a_;", Node::Ptr(new DeclareLocal(CoreType::BOOL, new Local("a_"))) }, { "int32 _;", Node::Ptr(new DeclareLocal(CoreType::INT32, new Local("_"))) }, { "int64 aa;", Node::Ptr(new DeclareLocal(CoreType::INT64, new Local("aa"))) }, { "float A;", Node::Ptr(new DeclareLocal(CoreType::FLOAT, new Local("A"))) }, { "double _A;", Node::Ptr(new DeclareLocal(CoreType::DOUBLE, new Local("_A"))) }, { "vec2i a1;", Node::Ptr(new DeclareLocal(CoreType::VEC2I, new Local("a1"))) }, { "vec2f _1;", Node::Ptr(new DeclareLocal(CoreType::VEC2F, new Local("_1"))) }, { "vec2d abc;", Node::Ptr(new DeclareLocal(CoreType::VEC2D, new Local("abc"))) }, { "vec3i a1;", Node::Ptr(new DeclareLocal(CoreType::VEC3I, new Local("a1"))) }, { "vec3f _1;", Node::Ptr(new DeclareLocal(CoreType::VEC3F, new Local("_1"))) }, { "vec3d abc;", Node::Ptr(new DeclareLocal(CoreType::VEC3D, new Local("abc"))) }, { "vec4i a1;", Node::Ptr(new DeclareLocal(CoreType::VEC4I, new Local("a1"))) }, { "vec4f _1;", Node::Ptr(new DeclareLocal(CoreType::VEC4F, new Local("_1"))) }, { "vec4d abc;", Node::Ptr(new DeclareLocal(CoreType::VEC4D, new Local("abc"))) }, { "mat3f _1;", Node::Ptr(new DeclareLocal(CoreType::MAT3F, new Local("_1"))) }, { "mat3d abc;", Node::Ptr(new DeclareLocal(CoreType::MAT3D, new Local("abc"))) }, { "mat4f _1;", Node::Ptr(new DeclareLocal(CoreType::MAT4F, new Local("_1"))) }, { "mat4d abc;", Node::Ptr(new DeclareLocal(CoreType::MAT4D, new Local("abc"))) }, { "string D1f;", Node::Ptr(new DeclareLocal(CoreType::STRING, new Local("D1f"))) }, { "float a = 1.0f;", Node::Ptr(new DeclareLocal(CoreType::FLOAT, new Local("a"), new Value<float>(1.0f))) }, { "float a = 1;", Node::Ptr(new DeclareLocal(CoreType::FLOAT, new Local("a"), new Value<int32_t>(1))) }, { "float a = a + 1;", Node::Ptr(new DeclareLocal(CoreType::FLOAT, new Local("a"), new BinaryOperator(new Local("a"), new Value<int32_t>(1), OperatorToken::PLUS))) }, { "float a = v.x;", Node::Ptr(new DeclareLocal(CoreType::FLOAT, new Local("a"), new ArrayUnpack(new Local("v"), new Value<int32_t>(0)))) }, { "vec3f v = {1, 2, 3};", Node::Ptr(new DeclareLocal(CoreType::VEC3F, new Local("v"), new ArrayPack({ new Value<int32_t>(1), new Value<int32_t>(2), new Value<int32_t>(3), }))) }, { "mat3f m = 1;", Node::Ptr(new DeclareLocal(CoreType::MAT3F, new Local("m"), new Value<int32_t>(1))) }, { "string s = \"foo\";", Node::Ptr(new DeclareLocal(CoreType::STRING, new Local("s"), new Value<std::string>("foo"))) }, { "float a = b = c;", Node::Ptr(new DeclareLocal(CoreType::FLOAT, new Local("a"), new AssignExpression(new Local("b"), new Local("c")))) }, }; } class TestDeclareLocalNode : public CppUnit::TestCase { public: CPPUNIT_TEST_SUITE(TestDeclareLocalNode); CPPUNIT_TEST(testSyntax); CPPUNIT_TEST(testASTNode); CPPUNIT_TEST_SUITE_END(); void testSyntax() { TEST_SYNTAX_PASSES(tests); } void testASTNode(); }; CPPUNIT_TEST_SUITE_REGISTRATION(TestDeclareLocalNode); void TestDeclareLocalNode::testASTNode() { for (const auto& test : tests) { const std::string& code = test.first; const Node* expected = test.second.get(); const Tree::ConstPtr tree = parse(code.c_str()); CPPUNIT_ASSERT_MESSAGE(ERROR_MSG("No AST returned", code), static_cast<bool>(tree)); // get the first statement const Node* result = tree->child(0)->child(0); CPPUNIT_ASSERT(result); CPPUNIT_ASSERT_MESSAGE(ERROR_MSG("Invalid AST node", code), Node::DeclareLocalNode == result->nodetype()); std::vector<const Node*> resultList, expectedList; linearize(*result, resultList); linearize(*expected, expectedList); if (!unittest_util::compareLinearTrees(expectedList, resultList)) { std::ostringstream os; os << "\nExpected:\n"; openvdb::ax::ast::print(*expected, true, os); os << "Result:\n"; openvdb::ax::ast::print(*result, true, os); CPPUNIT_FAIL(ERROR_MSG("Mismatching Trees for Declaration code", code) + os.str()); } } }
NVIDIA-Omniverse/ext-openvdb/openvdb_ax/openvdb_ax/test/frontend/TestArrayPack.cc
// Copyright Contributors to the OpenVDB Project // SPDX-License-Identifier: MPL-2.0 #include <openvdb_ax/ast/AST.h> #include <openvdb_ax/ast/Scanners.h> #include <openvdb_ax/ast/PrintTree.h> #include <openvdb_ax/Exceptions.h> #include <openvdb_ax/test/util.h> #include <cppunit/extensions/HelperMacros.h> #include <string> using namespace openvdb::ax::ast; using namespace openvdb::ax::ast::tokens; namespace { static const unittest_util::CodeTests tests = { { "{1, 2, {1,2,3}};", Node::Ptr(new ArrayPack({ new Value<int32_t>(1), new Value<int32_t>(2), new ArrayPack({ new Value<int32_t>(1), new Value<int32_t>(2), new Value<int32_t>(3) }) })) }, { "{1.f,2.0,3l};" , Node::Ptr(new ArrayPack({ new Value<float>(1.0f), new Value<double>(2.0), new Value<int64_t>(3) })) }, { "({1.f,2.0,3l});" , Node::Ptr(new ArrayPack({ new Value<float>(1.0f), new Value<double>(2.0), new Value<int64_t>(3) })) }, { "{{a,b,c}, {d,e,f}, {g,h,i}};", Node::Ptr(new ArrayPack({ new ArrayPack({ new Local("a"), new Local("b"), new Local("c") }), new ArrayPack({ new Local("d"), new Local("e"), new Local("f") }), new ArrayPack({ new Local("g"), new Local("h"), new Local("i") }) })) }, { "{(a),b+1,-c};", Node::Ptr(new ArrayPack({ new Local("a"), new BinaryOperator(new Local("b"), new Value<int32_t>(1), OperatorToken::PLUS), new UnaryOperator(new Local("c"), OperatorToken::MINUS) })) }, { "{@x,++z,true};", Node::Ptr(new ArrayPack({ new Attribute("x", CoreType::FLOAT, true), new Crement(new Local("z"), Crement::Operation::Increment, false), new Value<bool>(true) })) }, { "{@x,z++,\"bar\"};", Node::Ptr(new ArrayPack({ new Attribute("x", CoreType::FLOAT, true), new Crement(new Local("z"), Crement::Operation::Increment, true), new Value<std::string>("bar") })) }, { "{float(x),b=c,c.z};", Node::Ptr(new ArrayPack({ new Cast(new Local("x"), CoreType::FLOAT), new AssignExpression(new Local("b"), new Local("c")), new ArrayUnpack(new Local("c"), new Value<int32_t>(2)) })) }, { "{test(),a[0],b[1,2]};", Node::Ptr(new ArrayPack({ new FunctionCall("test"), new ArrayUnpack(new Local("a"), new Value<int32_t>(0)), new ArrayUnpack(new Local("b"), new Value<int32_t>(1), new Value<int32_t>(2)) })) }, { "{(1), (1,2), (1,2,(3))};", Node::Ptr(new ArrayPack({ new Value<int32_t>(1), new CommaOperator({ new Value<int32_t>(1), new Value<int32_t>(2) }), new CommaOperator({ new Value<int32_t>(1), new Value<int32_t>(2), new Value<int32_t>(3) }) })) }, { "{1,2,3,4,5,6,7,8,9};", Node::Ptr(new ArrayPack({ new Value<int32_t>(1), new Value<int32_t>(2), new Value<int32_t>(3), new Value<int32_t>(4), new Value<int32_t>(5), new Value<int32_t>(6), new Value<int32_t>(7), new Value<int32_t>(8), new Value<int32_t>(9) })) }, { "{ 1, 2, 3, 4, \ 5, 6, 7, 8, \ 9,10,11,12, \ 13,14,15,16 };", Node::Ptr(new ArrayPack({ new Value<int32_t>(1), new Value<int32_t>(2), new Value<int32_t>(3), new Value<int32_t>(4), new Value<int32_t>(5), new Value<int32_t>(6), new Value<int32_t>(7), new Value<int32_t>(8), new Value<int32_t>(9), new Value<int32_t>(10), new Value<int32_t>(11), new Value<int32_t>(12), new Value<int32_t>(13), new Value<int32_t>(14), new Value<int32_t>(15), new Value<int32_t>(16) })) }, }; } class TestArrayPack : public CppUnit::TestCase { public: CPPUNIT_TEST_SUITE(TestArrayPack); CPPUNIT_TEST(testSyntax); CPPUNIT_TEST(testASTNode); CPPUNIT_TEST_SUITE_END(); void testSyntax() { TEST_SYNTAX_PASSES(tests); } void testASTNode(); }; CPPUNIT_TEST_SUITE_REGISTRATION(TestArrayPack); void TestArrayPack::testASTNode() { for (const auto& test : tests) { const std::string& code = test.first; const Node* expected = test.second.get(); const Tree::ConstPtr tree = parse(code.c_str()); CPPUNIT_ASSERT_MESSAGE(ERROR_MSG("No AST returned", code), static_cast<bool>(tree)); // get the first statement const Node* result = tree->child(0)->child(0); CPPUNIT_ASSERT(result); CPPUNIT_ASSERT_MESSAGE(ERROR_MSG("Invalid AST node", code), Node::ArrayPackNode == result->nodetype()); std::vector<const Node*> resultList, expectedList; linearize(*result, resultList); linearize(*expected, expectedList); if (!unittest_util::compareLinearTrees(expectedList, resultList)) { std::ostringstream os; os << "\nExpected:\n"; openvdb::ax::ast::print(*expected, true, os); os << "Result:\n"; openvdb::ax::ast::print(*result, true, os); CPPUNIT_FAIL(ERROR_MSG("Mismatching Trees for Array Pack code", code) + os.str()); } } }
NVIDIA-Omniverse/ext-openvdb/openvdb_ax/openvdb_ax/test/compiler/TestAXRun.cc
// Copyright Contributors to the OpenVDB Project // SPDX-License-Identifier: MPL-2.0 #include <openvdb_ax/ax.h> #include <openvdb_ax/Exceptions.h> #include <openvdb/points/PointDataGrid.h> #include <openvdb/points/PointConversion.h> #include <cppunit/extensions/HelperMacros.h> class TestAXRun : public CppUnit::TestCase { public: CPPUNIT_TEST_SUITE(TestAXRun); CPPUNIT_TEST(singleRun); CPPUNIT_TEST(multiRun); CPPUNIT_TEST_SUITE_END(); void singleRun(); void multiRun(); }; CPPUNIT_TEST_SUITE_REGISTRATION(TestAXRun); void TestAXRun::singleRun() { openvdb::FloatGrid f; f.setName("a"); f.tree().setValueOn({0,0,0}, 0.0f); openvdb::ax::run("@a = 1.0f;", f); CPPUNIT_ASSERT_EQUAL(1.0f, f.tree().getValue({0,0,0})); openvdb::math::Transform::Ptr defaultTransform = openvdb::math::Transform::createLinearTransform(); const std::vector<openvdb::Vec3d> singlePointZero = {openvdb::Vec3d::zero()}; openvdb::points::PointDataGrid::Ptr points = openvdb::points::createPointDataGrid <openvdb::points::NullCodec, openvdb::points::PointDataGrid>(singlePointZero, *defaultTransform); openvdb::ax::run("@a = 1.0f;", *points); const auto leafIter = points->tree().cbeginLeaf(); const auto& descriptor = leafIter->attributeSet().descriptor(); CPPUNIT_ASSERT_EQUAL(size_t(2), descriptor.size()); const size_t idx = descriptor.find("a"); CPPUNIT_ASSERT(idx != openvdb::points::AttributeSet::INVALID_POS); CPPUNIT_ASSERT(descriptor.valueType(idx) == openvdb::typeNameAsString<float>()); openvdb::points::AttributeHandle<float> handle(leafIter->constAttributeArray(idx)); CPPUNIT_ASSERT_EQUAL(1.0f, handle.get(0)); } void TestAXRun::multiRun() { { // test error on points and volumes openvdb::FloatGrid::Ptr f(new openvdb::FloatGrid); openvdb::points::PointDataGrid::Ptr p(new openvdb::points::PointDataGrid); std::vector<openvdb::GridBase::Ptr> v1 { f, p }; CPPUNIT_ASSERT_THROW(openvdb::ax::run("@a = 1.0f;", v1), openvdb::AXCompilerError); std::vector<openvdb::GridBase::Ptr> v2 { p, f }; CPPUNIT_ASSERT_THROW(openvdb::ax::run("@a = 1.0f;", v2), openvdb::AXCompilerError); } { // multi volumes openvdb::FloatGrid::Ptr f1(new openvdb::FloatGrid); openvdb::FloatGrid::Ptr f2(new openvdb::FloatGrid); f1->setName("a"); f2->setName("b"); f1->tree().setValueOn({0,0,0}, 0.0f); f2->tree().setValueOn({0,0,0}, 0.0f); std::vector<openvdb::GridBase::Ptr> v { f1, f2 }; openvdb::ax::run("@a = @b = 1;", v); CPPUNIT_ASSERT_EQUAL(1.0f, f1->tree().getValue({0,0,0})); CPPUNIT_ASSERT_EQUAL(1.0f, f2->tree().getValue({0,0,0})); } { // multi points openvdb::math::Transform::Ptr defaultTransform = openvdb::math::Transform::createLinearTransform(); const std::vector<openvdb::Vec3d> singlePointZero = {openvdb::Vec3d::zero()}; openvdb::points::PointDataGrid::Ptr p1 = openvdb::points::createPointDataGrid <openvdb::points::NullCodec, openvdb::points::PointDataGrid>(singlePointZero, *defaultTransform); openvdb::points::PointDataGrid::Ptr p2 = openvdb::points::createPointDataGrid <openvdb::points::NullCodec, openvdb::points::PointDataGrid>(singlePointZero, *defaultTransform); std::vector<openvdb::GridBase::Ptr> v { p1, p2 }; openvdb::ax::run("@a = @b = 1;", v); const auto leafIter1 = p1->tree().cbeginLeaf(); const auto leafIter2 = p2->tree().cbeginLeaf(); const auto& descriptor1 = leafIter1->attributeSet().descriptor(); const auto& descriptor2 = leafIter1->attributeSet().descriptor(); CPPUNIT_ASSERT_EQUAL(size_t(3), descriptor1.size()); CPPUNIT_ASSERT_EQUAL(size_t(3), descriptor2.size()); const size_t idx1 = descriptor1.find("a"); CPPUNIT_ASSERT_EQUAL(idx1, descriptor2.find("a")); const size_t idx2 = descriptor1.find("b"); CPPUNIT_ASSERT_EQUAL(idx2, descriptor2.find("b")); CPPUNIT_ASSERT(idx1 != openvdb::points::AttributeSet::INVALID_POS); CPPUNIT_ASSERT(idx2 != openvdb::points::AttributeSet::INVALID_POS); CPPUNIT_ASSERT(descriptor1.valueType(idx1) == openvdb::typeNameAsString<float>()); CPPUNIT_ASSERT(descriptor1.valueType(idx2) == openvdb::typeNameAsString<float>()); CPPUNIT_ASSERT(descriptor2.valueType(idx1) == openvdb::typeNameAsString<float>()); CPPUNIT_ASSERT(descriptor2.valueType(idx2) == openvdb::typeNameAsString<float>()); openvdb::points::AttributeHandle<float> handle(leafIter1->constAttributeArray(idx1)); CPPUNIT_ASSERT_EQUAL(1.0f, handle.get(0)); handle = openvdb::points::AttributeHandle<float>(leafIter1->constAttributeArray(idx2)); CPPUNIT_ASSERT_EQUAL(1.0f, handle.get(0)); handle = openvdb::points::AttributeHandle<float>(leafIter2->constAttributeArray(idx1)); CPPUNIT_ASSERT_EQUAL(1.0f, handle.get(0)); handle = openvdb::points::AttributeHandle<float>(leafIter2->constAttributeArray(idx2)); CPPUNIT_ASSERT_EQUAL(1.0f, handle.get(0)); } }
NVIDIA-Omniverse/ext-openvdb/openvdb_ax/openvdb_ax/test/compiler/TestVolumeExecutable.cc
// Copyright Contributors to the OpenVDB Project // SPDX-License-Identifier: MPL-2.0 #include <openvdb_ax/compiler/Compiler.h> #include <openvdb_ax/compiler/VolumeExecutable.h> #include <cppunit/extensions/HelperMacros.h> #include <llvm/ExecutionEngine/ExecutionEngine.h> class TestVolumeExecutable : public CppUnit::TestCase { public: CPPUNIT_TEST_SUITE(TestVolumeExecutable); CPPUNIT_TEST(testConstructionDestruction); CPPUNIT_TEST(testCreateMissingGrids); CPPUNIT_TEST(testTreeExecutionLevel); CPPUNIT_TEST(testCompilerCases); CPPUNIT_TEST_SUITE_END(); void testConstructionDestruction(); void testCreateMissingGrids(); void testTreeExecutionLevel(); void testCompilerCases(); }; CPPUNIT_TEST_SUITE_REGISTRATION(TestVolumeExecutable); void TestVolumeExecutable::testConstructionDestruction() { // Test the building and teardown of executable objects. This is primarily to test // the destruction of Context and ExecutionEngine LLVM objects. These must be destructed // in the correct order (ExecutionEngine, then Context) otherwise LLVM will crash // must be initialized, otherwise construction/destruction of llvm objects won't // exhibit correct behaviour CPPUNIT_ASSERT(openvdb::ax::isInitialized()); std::shared_ptr<llvm::LLVMContext> C(new llvm::LLVMContext); std::unique_ptr<llvm::Module> M(new llvm::Module("test_module", *C)); std::shared_ptr<const llvm::ExecutionEngine> E(llvm::EngineBuilder(std::move(M)) .setEngineKind(llvm::EngineKind::JIT) .create()); CPPUNIT_ASSERT(!M); CPPUNIT_ASSERT(E); std::weak_ptr<llvm::LLVMContext> wC = C; std::weak_ptr<const llvm::ExecutionEngine> wE = E; // Basic construction openvdb::ax::ast::Tree tree; openvdb::ax::AttributeRegistry::ConstPtr emptyReg = openvdb::ax::AttributeRegistry::create(tree); openvdb::ax::VolumeExecutable::Ptr volumeExecutable (new openvdb::ax::VolumeExecutable(C, E, emptyReg, nullptr, {})); CPPUNIT_ASSERT_EQUAL(2, int(wE.use_count())); CPPUNIT_ASSERT_EQUAL(2, int(wC.use_count())); C.reset(); E.reset(); CPPUNIT_ASSERT_EQUAL(1, int(wE.use_count())); CPPUNIT_ASSERT_EQUAL(1, int(wC.use_count())); // test destruction volumeExecutable.reset(); CPPUNIT_ASSERT_EQUAL(0, int(wE.use_count())); CPPUNIT_ASSERT_EQUAL(0, int(wC.use_count())); } void TestVolumeExecutable::testCreateMissingGrids() { openvdb::ax::Compiler::UniquePtr compiler = openvdb::ax::Compiler::create(); openvdb::ax::VolumeExecutable::Ptr executable = compiler->compile<openvdb::ax::VolumeExecutable>("@[email protected];"); CPPUNIT_ASSERT(executable); executable->setCreateMissing(false); executable->setValueIterator(openvdb::ax::VolumeExecutable::IterType::ON); openvdb::GridPtrVec grids; CPPUNIT_ASSERT_THROW(executable->execute(grids), openvdb::AXExecutionError); CPPUNIT_ASSERT(grids.empty()); executable->setCreateMissing(true); executable->setValueIterator(openvdb::ax::VolumeExecutable::IterType::ON); executable->execute(grids); openvdb::math::Transform::Ptr defaultTransform = openvdb::math::Transform::createLinearTransform(); CPPUNIT_ASSERT_EQUAL(size_t(2), grids.size()); CPPUNIT_ASSERT(grids[0]->getName() == "b"); CPPUNIT_ASSERT(grids[0]->isType<openvdb::Vec3fGrid>()); CPPUNIT_ASSERT(grids[0]->empty()); CPPUNIT_ASSERT(grids[0]->transform() == *defaultTransform); CPPUNIT_ASSERT(grids[1]->getName() == "a"); CPPUNIT_ASSERT(grids[1]->isType<openvdb::FloatGrid>()); CPPUNIT_ASSERT(grids[1]->empty()); CPPUNIT_ASSERT(grids[1]->transform() == *defaultTransform); } void TestVolumeExecutable::testTreeExecutionLevel() { openvdb::ax::Compiler::UniquePtr compiler = openvdb::ax::Compiler::create(); openvdb::ax::VolumeExecutable::Ptr executable = compiler->compile<openvdb::ax::VolumeExecutable>("f@test = 1.0f;"); CPPUNIT_ASSERT(executable); using NodeT0 = openvdb::FloatGrid::Accessor::NodeT0; using NodeT1 = openvdb::FloatGrid::Accessor::NodeT1; using NodeT2 = openvdb::FloatGrid::Accessor::NodeT2; openvdb::FloatGrid test; test.setName("test"); // NodeT0 tile test.tree().addTile(1, openvdb::Coord(0), -2.0f, /*active*/true); CPPUNIT_ASSERT_EQUAL(openvdb::Index32(0), test.tree().leafCount()); CPPUNIT_ASSERT_EQUAL(openvdb::Index64(1), test.tree().activeTileCount()); CPPUNIT_ASSERT_EQUAL(openvdb::Index64(NodeT0::NUM_VOXELS), test.tree().activeVoxelCount()); CPPUNIT_ASSERT_EQUAL(-2.0f, test.tree().getValue(openvdb::Coord(0))); // default is leaf nodes, expect no change executable->execute(test); CPPUNIT_ASSERT_EQUAL(openvdb::Index32(0), test.tree().leafCount()); CPPUNIT_ASSERT_EQUAL(openvdb::Index64(1), test.tree().activeTileCount()); CPPUNIT_ASSERT_EQUAL(openvdb::Index64(NodeT0::NUM_VOXELS), test.tree().activeVoxelCount()); CPPUNIT_ASSERT_EQUAL(-2.0f, test.tree().getValue(openvdb::Coord(0))); executable->setTreeExecutionLevel(1); executable->execute(test); CPPUNIT_ASSERT_EQUAL(openvdb::Index32(0), test.tree().leafCount()); CPPUNIT_ASSERT_EQUAL(openvdb::Index64(1), test.tree().activeTileCount()); CPPUNIT_ASSERT_EQUAL(openvdb::Index64(NodeT0::NUM_VOXELS), test.tree().activeVoxelCount()); CPPUNIT_ASSERT_EQUAL(1.0f, test.tree().getValue(openvdb::Coord(0))); // NodeT1 tile test.tree().addTile(2, openvdb::Coord(0), -2.0f, /*active*/true); // level is set to 1, expect no change executable->execute(test); CPPUNIT_ASSERT_EQUAL(openvdb::Index32(0), test.tree().leafCount()); CPPUNIT_ASSERT_EQUAL(openvdb::Index64(1), test.tree().activeTileCount()); CPPUNIT_ASSERT_EQUAL(openvdb::Index64(NodeT1::NUM_VOXELS), test.tree().activeVoxelCount()); CPPUNIT_ASSERT_EQUAL(-2.0f, test.tree().getValue(openvdb::Coord(0))); executable->setTreeExecutionLevel(2); executable->execute(test); CPPUNIT_ASSERT_EQUAL(openvdb::Index32(0), test.tree().leafCount()); CPPUNIT_ASSERT_EQUAL(openvdb::Index64(1), test.tree().activeTileCount()); CPPUNIT_ASSERT_EQUAL(openvdb::Index64(NodeT1::NUM_VOXELS), test.tree().activeVoxelCount()); CPPUNIT_ASSERT_EQUAL(1.0f, test.tree().getValue(openvdb::Coord(0))); // NodeT2 tile test.tree().addTile(3, openvdb::Coord(0), -2.0f, /*active*/true); // level is set to 2, expect no change executable->execute(test); CPPUNIT_ASSERT_EQUAL(openvdb::Index32(0), test.tree().leafCount()); CPPUNIT_ASSERT_EQUAL(openvdb::Index64(1), test.tree().activeTileCount()); CPPUNIT_ASSERT_EQUAL(openvdb::Index64(NodeT2::NUM_VOXELS), test.tree().activeVoxelCount()); CPPUNIT_ASSERT_EQUAL(-2.0f, test.tree().getValue(openvdb::Coord(0))); executable->setTreeExecutionLevel(3); executable->execute(test); CPPUNIT_ASSERT_EQUAL(openvdb::Index32(0), test.tree().leafCount()); CPPUNIT_ASSERT_EQUAL(openvdb::Index64(1), test.tree().activeTileCount()); CPPUNIT_ASSERT_EQUAL(openvdb::Index64(NodeT2::NUM_VOXELS), test.tree().activeVoxelCount()); CPPUNIT_ASSERT_EQUAL(1.0f, test.tree().getValue(openvdb::Coord(0))); // test higher values throw CPPUNIT_ASSERT_THROW(executable->setTreeExecutionLevel(4), openvdb::RuntimeError); } void TestVolumeExecutable::testCompilerCases() { openvdb::ax::Compiler::UniquePtr compiler = openvdb::ax::Compiler::create(); CPPUNIT_ASSERT(compiler); { // with string only CPPUNIT_ASSERT(static_cast<bool>(compiler->compile<openvdb::ax::VolumeExecutable>("int i;"))); CPPUNIT_ASSERT_THROW(compiler->compile<openvdb::ax::VolumeExecutable>("i;"), openvdb::AXCompilerError); CPPUNIT_ASSERT_THROW(compiler->compile<openvdb::ax::VolumeExecutable>("i"), openvdb::AXCompilerError); // with AST only auto ast = openvdb::ax::ast::parse("i;"); CPPUNIT_ASSERT_THROW(compiler->compile<openvdb::ax::VolumeExecutable>(*ast), openvdb::AXCompilerError); } openvdb::ax::Logger logger([](const std::string&) {}); // using string and logger { openvdb::ax::VolumeExecutable::Ptr executable = compiler->compile<openvdb::ax::VolumeExecutable>("", logger); // empty CPPUNIT_ASSERT(executable); } logger.clear(); { openvdb::ax::VolumeExecutable::Ptr executable = compiler->compile<openvdb::ax::VolumeExecutable>("i;", logger); // undeclared variable error CPPUNIT_ASSERT(!executable); CPPUNIT_ASSERT(logger.hasError()); logger.clear(); openvdb::ax::VolumeExecutable::Ptr executable2 = compiler->compile<openvdb::ax::VolumeExecutable>("i", logger); // expected ; error (parser) CPPUNIT_ASSERT(!executable2); CPPUNIT_ASSERT(logger.hasError()); } logger.clear(); { openvdb::ax::VolumeExecutable::Ptr executable = compiler->compile<openvdb::ax::VolumeExecutable>("int i = 18446744073709551615;", logger); // warning CPPUNIT_ASSERT(executable); CPPUNIT_ASSERT(logger.hasWarning()); } // using syntax tree and logger logger.clear(); { openvdb::ax::ast::Tree::ConstPtr tree = openvdb::ax::ast::parse("", logger); CPPUNIT_ASSERT(tree); openvdb::ax::VolumeExecutable::Ptr executable = compiler->compile<openvdb::ax::VolumeExecutable>(*tree, logger); // empty CPPUNIT_ASSERT(executable); logger.clear(); // no tree for line col numbers openvdb::ax::VolumeExecutable::Ptr executable2 = compiler->compile<openvdb::ax::VolumeExecutable>(*tree, logger); // empty CPPUNIT_ASSERT(executable2); } logger.clear(); { openvdb::ax::ast::Tree::ConstPtr tree = openvdb::ax::ast::parse("i;", logger); CPPUNIT_ASSERT(tree); openvdb::ax::VolumeExecutable::Ptr executable = compiler->compile<openvdb::ax::VolumeExecutable>(*tree, logger); // undeclared variable error CPPUNIT_ASSERT(!executable); CPPUNIT_ASSERT(logger.hasError()); logger.clear(); // no tree for line col numbers openvdb::ax::VolumeExecutable::Ptr executable2 = compiler->compile<openvdb::ax::VolumeExecutable>(*tree, logger); // undeclared variable error CPPUNIT_ASSERT(!executable2); CPPUNIT_ASSERT(logger.hasError()); } logger.clear(); { openvdb::ax::ast::Tree::ConstPtr tree = openvdb::ax::ast::parse("int i = 18446744073709551615;", logger); CPPUNIT_ASSERT(tree); openvdb::ax::VolumeExecutable::Ptr executable = compiler->compile<openvdb::ax::VolumeExecutable>(*tree, logger); // warning CPPUNIT_ASSERT(executable); CPPUNIT_ASSERT(logger.hasWarning()); logger.clear(); // no tree for line col numbers openvdb::ax::VolumeExecutable::Ptr executable2 = compiler->compile<openvdb::ax::VolumeExecutable>(*tree, logger); // warning CPPUNIT_ASSERT(executable2); CPPUNIT_ASSERT(logger.hasWarning()); } logger.clear(); // with copied tree { openvdb::ax::ast::Tree::ConstPtr tree = openvdb::ax::ast::parse("", logger); openvdb::ax::VolumeExecutable::Ptr executable = compiler->compile<openvdb::ax::VolumeExecutable>(*(tree->copy()), logger); // empty CPPUNIT_ASSERT(executable); } logger.clear(); { openvdb::ax::ast::Tree::ConstPtr tree = openvdb::ax::ast::parse("i;", logger); openvdb::ax::VolumeExecutable::Ptr executable = compiler->compile<openvdb::ax::VolumeExecutable>(*(tree->copy()), logger); // undeclared variable error CPPUNIT_ASSERT(!executable); CPPUNIT_ASSERT(logger.hasError()); } logger.clear(); { openvdb::ax::ast::Tree::ConstPtr tree = openvdb::ax::ast::parse("int i = 18446744073709551615;", logger); openvdb::ax::VolumeExecutable::Ptr executable = compiler->compile<openvdb::ax::VolumeExecutable>(*(tree->copy()), logger); // warning CPPUNIT_ASSERT(executable); CPPUNIT_ASSERT(logger.hasWarning()); } logger.clear(); }
NVIDIA-Omniverse/ext-openvdb/openvdb_ax/openvdb_ax/test/compiler/TestPointExecutable.cc
// Copyright Contributors to the OpenVDB Project // SPDX-License-Identifier: MPL-2.0 #include <openvdb_ax/compiler/Compiler.h> #include <openvdb_ax/compiler/PointExecutable.h> #include <openvdb/points/PointDataGrid.h> #include <openvdb/points/PointConversion.h> #include <openvdb/points/PointAttribute.h> #include <openvdb/points/PointGroup.h> #include <cppunit/extensions/HelperMacros.h> #include <llvm/ExecutionEngine/ExecutionEngine.h> class TestPointExecutable : public CppUnit::TestCase { public: CPPUNIT_TEST_SUITE(TestPointExecutable); CPPUNIT_TEST(testConstructionDestruction); CPPUNIT_TEST(testCreateMissingAttributes); CPPUNIT_TEST(testGroupExecution); CPPUNIT_TEST(testCompilerCases); CPPUNIT_TEST_SUITE_END(); void testConstructionDestruction(); void testCreateMissingAttributes(); void testGroupExecution(); void testCompilerCases(); }; CPPUNIT_TEST_SUITE_REGISTRATION(TestPointExecutable); void TestPointExecutable::testConstructionDestruction() { // Test the building and teardown of executable objects. This is primarily to test // the destruction of Context and ExecutionEngine LLVM objects. These must be destructed // in the correct order (ExecutionEngine, then Context) otherwise LLVM will crash // must be initialized, otherwise construction/destruction of llvm objects won't // exhibit correct behaviour CPPUNIT_ASSERT(openvdb::ax::isInitialized()); std::shared_ptr<llvm::LLVMContext> C(new llvm::LLVMContext); std::unique_ptr<llvm::Module> M(new llvm::Module("test_module", *C)); std::shared_ptr<const llvm::ExecutionEngine> E(llvm::EngineBuilder(std::move(M)) .setEngineKind(llvm::EngineKind::JIT) .create()); CPPUNIT_ASSERT(!M); CPPUNIT_ASSERT(E); std::weak_ptr<llvm::LLVMContext> wC = C; std::weak_ptr<const llvm::ExecutionEngine> wE = E; // Basic construction openvdb::ax::ast::Tree tree; openvdb::ax::AttributeRegistry::ConstPtr emptyReg = openvdb::ax::AttributeRegistry::create(tree); openvdb::ax::PointExecutable::Ptr pointExecutable (new openvdb::ax::PointExecutable(C, E, emptyReg, nullptr, {})); CPPUNIT_ASSERT_EQUAL(2, int(wE.use_count())); CPPUNIT_ASSERT_EQUAL(2, int(wC.use_count())); C.reset(); E.reset(); CPPUNIT_ASSERT_EQUAL(1, int(wE.use_count())); CPPUNIT_ASSERT_EQUAL(1, int(wC.use_count())); // test destruction pointExecutable.reset(); CPPUNIT_ASSERT_EQUAL(0, int(wE.use_count())); CPPUNIT_ASSERT_EQUAL(0, int(wC.use_count())); } void TestPointExecutable::testCreateMissingAttributes() { openvdb::math::Transform::Ptr defaultTransform = openvdb::math::Transform::createLinearTransform(); const std::vector<openvdb::Vec3d> singlePointZero = {openvdb::Vec3d::zero()}; openvdb::points::PointDataGrid::Ptr grid = openvdb::points::createPointDataGrid <openvdb::points::NullCodec, openvdb::points::PointDataGrid>(singlePointZero, *defaultTransform); openvdb::ax::Compiler::UniquePtr compiler = openvdb::ax::Compiler::create(); openvdb::ax::PointExecutable::Ptr executable = compiler->compile<openvdb::ax::PointExecutable>("@[email protected];"); CPPUNIT_ASSERT(executable); executable->setCreateMissing(false); CPPUNIT_ASSERT_THROW(executable->execute(*grid), openvdb::AXExecutionError); executable->setCreateMissing(true); executable->execute(*grid); const auto leafIter = grid->tree().cbeginLeaf(); const auto& descriptor = leafIter->attributeSet().descriptor(); CPPUNIT_ASSERT_EQUAL(size_t(3), descriptor.size()); const size_t bIdx = descriptor.find("b"); CPPUNIT_ASSERT(bIdx != openvdb::points::AttributeSet::INVALID_POS); CPPUNIT_ASSERT(descriptor.valueType(bIdx) == openvdb::typeNameAsString<openvdb::Vec3f>()); openvdb::points::AttributeHandle<openvdb::Vec3f>::Ptr bHandle = openvdb::points::AttributeHandle<openvdb::Vec3f>::create(leafIter->constAttributeArray(bIdx)); CPPUNIT_ASSERT(bHandle->get(0) == openvdb::Vec3f::zero()); const size_t aIdx = descriptor.find("a"); CPPUNIT_ASSERT(aIdx != openvdb::points::AttributeSet::INVALID_POS); CPPUNIT_ASSERT(descriptor.valueType(aIdx) == openvdb::typeNameAsString<float>()); openvdb::points::AttributeHandle<float>::Ptr aHandle = openvdb::points::AttributeHandle<float>::create(leafIter->constAttributeArray(aIdx)); CPPUNIT_ASSERT(aHandle->get(0) == 0.0f); } void TestPointExecutable::testGroupExecution() { openvdb::math::Transform::Ptr defaultTransform = openvdb::math::Transform::createLinearTransform(0.1); // 4 points in 4 leaf nodes const std::vector<openvdb::Vec3d> positions = { {0,0,0}, {1,1,1}, {2,2,2}, {3,3,3}, }; openvdb::points::PointDataGrid::Ptr grid = openvdb::points::createPointDataGrid <openvdb::points::NullCodec, openvdb::points::PointDataGrid> (positions, *defaultTransform); // check the values of "a" auto checkValues = [&](const int expected) { auto leafIter = grid->tree().cbeginLeaf(); CPPUNIT_ASSERT(leafIter); const auto& descriptor = leafIter->attributeSet().descriptor(); const size_t aIdx = descriptor.find("a"); CPPUNIT_ASSERT(aIdx != openvdb::points::AttributeSet::INVALID_POS); for (; leafIter; ++leafIter) { openvdb::points::AttributeHandle<int> handle(leafIter->constAttributeArray(aIdx)); CPPUNIT_ASSERT(handle.size() == 1); CPPUNIT_ASSERT_EQUAL(expected, handle.get(0)); } }; openvdb::points::appendAttribute<int>(grid->tree(), "a", 0); openvdb::ax::Compiler::UniquePtr compiler = openvdb::ax::Compiler::create(); openvdb::ax::PointExecutable::Ptr executable = compiler->compile<openvdb::ax::PointExecutable>("i@a=1;"); CPPUNIT_ASSERT(executable); const std::string group = "test"; // non existent group executable->setGroupExecution(group); CPPUNIT_ASSERT_THROW(executable->execute(*grid), openvdb::LookupError); checkValues(0); openvdb::points::appendGroup(grid->tree(), group); // false group executable->execute(*grid); checkValues(0); openvdb::points::setGroup(grid->tree(), group, true); // true group executable->execute(*grid); checkValues(1); } void TestPointExecutable::testCompilerCases() { openvdb::ax::Compiler::UniquePtr compiler = openvdb::ax::Compiler::create(); CPPUNIT_ASSERT(compiler); { // with string only CPPUNIT_ASSERT(static_cast<bool>(compiler->compile<openvdb::ax::PointExecutable>("int i;"))); CPPUNIT_ASSERT_THROW(compiler->compile<openvdb::ax::PointExecutable>("i;"), openvdb::AXCompilerError); CPPUNIT_ASSERT_THROW(compiler->compile<openvdb::ax::PointExecutable>("i"), openvdb::AXCompilerError); // with AST only auto ast = openvdb::ax::ast::parse("i;"); CPPUNIT_ASSERT_THROW(compiler->compile<openvdb::ax::PointExecutable>(*ast), openvdb::AXCompilerError); } openvdb::ax::Logger logger([](const std::string&) {}); // using string and logger { openvdb::ax::PointExecutable::Ptr executable = compiler->compile<openvdb::ax::PointExecutable>("", logger); // empty CPPUNIT_ASSERT(executable); } logger.clear(); { openvdb::ax::PointExecutable::Ptr executable = compiler->compile<openvdb::ax::PointExecutable>("i;", logger); // undeclared variable error CPPUNIT_ASSERT(!executable); CPPUNIT_ASSERT(logger.hasError()); logger.clear(); openvdb::ax::PointExecutable::Ptr executable2 = compiler->compile<openvdb::ax::PointExecutable>("i", logger); // expected ; error (parser) CPPUNIT_ASSERT(!executable2); CPPUNIT_ASSERT(logger.hasError()); } logger.clear(); { openvdb::ax::PointExecutable::Ptr executable = compiler->compile<openvdb::ax::PointExecutable>("int i = 18446744073709551615;", logger); // warning CPPUNIT_ASSERT(executable); CPPUNIT_ASSERT(logger.hasWarning()); } // using syntax tree and logger logger.clear(); { openvdb::ax::ast::Tree::ConstPtr tree = openvdb::ax::ast::parse("", logger); CPPUNIT_ASSERT(tree); openvdb::ax::PointExecutable::Ptr executable = compiler->compile<openvdb::ax::PointExecutable>(*tree, logger); // empty CPPUNIT_ASSERT(executable); logger.clear(); // no tree for line col numbers openvdb::ax::PointExecutable::Ptr executable2 = compiler->compile<openvdb::ax::PointExecutable>(*tree, logger); // empty CPPUNIT_ASSERT(executable2); } logger.clear(); { openvdb::ax::ast::Tree::ConstPtr tree = openvdb::ax::ast::parse("i;", logger); CPPUNIT_ASSERT(tree); openvdb::ax::PointExecutable::Ptr executable = compiler->compile<openvdb::ax::PointExecutable>(*tree, logger); // undeclared variable error CPPUNIT_ASSERT(!executable); CPPUNIT_ASSERT(logger.hasError()); logger.clear(); // no tree for line col numbers openvdb::ax::PointExecutable::Ptr executable2 = compiler->compile<openvdb::ax::PointExecutable>(*tree, logger); // undeclared variable error CPPUNIT_ASSERT(!executable2); CPPUNIT_ASSERT(logger.hasError()); } logger.clear(); { openvdb::ax::ast::Tree::ConstPtr tree = openvdb::ax::ast::parse("int i = 18446744073709551615;", logger); CPPUNIT_ASSERT(tree); openvdb::ax::PointExecutable::Ptr executable = compiler->compile<openvdb::ax::PointExecutable>(*tree, logger); // warning CPPUNIT_ASSERT(executable); CPPUNIT_ASSERT(logger.hasWarning()); logger.clear(); // no tree for line col numbers openvdb::ax::PointExecutable::Ptr executable2 = compiler->compile<openvdb::ax::PointExecutable>(*tree, logger); // warning CPPUNIT_ASSERT(executable2); CPPUNIT_ASSERT(logger.hasWarning()); } logger.clear(); // with copied tree { openvdb::ax::ast::Tree::ConstPtr tree = openvdb::ax::ast::parse("", logger); openvdb::ax::PointExecutable::Ptr executable = compiler->compile<openvdb::ax::PointExecutable>(*(tree->copy()), logger); // empty CPPUNIT_ASSERT(executable); } logger.clear(); { openvdb::ax::ast::Tree::ConstPtr tree = openvdb::ax::ast::parse("i;", logger); openvdb::ax::PointExecutable::Ptr executable = compiler->compile<openvdb::ax::PointExecutable>(*(tree->copy()), logger); // undeclared variable error CPPUNIT_ASSERT(!executable); } logger.clear(); { openvdb::ax::ast::Tree::ConstPtr tree = openvdb::ax::ast::parse("int i = 18446744073709551615;", logger); openvdb::ax::PointExecutable::Ptr executable = compiler->compile<openvdb::ax::PointExecutable>(*(tree->copy()), logger); // warning CPPUNIT_ASSERT(executable); } logger.clear(); }
NVIDIA-Omniverse/ext-openvdb/openvdb_ax/openvdb_ax/test/ast/TestScanners.cc
// Copyright Contributors to the OpenVDB Project // SPDX-License-Identifier: MPL-2.0 #include <openvdb_ax/ast/AST.h> #include <openvdb_ax/ast/Scanners.h> #include <openvdb_ax/test/util.h> #include <cppunit/extensions/HelperMacros.h> #include <string> using namespace openvdb::ax::ast; using namespace openvdb::ax::ast::tokens; namespace { // No dependencies // - use @a once (read), no other variables const std::vector<std::string> none = { "@a;", "@a+1;", "@a=1;", "@a=func(5);", "-@a;", "@a[0]=1;", "if(true) @a = 1;", "if(@a) a=1;", "if (@e) if (@b) if (@c) @a;", "@b = c ? : @a;", "@a ? : c = 1;", "for (@a; @b; @c) ;", "while (@a) ;", "for(;true;) @a = 1;" }; // Self dependencies // - use @a potentially multiple times (read/write), no other variables const std::vector<std::string> self = { "@a=@a;", "@a+=1;", "++@a;", "@a--;", "func(@a);", "--@a + 1;", "if(@a) @a = 1;", "if(@a) ; else @a = 1;", "@a ? : @a = 2;", "for (@b;@a;@c) @a = 0;", "while(@a) @a = 1;" }; // Code where @a should have a direct dependency on @b only // - use @a once (read/write), use @b once const std::vector<std::string> direct = { "@a=@b;", "@a=-@b;", "@a=@b;", "@a=1+@b;", "@a=func(@b);", "@a=++@b;", "if(@b) @a=1;", "if(@b) {} else { @a=1; }", "@b ? @a = 1 : 0;", "@b ? : @a = 1;", "for (;@b;) @a = 1;", "while (@b) @a = 1;" }; // Code where @a should have a direct dependency on @b only // - use @a once (read/write), use @b once, b a vector const std::vector<std::string> directvec = { "@[email protected];", "@a=v@b[0];", "@[email protected] + 1;", "@a=v@b[0] * 3;", "if (v@b[0]) @a = 3;", }; // Code where @a should have dependencies on @b and c (c always first) const std::vector<std::string> indirect = { "c=@b; @a=c;", "c=@b; @a=c[0];", "c = {@b,1,2}; @a=c;", "int c=@b; @a=c;", "int c; c=@b; @a=c;", "if (c = @b) @a = c;", "(c = @b) ? @a=c : 0;", "(c = @b) ? : @a=c;", "for(int c = @b; true; e) @a = c;", "for(int c = @b;; @a = c) ;", "for(int c = @b; c; e) @a = c;", "for(c = @b; c; e) @a = c;", "int c; for(c = @b; c; e) @a = c;", "for(; c = @b;) @a = c;", "while(int c = @b) @a = c;", }; } class TestScanners : public CppUnit::TestCase { public: CPPUNIT_TEST_SUITE(TestScanners); CPPUNIT_TEST(testVisitNodeType); CPPUNIT_TEST(testFirstLastLocation); CPPUNIT_TEST(testAttributeDependencyTokens); // CPPUNIT_TEST(testVariableDependencies); CPPUNIT_TEST_SUITE_END(); void testVisitNodeType(); void testFirstLastLocation(); void testAttributeDependencyTokens(); // void testVariableDependencies(); }; CPPUNIT_TEST_SUITE_REGISTRATION(TestScanners); void TestScanners::testVisitNodeType() { size_t count = 0; auto counter = [&](const Node&) -> bool { ++count; return true; }; // "int64@a;" Node::Ptr node(new Attribute("a", CoreType::INT64)); visitNodeType<Node>(*node, counter); CPPUNIT_ASSERT_EQUAL(size_t(1), count); count = 0; visitNodeType<Local>(*node, counter); CPPUNIT_ASSERT_EQUAL(size_t(0), count); count = 0; visitNodeType<Variable>(*node, counter); CPPUNIT_ASSERT_EQUAL(size_t(1), count); count = 0; visitNodeType<Attribute>(*node, counter); CPPUNIT_ASSERT_EQUAL(size_t(1), count); // "{1.0f, 2.0, 3};" node.reset(new ArrayPack( { new Value<float>(1.0f), new Value<double>(2.0), new Value<int64_t>(3) })); count = 0; visitNodeType<Node>(*node, counter); CPPUNIT_ASSERT_EQUAL(size_t(4), count); count = 0; visitNodeType<Local>(*node, counter); CPPUNIT_ASSERT_EQUAL(size_t(0), count); count = 0; visitNodeType<ValueBase>(*node, counter); CPPUNIT_ASSERT_EQUAL(size_t(3), count); count = 0; visitNodeType<ArrayPack>(*node, counter); CPPUNIT_ASSERT_EQUAL(size_t(1), count); count = 0; visitNodeType<Expression>(*node, counter); CPPUNIT_ASSERT_EQUAL(size_t(4), count); count = 0; visitNodeType<Statement>(*node, counter); CPPUNIT_ASSERT_EQUAL(size_t(4), count); // "@a += [email protected] = x %= 1;" // @note 9 explicit nodes node.reset(new AssignExpression( new Attribute("a", CoreType::FLOAT, true), new AssignExpression( new ArrayUnpack( new Attribute("b", CoreType::VEC3F), new Value<int32_t>(0) ), new AssignExpression( new Local("x"), new Value<int32_t>(1), OperatorToken::MODULO ) ), OperatorToken::PLUS )); count = 0; visitNodeType<Node>(*node, counter); CPPUNIT_ASSERT_EQUAL(size_t(9), count); count = 0; visitNodeType<Local>(*node, counter); CPPUNIT_ASSERT_EQUAL(size_t(1), count); count = 0; visitNodeType<Attribute>(*node, counter); CPPUNIT_ASSERT_EQUAL(size_t(2), count); count = 0; visitNodeType<Value<int>>(*node, counter); CPPUNIT_ASSERT_EQUAL(size_t(2), count); count = 0; visitNodeType<ArrayUnpack>(*node, counter); CPPUNIT_ASSERT_EQUAL(size_t(1), count); count = 0; visitNodeType<AssignExpression>(*node, counter); CPPUNIT_ASSERT_EQUAL(size_t(3), count); count = 0; visitNodeType<Expression>(*node, counter); CPPUNIT_ASSERT_EQUAL(size_t(9), count); } void TestScanners::testFirstLastLocation() { // The list of above code sets which are expected to have the same // first and last use of @a. const std::vector<const std::vector<std::string>*> snippets { &none, &direct, &indirect }; for (const auto& samples : snippets) { for (const std::string& code : *samples) { const Tree::ConstPtr tree = parse(code.c_str()); CPPUNIT_ASSERT(tree); const Variable* first = firstUse(*tree, "@a"); const Variable* last = lastUse(*tree, "@a"); CPPUNIT_ASSERT_MESSAGE(ERROR_MSG("Unable to locate first @a AST node", code), first); CPPUNIT_ASSERT_MESSAGE(ERROR_MSG("Unable to locate last @a AST node", code), last); CPPUNIT_ASSERT_MESSAGE(ERROR_MSG("Invalid first/last AST node comparison", code), first == last); } } // Test some common edge cases // @a = @a; Node::Ptr node(new AssignExpression( new Attribute("a", CoreType::FLOAT), new Attribute("a", CoreType::FLOAT))); const Node* expectedFirst = static_cast<AssignExpression*>(node.get())->lhs(); const Node* expectedLast = static_cast<AssignExpression*>(node.get())->rhs(); CPPUNIT_ASSERT(expectedFirst != expectedLast); const Node* first = firstUse(*node, "@a"); const Node* last = lastUse(*node, "@a"); CPPUNIT_ASSERT_EQUAL_MESSAGE(ERROR_MSG("Unexpected location of @a AST node", "@a=@a"), first, expectedFirst); CPPUNIT_ASSERT_EQUAL_MESSAGE(ERROR_MSG("Unexpected location of @a AST node", "@a=@a"), last, expectedLast); // for(@a;@a;@a) { @a; } node.reset(new Loop( tokens::FOR, new Attribute("a", CoreType::FLOAT), new Block(new Attribute("a", CoreType::FLOAT)), new Attribute("a", CoreType::FLOAT), new Attribute("a", CoreType::FLOAT) )); expectedFirst = static_cast<Loop*>(node.get())->initial(); expectedLast = static_cast<Loop*>(node.get())->body()->child(0); CPPUNIT_ASSERT(expectedFirst != expectedLast); first = firstUse(*node, "@a"); last = lastUse(*node, "@a"); CPPUNIT_ASSERT_EQUAL_MESSAGE(ERROR_MSG("Unexpected location of @a AST node", "for(@a;@a;@a) { @a; }"), first, expectedFirst); CPPUNIT_ASSERT_EQUAL_MESSAGE(ERROR_MSG("Unexpected location of @a AST node", "for(@a;@a;@a) { @a; }"), last, expectedLast); // do { @a; } while(@a); node.reset(new Loop( tokens::DO, new Attribute("a", CoreType::FLOAT), new Block(new Attribute("a", CoreType::FLOAT)), nullptr, nullptr )); expectedFirst = static_cast<Loop*>(node.get())->body()->child(0); expectedLast = static_cast<Loop*>(node.get())->condition(); CPPUNIT_ASSERT(expectedFirst != expectedLast); first = firstUse(*node, "@a"); last = lastUse(*node, "@a"); CPPUNIT_ASSERT_EQUAL_MESSAGE(ERROR_MSG("Unexpected location of @a AST node", "do { @a; } while(@a);"), first, expectedFirst); CPPUNIT_ASSERT_EQUAL_MESSAGE(ERROR_MSG("Unexpected location of @a AST node", "do { @a; } while(@a);"), last, expectedLast); // if (@a) {} else if (@a) {} else { @a; } node.reset(new ConditionalStatement( new Attribute("a", CoreType::FLOAT), new Block(), new Block( new ConditionalStatement( new Attribute("a", CoreType::FLOAT), new Block(), new Block(new Attribute("a", CoreType::FLOAT)) ) ) )); expectedFirst = static_cast<ConditionalStatement*>(node.get())->condition(); expectedLast = static_cast<const ConditionalStatement*>( static_cast<ConditionalStatement*>(node.get()) ->falseBranch()->child(0)) ->falseBranch()->child(0); CPPUNIT_ASSERT(expectedFirst != expectedLast); first = firstUse(*node, "@a"); last = lastUse(*node, "@a"); CPPUNIT_ASSERT_EQUAL_MESSAGE(ERROR_MSG("Unexpected location of @a AST node", "if (@a) {} else if (1) {} else { @a; }"), first, expectedFirst); CPPUNIT_ASSERT_EQUAL_MESSAGE(ERROR_MSG("Unexpected location of @a AST node", "if (@a) {} else if (1) {} else { @a; }"), last, expectedLast); } void TestScanners::testAttributeDependencyTokens() { for (const std::string& code : none) { const Tree::ConstPtr tree = parse(code.c_str()); CPPUNIT_ASSERT(tree); std::vector<std::string> dependencies; attributeDependencyTokens(*tree, "a", tokens::CoreType::FLOAT, dependencies); CPPUNIT_ASSERT_MESSAGE(ERROR_MSG("Expected 0 deps", code), dependencies.empty()); } for (const std::string& code : self) { const Tree::ConstPtr tree = parse(code.c_str()); CPPUNIT_ASSERT(tree); std::vector<std::string> dependencies; attributeDependencyTokens(*tree, "a", tokens::CoreType::FLOAT, dependencies); CPPUNIT_ASSERT(!dependencies.empty()); CPPUNIT_ASSERT_EQUAL_MESSAGE(ERROR_MSG("Invalid variable dependency", code), dependencies.front(), std::string("float@a")); } for (const std::string& code : direct) { const Tree::ConstPtr tree = parse(code.c_str()); CPPUNIT_ASSERT(tree); std::vector<std::string> dependencies; attributeDependencyTokens(*tree, "a", tokens::CoreType::FLOAT, dependencies); CPPUNIT_ASSERT(!dependencies.empty()); CPPUNIT_ASSERT_EQUAL_MESSAGE(ERROR_MSG("Invalid variable dependency", code), dependencies.front(), std::string("float@b")); } for (const std::string& code : directvec) { const Tree::ConstPtr tree = parse(code.c_str()); CPPUNIT_ASSERT(tree); std::vector<std::string> dependencies; attributeDependencyTokens(*tree, "a", tokens::CoreType::FLOAT, dependencies); CPPUNIT_ASSERT(!dependencies.empty()); CPPUNIT_ASSERT_EQUAL_MESSAGE(ERROR_MSG("Invalid variable dependency", code), dependencies.front(), std::string("vec3f@b")); } for (const std::string& code : indirect) { const Tree::ConstPtr tree = parse(code.c_str()); CPPUNIT_ASSERT(tree); std::vector<std::string> dependencies; attributeDependencyTokens(*tree, "a", tokens::CoreType::FLOAT, dependencies); CPPUNIT_ASSERT(!dependencies.empty()); CPPUNIT_ASSERT_EQUAL_MESSAGE(ERROR_MSG("Invalid variable dependency", code), dependencies.front(), std::string("float@b")); } // Test a more complicated code snippet. Note that this also checks the // order which isn't strictly necessary const std::string complex = "int a = func(1,@e);" "pow(@d, a);" "mat3f m = 0;" "scale(m, v@v);" "" "float f1 = 0;" "float f2 = 0;" "float f3 = 0;" "" "f3 = @f;" "f2 = f3;" "f1 = f2;" "if (@a - @e > f1) {" " @b = func(m);" " if (true) {" " ++@c[0] = a;" " }" "}"; const Tree::ConstPtr tree = parse(complex.c_str()); CPPUNIT_ASSERT(tree); std::vector<std::string> dependencies; attributeDependencyTokens(*tree, "b", tokens::CoreType::FLOAT, dependencies); // @b should depend on: @a, @e, @f, v@v CPPUNIT_ASSERT_EQUAL(4ul, dependencies.size()); CPPUNIT_ASSERT_EQUAL(dependencies[0], std::string("float@a")); CPPUNIT_ASSERT_EQUAL(dependencies[1], std::string("float@e")); CPPUNIT_ASSERT_EQUAL(dependencies[2], std::string("float@f")); CPPUNIT_ASSERT_EQUAL(dependencies[3], std::string("vec3f@v")); // @c should depend on: @a, @c, @d, @e, @f dependencies.clear(); attributeDependencyTokens(*tree, "c", tokens::CoreType::FLOAT, dependencies); CPPUNIT_ASSERT_EQUAL(5ul, dependencies.size()); CPPUNIT_ASSERT_EQUAL(dependencies[0], std::string("float@a")); CPPUNIT_ASSERT_EQUAL(dependencies[1], std::string("float@c")); CPPUNIT_ASSERT_EQUAL(dependencies[2], std::string("float@d")); CPPUNIT_ASSERT_EQUAL(dependencies[3], std::string("float@e")); CPPUNIT_ASSERT_EQUAL(dependencies[4], std::string("float@f")); // @d should depend on: @d, @e dependencies.clear(); attributeDependencyTokens(*tree, "d", tokens::CoreType::FLOAT, dependencies); CPPUNIT_ASSERT_EQUAL(2ul, dependencies.size()); CPPUNIT_ASSERT_EQUAL(dependencies[0], std::string("float@d")); CPPUNIT_ASSERT_EQUAL(dependencies[1], std::string("float@e")); // @e should depend on itself dependencies.clear(); attributeDependencyTokens(*tree, "e", tokens::CoreType::FLOAT, dependencies); CPPUNIT_ASSERT_EQUAL(1ul, dependencies.size()); CPPUNIT_ASSERT_EQUAL(dependencies[0], std::string("float@e")); // @f should depend on nothing dependencies.clear(); attributeDependencyTokens(*tree, "f", tokens::CoreType::FLOAT, dependencies); CPPUNIT_ASSERT(dependencies.empty()); // @v should depend on: v@v dependencies.clear(); attributeDependencyTokens(*tree, "v", tokens::CoreType::VEC3F, dependencies); CPPUNIT_ASSERT_EQUAL(1ul, dependencies.size()); CPPUNIT_ASSERT_EQUAL(dependencies[0], std::string("vec3f@v")); } /* void TestScanners::testVariableDependencies() { for (const std::string& code : none) { const Tree::ConstPtr tree = parse(code.c_str()); CPPUNIT_ASSERT(tree); const Variable* last = lastUse(*tree, "@a"); CPPUNIT_ASSERT(last); std::vector<const Variable*> vars; variableDependencies(*last, vars); CPPUNIT_ASSERT_MESSAGE(ERROR_MSG("Expected 0 deps", code), vars.empty()); } for (const std::string& code : self) { const Tree::ConstPtr tree = parse(code.c_str()); CPPUNIT_ASSERT(tree); const Variable* last = lastUse(*tree, "@a"); CPPUNIT_ASSERT(last); std::vector<const Variable*> vars; variableDependencies(*last, vars); const Variable* var = vars.front(); CPPUNIT_ASSERT_MESSAGE(ERROR_MSG("Invalid variable dependency", code), var->isType<Attribute>()); const Attribute* attrib = static_cast<const Attribute*>(var); CPPUNIT_ASSERT_EQUAL_MESSAGE(ERROR_MSG("Invalid variable dependency", code), std::string("float@a"), attrib->tokenname()); } for (const std::string& code : direct) { const Tree::ConstPtr tree = parse(code.c_str()); CPPUNIT_ASSERT(tree); const Variable* last = lastUse(*tree, "@a"); CPPUNIT_ASSERT(last); std::vector<const Variable*> vars; variableDependencies(*last, vars); const Variable* var = vars.front(); CPPUNIT_ASSERT_MESSAGE(ERROR_MSG("Invalid variable dependency", code), var->isType<Attribute>()); CPPUNIT_ASSERT_EQUAL_MESSAGE(ERROR_MSG("Invalid variable dependency", code), std::string("b"), var->name()); } for (const std::string& code : indirect) { const Tree::ConstPtr tree = parse(code.c_str()); CPPUNIT_ASSERT(tree); const Variable* last = lastUse(*tree, "@a"); CPPUNIT_ASSERT(last); std::vector<const Variable*> vars; variableDependencies(*last, vars); // check c const Variable* var = vars[0]; CPPUNIT_ASSERT_MESSAGE(ERROR_MSG("Invalid variable dependency", code), var->isType<Local>()); CPPUNIT_ASSERT_EQUAL_MESSAGE(ERROR_MSG("Invalid variable dependency", code), std::string("c"), var->name()); // check @b var = vars[1]; CPPUNIT_ASSERT_MESSAGE(ERROR_MSG("Invalid variable dependency", code), var->isType<Attribute>()); CPPUNIT_ASSERT_EQUAL_MESSAGE(ERROR_MSG("Invalid variable dependency", code), std::string("b"), var->name()); } // Test a more complicated code snippet. Note that this also checks the // order which isn't strictly necessary const std::string complex = "int a = func(1,@e);" "pow(@d, a);" "mat3f m = 0;" "scale(m, v@v);" "" "float f1 = 0;" "float f2 = 0;" "float f3 = 0;" "" "f3 = @f;" "f2 = f3;" "f1 = f2;" "if (@a - @e > f1) {" " @b = func(m);" " if (true) {" " ++@c[0] = a;" " }" "}"; const Tree::ConstPtr tree = parse(complex.c_str()); CPPUNIT_ASSERT(tree); const Variable* lasta = lastUse(*tree, "@a"); const Variable* lastb = lastUse(*tree, "@b"); const Variable* lastc = lastUse(*tree, "@c"); const Variable* lastd = lastUse(*tree, "@d"); const Variable* laste = lastUse(*tree, "@e"); const Variable* lastf = lastUse(*tree, "@f"); const Variable* lastv = lastUse(*tree, "vec3f@v"); CPPUNIT_ASSERT(lasta); CPPUNIT_ASSERT(lastb); CPPUNIT_ASSERT(lastc); CPPUNIT_ASSERT(lastd); CPPUNIT_ASSERT(laste); CPPUNIT_ASSERT(lastf); CPPUNIT_ASSERT(lastv); std::vector<const Variable*> vars; variableDependencies(*lasta, vars); CPPUNIT_ASSERT(vars.empty()); // @b should depend on: m, m, v@v, @a, @e, @e, f1, f2, f3, @f variableDependencies(*lastb, vars); CPPUNIT_ASSERT_EQUAL(10ul, vars.size()); CPPUNIT_ASSERT(vars[0]->isType<Local>()); CPPUNIT_ASSERT(vars[0]->name() == "m"); CPPUNIT_ASSERT(vars[1]->isType<Local>()); CPPUNIT_ASSERT(vars[1]->name() == "m"); CPPUNIT_ASSERT(vars[2]->isType<Attribute>()); CPPUNIT_ASSERT(static_cast<const Attribute*>(vars[2])->tokenname() == "vec3f@v"); CPPUNIT_ASSERT(vars[3]->isType<Attribute>()); CPPUNIT_ASSERT(static_cast<const Attribute*>(vars[3])->tokenname() == "float@a"); CPPUNIT_ASSERT(vars[4]->isType<Attribute>()); CPPUNIT_ASSERT(static_cast<const Attribute*>(vars[4])->tokenname() == "float@e"); CPPUNIT_ASSERT(vars[5]->isType<Attribute>()); CPPUNIT_ASSERT(static_cast<const Attribute*>(vars[5])->tokenname() == "float@e"); CPPUNIT_ASSERT(vars[6]->isType<Local>()); CPPUNIT_ASSERT(vars[6]->name() == "f1"); CPPUNIT_ASSERT(vars[7]->isType<Local>()); CPPUNIT_ASSERT(vars[7]->name() == "f2"); CPPUNIT_ASSERT(vars[8]->isType<Local>()); CPPUNIT_ASSERT(vars[8]->name() == "f3"); CPPUNIT_ASSERT(vars[9]->isType<Attribute>()); CPPUNIT_ASSERT(static_cast<const Attribute*>(vars[9])->tokenname() == "float@f"); // @c should depend on: @c, a, @e, @d, a, @e, @a, @e, f1, f2, f3, @f vars.clear(); variableDependencies(*lastc, vars); CPPUNIT_ASSERT_EQUAL(11ul, vars.size()); CPPUNIT_ASSERT(vars[0]->isType<Attribute>()); CPPUNIT_ASSERT(static_cast<const Attribute*>(vars[0])->tokenname() == "float@c"); CPPUNIT_ASSERT(vars[1]->isType<Local>()); CPPUNIT_ASSERT(vars[1]->name() == "a"); CPPUNIT_ASSERT(vars[2]->isType<Attribute>()); CPPUNIT_ASSERT(static_cast<const Attribute*>(vars[2])->tokenname() == "float@e"); CPPUNIT_ASSERT(vars[3]->isType<Attribute>()); CPPUNIT_ASSERT(static_cast<const Attribute*>(vars[3])->tokenname() == "float@d"); CPPUNIT_ASSERT(vars[4]->isType<Local>()); CPPUNIT_ASSERT(vars[4]->name() == "a"); CPPUNIT_ASSERT(vars[5]->isType<Attribute>()); CPPUNIT_ASSERT(static_cast<const Attribute*>(vars[5])->tokenname() == "float@a"); CPPUNIT_ASSERT(vars[6]->isType<Attribute>()); CPPUNIT_ASSERT(static_cast<const Attribute*>(vars[6])->tokenname() == "float@e"); CPPUNIT_ASSERT(vars[7]->isType<Local>()); CPPUNIT_ASSERT(vars[7]->name() == "f1"); CPPUNIT_ASSERT(vars[8]->isType<Local>()); CPPUNIT_ASSERT(vars[8]->name() == "f2"); CPPUNIT_ASSERT(vars[9]->isType<Local>()); CPPUNIT_ASSERT(vars[9]->name() == "f3"); CPPUNIT_ASSERT(vars[10]->isType<Attribute>()); CPPUNIT_ASSERT(static_cast<const Attribute*>(vars[10])->tokenname() == "float@f"); // @d should depend on: @d, a, @e vars.clear(); variableDependencies(*lastd, vars); CPPUNIT_ASSERT_EQUAL(3ul, vars.size()); CPPUNIT_ASSERT(vars[0]->isType<Attribute>()); CPPUNIT_ASSERT(static_cast<const Attribute*>(vars[0])->tokenname() == "float@d"); CPPUNIT_ASSERT(vars[1]->isType<Local>()); CPPUNIT_ASSERT(vars[1]->name() == "a"); CPPUNIT_ASSERT(vars[2]->isType<Attribute>()); CPPUNIT_ASSERT(static_cast<const Attribute*>(vars[2])->tokenname() == "float@e"); // @e should depend on itself vars.clear(); variableDependencies(*laste, vars); CPPUNIT_ASSERT_EQUAL(1ul, vars.size()); CPPUNIT_ASSERT(vars[0]->isType<Attribute>()); CPPUNIT_ASSERT(static_cast<const Attribute*>(vars[0])->tokenname() == "float@e"); // @f should depend on nothing vars.clear(); variableDependencies(*lastf, vars); CPPUNIT_ASSERT(vars.empty()); // @v should depend on: m, v@v vars.clear(); variableDependencies(*lastv, vars); CPPUNIT_ASSERT_EQUAL(2ul, vars.size()); CPPUNIT_ASSERT(vars[0]->isType<Local>()); CPPUNIT_ASSERT(vars[0]->name() == "m"); CPPUNIT_ASSERT(vars[1]->isType<Attribute>()); CPPUNIT_ASSERT(static_cast<const Attribute*>(vars[1])->tokenname() == "vec3f@v"); } */
NVIDIA-Omniverse/ext-openvdb/openvdb_ax/openvdb_ax/test/ast/TestPrinters.cc
// Copyright Contributors to the OpenVDB Project // SPDX-License-Identifier: MPL-2.0 #include <openvdb_ax/ast/AST.h> #include <openvdb_ax/ast/Parse.h> #include <openvdb_ax/ast/PrintTree.h> #include <cppunit/extensions/HelperMacros.h> #include <string> #include <ostream> using namespace openvdb::ax::ast; using namespace openvdb::ax::ast::tokens; class TestPrinters : public CppUnit::TestCase { public: CPPUNIT_TEST_SUITE(TestPrinters); CPPUNIT_TEST(testReprint); CPPUNIT_TEST_SUITE_END(); void testReprint(); }; CPPUNIT_TEST_SUITE_REGISTRATION(TestPrinters); void TestPrinters::testReprint() { // Small function providing more verbose output on failures auto check = [](const std::string& in, const std::string& expected) { const size_t min = std::min(in.size(), expected.size()); for (size_t i = 0; i < min; ++i) { if (in[i] != expected[i]) { std::ostringstream msg; msg << "TestReprint failed at character " << i << '.' << '[' << in[i] << "] vs [" << expected[i] << "]\n" << "Got:\n" << in << "Expected:\n" << expected; CPPUNIT_FAIL(msg.str()); } } if (in.size() != expected.size()) { std::ostringstream msg; msg << "TestReprint failed at end character.\n" << "Got:\n" << in << "Expected:\n" << expected ; CPPUNIT_FAIL(msg.str()); } }; std::ostringstream os; // Test binary ops std::string in = "a + b * c / d % e << f >> g = h & i | j ^ k && l || m;"; std::string expected = "(((a + (((b * c) / d) % e)) << f) >> g = ((((h & i) | (j ^ k)) && l) || m));\n"; Tree::ConstPtr tree = parse(in.c_str()); CPPUNIT_ASSERT(tree.get()); reprint(*tree, os, ""); check(os.str(), ("{\n" + expected + "}\n")); // Test binary ops paren os.str(""); in = "(a + b) * (c / d) % e << (f) >> g = (((h & i) | j) ^ k) && l || m;"; expected = "(((((a + b) * (c / d)) % e) << f) >> g = (((((h & i) | j) ^ k) && l) || m));\n"; tree = parse(in.c_str()); CPPUNIT_ASSERT(tree.get()); reprint(*tree, os, ""); check(os.str(), ("{\n" + expected + "}\n")); // Test relational os.str(""); in = "a <= b; c >= d; e == f; g != h; i < j; k > l;"; expected = "(a <= b);\n(c >= d);\n(e == f);\n(g != h);\n(i < j);\n(k > l);\n"; tree = parse(in.c_str()); CPPUNIT_ASSERT(tree.get()); reprint(*tree, os, ""); check(os.str(), ("{\n" + expected + "}\n")); // Test assignments os.str(""); in = "a = b; b += c; c -= d; d /= e; e *= f; f %= 1; g &= 2; h |= 3; i ^= 4; j <<= 5; k >>= 6;"; expected = "a = b;\nb += c;\nc -= d;\nd /= e;\ne *= f;\nf %= 1;\ng &= 2;\nh |= 3;\ni ^= 4;\nj <<= 5;\nk >>= 6;\n"; tree = parse(in.c_str()); CPPUNIT_ASSERT(tree.get()); reprint(*tree, os, ""); check(os.str(), ("{\n" + expected + "}\n")); // Test crement os.str(""); in = "++++a; ----b; a++; b--;"; expected = "++++a;\n----b;\na++;\nb--;\n"; tree = parse(in.c_str()); CPPUNIT_ASSERT(tree.get()); reprint(*tree, os, ""); check(os.str(), ("{\n" + expected + "}\n")); // Test comma os.str(""); in = "a,b,(c,d),(e,(f,(g,h,i)));"; expected = "(a, b, (c, d), (e, (f, (g, h, i))));\n"; tree = parse(in.c_str()); CPPUNIT_ASSERT(tree.get()); reprint(*tree, os, ""); check(os.str(), ("{\n" + expected + "}\n")); // Test array unpack os.str(""); in = "a.x; b.y; c.z; d[0]; d[1,2]; e[(a.r, c.b), b.g];"; expected = "a[0];\nb[1];\nc[2];\nd[0];\nd[1, 2];\ne[(a[0], c[2]), b[1]];\n"; tree = parse(in.c_str()); CPPUNIT_ASSERT(tree.get()); reprint(*tree, os, ""); check(os.str(), ("{\n" + expected + "}\n")); // Test array pack os.str(""); in = "a = {0,1}; b = {2,3,4}; c = {a,(b,c), d};"; expected = "a = {0, 1};\nb = {2, 3, 4};\nc = {a, (b, c), d};\n"; tree = parse(in.c_str()); CPPUNIT_ASSERT(tree.get()); reprint(*tree, os, ""); check(os.str(), ("{\n" + expected + "}\n")); // Test declarations os.str(""); in = "bool a; int b,c; int32 d=0, e; int64 f; float g; double h, i=0;"; expected = "bool a;\nint32 b, c;\nint32 d = 0, e;\nint64 f;\nfloat g;\ndouble h, i = 0;\n"; tree = parse(in.c_str()); CPPUNIT_ASSERT(tree.get()); reprint(*tree, os, ""); check(os.str(), ("{\n" + expected + "}\n")); // Test conditionals os.str(""); in = "if (a) b; else if (c) d; else e; if (a) if (b) { c,d; } else { e,f; }"; expected = "if (a)\n{\nb;\n}\nelse\n{\nif (c)\n{\nd;\n}\nelse\n{\ne;\n}\n}\nif (a)\n{\nif (b)\n{\n(c, d);\n}\nelse\n{\n(e, f);\n}\n}\n"; tree = parse(in.c_str()); CPPUNIT_ASSERT(tree.get()); reprint(*tree, os, ""); check(os.str(), ("{\n" + expected + "}\n")); // Test keywords os.str(""); in = "return; break; continue; true; false;"; expected = "return;\nbreak;\ncontinue;\ntrue;\nfalse;\n"; tree = parse(in.c_str()); CPPUNIT_ASSERT(tree.get()); reprint(*tree, os, ""); check(os.str(), ("{\n" + expected + "}\n")); // Test attributes/externals os.str(""); in = "@a; $a; v@b; v$b; f@a; f$a; i@c; i$c; s@d; s$d;"; expected = "float@a;\nfloat$a;\nvec3f@b;\nvec3f$b;\nfloat@a;\nfloat$a;\nint32@c;\nint32$c;\nstring@d;\nstring$d;\n"; tree = parse(in.c_str()); CPPUNIT_ASSERT(tree.get()); reprint(*tree, os, ""); check(os.str(), ("{\n" + expected + "}\n")); // Test ternary os.str(""); in = "a ? b : c; a ? b ? c ? : d : e : f;"; expected = "a ? b : c;\na ? b ? c ?: d : e : f;\n"; tree = parse(in.c_str()); CPPUNIT_ASSERT(tree.get()); reprint(*tree, os, ""); check(os.str(), ("{\n" + expected + "}\n")); // Test loops os.str(""); in = "while (a) for (int32 b, c;;) do { d; } while (e)"; expected = "while (a)\n{\nfor (int32 b, c; true; )\n{\ndo\n{\nd;\n}\nwhile (e)\n}\n}\n"; tree = parse(in.c_str()); CPPUNIT_ASSERT(tree.get()); reprint(*tree, os, ""); check(os.str(), ("{\n" + expected + "}\n")); // Test loops with indents os.str(""); in = "while (a) for (int32 b, c;;) do { d; } while (e)"; expected = " while (a)\n {\n for (int32 b, c; true; )\n {\n do\n {\n d;\n }\n while (e)\n }\n }\n"; tree = parse(in.c_str()); CPPUNIT_ASSERT(tree.get()); reprint(*tree, os, " "); check(os.str(), ("{\n" + expected + "}\n")); }
NVIDIA-Omniverse/ext-openvdb/openvdb_ax/openvdb_ax/cmd/openvdb_ax.cc
// Copyright Contributors to the OpenVDB Project // SPDX-License-Identifier: MPL-2.0 /// @file cmd/openvdb_ax.cc /// /// @authors Nick Avramoussis, Richard Jones /// /// @brief The command line vdb_ax binary which provides tools to /// run and analyze AX code. /// #include <openvdb_ax/ast/AST.h> #include <openvdb_ax/ast/Scanners.h> #include <openvdb_ax/ast/PrintTree.h> #include <openvdb_ax/codegen/Functions.h> #include <openvdb_ax/compiler/Compiler.h> #include <openvdb_ax/compiler/AttributeRegistry.h> #include <openvdb_ax/compiler/CompilerOptions.h> #include <openvdb_ax/compiler/PointExecutable.h> #include <openvdb_ax/compiler/VolumeExecutable.h> #include <openvdb_ax/compiler/Logger.h> #include <openvdb/openvdb.h> #include <openvdb/version.h> #include <openvdb/util/logging.h> #include <openvdb/util/CpuTimer.h> #include <openvdb/points/PointDelete.h> #include <fstream> #include <iostream> #include <sstream> #include <string> #include <vector> const char* gProgName = ""; void usage [[noreturn]] (int exitStatus = EXIT_FAILURE) { std::cerr << "Usage: " << gProgName << " [input.vdb [output.vdb] | analyze] [-s \"string\" | -f file.txt] [OPTIONS]\n" << "Which: executes a string or file containing a code snippet on an input.vdb file\n\n" << "Options:\n" << " -s snippet execute code snippet on the input.vdb file\n" << " -f file.txt execute text file containing a code snippet on the input.vdb file\n" << " -v verbose (print timing and diagnostics)\n" << " --opt level set an optimization level on the generated IR [NONE, O0, O1, O2, Os, Oz, O3]\n" << " --werror set warnings as errors\n" << " --max-errors n sets the maximum number of error messages to n, a value of 0 (default) allows all error messages\n" << " analyze parse the provided code and enter analysis mode\n" << " --ast-print descriptive print the abstract syntax tree generated\n" << " --re-print re-interpret print of the provided code after ast traversal\n" << " --reg-print print the attribute registry (name, types, access, dependencies)\n" << " --try-compile [points|volumes] \n" << " attempt to compile the provided code for points or volumes, or both if no\n" << " additional option is provided, reporting any failures or success.\n" << " functions enter function mode to query available function information\n" << " --list [name] list all available functions, their documentation and their signatures.\n" << " optionally only list functions which whose name includes a provided string.\n" << " --list-names list all available functions names only\n" << "Warning:\n" << " Providing the same file-path to both input.vdb and output.vdb arguments will overwrite\n" << " the file. If no output file is provided, the input.vdb will be processed but will remain\n" << " unchanged on disk (this is useful for testing the success status of code).\n"; exit(exitStatus); } struct ProgOptions { enum Mode { Execute, Analyze, Functions }; enum Compilation { All, Points, Volumes }; Mode mMode = Execute; // Compilation options size_t mMaxErrors = 0; bool mWarningsAsErrors = false; // Execute options std::unique_ptr<std::string> mInputCode = nullptr; std::string mInputVDBFile = ""; std::string mOutputVDBFile = ""; bool mVerbose = false; openvdb::ax::CompilerOptions::OptLevel mOptLevel = openvdb::ax::CompilerOptions::OptLevel::O3; // Analyze options bool mPrintAST = false; bool mReprint = false; bool mAttribRegPrint = false; bool mInitCompile = false; Compilation mCompileFor = All; // Function Options bool mFunctionList = false; bool mFunctionNamesOnly = false; std::string mFunctionSearch = ""; }; inline std::string modeString(const ProgOptions::Mode mode) { switch (mode) { case ProgOptions::Execute : return "execute"; case ProgOptions::Analyze : return "analyze"; case ProgOptions::Functions : return "functions"; default : return ""; } } ProgOptions::Compilation tryCompileStringToCompilation(const std::string& str) { if (str == "points") return ProgOptions::Points; if (str == "volumes") return ProgOptions::Volumes; OPENVDB_LOG_FATAL("invalid option given for --try-compile level"); usage(); } openvdb::ax::CompilerOptions::OptLevel optStringToLevel(const std::string& str) { if (str == "NONE") return openvdb::ax::CompilerOptions::OptLevel::NONE; if (str == "O0") return openvdb::ax::CompilerOptions::OptLevel::O0; if (str == "O1") return openvdb::ax::CompilerOptions::OptLevel::O1; if (str == "O2") return openvdb::ax::CompilerOptions::OptLevel::O2; if (str == "Os") return openvdb::ax::CompilerOptions::OptLevel::Os; if (str == "Oz") return openvdb::ax::CompilerOptions::OptLevel::Oz; if (str == "O3") return openvdb::ax::CompilerOptions::OptLevel::O3; OPENVDB_LOG_FATAL("invalid option given for --opt level"); usage(); } inline std::string optLevelToString(const openvdb::ax::CompilerOptions::OptLevel level) { switch (level) { case openvdb::ax::CompilerOptions::OptLevel::NONE : return "NONE"; case openvdb::ax::CompilerOptions::OptLevel::O1 : return "O1"; case openvdb::ax::CompilerOptions::OptLevel::O2 : return "O2"; case openvdb::ax::CompilerOptions::OptLevel::Os : return "Os"; case openvdb::ax::CompilerOptions::OptLevel::Oz : return "Oz"; case openvdb::ax::CompilerOptions::OptLevel::O3 : return "O3"; default : return ""; } } void loadSnippetFile(const std::string& fileName, std::string& textString) { std::ifstream in(fileName.c_str(), std::ios::in | std::ios::binary); if (!in) { OPENVDB_LOG_FATAL("File Load Error: " << fileName); usage(); } textString = std::string(std::istreambuf_iterator<char>(in), std::istreambuf_iterator<char>()); } struct OptParse { int argc; char** argv; OptParse(int argc_, char* argv_[]): argc(argc_), argv(argv_) {} bool check(int idx, const std::string& name, int numArgs = 1) const { if (argv[idx] == name) { if (idx + numArgs >= argc) { OPENVDB_LOG_FATAL("option " << name << " requires " << numArgs << " argument" << (numArgs == 1 ? "" : "s")); usage(); } return true; } return false; } }; struct ScopedInitialize { ScopedInitialize(int argc, char *argv[]) { openvdb::logging::initialize(argc, argv); openvdb::initialize(); } ~ScopedInitialize() { if (openvdb::ax::isInitialized()) { openvdb::ax::uninitialize(); } openvdb::uninitialize(); } inline void initializeCompiler() const { openvdb::ax::initialize(); } inline bool isInitialized() const { return openvdb::ax::isInitialized(); } }; void printFunctions(const bool namesOnly, const std::string& search, std::ostream& os) { static const size_t maxHelpTextWidth = 100; openvdb::ax::FunctionOptions opts; opts.mLazyFunctions = false; const openvdb::ax::codegen::FunctionRegistry::UniquePtr registry = openvdb::ax::codegen::createDefaultRegistry(&opts); // convert to ordered map for alphabetical sorting // only include non internal functions and apply any search // criteria std::map<std::string, const openvdb::ax::codegen::FunctionGroup*> functionMap; for (const auto& iter : registry->map()) { if (iter.second.isInternal()) continue; if (!search.empty() && iter.first.find(search) == std::string::npos) { continue; } functionMap[iter.first] = iter.second.function(); } if (functionMap.empty()) return; if (namesOnly) { const size_t size = functionMap.size(); size_t pos = 0, count = 0; auto iter = functionMap.cbegin(); for (; iter != functionMap.cend(); ++iter) { if (count == size - 1) break; const std::string& name = iter->first; if (count != 0 && pos > maxHelpTextWidth) { os << '\n'; pos = 0; } pos += name.size() + 2; // 2=", " os << name << ',' << ' '; ++count; } os << iter->first << '\n'; } else { llvm::LLVMContext C; for (const auto& iter : functionMap) { const openvdb::ax::codegen::FunctionGroup* const function = iter.second; const char* cdocs = function->doc(); if (!cdocs || cdocs[0] == '\0') { cdocs = "<No documentation exists for this function>"; } // do some basic formatting on the help text std::string docs(cdocs); size_t pos = maxHelpTextWidth; while (pos < docs.size()) { while (docs[pos] != ' ' && pos != 0) --pos; if (pos == 0) break; docs.insert(pos, "\n| "); pos += maxHelpTextWidth; } os << iter.first << '\n' << '|' << '\n'; os << "| - " << docs << '\n' << '|' << '\n'; const auto& list = function->list(); for (const openvdb::ax::codegen::Function::Ptr& decl : list) { os << "| - "; decl->print(C, os); os << '\n'; } os << '\n'; } } } int main(int argc, char *argv[]) { OPENVDB_START_THREADSAFE_STATIC_WRITE gProgName = argv[0]; const char* ptr = ::strrchr(gProgName, '/'); if (ptr != nullptr) gProgName = ptr + 1; OPENVDB_FINISH_THREADSAFE_STATIC_WRITE if (argc == 1) usage(); OptParse parser(argc, argv); ProgOptions opts; openvdb::util::CpuTimer timer; auto getTime = [&timer]() -> std::string { const double msec = timer.milliseconds(); std::ostringstream os; openvdb::util::printTime(os, msec, "", "", 1, 1, 0); return os.str(); }; auto& os = std::cout; #define axlog(message) \ { if (opts.mVerbose) os << message; } #define axtimer() timer.restart() #define axtime() getTime() bool multiSnippet = false; for (int i = 1; i < argc; ++i) { std::string arg = argv[i]; if (arg[0] == '-') { if (parser.check(i, "-s")) { ++i; multiSnippet |= static_cast<bool>(opts.mInputCode); opts.mInputCode.reset(new std::string(argv[i])); } else if (parser.check(i, "-f")) { ++i; multiSnippet |= static_cast<bool>(opts.mInputCode); opts.mInputCode.reset(new std::string()); loadSnippetFile(argv[i], *opts.mInputCode); } else if (parser.check(i, "-v", 0)) { opts.mVerbose = true; } else if (parser.check(i, "--max-errors")) { opts.mMaxErrors = atoi(argv[++i]); } else if (parser.check(i, "--werror", 0)) { opts.mWarningsAsErrors = true; } else if (parser.check(i, "--list", 0)) { opts.mFunctionList = true; opts.mInitCompile = true; // need to intialize llvm opts.mFunctionNamesOnly = false; if (i + 1 >= argc) continue; if (argv[i+1][0] == '-') continue; ++i; opts.mFunctionSearch = std::string(argv[i]); } else if (parser.check(i, "--list-names", 0)) { opts.mFunctionList = true; opts.mFunctionNamesOnly = true; } else if (parser.check(i, "--ast-print", 0)) { opts.mPrintAST = true; } else if (parser.check(i, "--re-print", 0)) { opts.mReprint = true; } else if (parser.check(i, "--reg-print", 0)) { opts.mAttribRegPrint = true; } else if (parser.check(i, "--try-compile", 0)) { opts.mInitCompile = true; if (i + 1 >= argc) continue; if (argv[i+1][0] == '-') continue; ++i; opts.mCompileFor = tryCompileStringToCompilation(argv[i]); } else if (parser.check(i, "--opt")) { ++i; opts.mOptLevel = optStringToLevel(argv[i]); } else if (arg == "-h" || arg == "-help" || arg == "--help") { usage(EXIT_SUCCESS); } else { OPENVDB_LOG_FATAL("\"" + arg + "\" is not a valid option"); usage(); } } else if (!arg.empty()) { // if mode has already been set, no more positional arguments are expected // (except for execute which takes in and out) if (opts.mMode != ProgOptions::Mode::Execute) { OPENVDB_LOG_FATAL("unrecognized positional argument: \"" << arg << "\""); usage(); } if (arg == "analyze") opts.mMode = ProgOptions::Analyze; else if (arg == "functions") opts.mMode = ProgOptions::Functions; if (opts.mMode == ProgOptions::Mode::Execute) { opts.mInitCompile = true; // execute positional argument setup if (opts.mInputVDBFile.empty()) { opts.mInputVDBFile = arg; } else if (opts.mOutputVDBFile.empty()) { opts.mOutputVDBFile = arg; } else { OPENVDB_LOG_FATAL("unrecognized positional argument: \"" << arg << "\""); usage(); } } else if (!opts.mInputVDBFile.empty() || !opts.mOutputVDBFile.empty()) { OPENVDB_LOG_FATAL("unrecognized positional argument: \"" << arg << "\""); usage(); } } else { usage(); } } if (opts.mVerbose) { axlog("OpenVDB AX " << openvdb::getLibraryVersionString() << '\n'); axlog("----------------\n"); axlog("Inputs\n"); axlog(" mode : " << modeString(opts.mMode)); if (opts.mMode == ProgOptions::Analyze) { axlog(" ("); if (opts.mPrintAST) axlog("|ast out"); if (opts.mReprint) axlog("|reprint out"); if (opts.mAttribRegPrint) axlog("|registry out"); if (opts.mInitCompile) axlog("|compilation"); axlog("|)"); } axlog('\n'); if (opts.mMode == ProgOptions::Execute) { axlog(" vdb in : \"" << opts.mInputVDBFile << "\"\n"); axlog(" vdb out : \"" << opts.mOutputVDBFile << "\"\n"); } if (opts.mMode == ProgOptions::Execute || opts.mMode == ProgOptions::Analyze) { axlog(" ax code : "); if (opts.mInputCode && !opts.mInputCode->empty()) { const bool containsnl = opts.mInputCode->find('\n') != std::string::npos; if (containsnl) axlog("\n "); // indent output const char* c = opts.mInputCode->c_str(); while (*c != '\0') { axlog(*c); if (*c == '\n') axlog(" "); ++c; } } else { axlog("\"\""); } axlog('\n'); axlog('\n'); } axlog(std::flush); } if (opts.mMode != ProgOptions::Functions) { if (!opts.mInputCode) { OPENVDB_LOG_FATAL("expected at least one AX file or a code snippet"); usage(); } if (multiSnippet) { OPENVDB_LOG_WARN("multiple code snippets provided, only using last input."); } } if (opts.mMode == ProgOptions::Execute) { if (opts.mInputVDBFile.empty()) { OPENVDB_LOG_FATAL("expected at least one VDB file or analysis mode"); usage(); } if (opts.mOutputVDBFile.empty()) { OPENVDB_LOG_WARN("no output VDB File specified - nothing will be written to disk"); } } axtimer(); axlog("[INFO] Initializing OpenVDB" << std::flush); ScopedInitialize initializer(argc, argv); axlog(": " << axtime() << '\n'); // read vdb file data for openvdb::GridPtrVecPtr grids; openvdb::MetaMap::Ptr meta; if (opts.mMode == ProgOptions::Execute) { openvdb::io::File file(opts.mInputVDBFile); try { axtimer(); axlog("[INFO] Reading VDB data" << (openvdb::io::Archive::isDelayedLoadingEnabled() ? " (delay-load)" : "") << std::flush); file.open(); grids = file.getGrids(); meta = file.getMetadata(); file.close(); axlog(": " << axtime() << '\n'); } catch (openvdb::Exception& e) { OPENVDB_LOG_ERROR(e.what() << " (" << opts.mInputVDBFile << ")"); return EXIT_FAILURE; } } if (opts.mInitCompile) { axtimer(); axlog("[INFO] Initializing AX/LLVM" << std::flush); initializer.initializeCompiler(); axlog(": " << axtime() << '\n'); } if (opts.mMode == ProgOptions::Functions) { if (opts.mFunctionList) { axlog("Querying available functions\n" << std::flush); assert(opts.mFunctionNamesOnly || initializer.isInitialized()); printFunctions(opts.mFunctionNamesOnly, opts.mFunctionSearch, std::cout); } return EXIT_SUCCESS; } // set up logger openvdb::ax::Logger logs([](const std::string& msg) { std::cerr << msg << std::endl; }, [](const std::string& msg) { std::cerr << msg << std::endl; }); logs.setMaxErrors(opts.mMaxErrors); logs.setWarningsAsErrors(opts.mWarningsAsErrors); logs.setPrintLines(true); logs.setNumberedOutput(true); // parse axtimer(); axlog("[INFO] Parsing input code" << std::flush); const openvdb::ax::ast::Tree::ConstPtr syntaxTree = openvdb::ax::ast::parse(opts.mInputCode->c_str(), logs); axlog(": " << axtime() << '\n'); if (!syntaxTree) { return EXIT_FAILURE; } if (opts.mMode == ProgOptions::Analyze) { axlog("[INFO] Running analysis options\n" << std::flush); if (opts.mPrintAST) { axlog("[INFO] | Printing AST\n" << std::flush); openvdb::ax::ast::print(*syntaxTree, true, std::cout); } if (opts.mReprint) { axlog("[INFO] | Reprinting code\n" << std::flush); openvdb::ax::ast::reprint(*syntaxTree, std::cout); } if (opts.mAttribRegPrint) { axlog("[INFO] | Printing Attribute Registry\n" << std::flush); const openvdb::ax::AttributeRegistry::ConstPtr reg = openvdb::ax::AttributeRegistry::create(*syntaxTree); reg->print(std::cout); std::cout << std::flush; } if (!opts.mInitCompile) { return EXIT_SUCCESS; } } assert(opts.mInitCompile); axtimer(); axlog("[INFO] Creating Compiler\n"); axlog("[INFO] | Optimization Level [" << optLevelToString(opts.mOptLevel) << "]\n" << std::flush); openvdb::ax::CompilerOptions compOpts; compOpts.mOptLevel = opts.mOptLevel; openvdb::ax::Compiler::Ptr compiler = openvdb::ax::Compiler::create(compOpts); openvdb::ax::CustomData::Ptr customData = openvdb::ax::CustomData::create(); axlog("[INFO] | " << axtime() << '\n' << std::flush); // Check what we need to compile for if performing execution if (opts.mMode == ProgOptions::Execute) { assert(meta); assert(grids); bool points = false; bool volumes = false; for (auto grid : *grids) { points |= grid->isType<openvdb::points::PointDataGrid>(); volumes |= !points; if (points && volumes) break; } if (points && volumes) opts.mCompileFor = ProgOptions::Compilation::All; else if (points) opts.mCompileFor = ProgOptions::Compilation::Points; else if (volumes) opts.mCompileFor = ProgOptions::Compilation::Volumes; } if (opts.mMode == ProgOptions::Analyze) { bool psuccess = true; if (opts.mCompileFor == ProgOptions::Compilation::All || opts.mCompileFor == ProgOptions::Compilation::Points) { axtimer(); axlog("[INFO] Compiling for VDB Points\n" << std::flush); try { compiler->compile<openvdb::ax::PointExecutable>(*syntaxTree, logs, customData); if (logs.hasError()) { axlog("[INFO] Compilation error(s)!\n"); psuccess = false; } } catch (std::exception& e) { psuccess = false; axlog("[INFO] Fatal error!\n"); OPENVDB_LOG_ERROR(e.what()); } const bool hasWarning = logs.hasWarning(); if (psuccess) { axlog("[INFO] | Compilation successful"); if (hasWarning) axlog(" with warning(s)\n"); } axlog("[INFO] | " << axtime() << '\n' << std::flush); } bool vsuccess = true; if (opts.mCompileFor == ProgOptions::Compilation::All || opts.mCompileFor == ProgOptions::Compilation::Volumes) { axtimer(); axlog("[INFO] Compiling for VDB Volumes\n" << std::flush); try { compiler->compile<openvdb::ax::VolumeExecutable>(*syntaxTree, logs, customData); if (logs.hasError()) { axlog("[INFO] Compilation error(s)!\n"); vsuccess = false; } } catch (std::exception& e) { vsuccess = false; axlog("[INFO] Fatal error!\n"); OPENVDB_LOG_ERROR(e.what()); } const bool hasWarning = logs.hasWarning(); if (vsuccess) { axlog("[INFO] | Compilation successful"); if (hasWarning) axlog(" with warning(s)\n"); } axlog("[INFO] | " << axtime() << '\n' << std::flush); } return ((vsuccess && psuccess) ? EXIT_SUCCESS : EXIT_FAILURE); } // Execute points if (opts.mCompileFor == ProgOptions::Compilation::All || opts.mCompileFor == ProgOptions::Compilation::Points) { axlog("[INFO] VDB PointDataGrids Found\n" << std::flush); openvdb::ax::PointExecutable::Ptr pointExe; axtimer(); try { axlog("[INFO] Compiling for VDB Points\n" << std::flush); pointExe = compiler->compile<openvdb::ax::PointExecutable>(*syntaxTree, logs, customData); } catch (std::exception& e) { OPENVDB_LOG_FATAL("Fatal error!\nErrors:\n" << e.what()); return EXIT_FAILURE; } if (pointExe) { axlog("[INFO] | Compilation successful"); if (logs.hasWarning()) { axlog(" with warning(s)\n"); } } else { if (logs.hasError()) { axlog("[INFO] Compilation error(s)!\n"); } return EXIT_FAILURE; } axlog("[INFO] | " << axtime() << '\n' << std::flush); size_t total = 0, count = 1; if (opts.mVerbose) { for (auto grid : *grids) { if (!grid->isType<openvdb::points::PointDataGrid>()) continue; ++total; } } for (auto grid : *grids) { if (!grid->isType<openvdb::points::PointDataGrid>()) continue; openvdb::points::PointDataGrid::Ptr points = openvdb::gridPtrCast<openvdb::points::PointDataGrid>(grid); axtimer(); axlog("[INFO] Executing on \"" << points->getName() << "\" " << count << " of " << total << '\n' << std::flush); ++count; try { pointExe->execute(*points); if (openvdb::ax::ast::callsFunction(*syntaxTree, "deletepoint")) { openvdb::points::deleteFromGroup(points->tree(), "dead", false, false); } } catch (std::exception& e) { OPENVDB_LOG_FATAL("Execution error!\nErrors:\n" << e.what()); return EXIT_FAILURE; } axlog("[INFO] | Execution success.\n"); axlog("[INFO] | " << axtime() << '\n' << std::flush); } } // Execute volumes if (opts.mCompileFor == ProgOptions::Compilation::All || opts.mCompileFor == ProgOptions::Compilation::Volumes) { axlog("[INFO] VDB Volumes Found\n" << std::flush); openvdb::ax::VolumeExecutable::Ptr volumeExe; try { axlog("[INFO] Compiling for VDB Points\n" << std::flush); volumeExe = compiler->compile<openvdb::ax::VolumeExecutable>(*syntaxTree, logs, customData); } catch (std::exception& e) { OPENVDB_LOG_FATAL("Fatal error!\nErrors:\n" << e.what()); return EXIT_FAILURE; } if (volumeExe) { axlog("[INFO] | Compilation successful"); if (logs.hasWarning()) { axlog(" with warning(s)\n"); } } else { if (logs.hasError()) { axlog("[INFO] Compilation error(s)!\n"); } return EXIT_FAILURE; } axlog("[INFO] | " << axtime() << '\n' << std::flush); if (opts.mVerbose) { std::vector<const std::string*> names; axlog("[INFO] Executing using:\n"); for (auto grid : *grids) { if (grid->isType<openvdb::points::PointDataGrid>()) continue; axlog(" " << grid->getName() << '\n'); axlog(" " << grid->valueType() << '\n'); axlog(" " << grid->gridClassToString(grid->getGridClass()) << '\n'); } axlog(std::flush); } try { volumeExe->execute(*grids); } catch (std::exception& e) { OPENVDB_LOG_FATAL("Execution error!\nErrors:\n" << e.what()); return EXIT_FAILURE; } axlog("[INFO] | Execution success.\n"); axlog("[INFO] | " << axtime() << '\n' << std::flush); } if (!opts.mOutputVDBFile.empty()) { axtimer(); axlog("[INFO] Writing results" << std::flush); openvdb::io::File out(opts.mOutputVDBFile); try { out.write(*grids, *meta); } catch (openvdb::Exception& e) { OPENVDB_LOG_ERROR(e.what() << " (" << out.filename() << ")"); return EXIT_FAILURE; } axlog("[INFO] | " << axtime() << '\n' << std::flush); } return EXIT_SUCCESS; }
NVIDIA-Omniverse/ext-openvdb/openvdb_ax/openvdb_ax/cmd/CMakeLists.txt
# Copyright Contributors to the OpenVDB Project # SPDX-License-Identifier: MPL-2.0 # #[=======================================================================[ CMake Configuration for OpenVDB AX Binaries #]=======================================================================] cmake_minimum_required(VERSION 3.12) project(OpenVDBAXBinaries LANGUAGES CXX) include(GNUInstallDirs) ######################################################################### message(STATUS "----------------------------------------------------") message(STATUS "---------- Configuring OpenVDBAXBinaries -----------") message(STATUS "----------------------------------------------------") ########################################################################## if(NOT OPENVDB_BUILD_AX) set(OPENVDBAX_LIB OpenVDB::openvdb_ax) else() set(OPENVDBAX_LIB openvdb_ax) endif() set(VDB_AX_SOURCE_FILES openvdb_ax.cc) add_executable(vdb_ax ${VDB_AX_SOURCE_FILES}) target_link_libraries(vdb_ax ${OPENVDBAX_LIB}) if(OPENVDB_ENABLE_RPATH) set(RPATHS "") # @todo There is probably a better way to do this for imported targets list(APPEND RPATHS ${Boost_LIBRARY_DIRS} ${IlmBase_LIBRARY_DIRS} ${Log4cplus_LIBRARY_DIRS} ${Blosc_LIBRARY_DIRS} ${Tbb_LIBRARY_DIRS} ) if(OPENVDB_BUILD_AX) list(APPEND RPATHS ${CMAKE_INSTALL_LIBDIR}) else() list(APPEND RPATHS ${OpenVDB_LIBRARY_DIRS}) endif() list(REMOVE_DUPLICATES RPATHS) set_target_properties(vdb_ax PROPERTIES INSTALL_RPATH "${RPATHS}" ) unset(RPATHS) endif() install(TARGETS vdb_ax RUNTIME DESTINATION ${CMAKE_INSTALL_BINDIR})
NVIDIA-Omniverse/ext-openvdb/openvdb_ax/openvdb_ax/codegen/FunctionTypes.h
// Copyright Contributors to the OpenVDB Project // SPDX-License-Identifier: MPL-2.0 /// @file codegen/FunctionTypes.h /// /// @authors Nick Avramoussis /// /// @brief Contains frameworks for creating custom AX functions which can /// be registered within the FunctionRegistry and used during code /// generation. The intended and safest way to build a function is to /// use the FunctionBuilder struct with its addSignature methods. Note /// that the derived Function classes provided can also be subclassed /// for more granular control, however may be subject to more substantial /// API changes. /// /// @details There are a variety of different ways to build a function /// which are tailored towards different function types. The two currently /// supported function implementations are C Bindings and IR generation. /// Additionally, depending on the return type of the function, you may /// need to declare your function an SRET (structural return) function. /// /// C Bindings: /// As the name suggests, the CFunction class infrastructure provides /// the quickest and easiest way to bind to methods in your host /// application. The most important thing to consider when choosing /// this approach is performance. LLVM will have no knowledge of the /// function body during optimization passes. Depending on the /// implementation of your method and the user's usage from AX, C /// bindings may be subject to limited optimizations in comparison to /// IR functions. For example, a static function which is called from /// within a loop cannot be unrolled. See the CFunction templated /// class. /// /// IR Functions: /// IR Functions expect implementations to generate the body of the /// function directly into IR during code generation. This ensures /// optimal performance during optimization passes however can be /// trickier to design. Note that, in the future, AX functions will /// be internally supported to provide a better solution for /// IR generated functions. See the IRFunction templated class. /// /// SRET Functions: /// Both C Bindings and IR Functions can be marked as SRET methods. /// SRET methods, in AX, are any function which returns a value which /// is not a scalar (e.g. vectors, matrices). This follows the same /// optimization logic as clang which will rebuild function signatures /// with their return type as the first argument if the return type is /// greater than a given size. You should never attempt to return /// alloca's directly from functions (unless malloced). /// /// Some other things to consider: /// - Ensure C Binding dependencies have been correctly mapped. /// - Avoid calling B.CreateAlloca inside of IR functions - instead /// rely on the utility method insertStaticAlloca() where possible. /// - Ensure both floating point and integer argument signatures are /// provided if you wish to avoid floats truncating. /// - Array arguments (vectors/matrices) are always passed by pointer. /// Scalar arguments are always passed by copy. /// - Ensure array arguments which will not be modified are marked as /// readonly. Currently, only array arguments can be passed by /// "reference". /// - Ensure function bodies, return types and parameters and marked /// with desirable llvm attributes. /// #ifndef OPENVDB_AX_CODEGEN_FUNCTION_TYPES_HAS_BEEN_INCLUDED #define OPENVDB_AX_CODEGEN_FUNCTION_TYPES_HAS_BEEN_INCLUDED #include "Types.h" #include "Utils.h" // isValidCast #include "ConstantFolding.h" #include <openvdb/version.h> #include <llvm/IR/Constants.h> #include <llvm/IR/IRBuilder.h> #include <llvm/IR/Module.h> #include <algorithm> #include <functional> #include <memory> #include <stack> #include <type_traits> #include <unordered_map> #include <vector> namespace openvdb { OPENVDB_USE_VERSION_NAMESPACE namespace OPENVDB_VERSION_NAME { namespace ax { namespace codegen { //////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////// /// @brief Object to array conversion methods to allow functions to return /// vector types. These containers provided an interface for automatic /// conversion of C++ objects to LLVM types as array types. template <typename T, size_t _SIZE = 1> struct ArgType { using Type = T; static const size_t SIZE = _SIZE; using ArrayType = Type[SIZE]; ArrayType mData; }; template <typename T, size_t S> struct LLVMType<ArgType<T,S>> : public AliasTypeMap<ArgType<T,S>, T[S]> {}; using V2D = ArgType<double, 2>; using V2F = ArgType<float, 2>; using V2I = ArgType<int32_t, 2>; using V3D = ArgType<double, 3>; using V3F = ArgType<float, 3>; using V3I = ArgType<int32_t, 3>; using V4D = ArgType<double, 4>; using V4F = ArgType<float, 4>; using V4I = ArgType<int32_t, 4>; using M3D = ArgType<double, 9>; using M3F = ArgType<float, 9>; using M4D = ArgType<double, 16>; using M4F = ArgType<float, 16>; //////////////////////////////////////////////////////////////////////////////// /// @brief Type to symbol conversions - these characters are used to build each /// functions unique signature. They differ from standard AX or LLVM /// syntax to be as short as possible i.e. vec4d, [4 x double] = d4 template <typename T> struct TypeToSymbol { static inline std::string s() { return "?"; } }; template <> struct TypeToSymbol<void> { static inline std::string s() { return "v"; } }; template <> struct TypeToSymbol<char> { static inline std::string s() { return "c"; } }; template <> struct TypeToSymbol<int16_t> { static inline std::string s() { return "s"; } }; template <> struct TypeToSymbol<int32_t> { static inline std::string s() { return "i"; } }; template <> struct TypeToSymbol<int64_t> { static inline std::string s() { return "l"; } }; template <> struct TypeToSymbol<float> { static inline std::string s() { return "f"; } }; template <> struct TypeToSymbol<double> { static inline std::string s() { return "d"; } }; template <> struct TypeToSymbol<AXString> { static inline std::string s() { return "a"; } }; template <typename T> struct TypeToSymbol<T*> { static inline std::string s() { return TypeToSymbol<T>::s() + "*"; } }; template <typename T, size_t S> struct TypeToSymbol<T[S]> { static inline std::string s() { return TypeToSymbol<T>::s() + std::to_string(S); } }; template <typename T, size_t S> struct TypeToSymbol<ArgType<T,S>> : public TypeToSymbol<T[S]> {}; template <typename T> struct TypeToSymbol<math::Vec2<T>> : public TypeToSymbol<T[2]> {}; template <typename T> struct TypeToSymbol<math::Vec3<T>> : public TypeToSymbol<T[3]> {}; template <typename T> struct TypeToSymbol<math::Vec4<T>> : public TypeToSymbol<T[4]> {}; template <typename T> struct TypeToSymbol<math::Mat3<T>> : public TypeToSymbol<T[9]> {}; template <typename T> struct TypeToSymbol<math::Mat4<T>> : public TypeToSymbol<T[16]> {}; template <typename T> struct TypeToSymbol<const T> : public TypeToSymbol<T> {}; template <typename T> struct TypeToSymbol<const T*> : public TypeToSymbol<T*> {}; //////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////// /// @brief Templated argument iterator which implements various small functions /// per argument type, resolved at compile time. /// template <typename SignatureT, size_t I = FunctionTraits<SignatureT>::N_ARGS> struct ArgumentIterator { using ArgT = typename FunctionTraits<SignatureT>::template Arg<I-1>; using ArgumentValueType = typename ArgT::Type; template <typename OpT> static void apply(const OpT& op, const bool forwards) { if (forwards) { ArgumentIterator<SignatureT, I-1>::apply(op, forwards); op(ArgumentValueType()); } else { op(ArgumentValueType()); ArgumentIterator<SignatureT, I-1>::apply(op, forwards); } } }; template <typename SignatureT> struct ArgumentIterator<SignatureT, 0> { template <typename OpT> static void apply(const OpT&, const bool) {} }; //////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////// /// @brief Populate a vector of llvm types from a function signature declaration. /// /// @param C The llvm context /// @param types A vector of types to populate /// template <typename SignatureT> inline llvm::Type* llvmTypesFromSignature(llvm::LLVMContext& C, std::vector<llvm::Type*>* types = nullptr) { using Traits = FunctionTraits<SignatureT>; using ArgumentIteratorT = ArgumentIterator<SignatureT, Traits::N_ARGS>; if (types) { types->reserve(Traits::N_ARGS); auto callback = [&types, &C](auto type) { using Type = decltype(type); types->emplace_back(LLVMType<Type>::get(C)); }; ArgumentIteratorT::apply(callback, /*forwards*/true); } return LLVMType<typename Traits::ReturnType>::get(C); } /// @brief Generate an LLVM FunctionType from a function signature /// /// @param C The llvm context /// template <typename SignatureT> inline llvm::FunctionType* llvmFunctionTypeFromSignature(llvm::LLVMContext& C) { std::vector<llvm::Type*> types; llvm::Type* returnType = llvmTypesFromSignature<SignatureT>(C, &types); return llvm::FunctionType::get(/*Result=*/returnType, /*Params=*/llvm::ArrayRef<llvm::Type*>(types), /*isVarArg=*/false); } /// @brief Print a function signature to the provided ostream. /// /// @param os The stream to print to /// @param types The function argument types /// @param returnType The return type of the function. Must not be a nullptr /// @param name The name of the function. If not provided, the return type /// neighbours the first parenthesis /// @param names Names of the function parameters. If a name is nullptr, it /// skipped /// @param axTypes Whether to try and convert the llvm::Types provided to /// AX types. If false, the llvm types are used. void printSignature(std::ostream& os, const std::vector<llvm::Type*>& types, const llvm::Type* returnType, const char* name = nullptr, const std::vector<const char*>& names = {}, const bool axTypes = false); //////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////// /// @brief The base/abstract representation of an AX function. Derived classes /// must implement the Function::types call to describe their signature. struct Function { using Ptr = std::shared_ptr<Function>; Function(const size_t size, const std::string& symbol) : mSize(size) , mSymbol(symbol) , mAttributes(nullptr) , mNames() , mDeps() { // symbol must be a valid string assert(!symbol.empty()); } virtual ~Function() = default; /// @brief Populate a vector of llvm::Types which describe this function /// signature. This method is used by Function::create, /// Function::print and Function::match. virtual llvm::Type* types(std::vector<llvm::Type*>&, llvm::LLVMContext&) const = 0; /// @brief Converts and creates this AX function into a llvm Function. /// @details This method uses the result from Function::types() to construct /// a llvm::FunctionType and a subsequent a llvm::Function. Any /// parameter, return or function attributes are also added to the /// function. If a module is provided, the module if first checked /// to see if the function already exists. If it does, it is /// immediately returned. If the function doesn't exist in the /// module, its prototype is created and also inserted into the end /// of the modules function list. If no module is provided, the /// function is left detached and must be added to a valid Module /// to be callable. /// @note The body of the function is left to derived classes to /// implement. As you need a Module to generate the prototype/body, /// this function serves two purposes. The first is to return the /// detached function signature if only a context is provided. /// The second is to ensure the function prototype and body (if /// required) is inserted into the module prior to returning. /// @note It is possible to end up with function symbol collisions if you /// do not have unique function symbols in your module /// /// @param C The LLVM Context /// @param M The Module to write the function to virtual llvm::Function* create(llvm::LLVMContext& C, llvm::Module* M = nullptr) const; /// @brief Convenience method which always uses the provided module to find /// the function or insert it if necessary. /// @param M The llvm::Module to use llvm::Function* create(llvm::Module& M) const { return this->create(M.getContext(), &M); } /// @brief Uses the IRBuilder to create a call to this function with the /// given arguments, creating the function and inserting it into the /// IRBuilder's Module if necessary (through Function::create). /// @note The IRBuilder must have a valid llvm Module/Function/Block /// attached /// @note If the number of provided arguments do not match the size of the /// current function, invalid IR will be generated. /// @note If the provided argument types do not match the current function /// and cast is false, invalid IR will be generated. Additionally, /// invalid IR will be generated if cast is true but no valid cast /// exists for a given argument. /// @note When casting arguments, the readonly flags of the function are /// not checked (unlike Function::match). Casting an argument will /// cause a new copy of the argument to be created and passed to the /// function. These new values do not propagate back any changes to /// the original argument. Separate functions for all writable /// argument types must be created. /// /// @param args The llvm Value arguments to call this function with /// @param B The llvm IRBuilder /// @param cast Whether to allow implicit casting of arguments virtual llvm::Value* call(const std::vector<llvm::Value*>& args, llvm::IRBuilder<>& B, const bool cast = false) const; /// @brief The result type from calls to Function::match enum SignatureMatch { None = 0, Size, Implicit, Explicit }; /// @brief The base implementation for determining how a vector of llvm /// arguments translates to this functions signature. Returns an /// enum which represents the available mapping. /// @details This method calls types() to figure out the function signature, /// then compares each argument type to the type in the input /// vector. If the types match exactly, an Explicit match is found. /// If the sizes of the inputs and signature differ, no match is /// found and None is returned. If however, the sizes match and /// there exists a valid implicit cast from the input type to the /// signature type for every input, an Implicit match is returned. /// Finally, if the sizes match but there is no implicit cast /// mapping, Size is returned. /// i8 -> i32 : Implicit /// i32 -> i32 : Explicit /// str -> i32 : Size /// (i32,i32) -> i32 : None /// @note Due to the way CFunctionSRet is implemented, the LLVM Context /// must be provided in case we have a zero arg function signature /// with a SRET. /// @param inputs The input types /// @param C The LLVM Context virtual SignatureMatch match(const std::vector<llvm::Type*>& inputs, llvm::LLVMContext& C) const; /// @brief The number of arguments that this function has inline size_t size() const { return mSize; } /// @brief The function symbol name. /// @details This will be used as its identifier in IR and must be unique. inline const char* symbol() const { return mSymbol.c_str(); } /// @brief Returns the descriptive name of the given argument index /// @details If the index is greater than the number of arguments, an empty /// string is returned. /// /// @param idx The index of the argument inline const char* argName(const size_t idx) const { return idx < mNames.size() ? mNames[idx] : ""; } /// @brief Print this function's signature to the provided ostream. /// @details This is intended to return a descriptive front end user string /// rather than the function's IR representation. This function is /// virtual so that derived classes can customize how they present /// frontend information. /// @sa printSignature /// /// @param C The llvm context /// @param os The ostream to print to /// @param name The name to insert into the description. /// @param axTypes Whether to print llvm IR or AX Types. virtual void print(llvm::LLVMContext& C, std::ostream& os, const char* name = nullptr, const bool axTypes = true) const; /// Builder methods inline bool hasParamAttribute(const size_t i, const llvm::Attribute::AttrKind& kind) const { if (!mAttributes) return false; const auto iter = mAttributes->mParamAttrs.find(i); if (iter == mAttributes->mParamAttrs.end()) return false; const auto& vec = iter->second; return std::find(vec.begin(), vec.end(), kind) != vec.end(); } inline void setArgumentNames(std::vector<const char*> names) { mNames = names; } const std::vector<const char*>& dependencies() const { return mDeps; } inline void setDependencies(std::vector<const char*> deps) { mDeps = deps; } inline void setFnAttributes(const std::vector<llvm::Attribute::AttrKind>& in) { this->attrs().mFnAttrs = in; } inline void setRetAttributes(const std::vector<llvm::Attribute::AttrKind>& in) { this->attrs().mRetAttrs = in; } inline void setParamAttributes(const size_t i, const std::vector<llvm::Attribute::AttrKind>& in) { this->attrs().mParamAttrs[i] = in; } protected: /// @brief Cast the provided arguments to the given type as supported by /// implicit casting of function types. If the types already match /// OR if a cast cannot be performed, nothing is done to the argument. /// @todo This should really be generalized out for Function::call and /// Function::match to both use. However, due to SRET functions, /// this logic must be performed somewhere in the Function class /// hierarchy and not in FunctionGroup static void cast(std::vector<llvm::Value*>& args, const std::vector<llvm::Type*>& types, llvm::IRBuilder<>& B); private: struct Attributes { std::vector<llvm::Attribute::AttrKind> mFnAttrs, mRetAttrs; std::map<size_t, std::vector<llvm::Attribute::AttrKind>> mParamAttrs; }; inline Attributes& attrs() { if (!mAttributes) mAttributes.reset(new Attributes()); return *mAttributes; } llvm::AttributeList flattenAttrs(llvm::LLVMContext& C) const; const size_t mSize; const std::string mSymbol; std::unique_ptr<Attributes> mAttributes; std::vector<const char*> mNames; std::vector<const char*> mDeps; }; /// @brief Templated interface class for SRET functions. This struct provides /// the interface for functions that wish to return arrays (vectors or /// matrices) by internally remapping the first argument for the user. /// As far as LLVM and any bindings are concerned, the function /// signature remains unchanged - however the first argument becomes /// "invisible" to the user and is instead allocated by LLVM before the /// function is executed. Importantly, the argument has no impact on /// the user facing AX signature and doesn't affect declaration selection. /// @note This class is not intended to be instantiated directly, but instead /// used by derived implementation which hold a valid implementations /// of member functions required to create a llvm::Function (such as /// Function::types and Function::call). This exists as an interface to /// avoid virtual inheritance. /// template <typename SignatureT, typename DerivedFunction> struct SRetFunction : public DerivedFunction { using Ptr = std::shared_ptr<SRetFunction<SignatureT, DerivedFunction>>; using Traits = FunctionTraits<SignatureT>; // check there actually are arguments static_assert(Traits::N_ARGS > 0, "SRET Function object has been setup with the first argument as the return " "value, however the provided signature is empty."); // check no return value exists static_assert(std::is_same<typename Traits::ReturnType, void>::value, "SRET Function object has been setup with the first argument as the return " "value and a non void return type."); private: using FirstArgument = typename Traits::template Arg<0>::Type; static_assert(std::is_pointer<FirstArgument>::value, "SRET Function object has been setup with the first argument as the return " "value, but this argument it is not a pointer type."); using SRetType = typename std::remove_pointer<FirstArgument>::type; public: /// @brief Override of match which inserts the SRET type such that the base /// class methods ignore it. Function::SignatureMatch match(const std::vector<llvm::Type*>& args, llvm::LLVMContext& C) const override { // append return type and right rotate std::vector<llvm::Type*> inputs(args); inputs.emplace_back(LLVMType<SRetType*>::get(C)); std::rotate(inputs.rbegin(), inputs.rbegin() + 1, inputs.rend()); return DerivedFunction::match(inputs, C); } /// @brief Override of call which allocates the required SRET llvm::Value /// for this function. /// @note Unlike other function where the returned llvm::Value* is a /// llvm::CallInst (which also represents the return value), /// SRET functions return the allocated 1st argument i.e. not a /// llvm::CallInst llvm::Value* call(const std::vector<llvm::Value*>& args, llvm::IRBuilder<>& B, const bool cast) const override { // append return value and right rotate std::vector<llvm::Value*> inputs(args); llvm::Type* sret = LLVMType<SRetType>::get(B.getContext()); inputs.emplace_back(insertStaticAlloca(B, sret)); std::rotate(inputs.rbegin(), inputs.rbegin() + 1, inputs.rend()); DerivedFunction::call(inputs, B, cast); return inputs.front(); } /// @brief Override of print to avoid printing out the SRET type void print(llvm::LLVMContext& C, std::ostream& os, const char* name = nullptr, const bool axTypes = true) const override { std::vector<llvm::Type*> current; llvm::Type* ret = this->types(current, C); // left rotate std::rotate(current.begin(), current.begin() + 1, current.end()); ret = current.back(); current.pop_back(); std::vector<const char*> names; names.reserve(this->size()); for (size_t i = 0; i < this->size()-1; ++i) { names.emplace_back(this->argName(i)); } printSignature(os, current, ret, name, names, axTypes); } protected: /// @brief Forward all arguments to the derived class template <typename ...Args> SRetFunction(Args&&... ts) : DerivedFunction(ts...) {} }; /// @brief The base class for all C bindings. struct CFunctionBase : public Function { using Ptr = std::shared_ptr<CFunctionBase>; ~CFunctionBase() override = default; /// @brief Returns the global address of this function. /// @note This is only required for C bindings. virtual uint64_t address() const = 0; inline void setConstantFold(bool on) { mConstantFold = on; } inline bool hasConstantFold() const { return mConstantFold; } inline virtual llvm::Value* fold(const std::vector<llvm::Value*>&, llvm::LLVMContext&) const { return nullptr; } protected: CFunctionBase(const size_t size, const std::string& symbol) : Function(size, symbol) , mConstantFold(false) {} private: bool mConstantFold; }; /// @brief Represents a concrete C function binding. /// /// @note This struct is templated on the signature to allow for evaluation of /// the arguments to llvm types from any llvm context. /// template <typename SignatureT> struct CFunction : public CFunctionBase { using CFunctionT = CFunction<SignatureT>; using Ptr = std::shared_ptr<CFunctionT>; using Traits = FunctionTraits<SignatureT>; // Assert that the return argument is not a pointer. Note that this is // relaxed for IR functions where it's allowed if the function is embedded. static_assert(!std::is_pointer<typename Traits::ReturnType>::value, "CFunction object has been setup with a pointer return argument. C bindings " "cannot return memory locations to LLVM - Consider using a CFunctionSRet."); CFunction(const std::string& symbol, const SignatureT function) : CFunctionBase(Traits::N_ARGS, symbol) , mFunction(function) {} ~CFunction() override = default; inline llvm::Type* types(std::vector<llvm::Type*>& types, llvm::LLVMContext& C) const override { return llvmTypesFromSignature<SignatureT>(C, &types); } inline uint64_t address() const override final { return reinterpret_cast<uint64_t>(mFunction); } llvm::Value* call(const std::vector<llvm::Value*>& args, llvm::IRBuilder<>& B, const bool cast) const override { llvm::Value* result = this->fold(args, B.getContext()); if (result) return result; return Function::call(args, B, cast); } llvm::Value* fold(const std::vector<llvm::Value*>& args, llvm::LLVMContext& C) const override final { auto allconst = [](const std::vector<llvm::Value*>& vals) -> bool { for (auto& value : vals) { if (!llvm::isa<llvm::Constant>(value)) return false; } return true; }; if (!this->hasConstantFold()) return nullptr; if (!allconst(args)) return nullptr; std::vector<llvm::Constant*> constants; constants.reserve(args.size()); for (auto& value : args) { constants.emplace_back(llvm::cast<llvm::Constant>(value)); } // no guarantee that fold() will be able to cast all arguments return ConstantFolder<SignatureT>::fold(constants, *mFunction, C); } private: const SignatureT* mFunction; }; /// @brief The base/abstract definition for an IR function. struct IRFunctionBase : public Function { using Ptr = std::shared_ptr<IRFunctionBase>; /// @brief The IR callback function which will write the LLVM IR for this /// function's body. /// @details The first argument is the vector of functional arguments. i.e. /// a representation of the value that the callback has been invoked /// with. /// The last argument is the IR builder which should be used to /// generate the function body IR. /// @note You can return a nullptr from this method which will represent /// a ret void, a ret void instruction, or an actual value using GeneratorCb = std::function<llvm::Value* (const std::vector<llvm::Value*>&, llvm::IRBuilder<>&)>; llvm::Type* types(std::vector<llvm::Type*>& types, llvm::LLVMContext& C) const override = 0; /// @brief Enable or disable the embedding of IR. Embedded IR is currently /// required for function which use parent function parameters. inline void setEmbedIR(bool on) { mEmbedIR = on; } inline bool hasEmbedIR() const { return mEmbedIR; } /// @brief Override for the creation of an IR function. This ensures that /// the body and prototype of the function are generated if a Module /// is provided. /// @note A nullptr is returned if mEmbedIR is true and no action is /// performed. /// @note Throws if this function has been initialized with a nullptr /// generator callback. In this case, the function prototype will /// be created, but not the function body. /// @note Throws if the return type of the generator callback does not /// match the function prototype. In this case, both the prototype /// and the function body will be created and inserted, but the IR /// will be invalid. llvm::Function* create(llvm::LLVMContext& C, llvm::Module* M) const override; /// @brief Override for call, which is only necessary if mEmbedIR is true, /// as the IR generation for embedded functions is delayed until /// the function is called. If mEmbedIR is false, this simply calls /// Function::call llvm::Value* call(const std::vector<llvm::Value*>& args, llvm::IRBuilder<>& B, const bool cast) const override; protected: // @todo This should ideally live in FunctionGroup::execute, but the return // type is allowed to differ for sret C bindings. inline void verifyResultType(const llvm::Type* result, const llvm::Type* expected) const { if (result == expected) return; std::string source, target; if (result) llvmTypeToString(result, source); llvmTypeToString(expected, target); OPENVDB_THROW(AXCodeGenError, "Function \"" + std::string(this->symbol()) + "\" has been invoked with a mismatching return type. Expected: \"" + target + "\", got \"" + source + "\"."); } IRFunctionBase(const std::string& symbol, const GeneratorCb& gen, const size_t size) : Function(size, symbol) , mGen(gen) , mEmbedIR(false) {} ~IRFunctionBase() override = default; const GeneratorCb mGen; bool mEmbedIR; }; /// @brief Represents a concrete IR function. template <typename SignatureT> struct IRFunction : public IRFunctionBase { using Traits = FunctionTraits<SignatureT>; using Ptr = std::shared_ptr<IRFunction>; IRFunction(const std::string& symbol, const GeneratorCb& gen) : IRFunctionBase(symbol, gen, Traits::N_ARGS) {} inline llvm::Type* types(std::vector<llvm::Type*>& types, llvm::LLVMContext& C) const override { return llvmTypesFromSignature<SignatureT>(C, &types); } }; /// @brief Represents a concrete C function binding with the first argument as /// its return type. template <typename SignatureT> struct CFunctionSRet : public SRetFunction<SignatureT, CFunction<SignatureT>> { using BaseT = SRetFunction<SignatureT, CFunction<SignatureT>>; CFunctionSRet(const std::string& symbol, const SignatureT function) : BaseT(symbol, function) {} ~CFunctionSRet() override = default; }; /// @brief Represents a concrete IR function with the first argument as /// its return type. template <typename SignatureT> struct IRFunctionSRet : public SRetFunction<SignatureT, IRFunction<SignatureT>> { using BaseT = SRetFunction<SignatureT, IRFunction<SignatureT>>; IRFunctionSRet(const std::string& symbol, const IRFunctionBase::GeneratorCb& gen) : BaseT(symbol, gen) {} ~IRFunctionSRet() override = default; }; /// @brief todo struct FunctionGroup { using Ptr = std::shared_ptr<FunctionGroup>; using UniquePtr = std::unique_ptr<FunctionGroup>; using FunctionList = std::vector<Function::Ptr>; FunctionGroup(const char* name, const char* doc, const FunctionList& list) : mName(name) , mDoc(doc) , mFunctionList(list) {} ~FunctionGroup() = default; /// @brief Given a vector of llvm types, automatically returns the best /// possible function declaration from the stored function list. The /// 'best' declaration is determined by the provided types /// compatibility to each functions signature. /// @note If multiple implicit matches are found, the first match is /// returned. /// @note Returns a nullptr if no compatible match was found or if the /// function list is empty. A compatible match is defined as an /// Explicit or Implicit match. /// /// @param types A vector of types representing the function argument types /// @param C The llvm context /// @param type If provided, type is set to the type of match that occurred /// Function::Ptr match(const std::vector<llvm::Type*>& types, llvm::LLVMContext& C, Function::SignatureMatch* type = nullptr) const; /// @brief Given a vector of llvm values provided by the user, find the /// best possible function signature, generate and execute the /// function body. Returns the return value of the function (can be /// void). /// @note This function will throw if not compatible match is found or if /// no valid return is provided by the matched declarations /// implementation. /// /// @param args A vector of values representing the function arguments /// @param B The current llvm IRBuilder /// llvm::Value* execute(const std::vector<llvm::Value*>& args, llvm::IRBuilder<>& B) const; /// @brief Accessor to the underlying function signature list /// inline const FunctionList& list() const { return mFunctionList; } const char* name() const { return mName; } const char* doc() const { return mDoc; } private: const char* mName; const char* mDoc; const FunctionList mFunctionList; }; /// @brief The FunctionBuilder class provides a builder pattern framework to /// allow easy and valid construction of AX functions. There are a /// number of complex tasks which may need to be performed during /// construction of C or IR function which are delegated to this /// builder, whilst ensuring that the constructed functions are /// guaranteed to be valid. /// @details Use the FunctionBuilder::addSignature methods to append function /// signatures. Finalize the group of functions with /// FunctionBuilder::get. struct FunctionBuilder { enum DeclPreferrence { C, IR, Any }; struct Settings { using Ptr = std::shared_ptr<Settings>; inline bool isDefault() const { if (mNames) return false; if (!mDeps.empty()) return false; if (mConstantFold || mEmbedIR) return false; if (!mFnAttrs.empty()) return false; if (!mRetAttrs.empty()) return false; if (!mParamAttrs.empty()) return false; return true; } std::shared_ptr<std::vector<const char*>> mNames = nullptr; std::vector<const char*> mDeps = {}; bool mConstantFold = false; bool mEmbedIR = false; std::vector<llvm::Attribute::AttrKind> mFnAttrs = {}; std::vector<llvm::Attribute::AttrKind> mRetAttrs = {}; std::map<size_t, std::vector<llvm::Attribute::AttrKind>> mParamAttrs = {}; }; FunctionBuilder(const char* name) : mName(name) , mCurrentSettings(new Settings()) {} template <typename Signature, bool SRet = false> inline FunctionBuilder& addSignature(const IRFunctionBase::GeneratorCb& cb, const char* symbol = nullptr) { using IRFType = typename std::conditional <!SRet, IRFunction<Signature>, IRFunctionSRet<Signature>>::type; using IRPtr = typename IRFType::Ptr; Settings::Ptr settings = mCurrentSettings; if (!mCurrentSettings->isDefault()) { settings.reset(new Settings()); } std::string s; if (symbol) s = std::string(symbol); else s = this->genSymbol<Signature>(); auto ir = IRPtr(new IRFType(s, cb)); mIRFunctions.emplace_back(ir); mSettings[ir.get()] = settings; mCurrentSettings = settings; return *this; } template <typename Signature, bool SRet = false> inline FunctionBuilder& addSignature(const Signature* ptr, const char* symbol = nullptr) { using CFType = typename std::conditional <!SRet, CFunction<Signature>, CFunctionSRet<Signature>>::type; using CPtr = typename CFType::Ptr; Settings::Ptr settings = mCurrentSettings; if (!mCurrentSettings->isDefault()) { settings.reset(new Settings()); } std::string s; if (symbol) s = std::string(symbol); else s = this->genSymbol<Signature>(); auto c = CPtr(new CFType(s, ptr)); mCFunctions.emplace_back(c); mSettings[c.get()] = settings; mCurrentSettings = settings; return *this; } template <typename Signature, bool SRet = false> inline FunctionBuilder& addSignature(const IRFunctionBase::GeneratorCb& cb, const Signature* ptr, const char* symbol = nullptr) { this->addSignature<Signature, SRet>(cb, symbol); this->addSignature<Signature, SRet>(ptr, symbol); return *this; } inline FunctionBuilder& addDependency(const char* name) { mCurrentSettings->mDeps.emplace_back(name); return *this; } inline FunctionBuilder& setEmbedIR(bool on) { mCurrentSettings->mEmbedIR = on; return *this; } inline FunctionBuilder& setConstantFold(bool on) { mCurrentSettings->mConstantFold = on; return *this; } inline FunctionBuilder& setArgumentNames(const std::vector<const char*>& names) { mCurrentSettings->mNames.reset(new std::vector<const char*>(names)); return *this; } /// @details Parameter and Function Attributes. When designing a C binding, /// llvm will be unable to assign parameter markings to the return /// type, function body or parameter attributes due to there not /// being any visibility on the function itself during codegen. /// The best way to ensure performant C bindings is to ensure /// that the function is marked with the required llvm parameters. /// Some of the heavy hitters (which can have the most impact) /// are below: /// /// Functions: /// - norecurse /// This function attribute indicates that the function does /// not call itself either directly or indirectly down any /// possible call path. /// /// - willreturn /// This function attribute indicates that a call of this /// function will either exhibit undefined behavior or comes /// back and continues execution at a point in the existing /// call stack that includes the current invocation. /// /// - nounwind /// This function attribute indicates that the function never /// raises an exception. /// /// - readnone /// On a function, this attribute indicates that the function /// computes its result (or decides to unwind an exception) based /// strictly on its arguments, without dereferencing any pointer /// arguments or otherwise accessing any mutable state (e.g. memory, /// control registers, etc) visible to caller functions. /// /// - readonly /// On a function, this attribute indicates that the function /// does not write through any pointer arguments (including byval /// arguments) or otherwise modify any state (e.g. memory, control /// registers, etc) visible to caller functions. /// control registers, etc) visible to caller functions. /// /// - writeonly /// On a function, this attribute indicates that the function may /// write to but does not read from memory. /// /// Parameters: /// - noalias /// This indicates that objects accessed via pointer values based /// on the argument or return value are not also accessed, during /// the execution of the function, via pointer values not based on /// the argument or return value. /// /// - nonnull /// This indicates that the parameter or return pointer is not null. /// /// - readonly /// Indicates that the function does not write through this pointer /// argument, even though it may write to the memory that the pointer /// points to. /// /// - writeonly /// Indicates that the function may write to but does not read through /// this pointer argument (even though it may read from the memory /// that the pointer points to). /// inline FunctionBuilder& addParameterAttribute(const size_t idx, const llvm::Attribute::AttrKind attr) { mCurrentSettings->mParamAttrs[idx].emplace_back(attr); return *this; } inline FunctionBuilder& addReturnAttribute(const llvm::Attribute::AttrKind attr) { mCurrentSettings->mRetAttrs.emplace_back(attr); return *this; } inline FunctionBuilder& addFunctionAttribute(const llvm::Attribute::AttrKind attr) { mCurrentSettings->mFnAttrs.emplace_back(attr); return *this; } inline FunctionBuilder& setDocumentation(const char* doc) { mDoc = doc; return *this; } inline FunctionBuilder& setPreferredImpl(DeclPreferrence pref) { mDeclPref = pref; return *this; } inline FunctionGroup::UniquePtr get() const { for (auto& decl : mCFunctions) { const auto& s = mSettings.at(decl.get()); decl->setDependencies(s->mDeps); decl->setConstantFold(s->mConstantFold); if (!s->mFnAttrs.empty()) decl->setFnAttributes(s->mFnAttrs); if (!s->mRetAttrs.empty()) decl->setRetAttributes(s->mRetAttrs); if (!s->mParamAttrs.empty()) { for (auto& idxAttrs : s->mParamAttrs) { if (idxAttrs.first > decl->size()) continue; decl->setParamAttributes(idxAttrs.first, idxAttrs.second); } } if (s->mNames) decl->setArgumentNames(*s->mNames); } for (auto& decl : mIRFunctions) { const auto& s = mSettings.at(decl.get()); decl->setDependencies(s->mDeps); decl->setEmbedIR(s->mEmbedIR); if (!s->mFnAttrs.empty()) decl->setFnAttributes(s->mFnAttrs); if (!s->mRetAttrs.empty()) decl->setRetAttributes(s->mRetAttrs); if (!s->mParamAttrs.empty()) { for (auto& idxAttrs : s->mParamAttrs) { if (idxAttrs.first > decl->size()) continue; decl->setParamAttributes(idxAttrs.first, idxAttrs.second); } } if (s->mNames) decl->setArgumentNames(*s->mNames); } std::vector<Function::Ptr> functions; if (mDeclPref == DeclPreferrence::IR) { functions.insert(functions.end(), mIRFunctions.begin(), mIRFunctions.end()); } if (mDeclPref == DeclPreferrence::C) { functions.insert(functions.end(), mCFunctions.begin(), mCFunctions.end()); } if (functions.empty()) { functions.insert(functions.end(), mIRFunctions.begin(), mIRFunctions.end()); functions.insert(functions.end(), mCFunctions.begin(), mCFunctions.end()); } FunctionGroup::UniquePtr group(new FunctionGroup(mName, mDoc, functions)); return group; } private: template <typename Signature> std::string genSymbol() const { using Traits = FunctionTraits<Signature>; std::string args; auto callback = [&args](auto type) { using Type = decltype(type); args += TypeToSymbol<Type>::s(); }; ArgumentIterator<Signature>::apply(callback, /*forwards*/true); /// @note important to prefix all symbols with "ax." so that /// they will never conflict with internal llvm symbol /// names (such as standard library methods e.g, cos, cosh // assemble the symbol return "ax." + std::string(this->mName) + "." + TypeToSymbol<typename Traits::ReturnType>::s() + args; } const char* mName = ""; const char* mDoc = ""; DeclPreferrence mDeclPref = IR; std::vector<CFunctionBase::Ptr> mCFunctions = {}; std::vector<IRFunctionBase::Ptr> mIRFunctions = {}; std::map<const Function*, Settings::Ptr> mSettings = {}; Settings::Ptr mCurrentSettings = nullptr; }; } // namespace codegen } // namespace ax } // namespace OPENVDB_VERSION_NAME } // namespace openvdb #endif // OPENVDB_AX_CODEGEN_FUNCTION_TYPES_HAS_BEEN_INCLUDED
NVIDIA-Omniverse/ext-openvdb/openvdb_ax/openvdb_ax/codegen/PointComputeGenerator.h
// Copyright Contributors to the OpenVDB Project // SPDX-License-Identifier: MPL-2.0 /// @file codegen/PointComputeGenerator.h /// /// @authors Nick Avramoussis, Matt Warner, Francisco Gochez, Richard Jones /// /// @brief The visitor framework and function definition for point data /// grid code generation /// #ifndef OPENVDB_AX_POINT_COMPUTE_GENERATOR_HAS_BEEN_INCLUDED #define OPENVDB_AX_POINT_COMPUTE_GENERATOR_HAS_BEEN_INCLUDED #include "ComputeGenerator.h" #include "FunctionTypes.h" #include "Types.h" #include "Utils.h" #include "../compiler/AttributeRegistry.h" #include <openvdb/version.h> namespace openvdb { OPENVDB_USE_VERSION_NAMESPACE namespace OPENVDB_VERSION_NAME { namespace ax { namespace codegen { /// @brief The function definition and signature which is built by the /// PointComputeGenerator. /// /// The argument structure is as follows: /// /// 1) - A void pointer to the CustomData /// 2) - A void pointer to the leaf AttributeSet /// 3) - An unsigned integer, representing the leaf relative point /// id being executed /// 4) - A void pointer to a vector of void pointers, representing an /// array of attribute handles /// 5) - A void pointer to a vector of void pointers, representing an /// array of group handles /// 6) - A void pointer to a LeafLocalData object, used to track newly /// initialized attributes and arrays /// struct PointKernel { /// The signature of the generated function using Signature = void(const void* const, const void* const, uint64_t, void**, void**, void*); using FunctionTraitsT = codegen::FunctionTraits<Signature>; static const size_t N_ARGS = FunctionTraitsT::N_ARGS; /// The argument key names available during code generation static const std::array<std::string, N_ARGS>& argumentKeys(); static std::string getDefaultName(); }; /// @brief An additonal function built by the PointComputeGenerator. /// Currently both compute and compute range functions have the same /// signature struct PointRangeKernel : public PointKernel { static std::string getDefaultName(); }; /////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////// namespace codegen_internal { /// @brief Visitor object which will generate llvm IR for a syntax tree which has been generated from /// AX that targets point grids. The IR will represent 2 functions : one that executes over /// single points and one that executes over a collection of points. This is primarily used by the /// Compiler class. struct PointComputeGenerator : public ComputeGenerator { /// @brief Constructor /// @param module llvm Module for generating IR /// @param options Options for the function registry behaviour /// @param functionRegistry Function registry object which will be used when generating IR /// for function calls /// @param logger Logger for collecting logical errors and warnings PointComputeGenerator(llvm::Module& module, const FunctionOptions& options, FunctionRegistry& functionRegistry, Logger& logger); ~PointComputeGenerator() override = default; using ComputeGenerator::traverse; using ComputeGenerator::visit; AttributeRegistry::Ptr generate(const ast::Tree& node); bool visit(const ast::Attribute*) override; private: llvm::Value* attributeHandleFromToken(const std::string&); void getAttributeValue(const std::string& globalName, llvm::Value* location); }; } // namespace namespace codegen_internal } // namespace codegen } // namespace ax } // namespace OPENVDB_VERSION_NAME } // namespace openvdb #endif // OPENVDB_AX_POINT_COMPUTE_GENERATOR_HAS_BEEN_INCLUDED