file_path
stringlengths 21
202
| content
stringlengths 13
1.02M
| size
int64 13
1.02M
| lang
stringclasses 9
values | avg_line_length
float64 5.43
98.5
| max_line_length
int64 12
993
| alphanum_fraction
float64 0.27
0.91
|
---|---|---|---|---|---|---|
NVIDIA-Omniverse/kit-extension-sample-ui-window/exts/omni.example.ui_gradient_window/omni/example/ui_gradient_window/window.py | # Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved./icons/
#
# 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.
#
__all__ = ["PropertyWindowExample"]
from ast import With
from ctypes import alignment
import omni.kit
import omni.ui as ui
from .style import main_window_style, get_gradient_color, build_gradient_image
from .style import cl_combobox_background, cls_temperature_gradient, cls_color_gradient, cls_tint_gradient, cls_grey_gradient, cls_button_gradient
from .color_widget import ColorWidget
from .collapsable_widget import CustomCollsableFrame, build_collapsable_header
LABEL_WIDTH = 120
SPACING = 10
def _get_plus_glyph():
return omni.kit.ui.get_custom_glyph_code("${glyphs}/menu_context.svg")
def _get_search_glyph():
return omni.kit.ui.get_custom_glyph_code("${glyphs}/menu_search.svg")
class PropertyWindowExample(ui.Window):
"""The class that represents the window"""
def __init__(self, title: str, delegate=None, **kwargs):
self.__label_width = LABEL_WIDTH
super().__init__(title, **kwargs)
# Apply the style to all the widgets of this window
self.frame.style = main_window_style
# Set the function that is called to build widgets when the window is visible
self.frame.set_build_fn(self._build_fn)
def destroy(self):
# It will destroy all the children
super().destroy()
@property
def label_width(self):
"""The width of the attribute label"""
return self.__label_width
@label_width.setter
def label_width(self, value):
"""The width of the attribute label"""
self.__label_width = value
self.frame.rebuild()
def _build_transform(self):
"""Build the widgets of the "Calculations" group"""
with ui.ZStack():
with ui.VStack():
ui.Spacer(height=5)
with ui.HStack():
ui.Spacer()
ui.Image(name="transform", fill_policy=ui.FillPolicy.PRESERVE_ASPECT_FIT, width=24, height=24)
ui.Spacer(width=30)
ui.Spacer()
with CustomCollsableFrame("TRANSFORMS").collapsable_frame:
with ui.VStack(height=0, spacing=SPACING):
ui.Spacer(height=2)
self._build_vector_widget("Position", 70)
self._build_vector_widget("Rotation", 70)
with ui.ZStack():
self._build_vector_widget("Scale", 85)
with ui.HStack():
ui.Spacer(width=42)
ui.Image(name="link", fill_policy=ui.FillPolicy.PRESERVE_ASPECT_FIT, width=20)
def _build_path(self):
CustomCollsableFrame("PATH", collapsed=True)
def _build_light_properties(self):
"""Build the widgets of the "Parameters" group"""
with CustomCollsableFrame("LIGHT PROPERTIES").collapsable_frame:
with ui.VStack(height=0, spacing=SPACING):
ui.Spacer(height=2)
self._build_combobox("Type", ["Sphere Light", "Disk Light", "Rect Light"])
self.color_gradient_data, self.tint_gradient_data, self.grey_gradient_data = self._build_color_widget("Color")
self._build_color_temperature()
self.diffuse_button_data = self._build_gradient_float_slider("Diffuse Multiplier")
self.exposture_button_data = self._build_gradient_float_slider("Exposture")
self.intensity_button_data = self._build_gradient_float_slider("Intensity", default_value=3000, min=0, max=6000)
self._build_checkbox("Normalize Power", False)
self._build_combobox("Purpose", ["Default", "Customized"])
self.radius_button_data = self._build_gradient_float_slider("Radius")
self._build_shaping()
self.specular_button_data = self._build_gradient_float_slider("Specular Multiplier")
self._build_checkbox("Treat As Point")
def _build_line_dot(self, line_width, height):
with ui.HStack():
ui.Spacer(width=10)
with ui.VStack(width=line_width):
ui.Spacer(height=height)
ui.Line(name="group_line", alignment=ui.Alignment.TOP)
with ui.VStack(width=6):
ui.Spacer(height=height-2)
ui.Circle(name="group_circle", width=6, height=6, alignment=ui.Alignment.BOTTOM)
def _build_shaping(self):
"""Build the widgets of the "SHAPING" group"""
with ui.ZStack():
with ui.HStack():
ui.Spacer(width=3)
self._build_line_dot(10, 17)
with ui.HStack():
ui.Spacer(width=13)
with ui.VStack():
ui.Spacer(height=17)
ui.Line(name="group_line", alignment=ui.Alignment.RIGHT, width=0)
ui.Spacer(height=80)
with ui.CollapsableFrame(" SHAPING", name="group", build_header_fn=build_collapsable_header):
with ui.VStack(height=0, spacing=SPACING):
self.angle_button_data = self._build_gradient_float_slider("Cone Angle")
self.softness_button_data = self._build_gradient_float_slider("Cone Softness")
self.focus_button_data = self._build_gradient_float_slider("Focus")
self.focus_color_data, self.focus_tint_data, self.focus_grey_data = self._build_color_widget("Focus Tint")
def _build_vector_widget(self, widget_name, space):
with ui.HStack():
ui.Label(widget_name, name="attribute_name", width=0)
ui.Spacer(width=space)
# The custom compound widget
ColorWidget(1.0, 1.0, 1.0, draw_colorpicker=False)
ui.Spacer(width=10)
def _build_color_temperature(self):
with ui.ZStack():
with ui.HStack():
ui.Spacer(width=10)
with ui.VStack():
ui.Spacer(height=8)
ui.Line(name="group_line", alignment=ui.Alignment.RIGHT, width=0)
with ui.VStack(height=0, spacing=SPACING):
with ui.HStack():
self._build_line_dot(10, 8)
ui.Label("Enable Color Temperature", name="attribute_name", width=0)
ui.Spacer()
ui.Image(name="on_off", fill_policy=ui.FillPolicy.PRESERVE_ASPECT_FIT, width=20)
rect_changed, rect_default = self.__build_value_changed_widget()
self.temperature_button_data = self._build_gradient_float_slider(" Color Temperature", default_value=6500.0)
self.temperature_slider_data = self._build_slider_handle(cls_temperature_gradient)
with ui.HStack():
ui.Spacer(width=10)
ui.Line(name="group_line", alignment=ui.Alignment.TOP)
def _build_color_widget(self, widget_name):
with ui.ZStack():
with ui.HStack():
ui.Spacer(width=10)
with ui.VStack():
ui.Spacer(height=8)
ui.Line(name="group_line", alignment=ui.Alignment.RIGHT, width=0)
with ui.VStack(height=0, spacing=SPACING):
with ui.HStack():
self._build_line_dot(40, 9)
ui.Label(widget_name, name="attribute_name", width=0)
# The custom compound widget
ColorWidget(0.25, 0.5, 0.75)
ui.Spacer(width=10)
color_data = self._build_slider_handle(cls_color_gradient)
tint_data = self._build_slider_handle(cls_tint_gradient)
grey_data = self._build_slider_handle(cls_grey_gradient)
with ui.HStack():
ui.Spacer(width=10)
ui.Line(name="group_line", alignment=ui.Alignment.TOP)
return color_data, tint_data, grey_data
def _build_slider_handle(self, colors):
handle_Style = {"background_color": colors[0], "border_width": 2, "border_color": cl_combobox_background}
def set_color(placer, handle, offset):
# first clamp the value
max = placer.computed_width - handle.computed_width
if offset < 0:
placer.offset_x = 0
elif offset > max:
placer.offset_x = max
color = get_gradient_color(placer.offset_x.value, max, colors)
handle_Style.update({"background_color": color})
handle.style = handle_Style
with ui.HStack():
ui.Spacer(width=18)
with ui.ZStack():
with ui.VStack():
ui.Spacer(height=3)
byte_provider = build_gradient_image(colors, 8, "gradient_slider")
with ui.HStack():
handle_placer = ui.Placer(draggable=True, drag_axis=ui.Axis.X, offset_x=0)
with handle_placer:
handle = ui.Circle(width=15, height=15, style=handle_Style)
handle_placer.set_offset_x_changed_fn(lambda offset: set_color(handle_placer, handle, offset.value))
ui.Spacer(width=22)
return byte_provider
def _build_fn(self):
"""
The method that is called to build all the UI once the window is
visible.
"""
with ui.ScrollingFrame(name="main_frame"):
with ui.VStack(height=0, spacing=SPACING):
self._build_head()
self._build_transform()
self._build_path()
self._build_light_properties()
ui.Spacer(height=30)
def _build_head(self):
with ui.ZStack():
ui.Image(name="header_frame", height=150, fill_policy=ui.FillPolicy.STRETCH)
with ui.HStack():
ui.Spacer(width=12)
with ui.VStack(spacing=8):
self._build_tabs()
ui.Spacer(height=1)
self._build_selection_widget()
self._build_stage_path_widget()
self._build_search_field()
ui.Spacer(width=12)
def _build_tabs(self):
with ui.HStack(height=35):
ui.Label("DETAILS", width=ui.Percent(17), name="details")
with ui.ZStack():
ui.Image(name="combobox", fill_policy=ui.FillPolicy.STRETCH, height=35)
with ui.HStack():
ui.Spacer(width=15)
ui.Label("LAYERS | ", name="layers", width=0)
ui.Label(f"{_get_plus_glyph()}", width=0)
ui.Spacer()
ui.Image(name="pin", width=20)
def _build_selection_widget(self):
with ui.HStack(height=20):
add_button = ui.Button(f"{_get_plus_glyph()} Add", width=60, name="add")
ui.Spacer(width=14)
ui.StringField(name="add").model.set_value("(2 models selected)")
ui.Spacer(width=8)
ui.Image(name="expansion", width=20)
def _build_stage_path_widget(self):
with ui.HStack(height=20):
ui.Spacer(width=3)
ui.Label("Stage Path", name="header_attribute_name", width=70)
ui.StringField(name="path").model.set_value("/World/environment/tree")
def _build_search_field(self):
with ui.HStack():
ui.Spacer(width=2)
# would add name="search" style, but there is a bug to use glyph together with style
# make sure the test passes for now
ui.StringField(height=23).model.set_value(f"{_get_search_glyph()} Search")
def _build_checkbox(self, label_name, default_value=True):
def _restore_default(rect_changed, rect_default):
image.name = "checked" if default_value else "unchecked"
rect_changed.visible = False
rect_default.visible = True
def _on_value_changed(image, rect_changed, rect_default):
image.name = "unchecked" if image.name == "checked" else "checked"
if (default_value and image.name == "unchecked") or (not default_value and image.name == "checked"):
rect_changed.visible = True
rect_default.visible = False
else:
rect_changed.visible = False
rect_default.visible = True
with ui.HStack():
ui.Label(label_name, name=f"attribute_bool", width=self.label_width, height=20)
name = "checked" if default_value else "unchecked"
image =ui.Image(name=name, fill_policy=ui.FillPolicy.PRESERVE_ASPECT_FIT, height=18, width=18)
ui.Spacer()
rect_changed, rect_default = self.__build_value_changed_widget()
image.set_mouse_pressed_fn(lambda x, y, b, m: _on_value_changed(image, rect_changed, rect_default))
# add call back to click the rect_changed to restore the default value
rect_changed.set_mouse_pressed_fn(lambda x, y, b, m: _restore_default(rect_changed, rect_default))
def __build_value_changed_widget(self):
with ui.VStack(width=20):
ui.Spacer(height=3)
rect_changed = ui.Rectangle(name="attribute_changed", width=15, height=15, visible= False)
ui.Spacer(height=4)
with ui.HStack():
ui.Spacer(width=3)
rect_default = ui.Rectangle(name="attribute_default", width=5, height=5, visible= True)
return rect_changed, rect_default
def _build_gradient_float_slider(self, label_name, default_value=0, min=0, max=1):
def _on_value_changed(model, rect_changed, rect_defaul):
if model.as_float == default_value:
rect_changed.visible = False
rect_defaul.visible = True
else:
rect_changed.visible = True
rect_defaul.visible = False
def _restore_default(slider):
slider.model.set_value(default_value)
with ui.HStack():
ui.Label(label_name, name=f"attribute_name", width=self.label_width)
with ui.ZStack():
button_background_gradient = build_gradient_image(cls_button_gradient, 22, "button_background_gradient")
with ui.VStack():
ui.Spacer(height=1.5)
with ui.HStack():
slider = ui.FloatSlider(name="float_slider", height=0, min=min, max=max)
slider.model.set_value(default_value)
ui.Spacer(width=1.5)
ui.Spacer(width=4)
rect_changed, rect_default = self.__build_value_changed_widget()
# switch the visibility of the rect_changed and rect_default to indicate value changes
slider.model.add_value_changed_fn(lambda model: _on_value_changed(model, rect_changed, rect_default))
# add call back to click the rect_changed to restore the default value
rect_changed.set_mouse_pressed_fn(lambda x, y, b, m: _restore_default(slider))
return button_background_gradient
def _build_combobox(self, label_name, options):
def _on_value_changed(model, rect_changed, rect_defaul):
index = model.get_item_value_model().get_value_as_int()
if index == 0:
rect_changed.visible = False
rect_defaul.visible = True
else:
rect_changed.visible = True
rect_defaul.visible = False
def _restore_default(combo_box):
combo_box.model.get_item_value_model().set_value(0)
with ui.HStack():
ui.Label(label_name, name=f"attribute_name", width=self.label_width)
with ui.ZStack():
ui.Image(name="combobox", fill_policy=ui.FillPolicy.STRETCH, height=35)
with ui.HStack():
ui.Spacer(width=10)
with ui.VStack():
ui.Spacer(height=10)
option_list = list(options)
combo_box = ui.ComboBox(0, *option_list, name="dropdown_menu")
with ui.VStack(width=0):
ui.Spacer(height=10)
rect_changed, rect_default = self.__build_value_changed_widget()
# switch the visibility of the rect_changed and rect_default to indicate value changes
combo_box.model.add_item_changed_fn(lambda m, i: _on_value_changed(m, rect_changed, rect_default))
# add call back to click the rect_changed to restore the default value
rect_changed.set_mouse_pressed_fn(lambda x, y, b, m: _restore_default(combo_box))
| 17,220 | Python | 45.923706 | 146 | 0.573403 |
NVIDIA-Omniverse/kit-extension-sample-ui-window/exts/omni.example.ui_gradient_window/omni/example/ui_gradient_window/tests/test_window.py | # Copyright (c) 2022, 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.
#
__all__ = ["TestWindow"]
from omni.example.ui_gradient_window import PropertyWindowExample
from omni.ui.tests.test_base import OmniUiTest
from pathlib import Path
import omni.kit.app
import omni.kit.test
EXTENSION_FOLDER_PATH = Path(omni.kit.app.get_app().get_extension_manager().get_extension_path_by_module(__name__))
TEST_DATA_PATH = EXTENSION_FOLDER_PATH.joinpath("data/tests")
class TestWindow(OmniUiTest):
async def test_general(self):
"""Testing general look of section"""
window = PropertyWindowExample("Test")
await omni.kit.app.get_app().next_update_async()
await self.docked_test_window(
window=window,
width=450,
height=600,
)
# Wait for images
for _ in range(20):
await omni.kit.app.get_app().next_update_async()
await self.finalize_test(golden_img_dir=TEST_DATA_PATH, golden_img_name="window.png")
| 1,363 | Python | 34.894736 | 115 | 0.710198 |
NVIDIA-Omniverse/kit-extension-sample-ui-window/exts/omni.example.ui_gradient_window/docs/CHANGELOG.md | # Changelog
## [1.0.1] - 2022-06-22
### Changed
- Added README.md
- Clean up the style a bit and change some of the widgets function name
## [1.0.0] - 2022-06-09
### Added
- Initial window
| 191 | Markdown | 16.454544 | 71 | 0.65445 |
NVIDIA-Omniverse/kit-extension-sample-ui-window/exts/omni.example.ui_gradient_window/docs/README.md | # Gradient Window (omni.example.ui_gradient_window)

# Overview
In this example, we create a window which heavily uses graident style in various widgets. The window is build using `omni.ui`.
It contains the best practices of how to build customized widgets and leverage to reuse them without duplicating the code.
## [Tutorial](../tutorial/tutorial.md)
This extension sample also includes a step-by-step tutorial to accelerate your growth as you learn to build your own
Omniverse Kit extensions. [Get started with the tutorial.](../tutorial/tutorial.md)
# Customized Widgets
A customized widget can be a class or a function. It's not required to derive from anything. We build customized widget so that we can use them just like default `omni.ui` widgets which allows us to reuse the code and saves us from reinventing the wheel again and again.
## Gradient Image
Gradient images are used a lot in this example. It is used in the customized slider and field background. Therefore, we encapsulate it into a function `build_gradient_image` which is a customized `ui.ImageWithProvider` under the hood. The `ImageWithProvider` has a source data which is generated by `ui.ByteImageProvider`. We define how to generate the byte data into a function called `generate_byte_data`. We use one pixel height data to generate the image data. For users' conveniences, we provide the function signature as an array of hex colors, so we provided a function to achieve `hex_to_color` conversion.
```
def hex_to_color(hex: int) -> tuple:
# convert Value from int
red = hex & 255
green = (hex >> 8) & 255
blue = (hex >> 16) & 255
alpha = (hex >> 24) & 255
rgba_values = [red, green, blue, alpha]
return rgba_values
def generate_byte_data(colors):
data = []
for color in colors:
data += hex_to_color(color)
_byte_provider = ui.ByteImageProvider()
_byte_provider.set_bytes_data(data, [len(colors), 1])
return _byte_provider
def build_gradient_image(colors, height, style_name):
byte_provider = generate_byte_data(colors)
ui.ImageWithProvider(byte_provider,fill_policy=omni.ui.IwpFillPolicy.IWP_STRETCH, height=height, name=style_name)
return byte_provider
```
With this, the user will be able to generate gradient image easily which also allows flexibly set the height and style. Here are a couple of examples used in the example:
```
colors = cls_color_gradient = [cl("#fa0405"), cl("#95668C"), cl("#4b53B4"), cl("#33C287"), cl("#9fE521"), cl("#ff0200")]
byte_provider = build_gradient_image(colors, 8, "gradient_slider")
cls_button_gradient = [cl("#232323"), cl("#656565")]
button_background_gradient = build_gradient_image(cls_button_gradient, 22, "button_background_gradient")
```

## Value Changed Widget
In this example, almost every attribute has got a widget which indicates whether the value has been changed or not. By default, the widget is a small gray rectangle, while the value has been changed it becomes a bigger blue rectangle. We wrapped this up into a function called `__build_value_changed_widget` and returns both rectangles so that the caller can switch the visiblity of them.
It is not only an indicator of value change, it is also a button. While you click on it when the value has changed, it has the callback to restore the default value for the attribute. Since different attribute has different data model, the restore callbacks are added into different widgets instead of the value change widget itself.
## Gradient Float Slider
Almost all the numeric attribute in this example is using gradient float slider which is defined by `_build_gradient_float_slider`. This customized float slider are consisted of three parts: the label, the float slider, and the value-changed-widget.
The label is just a usual `ui.Label`.
The slider is a normal `ui.FloatSlider` with a gradient image, composed by `ui.ZStack`.
We also added the `add_value_changed_fn` callback for slider model change to trigger the value-changed-widget change visiblity and `rect_changed.set_mouse_pressed_fn` to add the callback to restore the default value of the silder.
```
rect_changed, rect_default = self.__build_value_changed_widget()
# switch the visibility of the rect_changed and rect_default to indicate value changes
slider.model.add_value_changed_fn(lambda model: _on_value_changed(model, rect_changed, rect_default))
# add call back to click the rect_changed to restore the default value
rect_changed.set_mouse_pressed_fn(lambda x, y, b, m: _restore_default(slider))
```

## Customized CheckBox
The customized Checkbox is defined by `_build_checkbox`. It is also consisted of three parts: the label, the check box, and the value-changed-widget.
The label is just a usual `ui.Label`.
For the check box, since we have completely two different images for the checked and unchecked status. Therefore, we use `ui.Image` as the base for the customized CheckBox. The `name` of the image is used to switch between the corresponding styles which changes the `image_url` for the image.
The callbacks of value-changed-widget are added similarly as gradient float slider.


## Customized ComboBox
The customized ComboBox is defined by `_build_combobox`. It is also consisted of three parts: the label, the ComnoBox, and the value-changed-widget.
The label is just a usual `ui.Label`. The ComboBox is a normal `ui.ComboBox` with a gradient image, composed by `ui.ZStack`. The callbacks of value-changed-widget are added similarly as gradient float slider.


## Customized CollsableFrame
The customized CollsableFrame is wrapped in `CustomCollsableFrame` class. It is a normal `ui.CollapsableFrame` with a customized header. It is the main widget groups other widgets as a collapsable frame.

## Customized ColorWidget
The customized ColorWidget is wrapped in `ColorWidget` class.

The RGB values `self.__multifield` is represented by a normal `ui.MultiFloatDragField`, composed with three gradient images of red, green and blue using `ui.ZStack`, as well as the lable and circle dots in between the three values.
The colorpicker is just a normal `ui.ColorWidget`, which shares the same model of `self.__multifield`, so that these two widgets are connected.
We also added the `add_item_changed_fn` callback for the shared model. When the model item changes, it will trigger the value-changed-widget to switch the visiblity and `rect_changed.set_mouse_pressed_fn` to add the callback to restore the default value for the shared model.
# Style
We kept all the styles of all the widgets in `style.py`. One advantage is that specific style or colors could be reused without duplication. The other advantage is that users don't need to go through the lengthy widgets code to change the styles.
All the styles are recommended to be arranged and named in a self-explanatory way.
# Window
It's handy to derive a custom window from the class `ui.Window`. The UI can be
defined right in __init__, so it's created immediately or it can be defined in
a `set_build_fn` callback and it will be created when the window is visible. The later one is used in this example.
```
class PropertyWindowExample(ui.Window):
"""The class that represents the window"""
def __init__(self, title: str, delegate=None, **kwargs):
self.__label_width = LABEL_WIDTH
super().__init__(title, **kwargs)
# Apply the style to all the widgets of this window
self.frame.style = example_window_style
# Set the function that is called to build widgets when the window is visible
self.frame.set_build_fn(self._build_fn)
```
Inside the `self._build_fn`, we use the customized widgets to match the design layout for the window.
# Extension
When the extension starts up, we register a new menu item that controls the window and shows the window.
A very important part is using `ui.Workspace.set_show_window_fn` to register the window in `omni.ui`. It will help to save and load the layout of Kit.
```
ui.Workspace.set_show_window_fn(ExampleWindowExtension.WINDOW_NAME, partial(self.show_window, None))
```
When the extension shuts down, we remove the menu item and deregister the window callback. | 8,457 | Markdown | 52.194968 | 614 | 0.753104 |
NVIDIA-Omniverse/kit-extension-sample-ui-window/exts/omni.example.ui_julia_modeler/tutorial/tutorial.md | # How to Understand and Navigate Omniverse Code from Other Developers
This tutorial teaches how to access, navigate and understand source code from extensions written by other developers. This is done by opening an extension, navigating to its code and learning how its user interface is put together. It also teaches how custom widgets are organized. With this information developers can find user interface elements in other developers' extensions and re-use or extend them. The extension itself is a UI mockup for a [julia quaternion modeling tool](http://paulbourke.net/fractals/quatjulia/).
## Learning Objectives
- Access Source of Omniverse Extensions
- Understand UI Code Structure
- Re-use Widget Code from Other Developers
## Prerequisites
- [UI Window Tutorial](https://github.com/NVIDIA-Omniverse/kit-extension-sample-ui-window/blob/main/exts/omni.example.ui_window/tutorial/tutorial.md)
- [UI Gradient Tutorial](https://github.com/NVIDIA-Omniverse/kit-extension-sample-ui-window/blob/main/exts/omni.example.ui_gradient_window/tutorial/tutorial.md)
- Omniverse Code version 2022.1.1 or higher
- Working understanding of GitHub
- Visual Studio Code
## Step 1: Clone the Repository
Clone the `main` branch of the `kit-extension-sample-ui-window` [GitHub repository](https://github.com/NVIDIA-Omniverse/kit-extension-sample-ui-window):
```shell
git clone https://github.com/NVIDIA-Omniverse/kit-extension-sample-ui-window.git
```
This repository contains the code you use in this tutorial.
## Step 2: Add the Extension to Omniverse Code
In order to use and test your Extension, you need to add it to Omniverse Code.
### Step 2.1: Navigate to the Extensions List
In Omniverse Code, navigate to the *Extensions* panel:

Here, you see a list of Omniverse Extensions that you can activate and use in Code.
> **Note:** If you don't see the *Extensions* panel, enable **Window > Extensions**:
>
> 
### Step 2.2: Navigate to the *Extension Search Paths*
Click the **gear** icon to open *Extension Search Paths*:

In this panel, you can add your custom Extension to the Extensions list.
### Step 2.3: Create a New Search Path
Create a new search path to the `exts` directory of your Extension by clicking the green **plus** icon and double-clicking on the **path** field:

When you submit your new search path, you should be able to find your extension in the *Extensions* list. Search for "omni.example.ui_" to filter down the list. Activate the "OMNI.UI JULIA QUATERNION MO..." Extension:

Now that your Extension is added and enabled, you can make changes to the code and see them in your Application. You will see the user interface pictured below:
<p align="center">
<img src="Images/JuliaUI.png" width=25%>
<p>
## Step 3: View the User Interface and Source Code
### Step 3.1: Review the User Interface
Take a moment to think like a connoisseur of excellent user interface elements. What aspects of this user interface are worth collecting? Notice the styling on the collapsable frames, the backgrounds on the sliders. Edit some of the values and notice that the arrow on the right is now highlighted in blue. Click on that arrow and notice that the slider returns to a default value. Focus on the best aspects because you can collect those and leave the lesser features behind.
### Step 3.2: Access the Source Code
Now, go back to the extensions window and navigate to the `Julia` extension. Along the top of its details window lies a row of icons as pictured below:
<p align="center">
<img src="Images/VisualStudioIcon.png" width=75%>
<p>
Click on the Visual Studio icon to open the Extension's source in Visual Studio. This is a great way to access extension source code and learn how they were written.
## Step 4: Find `extension.py`
This section explains how to start navigation of an extension's source code.
### Step 4.1: Access the Extension Source Code
Open the Visual Studio window and expand the `exts` folder. The image below will now be visible:
<p align="center">
<img src="Images/FolderStructure.png" width=35%>
<p>
Click on `omni\example\ui_julia_modeler` to expand it and see the files in that folder as shown below:
<p align="center">
<img src="Images/DevFiles.png" width=35%>
<p>
### Step 4.2: Open `extension.py`
The file named `extension.py` is a great place to start. It contains a class that derives from `omni.ext.IExt`.
### Step 4.3: Find the `on_startup` Function
Look for the `on_startup`. This function runs when the extension first starts and is where the UI should be built. It has been included below:
```Python
def on_startup(self):
# The ability to show the window if the system requires it. We use it
# in QuickLayout.
ui.Workspace.set_show_window_fn(JuliaModelerExtension.WINDOW_NAME, partial(self.show_window, None))
# Add the new menu
editor_menu = omni.kit.ui.get_editor_menu()
if editor_menu:
self._menu = editor_menu.add_item(
JuliaModelerExtension.MENU_PATH, self.show_window, toggle=True, value=True
)
# Show the window. It will call `self.show_window`
ui.Workspace.show_window(JuliaModelerExtension.WINDOW_NAME)
```
This function does a few steps that are common for a window-based extension. Not all extensions will be written in exactly this way, but these are best practices and are good things to look for.
1. It registers a `show` function with the application.
2. It adds the extension to the `Window` application menu.
3. It requests that the window be shown using the `show` function registered before.
### Step 4.4: Find the Function that Builds the Window
What function has been registered to show the `Julia` extension window? It is `self.show_window()`. Scroll down until you find it in `extension.py`. It has been included below for convenience:
```Python
def show_window(self, menu, value):
if value:
self._window = JuliaModelerWindow(
JuliaModelerExtension.WINDOW_NAME, width=WIN_WIDTH, height=WIN_HEIGHT)
self._window.set_visibility_changed_fn(self._visiblity_changed_fn)
elif self._window:
self._window.visible = False
```
In this function `value` is a boolean that is `True` if the window should be shown and `False` if the window should be hidden. Take a look at the code block that will run if `value` is `True` and you will see that `self._window` is set equal to a class constructor.
### Step 4.5: Navigate to the Window Class
To find out where this class originates, hold the `ctrl` button and click on `JuliaModelerWindow` in the third line of the function. This will navigate to that symbol's definition. In this case it opens the `window.py` file and takes the cursor to definition of the `JuliaModelerWindow` class. The next section explores this class and how the window is built.
## Step 5: Explore `JuliaModelerWindow`
This sections explores the `JuliaModelerWindow` class, continuing the exploration of this extension, navigating the code that builds the UI from the top level towards specific elements.
### Step 5.1: Read `show_window()`
The `show_window()` function in the previous section called the constructor from the `JuliaModelerWindow` class. The constructor in Python is the `__init__()` function and is copied below:
```Python
def __init__(self, title: str, delegate=None, **kwargs):
self.__label_width = ATTR_LABEL_WIDTH
super().__init__(title, **kwargs)
# Apply the style to all the widgets of this window
self.frame.style = julia_modeler_style
# Set the function that is called to build widgets when the window is
# visible
self.frame.set_build_fn(self._build_fn)
```
The first statement simply sets a label width. The next statement calls `super().__init__()`. This initializes all base classes of `JuliaModelerWindow`. This has to do with inheritance, a topic that will be briefly covered later in this tutorial. The third statement sets the window style, which is useful information, but is the topic of another tutorial. These styles are contained in `style.py` for the curious. Finally, the function registers the `self._build_fn` callback as the frame's build function. This is the function of interest.
### Step 5.2: Navigate to `_build_fn()`
Hold ctrl and click on `self._build_fn` which has been reproduced below:
```Python
def _build_fn(self):
"""
The method that is called to build all the UI once the window is
visible.
"""
with ui.ScrollingFrame(name="window_bg",
horizontal_scrollbar_policy=ui.ScrollBarPolicy.SCROLLBAR_ALWAYS_OFF):
with ui.VStack(height=0):
self._build_title()
self._build_calculations()
self._build_parameters()
self._build_light_1()
self._build_scene()
```
This function builds an outer scrolling frame, a vertical stack, and then builds a few sections to add to that stack. Each of these methods has useful information worth taking a look at, but this tutorial will focus on `_build_parameters()`.
### Step 5.3: Navigate to `_build_parameters()`
Navigate to `_build_parameters` using ctrl+click. As usual, it is duplicated below:
```Python
def _build_parameters(self):
"""Build the widgets of the "Parameters" group"""
with ui.CollapsableFrame("Parameters".upper(), name="group",
build_header_fn=self._build_collapsable_header):
with ui.VStack(height=0, spacing=SPACING):
ui.Spacer(height=6)
CustomSliderWidget(min=-2, max=2, display_range=True,
label="Iterations", default_val=0.75)
CustomSliderWidget(min=0, max=2, display_range=True,
label="i", default_val=0.65)
CustomSliderWidget(min=0, max=2, display_range=True,
label="j", default_val=0.25)
CustomSliderWidget(min=0, max=2, display_range=True,
label="k", default_val=0.55)
CustomSliderWidget(min=0, max=3.14, display_range=True,
label="Theta", default_val=1.25)
```
Here is a collapsable frame, a vertical stack, and then instead of the horizontal stacks with combinations of labels and controls seen in the `UI_Window` tutorial, there is a list of custom controls. In fact, scrolling up and down the class to look at the other build functions reveals quite a few custom controls. These custom controls are what gives the user interface a variety of controls, maintains a consistent look and feel, and gives them all the same functionality to restore a default value. Taking a closer at constructor for each `CustomSliderWidget` above reveals that each sets a default value for its respective widget.
### Step 5.4: Identify Custom Widgets
In the folder structure are a few files that look like they contain custom widgets, namely:
- `custom_base_widget.py`
- `custom_bool_widget.py`
- `custom_color_widget.py`
- `custom_combobox_widget.py`
- `custom_multifield_widget.py`
- `custom_path_widget.py`
- `custom_radio_widget.py`
- `custom_slider_widget.py`
### Step 5.5: Recognize Hierarchical Class Structure
`custom_base_widget.py` contains `CustomBaseWidget` which many of the other widgets `inherit` from. For example, open one of the widget modules such as `custom_slider_widget.py` and take a look at its class declaration:
```Python
class CustomSliderWidget(CustomBaseWidget):
```
There, in parentheses is `CustomBaseWidget`, confirming that this is a hierarchical class structure with the specific widgets inheriting from `CustomBaseWidget`. For those unfamiliar with inheritance, a quick explanation in the next section is in order.
## Step 6: Inheritance
In Python (and other programming languages) it is possible to group classes together if they have some things in common but are different in other ways and this is called inheritance. With inheritance, a base class is made containing everything in common, and sub-classes are made that contain the specific elements of each object. 2D Shapes are a classic example.
<p align="center">
<img src="Images/Shape.svg" width=35%>
<p>
In this case all shapes have a background color, you can get their area, and you can get their perimeter. Circles, however have a radius where rectangles have a length and a width. When you use inheritance, the common code can be in a single location in the base class where the sub-classes contain the specific code. The next step is to look at `CustomBaseWidget` to see what all of the custom widgets have in common. Either navigate to `custom_base_widget.py` or ctrl+click on `CustomBaseWidget` in any of the sub-classes.
Inheritance is one element of object-oriented programming (OOP). To learn more about OOP, check out [this video](https://www.youtube.com/watch?v=pTB0EiLXUC8). To learn more about inheritance syntax in Python, check out [this article](https://www.w3schools.com/Python/Python_inheritance.asp).
## Step 7: Explore `custom_base_widget.py`
This section explores the code in `custom_base_widget.py`
### Step 7.1: Identify Code Patterns
The developer who wrote this extension has a consistent style, so you should see a lot in common between this class and `JuliaModelerWindow` class. It starts with `__init__()` and `destroy()` functions and further down has a few `_build` functions: `_build_head()`, `_build_body()`, `_build_tail()`, and `_build_fn()`. The `_build_fn()` function is called from the constructor and in turn calls each of the other build functions.
### Step 7.2: Characterize Custom Widget Layout
From this it can be determined that each of the custom widgets has a head, body and tail and if we look at the controls in the UI this makes sense as illustrated below:
<p align="center">
<img src="Images/HeadBodyTail.png" width=35%>
<p>
This image shows a vertical stack containing 5 widgets. Each widget is a collection of smaller controls. The first highlighted column contains the head of each widget, the second contains their content and the third holds each tail. This tutorial will now look at how the head, content, and tail are created in turn.
### Step 7.3: Inspect `_build_head()`
`_build_head()` is as follows:
```Python
def _build_head(self):
"""Build the left-most piece of the widget line (label in this case)"""
ui.Label(
self.__attr_label,
name="attribute_name",
width=ATTR_LABEL_WIDTH
)
```
It has a single label that displays the text passed into the widget's constructor. This makes sense when looking at the UI, each control has a label and they are all aligned.
### Step 7.4: Inspect `_build_body()`
`_build_body()` is as follows:
```Python
def _build_body(self):
"""Build the custom part of the widget. Most custom widgets will
override this method, as it is where the meat of the custom widget is.
"""
ui.Spacer()
```
In the comments it says that most widgets will override this method. This has to do with the inheritance mentioned before. Just like with `GetArea()` in the shape class, each shape has an area, but that area is calculated differently. In this situation, the function is placed in the base class but each sub-class implements that function in its own way. In this case `_build_body()` is essentially empty, and if you look at each custom widget sub-class, they each have their own `_build_body()` function that runs in place of the one in `CustomBaseWidget`.
### Step 7.5: Inspect `_build_tail()`
Finally, the `_build_tail()` function contains the following code:
```Python
def _build_tail(self):
"""Build the right-most piece of the widget line. In this case,
we have a Revert Arrow button at the end of each widget line.
"""
with ui.HStack(width=0):
ui.Spacer(width=5)
with ui.VStack(height=0):
ui.Spacer(height=3)
self.revert_img = ui.Image(
name="revert_arrow",
fill_policy=ui.FillPolicy.PRESERVE_ASPECT_FIT,
width=12,
height=13,
enabled=False,
)
ui.Spacer(width=5)
# call back for revert_img click, to restore the default value
self.revert_img.set_mouse_pressed_fn(
lambda x, y, b, m: self._restore_default())
```
This function draws the reverse arrow that lets a user revert a control to a default value and is the same for every custom control. In this way the author of this extension has ensured that all of the custom widgets are well aligned, have a consistent look and feel and don't have the same code repeated in each class. They each implemented their own body, but other than that are the same.
The next section will show how the widget body is implmeneted in the `CustomSliderWidget` class.
## Step 8: Explore `custom_slider_widget.py`
To view the `CustomSliderWidget` class open `custom_slider_widget.py` and take a look at the `build_body()` function which contains the following code:
```Python
def _build_body(self):
"""Main meat of the widget. Draw the Slider, display range text, Field,
and set up callbacks to keep them updated.
"""
with ui.HStack(spacing=0):
# the user provided a list of default values
with ui.VStack(spacing=3, width=ui.Fraction(3)):
with ui.ZStack():
# Put texture image here, with rounded corners, then make slider
# bg be fully transparent, and fg be gray and partially transparent
with ui.Frame(width=SLIDER_WIDTH, height=FIELD_HEIGHT,
horizontal_clipping=True):
# Spacing is negative because "tileable" texture wasn't
# perfectly tileable, so that adds some overlap to line up better.
with ui.HStack(spacing=-12):
for i in range(50): # tiling the texture
ui.Image(name=TEXTURE_NAME,
fill_policy=ui.FillPolicy.PRESERVE_ASPECT_CROP,
width=50,)
slider_cls = (
ui.FloatSlider if self.__num_type == "float" else ui.IntSlider
)
self.__slider = slider_cls(
height=FIELD_HEIGHT,
min=self.__min, max=self.__max, name="attr_slider"
)
if self.__display_range:
self._build_display_range()
with ui.VStack(width=ui.Fraction(1)):
model = self.__slider.model
model.set_value(self.__default_val)
field_cls = (
ui.FloatField if self.__num_type == "float" else ui.IntField
)
# Note: This is a hack to allow for text to fill the Field space more, as there was a bug
# with Field padding. It is fixed, and will be available in the next release of Kit.
with ui.ZStack():
# height=FIELD_HEIGHT-1 to account for the border, so the field isn't
# slightly taller than the slider
ui.Rectangle(
style_type_name_override="Field",
name="attr_field",
height=FIELD_HEIGHT - 1
)
with ui.HStack(height=0):
ui.Spacer(width=2)
self.__numberfield = field_cls(
model,
height=0,
style={
"background_color": cl.transparent,
"border_color": cl.transparent,
"padding": 4,
"font_size": fl.field_text_font_size,
},
)
if self.__display_range:
ui.Spacer()
```
This function is significantly longer than others in this tutorial and could be overwhelming at first glance. This is the perfect situation to take advantage of code folding. If you hover over the blank column between the line numbers and the code window inside visual studio, downward carrats will appear next to code blocks. Click on the carrats next to the two vertical stacks to collapse those blocks of code and make the function easier to navigate.
<p align="center">
<img src="Images/FoldedCode.png" width=75%>
<p>
Now it's clear that this function creates an outer horizontal stack which contains two vertical stacks. If you dig deeper you will find that the first vertical stack contains a float slider with an image background. In order to learn how to create an image background like this, check out the [UI Gradient Tutorial](https://github.com/NVIDIA-Omniverse/kit-extension-sample-ui-window/blob/main/exts/omni.example.ui_gradient_window/tutorial/tutorial.md). The second vertical stack contains a number field which displays the number set by the float slider.
If you take a look at the other custom widgets, you will see that each of them has its own `_build_body` function. Exploring these is a great way to get ideas on how to create your own user interface.
## Step 9: Reusing UI code
By exploring extensions in this manner, developers can get a head start creating their own user interfaces. This can range from copying and pasting controls from other extensions, to creating new sub-classes on top of existing base classes, to simply reading and understanding the code written by others to learn from it. Hopefully this tutorial has given you a few tips and tricks as you navigate code written by others.
## Conclusion
This tutorial has explained how to navigate the file and logical structure of a typical Omniverse extension. In addition it has explained how custom widgets work, even when they are part of a hieararchical inheritance structure.
| 22,207 | Markdown | 50.7669 | 634 | 0.701806 |
NVIDIA-Omniverse/kit-extension-sample-ui-window/exts/omni.example.ui_julia_modeler/omni/example/ui_julia_modeler/custom_radio_collection.py | # Copyright (c) 2022, 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.
#
__all__ = ["CustomRadioCollection"]
from typing import List, Optional
import omni.ui as ui
from .style import ATTR_LABEL_WIDTH
SPACING = 5
class CustomRadioCollection:
"""A custom collection of radio buttons. The group_name is on the first
line, and each label and radio button are on subsequent lines. This one
does not inherit from CustomBaseWidget because it doesn't have the same
Head label, and doesn't have a Revert button at the end.
"""
def __init__(self,
group_name: str,
labels: List[str],
model: ui.AbstractItemModel = None,
default_value: bool = True,
**kwargs):
self.__group_name = group_name
self.__labels = labels
self.__default_val = default_value
self.__images = []
self.__selection_model = ui.SimpleIntModel(default_value)
self.__frame = ui.Frame()
with self.__frame:
self._build_fn()
def destroy(self):
self.__images = []
self.__selection_model = None
self.__frame = None
@property
def model(self) -> Optional[ui.AbstractValueModel]:
"""The widget's model"""
if self.__selection_model:
return self.__selection_model
@model.setter
def model(self, value: int):
"""The widget's model"""
self.__selection_model.set(value)
def __getattr__(self, attr):
"""
Pretend it's self.__frame, so we have access to width/height and
callbacks.
"""
return getattr(self.__frame, attr)
def _on_value_changed(self, index: int = 0):
"""Set states of all radio buttons so only one is On."""
self.__selection_model.set_value(index)
for i, img in enumerate(self.__images):
img.checked = i == index
img.name = "radio_on" if img.checked else "radio_off"
def _build_fn(self):
"""Main meat of the widget. Draw the group_name label, label and
radio button for each row, and set up callbacks to keep them updated.
"""
with ui.VStack(spacing=SPACING):
ui.Spacer(height=2)
ui.Label(self.__group_name.upper(), name="radio_group_name",
width=ATTR_LABEL_WIDTH)
for i, label in enumerate(self.__labels):
with ui.HStack():
ui.Label(label, name="attribute_name",
width=ATTR_LABEL_WIDTH)
with ui.HStack():
with ui.VStack():
ui.Spacer(height=2)
self.__images.append(
ui.Image(
name=("radio_on" if self.__default_val == i else "radio_off"),
fill_policy=ui.FillPolicy.PRESERVE_ASPECT_FIT,
height=16, width=16, checked=self.__default_val
)
)
ui.Spacer()
ui.Spacer(height=2)
# Set up a mouse click callback for each radio button image
for i in range(len(self.__labels)):
self.__images[i].set_mouse_pressed_fn(
lambda x, y, b, m, i=i: self._on_value_changed(i))
| 3,781 | Python | 35.718446 | 98 | 0.556467 |
NVIDIA-Omniverse/kit-extension-sample-ui-window/exts/omni.example.ui_julia_modeler/omni/example/ui_julia_modeler/custom_bool_widget.py | # Copyright (c) 2022, 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.
#
__all__ = ["CustomBoolWidget"]
import omni.ui as ui
from .custom_base_widget import CustomBaseWidget
class CustomBoolWidget(CustomBaseWidget):
"""A custom checkbox or switch widget"""
def __init__(self,
model: ui.AbstractItemModel = None,
default_value: bool = True,
**kwargs):
self.__default_val = default_value
self.__bool_image = None
# Call at the end, rather than start, so build_fn runs after all the init stuff
CustomBaseWidget.__init__(self, model=model, **kwargs)
def destroy(self):
CustomBaseWidget.destroy()
self.__bool_image = None
def _restore_default(self):
"""Restore the default value."""
if self.revert_img.enabled:
self.__bool_image.checked = self.__default_val
self.__bool_image.name = (
"checked" if self.__bool_image.checked else "unchecked"
)
self.revert_img.enabled = False
def _on_value_changed(self):
"""Swap checkbox images and set revert_img to correct state."""
self.__bool_image.checked = not self.__bool_image.checked
self.__bool_image.name = (
"checked" if self.__bool_image.checked else "unchecked"
)
self.revert_img.enabled = self.__default_val != self.__bool_image.checked
def _build_body(self):
"""Main meat of the widget. Draw the appropriate checkbox image, and
set up callback.
"""
with ui.HStack():
with ui.VStack():
# Just shift the image down slightly (2 px) so it's aligned the way
# all the other rows are.
ui.Spacer(height=2)
self.__bool_image = ui.Image(
name="checked" if self.__default_val else "unchecked",
fill_policy=ui.FillPolicy.PRESERVE_ASPECT_FIT,
height=16, width=16, checked=self.__default_val
)
# Let this spacer take up the rest of the Body space.
ui.Spacer()
self.__bool_image.set_mouse_pressed_fn(
lambda x, y, b, m: self._on_value_changed())
| 2,626 | Python | 37.072463 | 87 | 0.604722 |
NVIDIA-Omniverse/kit-extension-sample-ui-window/exts/omni.example.ui_julia_modeler/omni/example/ui_julia_modeler/custom_multifield_widget.py | # Copyright (c) 2022, 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.
#
__all__ = ["CustomMultifieldWidget"]
from typing import List, Optional
import omni.ui as ui
from .custom_base_widget import CustomBaseWidget
class CustomMultifieldWidget(CustomBaseWidget):
"""A custom multifield widget with a variable number of fields, and
customizable sublabels.
"""
def __init__(self,
model: ui.AbstractItemModel = None,
sublabels: Optional[List[str]] = None,
default_vals: Optional[List[float]] = None,
**kwargs):
self.__field_labels = sublabels or ["X", "Y", "Z"]
self.__default_vals = default_vals or [0.0] * len(self.__field_labels)
self.__multifields = []
# Call at the end, rather than start, so build_fn runs after all the init stuff
CustomBaseWidget.__init__(self, model=model, **kwargs)
def destroy(self):
CustomBaseWidget.destroy()
self.__multifields = []
@property
def model(self, index: int = 0) -> Optional[ui.AbstractItemModel]:
"""The widget's model"""
if self.__multifields:
return self.__multifields[index].model
@model.setter
def model(self, value: ui.AbstractItemModel, index: int = 0):
"""The widget's model"""
self.__multifields[index].model = value
def _restore_default(self):
"""Restore the default values."""
if self.revert_img.enabled:
for i in range(len(self.__multifields)):
model = self.__multifields[i].model
model.as_float = self.__default_vals[i]
self.revert_img.enabled = False
def _on_value_changed(self, val_model: ui.SimpleFloatModel, index: int):
"""Set revert_img to correct state."""
val = val_model.as_float
self.revert_img.enabled = self.__default_vals[index] != val
def _build_body(self):
"""Main meat of the widget. Draw the multiple Fields with their
respective labels, and set up callbacks to keep them updated.
"""
with ui.HStack():
for i, (label, val) in enumerate(zip(self.__field_labels, self.__default_vals)):
with ui.HStack(spacing=3):
ui.Label(label, name="multi_attr_label", width=0)
model = ui.SimpleFloatModel(val)
# TODO: Hopefully fix height after Field padding bug is merged!
self.__multifields.append(
ui.FloatField(model=model, name="multi_attr_field"))
if i < len(self.__default_vals) - 1:
# Only put space between fields and not after the last one
ui.Spacer(width=15)
for i, f in enumerate(self.__multifields):
f.model.add_value_changed_fn(lambda v: self._on_value_changed(v, i))
| 3,255 | Python | 39.19753 | 92 | 0.614132 |
NVIDIA-Omniverse/kit-extension-sample-ui-window/exts/omni.example.ui_julia_modeler/omni/example/ui_julia_modeler/custom_color_widget.py | # Copyright (c) 2022, 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.
#
__all__ = ["CustomColorWidget"]
from ctypes import Union
import re
from typing import List, Optional
import omni.ui as ui
from .custom_base_widget import CustomBaseWidget
from .style import BLOCK_HEIGHT
COLOR_PICKER_WIDTH = ui.Percent(35)
FIELD_WIDTH = ui.Percent(65)
COLOR_WIDGET_NAME = "color_block"
SPACING = 4
class CustomColorWidget(CustomBaseWidget):
"""The compound widget for color input. The color picker widget model converts
its 3 RGB values into a comma-separated string, to display in the StringField.
And vice-versa.
"""
def __init__(self, *args, model=None, **kwargs):
self.__defaults: List[Union[float, int]] = [a for a in args if a is not None]
self.__strfield: Optional[ui.StringField] = None
self.__colorpicker: Optional[ui.ColorWidget] = None
self.__color_sub = None
self.__strfield_sub = None
# Call at the end, rather than start, so build_fn runs after all the init stuff
CustomBaseWidget.__init__(self, model=model, **kwargs)
def destroy(self):
CustomBaseWidget.destroy()
self.__strfield = None
self.__colorpicker = None
self.__color_sub = None
self.__strfield_sub = None
@property
def model(self) -> Optional[ui.AbstractItemModel]:
"""The widget's model"""
if self.__colorpicker:
return self.__colorpicker.model
@model.setter
def model(self, value: ui.AbstractItemModel):
"""The widget's model"""
self.__colorpicker.model = value
@staticmethod
def simplify_str(val):
s = str(round(val, 3))
s_clean = re.sub(r'0*$', '', s) # clean trailing 0's
s_clean = re.sub(r'[.]$', '', s_clean) # clean trailing .
s_clean = re.sub(r'^0', '', s_clean) # clean leading 0
return s_clean
def set_color_stringfield(self, item_model: ui.AbstractItemModel,
children: List[ui.AbstractItem]):
"""Take the colorpicker model that has 3 child RGB values,
convert them to a comma-separated string, and set the StringField value
to that string.
Args:
item_model: Colorpicker model
children: child Items of the colorpicker
"""
field_str = ", ".join([self.simplify_str(item_model.get_item_value_model(c).as_float)
for c in children])
self.__strfield.model.set_value(field_str)
if self.revert_img:
self._on_value_changed()
def set_color_widget(self, str_model: ui.SimpleStringModel,
children: List[ui.AbstractItem]):
"""Parse the new StringField value and set the ui.ColorWidget
component items to the new values.
Args:
str_model: SimpleStringModel for the StringField
children: Child Items of the ui.ColorWidget's model
"""
joined_str = str_model.get_value_as_string()
for model, comp_str in zip(children, joined_str.split(",")):
comp_str_clean = comp_str.strip()
try:
self.__colorpicker.model.get_item_value_model(model).as_float = float(comp_str_clean)
except ValueError:
# Usually happens in the middle of typing
pass
def _on_value_changed(self, *args):
"""Set revert_img to correct state."""
default_str = ", ".join([self.simplify_str(val) for val in self.__defaults])
cur_str = self.__strfield.model.as_string
self.revert_img.enabled = default_str != cur_str
def _restore_default(self):
"""Restore the default values."""
if self.revert_img.enabled:
field_str = ", ".join([self.simplify_str(val) for val in self.__defaults])
self.__strfield.model.set_value(field_str)
self.revert_img.enabled = False
def _build_body(self):
"""Main meat of the widget. Draw the colorpicker, stringfield, and
set up callbacks to keep them updated.
"""
with ui.HStack(spacing=SPACING):
# The construction of the widget depends on what the user provided,
# defaults or a model
if self.existing_model:
# the user provided a model
self.__colorpicker = ui.ColorWidget(
self.existing_model,
width=COLOR_PICKER_WIDTH,
height=BLOCK_HEIGHT,
name=COLOR_WIDGET_NAME
)
color_model = self.existing_model
else:
# the user provided a list of default values
self.__colorpicker = ui.ColorWidget(
*self.__defaults,
width=COLOR_PICKER_WIDTH,
height=BLOCK_HEIGHT,
name=COLOR_WIDGET_NAME
)
color_model = self.__colorpicker.model
self.__strfield = ui.StringField(width=FIELD_WIDTH, name="attribute_color")
self.__color_sub = self.__colorpicker.model.subscribe_item_changed_fn(
lambda m, _, children=color_model.get_item_children():
self.set_color_stringfield(m, children))
self.__strfield_sub = self.__strfield.model.subscribe_value_changed_fn(
lambda m, children=color_model.get_item_children():
self.set_color_widget(m, children))
# show data at the start
self.set_color_stringfield(self.__colorpicker.model,
children=color_model.get_item_children())
| 6,076 | Python | 39.245033 | 101 | 0.59842 |
NVIDIA-Omniverse/kit-extension-sample-ui-window/exts/omni.example.ui_julia_modeler/omni/example/ui_julia_modeler/custom_path_button.py | # Copyright (c) 2022, 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.
#
__all__ = ["CustomPathButtonWidget"]
from typing import Callable, Optional
import omni.ui as ui
from .style import ATTR_LABEL_WIDTH, BLOCK_HEIGHT
class CustomPathButtonWidget:
"""A compound widget for holding a path in a StringField, and a button
that can perform an action.
TODO: Get text ellision working in the path field, to start with "..."
"""
def __init__(self,
label: str,
path: str,
btn_label: str,
btn_callback: Callable):
self.__attr_label = label
self.__pathfield: ui.StringField = None
self.__path = path
self.__btn_label = btn_label
self.__btn = None
self.__callback = btn_callback
self.__frame = ui.Frame()
with self.__frame:
self._build_fn()
def destroy(self):
self.__pathfield = None
self.__btn = None
self.__callback = None
self.__frame = None
@property
def model(self) -> Optional[ui.AbstractItem]:
"""The widget's model"""
if self.__pathfield:
return self.__pathfield.model
@model.setter
def model(self, value: ui.AbstractItem):
"""The widget's model"""
self.__pathfield.model = value
def get_path(self):
return self.model.as_string
def _build_fn(self):
"""Draw all of the widget parts and set up callbacks."""
with ui.HStack():
ui.Label(
self.__attr_label,
name="attribute_name",
width=ATTR_LABEL_WIDTH
)
self.__pathfield = ui.StringField(
name="path_field",
height=BLOCK_HEIGHT,
width=ui.Fraction(2),
)
# TODO: Add clippingType=ELLIPSIS_LEFT for long paths
self.__pathfield.model.set_value(self.__path)
self.__btn = ui.Button(
self.__btn_label,
name="tool_button",
height=BLOCK_HEIGHT,
width=ui.Fraction(1),
clicked_fn=lambda path=self.get_path(): self.__callback(path),
)
| 2,599 | Python | 30.707317 | 78 | 0.576376 |
NVIDIA-Omniverse/kit-extension-sample-ui-window/exts/omni.example.ui_julia_modeler/omni/example/ui_julia_modeler/custom_slider_widget.py | # Copyright (c) 2022, 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.
#
__all__ = ["CustomSliderWidget"]
from typing import Optional
import omni.ui as ui
from omni.ui import color as cl
from omni.ui import constant as fl
from .custom_base_widget import CustomBaseWidget
NUM_FIELD_WIDTH = 50
SLIDER_WIDTH = ui.Percent(100)
FIELD_HEIGHT = 22 # TODO: Once Field padding is fixed, this should be 18
SPACING = 4
TEXTURE_NAME = "slider_bg_texture"
class CustomSliderWidget(CustomBaseWidget):
"""A compound widget for scalar slider input, which contains a
Slider and a Field with text input next to it.
"""
def __init__(self,
model: ui.AbstractItemModel = None,
num_type: str = "float",
min=0.0,
max=1.0,
default_val=0.0,
display_range: bool = False,
**kwargs):
self.__slider: Optional[ui.AbstractSlider] = None
self.__numberfield: Optional[ui.AbstractField] = None
self.__min = min
self.__max = max
self.__default_val = default_val
self.__num_type = num_type
self.__display_range = display_range
# Call at the end, rather than start, so build_fn runs after all the init stuff
CustomBaseWidget.__init__(self, model=model, **kwargs)
def destroy(self):
CustomBaseWidget.destroy()
self.__slider = None
self.__numberfield = None
@property
def model(self) -> Optional[ui.AbstractItemModel]:
"""The widget's model"""
if self.__slider:
return self.__slider.model
@model.setter
def model(self, value: ui.AbstractItemModel):
"""The widget's model"""
self.__slider.model = value
self.__numberfield.model = value
def _on_value_changed(self, *args):
"""Set revert_img to correct state."""
if self.__num_type == "float":
index = self.model.as_float
else:
index = self.model.as_int
self.revert_img.enabled = self.__default_val != index
def _restore_default(self):
"""Restore the default value."""
if self.revert_img.enabled:
self.model.set_value(self.__default_val)
self.revert_img.enabled = False
def _build_display_range(self):
"""Builds just the tiny text range under the slider."""
with ui.HStack():
ui.Label(str(self.__min), alignment=ui.Alignment.LEFT, name="range_text")
if self.__min < 0 and self.__max > 0:
# Add middle value (always 0), but it may or may not be centered,
# depending on the min/max values.
total_range = self.__max - self.__min
# subtract 25% to account for end number widths
left = 100 * abs(0 - self.__min) / total_range - 25
right = 100 * abs(self.__max - 0) / total_range - 25
ui.Spacer(width=ui.Percent(left))
ui.Label("0", alignment=ui.Alignment.CENTER, name="range_text")
ui.Spacer(width=ui.Percent(right))
else:
ui.Spacer()
ui.Label(str(self.__max), alignment=ui.Alignment.RIGHT, name="range_text")
ui.Spacer(height=.75)
def _build_body(self):
"""Main meat of the widget. Draw the Slider, display range text, Field,
and set up callbacks to keep them updated.
"""
with ui.HStack(spacing=0):
# the user provided a list of default values
with ui.VStack(spacing=3, width=ui.Fraction(3)):
with ui.ZStack():
# Put texture image here, with rounded corners, then make slider
# bg be fully transparent, and fg be gray and partially transparent
with ui.Frame(width=SLIDER_WIDTH, height=FIELD_HEIGHT,
horizontal_clipping=True):
# Spacing is negative because "tileable" texture wasn't
# perfectly tileable, so that adds some overlap to line up better.
with ui.HStack(spacing=-12):
for i in range(50): # tiling the texture
ui.Image(name=TEXTURE_NAME,
fill_policy=ui.FillPolicy.PRESERVE_ASPECT_CROP,
width=50,)
slider_cls = (
ui.FloatSlider if self.__num_type == "float" else ui.IntSlider
)
self.__slider = slider_cls(
height=FIELD_HEIGHT,
min=self.__min, max=self.__max, name="attr_slider"
)
if self.__display_range:
self._build_display_range()
with ui.VStack(width=ui.Fraction(1)):
model = self.__slider.model
model.set_value(self.__default_val)
field_cls = (
ui.FloatField if self.__num_type == "float" else ui.IntField
)
# Note: This is a hack to allow for text to fill the Field space more, as there was a bug
# with Field padding. It is fixed, and will be available in the next release of Kit.
with ui.ZStack():
# height=FIELD_HEIGHT-1 to account for the border, so the field isn't
# slightly taller than the slider
ui.Rectangle(
style_type_name_override="Field",
name="attr_field",
height=FIELD_HEIGHT - 1
)
with ui.HStack(height=0):
ui.Spacer(width=2)
self.__numberfield = field_cls(
model,
height=0,
style={
"background_color": cl.transparent,
"border_color": cl.transparent,
"padding": 4,
"font_size": fl.field_text_font_size,
},
)
if self.__display_range:
ui.Spacer()
model.add_value_changed_fn(self._on_value_changed)
| 6,797 | Python | 40.451219 | 105 | 0.529351 |
NVIDIA-Omniverse/kit-extension-sample-ui-window/exts/omni.example.ui_julia_modeler/omni/example/ui_julia_modeler/window.py | # Copyright (c) 2022, 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.
#
__all__ = ["JuliaModelerWindow"]
import omni.ui as ui
from omni.kit.window.popup_dialog import MessageDialog
from .custom_bool_widget import CustomBoolWidget
from .custom_color_widget import CustomColorWidget
from .custom_combobox_widget import CustomComboboxWidget
from .custom_multifield_widget import CustomMultifieldWidget
from .custom_path_button import CustomPathButtonWidget
from .custom_radio_collection import CustomRadioCollection
from .custom_slider_widget import CustomSliderWidget
from .style import julia_modeler_style, ATTR_LABEL_WIDTH
SPACING = 5
class JuliaModelerWindow(ui.Window):
"""The class that represents the window"""
def __init__(self, title: str, delegate=None, **kwargs):
self.__label_width = ATTR_LABEL_WIDTH
super().__init__(title, **kwargs)
# Apply the style to all the widgets of this window
self.frame.style = julia_modeler_style
# Set the function that is called to build widgets when the window is
# visible
self.frame.set_build_fn(self._build_fn)
def destroy(self):
# Destroys all the children
super().destroy()
@property
def label_width(self):
"""The width of the attribute label"""
return self.__label_width
@label_width.setter
def label_width(self, value):
"""The width of the attribute label"""
self.__label_width = value
self.frame.rebuild()
def on_export_btn_click(self, path):
"""Sample callback that is used when the Export button is pressed."""
dialog = MessageDialog(
title="Button Pressed Dialog",
message=f"Export Button was clicked with path inside: {path}",
disable_cancel_button=True,
ok_handler=lambda dialog: dialog.hide()
)
dialog.show()
def _build_title(self):
with ui.VStack():
ui.Spacer(height=10)
ui.Label("JULIA QUATERNION MODELER - 1.0", name="window_title")
ui.Spacer(height=10)
def _build_collapsable_header(self, collapsed, title):
"""Build a custom title of CollapsableFrame"""
with ui.VStack():
ui.Spacer(height=8)
with ui.HStack():
ui.Label(title, name="collapsable_name")
if collapsed:
image_name = "collapsable_opened"
else:
image_name = "collapsable_closed"
ui.Image(name=image_name, width=10, height=10)
ui.Spacer(height=8)
ui.Line(style_type_name_override="HeaderLine")
def _build_calculations(self):
"""Build the widgets of the "Calculations" group"""
with ui.CollapsableFrame("Calculations".upper(), name="group",
build_header_fn=self._build_collapsable_header):
with ui.VStack(height=0, spacing=SPACING):
ui.Spacer(height=6)
CustomSliderWidget(min=0, max=20, num_type="int",
label="Precision", default_val=6)
CustomSliderWidget(min=0, max=20, num_type="int",
label="Iterations", default_val=10)
def _build_parameters(self):
"""Build the widgets of the "Parameters" group"""
with ui.CollapsableFrame("Parameters".upper(), name="group",
build_header_fn=self._build_collapsable_header):
with ui.VStack(height=0, spacing=SPACING):
ui.Spacer(height=6)
CustomSliderWidget(min=-2, max=2, display_range=True,
label="Iterations", default_val=0.75)
CustomSliderWidget(min=0, max=2, display_range=True,
label="i", default_val=0.65)
CustomSliderWidget(min=0, max=2, display_range=True,
label="j", default_val=0.25)
CustomSliderWidget(min=0, max=2, display_range=True,
label="k", default_val=0.55)
CustomSliderWidget(min=0, max=3.14, display_range=True,
label="Theta", default_val=1.25)
def _build_light_1(self):
"""Build the widgets of the "Light 1" group"""
with ui.CollapsableFrame("Light 1".upper(), name="group",
build_header_fn=self._build_collapsable_header):
with ui.VStack(height=0, spacing=SPACING):
ui.Spacer(height=6)
CustomMultifieldWidget(
label="Orientation",
default_vals=[0.0, 0.0, 0.0]
)
CustomSliderWidget(min=0, max=1.75, label="Intensity", default_val=1.75)
CustomColorWidget(1.0, 0.875, 0.5, label="Color")
CustomBoolWidget(label="Shadow", default_value=True)
CustomSliderWidget(min=0, max=2, label="Shadow Softness", default_val=.1)
def _build_scene(self):
"""Build the widgets of the "Scene" group"""
with ui.CollapsableFrame("Scene".upper(), name="group",
build_header_fn=self._build_collapsable_header):
with ui.VStack(height=0, spacing=SPACING):
ui.Spacer(height=6)
CustomSliderWidget(min=0, max=160, display_range=True,
num_type="int", label="Field of View", default_val=60)
CustomMultifieldWidget(
label="Orientation",
default_vals=[0.0, 0.0, 0.0]
)
CustomSliderWidget(min=0, max=2, label="Camera Distance", default_val=.1)
CustomBoolWidget(label="Antialias", default_value=False)
CustomBoolWidget(label="Ambient Occlusion", default_value=True)
CustomMultifieldWidget(
label="Ambient Distance",
sublabels=["Min", "Max"],
default_vals=[0.0, 200.0]
)
CustomComboboxWidget(label="Ambient Falloff",
options=["Linear", "Quadratic", "Cubic"])
CustomColorWidget(.6, 0.62, 0.9, label="Background Color")
CustomRadioCollection("Render Method", labels=["Path Traced", "Volumetric"],
default_value=1)
CustomPathButtonWidget(
label="Export Path",
path=".../export/mesh1.usd",
btn_label="Export",
btn_callback=self.on_export_btn_click,
)
ui.Spacer(height=10)
def _build_fn(self):
"""
The method that is called to build all the UI once the window is
visible.
"""
with ui.ScrollingFrame(name="window_bg",
horizontal_scrollbar_policy=ui.ScrollBarPolicy.SCROLLBAR_ALWAYS_OFF):
with ui.VStack(height=0):
self._build_title()
self._build_calculations()
self._build_parameters()
self._build_light_1()
self._build_scene()
| 7,703 | Python | 37.909091 | 100 | 0.564975 |
NVIDIA-Omniverse/kit-extension-sample-ui-window/exts/omni.example.ui_julia_modeler/docs/CHANGELOG.md | # Changelog
## [1.0.1] - 2022-06-23
### Added
- Readme
## [1.0.0] - 2022-06-22
### Added
- Initial window
| 108 | Markdown | 9.899999 | 23 | 0.555556 |
NVIDIA-Omniverse/kit-extension-sample-ui-window/exts/omni.example.ui_julia_modeler/docs/README.md | # Julia Modeler (omni.example.ui_julia_modeler)

## Overview
In this example, we create a window which uses custom widgets that follow a similar pattern. The window is built using `omni.ui`.
It contains the best practices of how to build customized widgets and reuse them without duplicating the code. The structure is very similar to that of `omni.example.ui_window`, so we won't duplicate all of that same documentation here.
## [Tutorial](../tutorial/tutorial.md)
This extension sample also includes a step-by-step tutorial to accelerate your growth as you learn to build your own Omniverse Kit extensions. [Get started with the tutorial.](../tutorial/tutorial.md)
## Usage
This is just a UI demo. You can interact with the various controls, but they have not additional effect in the Application.
## Explanations
### Custom Widgets
Because this design had a pattern for most of its attribute rows, like:
`<head><body><tail>`
where "head" is always the same kind of attribute label, the "body" is the customized part of the widget, and then the "tail" is either a revert arrow button, or empty space, we decided it would be useful to make a base class for all of the similar custom widgets, to reduce code duplication, and to make sure that the 3 parts always line up in the UI.

By structuring the base class with 3 main methods for building the 3 sections, child classes can focus on just building the "body" section, by implementing `_build_body()`. These are the 3 main methods in the base class, and the `_build_fn()` method that puts them all together:
```python
def _build_head(self):
# The main attribute label
ui.Label(
self.__attr_label,
name="attribute_name",
width=ATTR_LABEL_WIDTH
)
def _build_body(self):
# Most custom widgets will override this method,
# as it is where the meat of the custom widget is
ui.Spacer()
def _build_tail(self):
# In this case, we have a Revert Arrow button
# at the end of each widget line
with ui.HStack(width=0):
ui.Spacer(width=5)
with ui.VStack(height=0):
ui.Spacer(height=3)
self.revert_img = ui.Image(
name="revert_arrow",
fill_policy=ui.FillPolicy.PRESERVE_ASPECT_FIT,
width=12,
height=13,
enabled=False,
)
ui.Spacer(width=5)
# add call back to revert_img click to restore the default value
self.revert_img.set_mouse_pressed_fn(
lambda x, y, b, m: self._restore_default())
def _build_fn(self):
# Put all the parts together
with ui.HStack():
self._build_head()
self._build_body()
self._build_tail()
```
and this is an example of implementing `_build_body()` in a child class:
```python
def _build_body(self):
with ui.HStack():
with ui.VStack():
ui.Spacer(height=2)
self.__bool_image = ui.Image(
name="checked" if self.__default_val else "unchecked",
fill_policy=ui.FillPolicy.PRESERVE_ASPECT_FIT,
height=16, width=16, checked=self.__default_val
)
ui.Spacer()
self.__bool_image.set_mouse_pressed_fn(
lambda x, y, b, m: self._on_value_changed())
```
#### Value Changed "Revert" Widget
In this example, almost every attribute row has a widget which indicates whether the value has been changed or not. By default, the revert arrow button is disabled and gray, and when the value has been changed it turns light blue and is enabled. Most of the functionality for this widget lives in the CustomBaseWidget class.
The base class also calls a _restore_value method that needs to be implemented in the child class. Each child class can handle attribute values differently, so the logic of how to revert back needs to live at that level. The child class also takes care of enabling the revert button when the value has changed, turning it blue.


#### Custom Int/Float Slider

At a high level, this custom widget is just the combination of a `ui.FloatSlider` or `ui.IntSlider` and a `ui.FloatField` or `ui.IntField`. But there are a few more aspects that make this widget interesting:
- The background of the slider has a diagonal lines texture. To accomplish that, a tiled image of that texture is placed behind the rest of the widget using a ZStack. A Slider is placed over top, almost completely transparent. The background color is transparent and the text is transparent. The foreground color, called the `secondary_color` is light gray with some transparency to let the texture show through.
- Immediately below the slider is some optional tiny text that denotes the range of the slider. If both min and max are positive or both are negative, only the endpoints are shown. If the min is negative, and the max is positive, however, the 0 point is also added in between, based on where it would be. That tiny text is displayed by using `display_range=True` when creating a `CustomSliderWidget`.
- There was a bug with sliders and fields around how the padding worked. It is fixed and will be available in the next version of Kit, but until then, there was a workaround to make things look right: a ui.Rectangle with the desired border is placed behind a ui.FloatField. The Field has a transparent background so all that shows up from it is the text. That way the Slider and Field can line up nicely and the text in the Field can be the same size as with other widgets in the UI.
#### Customized ColorWidget
The customized ColorWidget wraps a `ui.ColorWidget` widget and a `ui.StringField` widget in a child class of CustomBaseWidget.

The colorpicker widget is a normal `ui.ColorWidget`, but the text part is really just a `ui.StringField` with comma-separated values, rather than a `ui.MultiFloatDragField` with separate R, G, and B values. So it wasn't as easy to just use the same model for both. Instead, to make them connect in both directions, we set up a callback for each widget, so that each would update the other one on any changes:
```python
self.__color_sub = self.__colorpicker.model.subscribe_item_changed_fn(
lambda m, _, children=color_model.get_item_children(): self.set_color_stringfield(m, children))
self.__strfield_sub = self.__strfield.model.subscribe_value_changed_fn(
lambda m, children=color_model.get_item_children():
self.set_color_widget(m, children))
```
#### Custom Path & Button Widget
The Custom Path & Button widget doesn't follow quite the same pattern as most of the others, because it doesn't have a Revert button at the end, and the Field and Button take different proportions of the space.

In the widget's `_build_fn()` method, we draw the entire row all in one place. There's the typical label on the left, a StringField in the middle, and a Button at the end:
```python
with ui.HStack():
ui.Label(
self.__attr_label,
name="attribute_name",
width=ATTR_LABEL_WIDTH
)
self.__pathfield = ui.StringField(
name="path_field",
height=BLOCK_HEIGHT,
width=ui.Fraction(2),
)
self.__pathfield.model.set_value(self.__path)
self.__btn = ui.Button(
self.__btn_label,
name="tool_button",
height=BLOCK_HEIGHT,
width=ui.Fraction(1),
clicked_fn=lambda path=self.get_path(): self.__callback(path),
)
```
All of those strings for labels and paths are customizable when creating the Widget. In window.py, this is how we instantiate the Export-style version:
_(Note: In a real situation we would use the entire path, but we added the "..." ellipsis to show an ideal way to clip the text in the future.)_
```python
CustomPathButtonWidget(
label="Export Path",
path=".../export/mesh1.usd",
btn_label="Export",
btn_callback=self.on_export_btn_click,
)
```
And we show a sample callback hooked up to the button -- `self.on_export_btn_click`, which for this example, just pops up a MessageDialog telling the user what the path was that is in the Field:
```python
def on_export_btn_click(self, path):
"""Sample callback that is used when the Export button is pressed."""
dialog = MessageDialog(
title="Button Pressed Dialog",
message=f"Export Button was clicked with path inside: {path}",
disable_cancel_button=True,
ok_handler=lambda dialog: dialog.hide()
)
dialog.show()
```
### Style
Although the style can be applied to any widget, we recommend keeping the style
dictionary in one location, such as `styles.py`.
One comment on the organization of the styles. You may notice named constants that seem redundant, that could be consolidated, such as multiple font type sizes that are all `14`.
```python
fl.window_title_font_size = 18
fl.field_text_font_size = 14
fl.main_label_font_size = 14
fl.multi_attr_label_font_size = 14
fl.radio_group_font_size = 14
fl.collapsable_header_font_size = 13
fl.range_text_size = 10
```
While you definitely _could_ combine all of those into a single constant, it can be useful to break them out by type of label/text, so that if you later decide that you want just the Main Labels to be `15` instead of `14`, you can adjust just the one constant, without having to break out all of the other types of text that were using the same font size by coincidence. This same organization applies equally well to color assignments also.
### Window
It's handy to derive a custom window from the class `ui.Window`. The UI can be
defined right in `__init__`, so it's created immediately or it can be defined in
a `set_build_fn` callback and it will be created when the window is visible. The later one is used in this example.
```python
class PropertyWindowExample(ui.Window):
"""The class that represents the window"""
def __init__(self, title: str, delegate=None, **kwargs):
self.__label_width = LABEL_WIDTH
super().__init__(title, **kwargs)
# Apply the style to all the widgets of this window
self.frame.style = julia_modeler_style
# Set the function that is called to build widgets when the window is visible
self.frame.set_build_fn(self._build_fn)
```
Inside the `self._build_fn`, we use the customized widgets to match the design layout for the window.
### Extension
When the extension starts up, we register a new menu item that controls the window and shows the window.
A very important part is using `ui.Workspace.set_show_window_fn` to register the window in `omni.ui`. It will help to save and load the layout of Kit.
```python
ui.Workspace.set_show_window_fn(JuliaModelerExtension.WINDOW_NAME, partial(self.show_window, None))
```
When the extension shuts down, we remove the menu item and deregister the window callback. | 11,458 | Markdown | 49.480176 | 486 | 0.686245 |
NVIDIA-Omniverse/kit-extension-sample-ui-window/exts/omni.example.ui_window/tutorial/tutorial.md | # UI Window Tutorial
In this tutorial, you learn how to create an Omniverse Extension that has a window and user interface (UI) elements inside that window.
## Learning Objectives
* Create a window.
* Add it to the **Window** menu.
* Add various control widgets into different collapsable group with proper layout and alignment.
## Step 1: Clone the Repository
Clone the `ui-window-tutorial-start` branch of the `kit-extension-sample-ui-window` [GitHub repository](https://github.com/NVIDIA-Omniverse/kit-extension-sample-ui-window/tree/ui-window-tutorial-start):
```shell
git clone -b ui-window-tutorial-start https://github.com/NVIDIA-Omniverse/kit-extension-sample-ui-window.git
```
This repository contains the starting code you use in this tutorial.
## Step 2: Add the Extension to Omniverse Code
In order to use and test your Extension, you need to add it to Omniverse Code.
### Step 2.1: Navigate to the Extensions List
In Omniverse Code, navigate to the *Extensions* panel:

Here, you see a list of Omniverse Extensions that you can activate and use in Code.
> **Note:** If you don't see the *Extensions* panel, enable **Window > Extensions**:
>
> 
### Step 2.2: Navigate to the *Extension Search Paths*
Click the **gear** icon to open *Extension Search Paths*:

In this panel, you can add your custom Extension to the Extensions list.
### Step 2.3: Create a New Search Path
Create a new search path to the `exts` directory of your Extension by clicking the green **plus** icon and double-clicking on the **path** field:

When you submit your new search path, you should be able to find your extension in the *Extensions* list. Search for "omni.example.ui_" to filter down the list. Activate the "OMNI.UI WINDOW EXAMPLE" Extension:

Now that your Extension is added and enabled, you can make changes to the code and see them in your Application.
## Step 3: Create A Window
In this section, you create an empty window that you can hide and show and is integrated into the **Application** menu. This window incorporates a few best practices so that it's well-connected with Omniverse and feels like a natural part of the application it's being used from. You do all of this in the `extension.py` file.
### Step 3.1: Support Hide/Show
Windows can be hidden and shown from outside the window code that you write. If you would like Omniverse to be able to show a window after it has been hidden, you must register a callback function to run when the window visibility changes. To do this, open the `extension.py` file, go to the `on_startup()` definition, and edit the function to match the following code:
```python
def on_startup(self):
# The ability to show the window if the system requires it. We use it
# in QuickLayout.
ui.Workspace.set_show_window_fn(ExampleWindowExtension.WINDOW_NAME, partial(self.show_window, None))
# Add a Menu Item for the window
# Show the window through the 'set_show_window_fn' you wired up above
# It will call `self.show_window`
```
The added line registers the `self.show_window` callback to be run whenever the visibility of your extension is changed. The `pass` line of code is deleted because it is no longer necessary. It was only included because all code had been removed from that function.
### Step 3.2: Add a Menu Item
It is helpful to add extensions to the application menu so that if a user closes a window they can reopen it. This is done by adding the following code to `on_startup()`:
```python
def on_startup(self):
# The ability to show the window if the system requires it.
# You use it in QuickLayout.
ui.Workspace.set_show_window_fn(ExampleWindowExtension.WINDOW_NAME, partial(self.show_window, None))
# Add a Menu Item for the window
editor_menu = omni.kit.ui.get_editor_menu()
if editor_menu:
self._menu = editor_menu.add_item(
ExampleWindowExtension.MENU_PATH, self.show_window, toggle=True, value=True
)
# Show the window through the 'set_show_window_fn' you wired up above
# It will call `self.show_window`
```
The first added line grabs a reference to the application menu. The second new line adds a new menu item where `MENU_PATH` determines where the menu item will appear in the menu system, and `self.show_window` designates the function to run when the user toggles the window visibility by clicking on the menu item.
### Step 3.3: Show the Window
To finish with `on_startup()`, add the following:
```python
def on_startup(self):
# The ability to show the window if the system requires it.
# You use it in QuickLayout.
ui.Workspace.set_show_window_fn(ExampleWindowExtension.WINDOW_NAME, partial(self.show_window, None))
# Add a Menu Item for the window
editor_menu = omni.kit.ui.get_editor_menu()
if editor_menu:
self._menu = editor_menu.add_item(
ExampleWindowExtension.MENU_PATH, self.show_window, toggle=True, value=True
)
# Show the window through the 'set_show_window_fn' you wired up above
# It will call `self.show_window`
ui.Workspace.show_window(ExampleWindowExtension.WINDOW_NAME)
```
This calls `show_window()` through the registration you set up earlier.
### Step 3.4: Call the Window Constructor
Finally, in the `extension.py` file, scroll down to the `show_window` method which is currently the code below:
```python
def show_window(self, menu, value):
#value is true if the window should be shown
if value:
#call our custom window constructor
#Handles the change in visibility of the window gracefuly
self._window.set_visibility_changed_fn(self._visiblity_changed_fn)
elif self._window:
self._window.visible = False
```
Add the following line to this function:
```python
def show_window(self, menu, value):
#value is true if the window should be shown
if value:
#call our custom window constructor
self._window = ExampleWindow(ExampleWindowExtension.WINDOW_NAME, width=300, height=365)
#Handles the change in visibility of the window gracefuly
self._window.set_visibility_changed_fn(self._visiblity_changed_fn)
elif self._window:
self._window.visible = False
```
This calls the constructor of the custom window class in `window.py` and assigns it to the extension `self._window`.
## Step 4: Custom Window
The custom window class can be found in `window.py`. It is possible to simply build all of your user interface in `extension.py`, but this is only a good practice for very simple extensions. More complex extensions should be broken into managable pieces. It is a good practice to put your user interface into its own file. Note that `window.py` contains a class that inherits from `ui.Window`. Change the `__init__()` function to include the line added below:
```python
def __init__(self, title: str, delegate=None, **kwargs):
self.__label_width = LABEL_WIDTH
super().__init__(title, **kwargs)
# Apply the style to all the widgets of this window
self.frame.style = example_window_style
# Set the function that is called to build widgets when the window is
# visible
self.frame.set_build_fn(self._build_fn)
```
This line registers the `self._build_fn` callback to run when the window is visible, which is where you will build the user interface for this tutorial.
### Step 4.1: Create a Scrolling Frame
Now scroll down to `_build_fn` at the bottom of `window.py` and edit it to match the following:
```python
def _build_fn(self):
# The method that is called to build all the UI once the window is visible.
with ui.ScrollingFrame():
pass
```
The `with` statement begins a context block and you are creating a `ScrollingFrame`. What this means is that everything intended below the `with` will be a child of the `ScrollingFrame`.
A [ScrollingFrame](https://docs.omniverse.nvidia.com/py/kit/source/extensions/omni.ui/docs/index.html#omni.ui.ScrollingFrame) is an area within your user interface with a scroll bar. By creating one first, if the user makes the window small, a scrollbar will appear, allowing the user to still access all content in the user interface.
### Step 4.2: Create a Vertical Stack
Next edit the `_build_fn()` definition by replacing the `pass` line with the following context block and put a `pass` keyword inside the new context block as shown below:
```python
def _build_fn(self):
# The method that is called to build all the UI once the window is visible.
with ui.ScrollingFrame():
with ui.VStack(height=0):
pass
```
Here you added a `VStack`, which stacks its children vertically. The first item is at the top and each subsequent item is placed below the previous item as demonstrated in the schematic below:
<p align="center">
<img src="Images/VerticalStack.png" width=25%>
<p>
This will be used to organize the controls into rows.
### Step 4.3: Break the Construction into Chunks
While it would be possible to create the entire user interface in this tutorial directly in `_build_fn()`, as a user interface gets large it can be unwieldly to have it entirely within one function. In order to demonstrate best practices, this tutorial builds each item in the vertical stack above in its own function. Go ahead and edit your code to match the block below:
```python
def _build_fn(self):
# The method that is called to build all the UI once the window is visible.
with ui.ScrollingFrame():
with ui.VStack(height=0):
self._build_calculations()
self._build_parameters()
self._build_light_1()
```
Each of these functions: `_build_calculations()`, `_build_parameters()`, and `_build_light_1()` builds an item in the vertical stack. Each of those items is a group of well-organized controls made with a consistent look and layout.
If you save `window.py` it will `hot reload`, but will not look any different from before. That is because both `ScrollingFrame` and `VStack` are layout controls. This means that they are meant to organize content within them, not be displayed themselves. A `ScrollingFrame` can show a scroll bar, but only if it has content to be scrolled.
## Step 5: Build Calculations
The first group you will create is the `Calculations group`. In this section `CollapsableFrame`, `HStack`, `Label`, and `IntSlider` will be introduced. Scroll up to the `_build_calculations` which looks like the following block of code:
```python
def _build_calculations(self):
# Build the widgets of the "Calculations" group
# A VStack is a vertical stack and aligns widgets vertically one after the other
# An HStack is a horizontal stack and aligns widgets horizontally one after the other
# A label displays text
# An IntSlider lets a user choose an integer by sliding a bar back and forth
# Pairing a label with a control is a common UI comb
# The label makes the purpose of the control clear
# You can set the min and max value on an IntSlider
pass
```
In the remaining sub-sections you will fill this in and create your first group of controls.
### Step 5.1: Create a Collapsable Frame
Edit `_build_calculations()` to match the following:
```python
def _build_calculations(self):
# Build the widgets of the "Calculations" group
with ui.CollapsableFrame("Calculations", name="group", build_header_fn=self._build_collapsable_header):
# A VStack is a vertical stack and aligns widgets vertically one after the other
# An HStack is a horizontal stack and aligns widgets horizontally one after the other
# A label displays text
# An IntSlider lets a user choose an integer by sliding a bar back and forth
# Pairing a label with a control is a common UI comb
# The label makes the purpose of the control clear
# You can set the min and max value on an IntSlider
pass
```
A `CollapsableFrame` is a control that you can expand and contract by clicking on its header, which will show or hide its content. The first argument passed into its constructor is the title string. The second argument is its name and the final argument is a reference to the function that builds its header. You can write this function to give the header whatever look you want. At this point if you save `window.py` and then test in Omniverse Code you will see a change in your extension's window. The `CollapsableFrame` will be visible and should look like this:
<p align="center">
<img src="Images/CollapsableFrame.png" width=25%>
<p>
Next we will add content inside this `CollapsableFrame`.
### Step 5.2: Create a Horizontal Stack
The next three steps demonstrate a very common user interface pattern, which is to have titled controls that are well aligned. A common mistake is to create a user interface that looks like this:
<p align="center">
<img src="Images/BadUI.png" width=25%>
<p>
The controls have description labels, but they have inconsistent positions and alignments. The following is a better design:
<p align="center">
<img src="Images/GoodUI.png" width=25%>
<p>
Notice that the description labels are all to the left of their respective controls, the labels are aligned, and the controls have a consistent width.
This will be demonstrated twice within a `VStack` in this section. Add a `VStack` and then to create this common description-control layout, add an `HStack` to the user interface as demonstrated in the following code block:
```python
def _build_calculations(self):
# Build the widgets of the "Calculations" group
with ui.CollapsableFrame("Calculations", name="group", build_header_fn=self._build_collapsable_header):
# A VStack is a vertical stack and aligns widgets vertically one after the other
with ui.VStack(height=0, spacing=SPACING):
# An HStack is a horizontal stack and aligns widgets horizontally one after the other
with ui.HStack():
# A label displays text
# An IntSlider allows a user choose an integer by sliding a bar back and forth
pass
# Pairing a label with a control is a common UI comb
# The label makes the purpose of the control clear
# You can set the min and max value on an IntSlider
pass
```
An `HStack` is very similar to a `VStack` except that it stacks its content horizontally rather than vertically. Note that a `pass` you added to the `VStack` simply so that the code will run until you add more controls to this context.
### Step 5.3: Create a Label
Next add a `Label` to the `HStack`:
```python
def _build_calculations(self):
# Build the widgets of the "Calculations" group
with ui.CollapsableFrame("Calculations", name="group", build_header_fn=self._build_collapsable_header):
# A VStack is a vertical stack and aligns widgets vertically one after the other
with ui.VStack(height=0, spacing=SPACING):
# An HStack is a horizontal stack and aligns widgets horizontally one after the other
with ui.HStack():
# A label displays text
ui.Label("Precision", name="attribute_name", width=self.label_width)
# An IntSlider allows a user choose an integer by sliding a bar back and forth
# Pairing a label with a control is a common UI comb
# The label makes the purpose of the control clear
# You can set the min and max value on an IntSlider
```
If you save the file and go to `Code` you will see that the `Label` appears in the user interface. Take special note of the `width` attribute passed into the constructor. By making all of the labels the same width inside their respective `HStack` controls, the labels and the controls they describe will be aligned. Note also that all contexts now have code, so we have removed the `pass` statements.
### Step 5.4: Create an IntSlider
Next add an `IntSlider` as shown below:
```python
def _build_calculations(self):
# Build the widgets of the "Calculations" group
with ui.CollapsableFrame("Calculations", name="group", build_header_fn=self._build_collapsable_header):
# A VStack is a vertical stack and aligns widgets vertically one after the other
with ui.VStack(height=0, spacing=SPACING):
# An HStack is a horizontal stack and aligns widgets horizontally one after the other
with ui.HStack():
# A label displays text
ui.Label("Precision", name="attribute_name", width=self.label_width)
# An IntSlider allows a user choose an integer by sliding a bar back and forth
ui.IntSlider(name="attribute_int")
# Pairing a label with a control is a common UI comb
# The label makes the purpose of the control clear
# You can set the min and max value on an IntSlider
```
An `IntSlider` is a slider bar that a user can click and drag to control an integer value. If you save your file and go to Omniverse Code, your user interface should now look like this:
<p align="center">
<img src="Images/IntSlider.png" width=25%>
<p>
Go ahead and add a second label/control pair by adding the following code:
```python
def _build_calculations(self):
# Build the widgets of the "Calculations" group
with ui.CollapsableFrame("Calculations", name="group", build_header_fn=self._build_collapsable_header):
# A VStack is a vertical stack and aligns widgets vertically one after the other
with ui.VStack(height=0, spacing=SPACING):
# An HStack is a horizontal stack and aligns widgets horizontally one after the other
with ui.HStack():
# A label displays text
ui.Label("Precision", name="attribute_name", width=self.label_width)
# An IntSlider allows a user choose an integer by sliding a bar back and forth
ui.IntSlider(name="attribute_int")
# Pairing a label with a control is a common UI comb
with ui.HStack():
# The label makes the purpose of the control clear
ui.Label("Iterations", name="attribute_name", width=self.label_width)
# You can set the min and max value on an IntSlider
ui.IntSlider(name="attribute_int", min=0, max=5)
```
You have added another `HStack`. This one has a `Label` set to the same width as the first `Label`. This gives the group consistent alignment. `min` and `max` values have also been set on the second `IntSlider` as a demonstration. Save `window.py` and test the extension in Omniverse Code. Expand and collapse the `CollapsableFrame`, resize the window, and change the integer values. It is a good practice to move and resize your extension windows as you code to make sure that the layout looks good no matter how the user resizes it.
## Step 6: Build Parameters
In this section you will introduce the `FloatSlider` and demonstrate how to keep the UI consistent across multiple groups. You will be working in the `_build_parameters()` definition which starts as shown below:
```python
def _build_parameters(self):
# Build the widgets of the "Parameters" group
# A Float Slider is similar to an Int Slider
# controls a 'float' which is a number with a decimal point (A Real number)
# You can set the min and max of a float slider as well
# Setting the labels all to the same width gives the UI a nice alignment
# A few more examples of float sliders
pass
```
Hopefullly this is starting to feel a bit more familiar. You have an empty function that has a `pass` command at the end as a placeholder until you add code to all of its contexts.
### Step 6.1: Create a FloatSlider
A `FloatSlider` is very similar to an `IntSlider`. The difference is that it controls a `float` number rather than an `integer`. Match the code below to add one to your extension:
```python
def _build_parameters(self):
# Build the widgets of the "Parameters" group
with ui.CollapsableFrame("Parameters", name="group", build_header_fn=self._build_collapsable_header):
with ui.VStack(height=0, spacing=SPACING):
with ui.HStack():
ui.Label("Value", name="attribute_name", width=self.label_width)
# A Float Slider is similar to an Int Slider
# controls a 'float' which is a number with a decimal point (A Real number)
ui.FloatSlider(name="attribute_float")
# You can set the min and max of a float slider as well
# Setting the labels all to the same width gives the UI a nice alignment
# A few more examples of float sliders
```
Here you added a second `CollapsableFrame` with a `VStack` inside of it. This will allow you to add as many label/control pairs as you want to this group. Note that the `Label` has the same width as the label above. Save `window.py` and you should see the following in Omniverse Code:
<p align="center">
<img src="Images/SecondGroup.png" width=25%>
<p>
Note that the description labels and controls in the first and second group are aligned with each other.
### Step 6.2: Make a Consistent UI
By using these description control pairs inside of collapsable groups, you can add many controls to a window while maintaining a clean, easy to navigate experience. The following code adds a few more `FloatSlider` controls to the user interface:
```python
def _build_parameters(self):
# Build the widgets of the "Parameters" group
with ui.CollapsableFrame("Parameters", name="group", build_header_fn=self._build_collapsable_header):
with ui.VStack(height=0, spacing=SPACING):
with ui.HStack():
ui.Label("Value", name="attribute_name", width=self.label_width)
# A Float Slider is similar to an Int Slider
# controls a 'float' which is a number with a decimal point (A Real number)
ui.FloatSlider(name="attribute_float")
with ui.HStack():
ui.Label("i", name="attribute_name", width=self.label_width)
# You can set the min and max of a float slider as well
ui.FloatSlider(name="attribute_float", min=-1, max=1)
# Setting the labels all to the same width gives the UI a nice alignment
with ui.HStack():
ui.Label("j", name="attribute_name", width=self.label_width)
ui.FloatSlider(name="attribute_float", min=-1, max=1)
# A few more examples of float sliders
with ui.HStack():
ui.Label("k", name="attribute_name", width=self.label_width)
ui.FloatSlider(name="attribute_float", min=-1, max=1)
with ui.HStack():
ui.Label("Theta", name="attribute_name", width=self.label_width)
ui.FloatSlider(name="attribute_float")
```
Save `window.py` and take a look in Omniverse Code. Your window should look like this:
<p align="center">
<img src="Images/SecondGroupComplete.png" width=25%>
<p>
Note that a few of the sliders have `min` and `max` values and they they are all well-aligned.
## Step 7: Build Light
In your final group you will add a few other control types to help give you a feel for what can be done in an extension UI. This will also be well-arranged, even though they are different control types to give the overall extension a consistent look and feel, even though it has a variety of control types. You will be working in `_build_light_1()`, which starts as shown below:
```python
def _build_light_1(self):
# Build the widgets of the "Light 1" group
# A multi float drag field lets you control a group of floats
# Notice what you use the same label width in all of the collapsable frames
# This ensures that the entire UI has a consistent feel
#Feel free to copy this color widget and use it in your own UIs
# The custom compound widget
#An example of a checkbox
pass
```
First you will add a `MultiFloatDragField` to it, then a custom color picker widget and finally a `Checkbox`.
### Step 7.1: Create a MultiFloatDragField
Edit `_build_light_1` to match the following:
```python
def _build_light_1(self):
# Build the widgets of the "Light 1" group
with ui.CollapsableFrame("Light 1", name="group", build_header_fn=self._build_collapsable_header):
with ui.VStack(height=0, spacing=SPACING):
with ui.HStack():
ui.Label("Orientation", name="attribute_name", width=self.label_width)
# A multi float drag field allows you control a group of floats (Real numbers)
ui.MultiFloatDragField(0.0, 0.0, 0.0, h_spacing=SPACING, name="attribute_vector")
# Notice what you use the same label width in all of the collapsable frames
# This ensures that the entire UI has a consistent feel
with ui.HStack():
ui.Label("Intensity", name="attribute_name", width=self.label_width)
ui.FloatSlider(name="attribute_float")
#Feel free to copy this color widget and use it in your own UIs
# The custom compound widget
#An example of a checkbox
```
This adds a third `CollapsableFrame` with a `VStack` to hold its controls. Then it adds a label/control pair with a `MultiFloatDragField`. A `MultiFloatDragField` lets a user edit as many values as you put into its constructor, and is commonly used to edit 3-component vectors such as position and rotation.
You also added a second label and control pair with a `FloatSlider` similar to the one you added in [section 5.1](#51-create-a-floatslider).
### Step 7.2: Add a Custom Widget
Developers can create custom widgets and user interface elements. The color picker added in this section is just such an example. Add it to your extension with the following code:
```python
def _build_light_1(self):
# Build the widgets of the "Light 1" group
with ui.CollapsableFrame("Light 1", name="group", build_header_fn=self._build_collapsable_header):
with ui.VStack(height=0, spacing=SPACING):
with ui.HStack():
ui.Label("Orientation", name="attribute_name", width=self.label_width)
# A multi float drag field lets you control a group of floats (Real numbers)
ui.MultiFloatDragField(0.0, 0.0, 0.0, h_spacing=SPACING, name="attribute_vector")
# Notice what you use the same label width in all of the collapsable frames
# This ensures that the entire UI has a consistent feel
with ui.HStack():
ui.Label("Intensity", name="attribute_name", width=self.label_width)
ui.FloatSlider(name="attribute_float")
#Feel free to copy this color widget and use it in your own UIs
with ui.HStack():
ui.Label("Color", name="attribute_name", width=self.label_width)
# The custom compound widget
ColorWidget(0.25, 0.5, 0.75)
#An example of a checkbox
```
This widget lets users click and then select a color. Feel free to use this widget in your own applications and feel free to write and share your own widgets. Over time you will have a wide variety of useful widgets and controls for everyone to use in their extensions.
### Step 7.3: Add a Checkbox
Finally, edit `_build_light_1()` to match the following:
```python
def _build_light_1(self):
# Build the widgets of the "Light 1" group
with ui.CollapsableFrame("Light 1", name="group", build_header_fn=self._build_collapsable_header):
with ui.VStack(height=0, spacing=SPACING):
with ui.HStack():
ui.Label("Orientation", name="attribute_name", width=self.label_width)
# A multi float drag field lets you control a group of floats (Real numbers)
ui.MultiFloatDragField(0.0, 0.0, 0.0, h_spacing=SPACING, name="attribute_vector")
# Notice what you use the same label width in all of the collapsable frames
# This ensures that the entire UI has a consistent feel
with ui.HStack():
ui.Label("Intensity", name="attribute_name", width=self.label_width)
ui.FloatSlider(name="attribute_float")
#Feel free to copy this color widget and use it in your own UIs
with ui.HStack():
ui.Label("Color", name="attribute_name", width=self.label_width)
# The custom compound widget
ColorWidget(0.25, 0.5, 0.75)
#An example of a checkbox
with ui.HStack():
ui.Label("Shadow", name="attribute_name", width=self.label_width)
ui.CheckBox(name="attribute_bool")
```
This adds a label/control pair with a `CheckBox`. A `CheckBox` control allows a user to set a boolean value.
Save your `window.py` file and open Omniverse Code. Your user interface should look like this if you collapse the `Parameters` section:
<p align="center">
<img src="Images/Complete.png" width=25%>
<p>
There are three collapsable groups, each with a variety of controls with a variety of settings and yet they are all well-aligned with a consistent look and feel.
## Conclusion
In this tutorial you created an extension user interface using coding best practices to integrate it into an Omniverse application. It contains a variety of controls that edit integers, float, colors and more. These controls are well organized so that a user can easily find their way around the window.
We look forward to seeing the excellent extensions you come up with and how you can help Omniverse users accomplish things that were hard or even impossible to do before you wrote an extension to help them.
| 30,589 | Markdown | 47.478605 | 565 | 0.696296 |
NVIDIA-Omniverse/kit-extension-sample-ui-window/exts/omni.example.ui_window/omni/example/ui_window/style.py | # Copyright (c) 2022, 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.
#
__all__ = ["example_window_style"]
from omni.ui import color as cl
from omni.ui import constant as fl
from omni.ui import url
import omni.kit.app
import omni.ui as ui
import pathlib
EXTENSION_FOLDER_PATH = pathlib.Path(
omni.kit.app.get_app().get_extension_manager().get_extension_path_by_module(__name__)
)
# Pre-defined constants. It's possible to change them runtime.
cl.example_window_attribute_bg = cl("#1f2124")
cl.example_window_attribute_fg = cl("#0f1115")
cl.example_window_hovered = cl("#FFFFFF")
cl.example_window_text = cl("#CCCCCC")
fl.example_window_attr_hspacing = 10
fl.example_window_attr_spacing = 1
fl.example_window_group_spacing = 2
url.example_window_icon_closed = f"{EXTENSION_FOLDER_PATH}/data/closed.svg"
url.example_window_icon_opened = f"{EXTENSION_FOLDER_PATH}/data/opened.svg"
# The main style dict
example_window_style = {
"Label::attribute_name": {
"alignment": ui.Alignment.RIGHT_CENTER,
"margin_height": fl.example_window_attr_spacing,
"margin_width": fl.example_window_attr_hspacing,
},
"Label::attribute_name:hovered": {"color": cl.example_window_hovered},
"Label::collapsable_name": {"alignment": ui.Alignment.LEFT_CENTER},
"Slider::attribute_int:hovered": {"color": cl.example_window_hovered},
"Slider": {
"background_color": cl.example_window_attribute_bg,
"draw_mode": ui.SliderDrawMode.HANDLE,
},
"Slider::attribute_float": {
"draw_mode": ui.SliderDrawMode.FILLED,
"secondary_color": cl.example_window_attribute_fg,
},
"Slider::attribute_float:hovered": {"color": cl.example_window_hovered},
"Slider::attribute_vector:hovered": {"color": cl.example_window_hovered},
"Slider::attribute_color:hovered": {"color": cl.example_window_hovered},
"CollapsableFrame::group": {"margin_height": fl.example_window_group_spacing},
"Image::collapsable_opened": {"color": cl.example_window_text, "image_url": url.example_window_icon_opened},
"Image::collapsable_closed": {"color": cl.example_window_text, "image_url": url.example_window_icon_closed},
}
| 2,530 | Python | 42.63793 | 112 | 0.717787 |
NVIDIA-Omniverse/kit-extension-sample-ui-window/exts/omni.example.ui_window/omni/example/ui_window/color_widget.py | # Copyright (c) 2022, 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.
#
__all__ = ["ColorWidget"]
from ctypes import Union
from typing import List, Optional
import omni.ui as ui
COLOR_PICKER_WIDTH = 20
SPACING = 4
class ColorWidget:
"""The compound widget for color input"""
def __init__(self, *args, model=None, **kwargs):
self.__defaults: List[Union[float, int]] = args
self.__model: Optional[ui.AbstractItemModel] = kwargs.pop("model", None)
self.__multifield: Optional[ui.MultiFloatDragField] = None
self.__colorpicker: Optional[ui.ColorWidget] = None
self.__frame = ui.Frame()
with self.__frame:
self._build_fn()
def destroy(self):
self.__model = None
self.__multifield = None
self.__colorpicker = None
self.__frame = None
def __getattr__(self, attr):
"""
Pretend it's self.__frame, so we have access to width/height and
callbacks.
"""
return getattr(self.__root_frame, attr)
@property
def model(self) -> Optional[ui.AbstractItemModel]:
"""The widget's model"""
if self.__multifield:
return self.__multifield.model
@model.setter
def model(self, value: ui.AbstractItemModel):
"""The widget's model"""
self.__multifield.model = value
self.__colorpicker.model = value
def _build_fn(self):
with ui.HStack(spacing=SPACING):
# The construction of multi field depends on what the user provided,
# defaults or a model
if self.__model:
# the user provided a model
self.__multifield = ui.MultiFloatDragField(
min=0, max=1, model=self.__model, h_spacing=SPACING, name="attribute_color"
)
model = self.__model
else:
# the user provided a list of default values
self.__multifield = ui.MultiFloatDragField(
*self.__defaults, min=0, max=1, h_spacing=SPACING, name="attribute_color"
)
model = self.__multifield.model
self.__colorpicker = ui.ColorWidget(model, width=COLOR_PICKER_WIDTH)
| 2,600 | Python | 33.223684 | 95 | 0.611538 |
NVIDIA-Omniverse/kit-extension-sample-ui-window/exts/omni.example.ui_window/omni/example/ui_window/window.py | # Copyright (c) 2022, 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.
#
__all__ = ["ExampleWindow"]
import omni.ui as ui
from .style import example_window_style
from .color_widget import ColorWidget
LABEL_WIDTH = 120
SPACING = 4
class ExampleWindow(ui.Window):
"""The class that represents the window"""
def __init__(self, title: str, delegate=None, **kwargs):
self.__label_width = LABEL_WIDTH
super().__init__(title, **kwargs)
# Apply the style to all the widgets of this window
self.frame.style = example_window_style
# Set the function that is called to build widgets when the window is
# visible
self.frame.set_build_fn(self._build_fn)
def destroy(self):
# It will destroy all the children
super().destroy()
@property
def label_width(self):
"""The width of the attribute label"""
return self.__label_width
@label_width.setter
def label_width(self, value):
"""The width of the attribute label"""
self.__label_width = value
self.frame.rebuild()
def _build_collapsable_header(self, collapsed, title):
"""Build a custom title of CollapsableFrame"""
with ui.HStack():
ui.Label(title, name="collapsable_name")
if collapsed:
image_name = "collapsable_opened"
else:
image_name = "collapsable_closed"
ui.Image(name=image_name, width=20, height=20)
def _build_calculations(self):
"""Build the widgets of the "Calculations" group"""
with ui.CollapsableFrame("Calculations", name="group", build_header_fn=self._build_collapsable_header):
with ui.VStack(height=0, spacing=SPACING):
with ui.HStack():
ui.Label("Precision", name="attribute_name", width=self.label_width)
ui.IntSlider(name="attribute_int")
with ui.HStack():
ui.Label("Iterations", name="attribute_name", width=self.label_width)
ui.IntSlider(name="attribute_int", min=0, max=5)
def _build_parameters(self):
"""Build the widgets of the "Parameters" group"""
with ui.CollapsableFrame("Parameters", name="group", build_header_fn=self._build_collapsable_header):
with ui.VStack(height=0, spacing=SPACING):
with ui.HStack():
ui.Label("Value", name="attribute_name", width=self.label_width)
ui.FloatSlider(name="attribute_float")
with ui.HStack():
ui.Label("i", name="attribute_name", width=self.label_width)
ui.FloatSlider(name="attribute_float", min=-1, max=1)
with ui.HStack():
ui.Label("j", name="attribute_name", width=self.label_width)
ui.FloatSlider(name="attribute_float", min=-1, max=1)
with ui.HStack():
ui.Label("k", name="attribute_name", width=self.label_width)
ui.FloatSlider(name="attribute_float", min=-1, max=1)
with ui.HStack():
ui.Label("Theta", name="attribute_name", width=self.label_width)
ui.FloatSlider(name="attribute_float")
def _build_light_1(self):
"""Build the widgets of the "Light 1" group"""
with ui.CollapsableFrame("Light 1", name="group", build_header_fn=self._build_collapsable_header):
with ui.VStack(height=0, spacing=SPACING):
with ui.HStack():
ui.Label("Orientation", name="attribute_name", width=self.label_width)
ui.MultiFloatDragField(0.0, 0.0, 0.0, h_spacing=SPACING, name="attribute_vector")
with ui.HStack():
ui.Label("Intensity", name="attribute_name", width=self.label_width)
ui.FloatSlider(name="attribute_float")
with ui.HStack():
ui.Label("Color", name="attribute_name", width=self.label_width)
# The custom compound widget
ColorWidget(0.25, 0.5, 0.75)
with ui.HStack():
ui.Label("Shadow", name="attribute_name", width=self.label_width)
ui.CheckBox(name="attribute_bool")
def _build_fn(self):
"""
The method that is called to build all the UI once the window is
visible.
"""
with ui.ScrollingFrame():
with ui.VStack(height=0):
self._build_calculations()
self._build_parameters()
self._build_light_1()
| 5,056 | Python | 39.13492 | 111 | 0.584256 |
NVIDIA-Omniverse/kit-extension-sample-ui-window/exts/omni.example.ui_window/docs/README.md |
# Generic Window (omni.example.ui_window)

## Overview
This extension provides an end-to-end example and general recommendations on creating a
simple window using `omni.ui`. It contains the best practices of building an extension, a menu item, a window itself, a custom widget, and a generic style.
## [Tutorial](../tutorial/tutorial.md)
This extension sample also includes a step-by-step tutorial to accelerate your growth as you learn to build your own
Omniverse Kit extensions. [Get started with the tutorial.](../tutorial/tutorial.md)
## Usage
This is just a UI demo. You can interact with the various controls, but they have not additional effect in the Application.
## Explanations
### Extension
When the extension starts up, we register a new menu item that controls the
window and shows the window.
A very important part is using `ui.Workspace.set_show_window_fn` to register the
window in `omni.ui`. It will help to save and load the layout of Kit.
```
# The ability to show up the window if the system requires it. We use it
# in QuickLayout.
ui.Workspace.set_show_window_fn(ExampleWindowExtension.WINDOW_NAME, partial(self.show_window, None))
```
When the extension shuts down, we remove the menu item and deregister the window
callback.
### Window
It's handy to derive a custom window from the class `ui.Window`. The UI can be
defined right in __init__, so it's created immediately. Or it can be defined in
a callback and it will be created when the window is visible.
```
class ExampleWindow(ui.Window):
"""The class that represents the window"""
def __init__(self, title: str, delegate=None, **kwargs):
self.__label_width = LABEL_WIDTH
super().__init__(title, **kwargs)
# Apply the style to all the widgets of this window
self.frame.style = example_window_style
# Set the function that is called to build widgets when the window is
# visible
self.frame.set_build_fn(self._build_fn)
```
### Custom Widget
A custom widget can be a class or a function. It's not required to derive
anything. It's only necessary to create sub-widgets.
```
class ColorWidget:
"""The compound widget for color input"""
def __init__(self, *args, model=None, **kwargs):
self.__defaults: List[Union[float, int]] = args
self.__model: Optional[ui.AbstractItemModel] = kwargs.pop("model", None)
self.__multifield: Optional[ui.MultiFloatDragField] = None
self.__colorpicker: Optional[ui.ColorWidget] = None
self.__frame = ui.Frame()
with self.__frame:
self._build_fn()
```
### Style
Although the style can be applied to any widget, we recommend keeping the style
dictionary in one location.
There is an exception to this recommendation. It's recommended to use styles
directly on the widgets to hide a part of the widget. For example, it's OK to
set {"color": cl.transparent} on a slider to hide the text. Or
"background_color": cl.transparent to disable background on a field.
| 3,040 | Markdown | 35.202381 | 155 | 0.715789 |
NVIDIA-Omniverse/USD-Tutorials-And-Examples/README.md | # USD Tutorials and Examples
## About
This project showcases educational material for [Pixar's Universal Scene Description](https://graphics.pixar.com/usd/docs/index.html) (USD).
For convenience, the Jupyter notebook from the GTC session is available on Google Colaboratory, which offers an interactive environment from the comfort of your web browser. Colaboratory makes it possible to:
* Try code snippets without building or installing USD on your machine
* Run the samples on any device
* Share code experiments with others
Should you prefer to run the notebook on your local machine instead, simply download and execute it after [installing Jupyter](https://jupyter.org).
## Sample Notebook
Follow along the tutorial using the sample notebook from the GTC session, or get acquainted with USD using other examples:
|Notebook|Google Colab link|
|--------|:----------------:|
|Introduction to USD|[](https://colab.research.google.com/github/NVIDIA-Omniverse/USD-Tutorials-And-Examples/blob/main/ColaboratoryNotebooks/usd_introduction.ipynb)|
|Opening USD Stages|[](https://colab.research.google.com/github/NVIDIA-Omniverse/USD-Tutorials-And-Examples/blob/main/ColaboratoryNotebooks/opening_stages.ipynb)|
|Prims, Attributes and Metadata|[](https://colab.research.google.com/github/NVIDIA-Omniverse/USD-Tutorials-And-Examples/blob/main/ColaboratoryNotebooks/prims_attributes_and_metadata.ipynb)|
|Hierarchy and Traversal|[](https://colab.research.google.com/github/NVIDIA-Omniverse/USD-Tutorials-And-Examples/blob/main/ColaboratoryNotebooks/hierarchy_and_traversal.ipynb)|
## Additional Resources
* [Pixar's USD](https://graphics.pixar.com/usd)
* [USD at NVIDIA](https://usd.nvidia.com)
* [USD training content on _NVIDIA On-Demand_](https://www.nvidia.com/en-us/on-demand/playlist/playList-911c5614-4b7f-4668-b9eb-37f627ac8d17/)
| 2,140 | Markdown | 78.296293 | 263 | 0.784112 |
NVIDIA-Omniverse/kit-project-template/repo.toml | ########################################################################################################################
# Repo tool base settings
########################################################################################################################
[repo]
# Use the Kit Template repo configuration as a base. Only override things specific to the repo.
import_configs = [
"${root}/_repo/deps/repo_kit_tools/kit-template/repo.toml",
"${root}/_repo/deps/repo_kit_tools/kit-template/repo-external.toml",
]
extra_tool_paths = [
"${root}/kit/dev",
]
########################################################################################################################
# Extensions precacher
########################################################################################################################
[repo_precache_exts]
# Apps to run and precache
apps = [
"${root}/source/apps/my_name.my_app.kit"
]
| 949 | TOML | 31.75862 | 120 | 0.33509 |
NVIDIA-Omniverse/kit-project-template/README.md | # *Omniverse Kit* Project Template
This project is a template for developing apps and extensions for *Omniverse Kit*.
# Important Links
- [Omniverse Documentation Site](https://docs.omniverse.nvidia.com/kit/docs/kit-project-template)
- [Github Repo for this Project Template](https://github.com/NVIDIA-Omniverse/kit-project-template)
- [Extension System](https://docs.omniverse.nvidia.com/kit/docs/kit-manual/latest/guide/extensions_advanced.html)
# Getting Started
1. Fork/Clone the Kit Project Template repo [link](https://github.com/NVIDIA-Omniverse/kit-project-template) to a local folder, for example in `C:\projects\kit-project-template`
2. (Optional) Open this cloned repo using Visual Studio Code: `code C:\projects\kit-project-template`. It will likely suggest installing a few extensions to improve python experience. None are required, but they may be helpful.
3. In a CLI terminal (if in VS Code, CTRL + \` or choose Terminal->New Terminal from the menu) run `pull_kit_kernel.bat` (windows) / `pull_kit_kernel.sh` (linux) to pull the *Omniverse Kit Kernel*. `kit` folder link will be created under the main folder in which your project is located.
4. Run the example app that includes example extensions: `source/apps/my_name.my_app.bat` (windows) / `./source/apps/my_name.my_app.sh` (linux) to ensure everything is working. The first start will take a while as it will pull all the extensions from the extension registry and build various caches. Subsequent starts will be much faster. Once finished, you should see a "Kit Base Editor" window and a welcome screen. Feel free to browse through the base application and exit when finished. You are now ready to begin development!
## An Omniverse App
If you look inside a `source/apps/my_name.my_app.bat` or any other *Omniverse App*, they all run off of an SDK we call *Omniverse Kit* . The base application for *Omniverse Kit* (`kit.exe`) is the runtime that powers *Apps* build out of extensions.
Think of it as `python.exe`. It is a small runtime, that enables all the basics, like settings, python, logging and searches for extensions. **All other functionality is provided by extensions.**
To start an app we pass a `kit` file, which is a configuration file with a `kit` extension. It describes which extensions to pull and load, and which settings to apply. One kit file fully describes an app, but you may find value in having several for different methods to run and test your application.
Notice that it includes `omni.hello.world` extension; that is an example extension found in this repo. All the other extensions are pulled from the `extension registry` on first startup.
More info on building kit files: [doc](https://docs.omniverse.nvidia.com/kit/docs/kit-manual/latest/guide/creating_kit_apps.html)
### Packaging an App
Once you have developed, tested, and documented your app or extension, you will want to publish it. Before publishing the app, we must first assemble all its components into a single deliverable. This step is called "packaging".
To package an app run `tools/package.bat` (or `repo package`). The package will be created in the `_build/packages` folder.
To use the package, unzip the package that was created by the above step into its own separate folder. Then, run `pull_kit_kernel.bat` inside the new folder once before running the app.
### Version Lock
An app `kit` file fully defines all the extensions, but their versions are not `locked`, which is to say that by default the latest versions of a given extension will be used. Also, many extensions have dependencies themselves which cause kit to download and enable other extensions.
This said, for the final app it is important that it always gets the same extensions and the same versions on each run. This is meant to provide reliable and reproducible builds. This is called a *version lock* and we have a separate section at the end of `kit` file to lock versions of all extensions and all their dependencies.
It is also important to update the version lock section when adding new extensions or updating existing ones. To update version lock the `precache_exts` tool is used.
**To update version lock run:** `tools/update_version_lock.bat`.
Once you've done this, use your source control methods to commit any changes to a kit file as part of the source necessary to reproduce the build.
The packaging tool will verify that version locks exist and will fail if they do not.
More info on dependency management: [doc](https://docs.omniverse.nvidia.com/kit/docs/kit-manual/latest/guide/creating_kit_apps.html#application-dependencies-management)
## An Omniverse Extension
This template includes one simple extension: `omni.hello.world`. It is loaded in the example app, but can also be loaded and tested in any other *Omniverse App*. You should feel free to copy or rename this extension to one that you wish to create. Please refer to Omniverse Documentation for more information on developing extensions.
### Using Omniverse Launcher
1. Install *Omniverse Launcher*: [download](https://www.nvidia.com/en-us/omniverse/download)
2. Install and launch one of *Omniverse* apps in the Launcher. For instance: *Code*.
### Add a new extension to your *Omniverse App*
If you want to add extensions from this repo to your other existing Omniverse App.
1. In the *Omniverse App* open extension manager: *Window* → *Extensions*.
2. In the *Extension Manager Window* open a settings page, with a small gear button in the top left bar.
3. In the settings page there is a list of *Extension Search Paths*. Add cloned repo `source/extensions` subfolder there as another search path: `C:/projects/kit-project-template/source/extensions`

4. Now you can find `omni.hello.world` extension in the top left search bar. Select and enable it.
5. "My Window" window will pop up. *Extension Manager* watches for any file changes. You can try changing some code in this extension and see them applied immediately with a hotreload.
### Adding a new extension
* Now that `source/extensions` folder was added to the search you can add new extensions to this folder and they will be automatically found by the *App*.
* Look at the *Console* window for warnings and errors. It also has a small button to open current log file.
* All the same commands work on linux. Replace `.bat` with `.sh` and `\` with `/`.
* Extension name is a folder name in `source/extensions`, in this example: `omni.hello.world`. This is most often the same name as the "Extension ID".
* The most important thing that an extension has is its config file: `extension.toml`. You should familiarize yourself with its contents.
* In the *Extensions* window, press *Burger* button near the search bar and select *Show Extension Graph*. It will show how the current *App* comes to be by displaying all its dependencies.
* Extensions system documentation can be found [here](https://docs.omniverse.nvidia.com/kit/docs/kit-manual/latest/guide/extensions_advanced.html)
### Alternative way to add a new extension
To get a better understanding of the extension topology, we recommend following:
1. Run bare `kit.exe` with `source/extensions` folder added as an extensions search path and new extension enabled:
```bash
> kit\kit.exe --ext-folder source/extensions --enable omni.hello.world
```
- `--ext-folder [path]` - adds new folder to the search path
- `--enable [extension]` - enables an extension on startup.
Use `-h` for help:
```bash
> kit\kit.exe -h
```
2. After the *App* starts you should see:
* new "My Window" window popup.
* extension search paths in *Extensions* window as in the previous section.
* extension enabled in the list of extensions.
It starts much faster and will only have extensions enabled that are required for this new extension (look at `[dependencies]` section of `extension.toml`). You can enable more extensions: try adding `--enable omni.kit.window.extensions` to have extensions window enabled (yes, extension window is an extension too!):
```bash
> kit\kit.exe --ext-folder source/extensions --enable omni.hello.world --enable omni.kit.window.extensions
```
You should see a menu in the top left. From this UI you can browse and enable more extensions. It is important to note that these enabled extensions are NOT added to your kit file, but instead live in a local "user" file as an addendum. If you want the extension to be a part of your app, you must add its name to the list of dependencies in the `[dependencies]` section.
# A third way to add an extension
Here is how to add an extension by copying the "hello world" extension as a template:
1. copy `source/extensions/omni.hello.world` to `source/extensions/[new extension id]`
2. rename python module (namespace) in `source/extensions/[new extension id]/omni/hello/world` to `source/extensions/[new extension id]/[new python module]`
3. update `source/extensions/[new extension name]/config/extension.toml`, most importantly specify new python module to load:
4. Optionally, add the `[extension id]` to the `[dependencies]` section of the app's kit file.
[[python.module]]
name = "[new python module]"
# Running Tests
To run tests we run a new configuration where only the tested extension (and its dependencies) is enabled. Like in example above + testing system (`omni.kit.test` extension). There are 2 ways to run extension tests:
1. Run: `tools\test_ext.bat omni.hello.world`
That will run a test process with all tests and exit. For development mode pass `--dev`: that will open test selection window. As everywhere, hotreload also works in this mode, give it a try by changing some code!
2. Alternatively, in *Extension Manager* (*Window → Extensions*) find your extension, click on *TESTS* tab, click *Run Test*
For more information about testing refer to: [testing doc](https://docs.omniverse.nvidia.com/kit/docs/kit-manual/latest/guide/testing_exts_python.html).
No restart is needed, you should be able to find and enable `[new extension name]` in extension manager.
# Sharing extensions
To make extension available to other users use [Github Releases](https://docs.github.com/en/repositories/releasing-projects-on-github/managing-releases-in-a-repository).
1. Make sure the repo has [omniverse-kit-extension](https://github.com/topics/omniverse-kit-extension) topic set for auto discovery.
2. For each new release increment extension version (in `extension.toml`) and update the changelog (in `docs/CHANGELOG.md`). [Semantic versionning](https://semver.org/) must be used to express severity of API changes.
# Contributing
The source code for this repository is provided as-is and we are not accepting outside contributions.
# License
By using any part of the files in the KIT-PROJECT-TEMPLATE repo you agree to the terms of the NVIDIA Omniverse License Agreement, the most recent version of which is available [here](https://docs.omniverse.nvidia.com/composer/latest/common/NVIDIA_Omniverse_License_Agreement.html). | 11,077 | Markdown | 69.560509 | 533 | 0.769613 |
NVIDIA-Omniverse/kit-project-template/tools/deps/repo-deps.packman.xml | <project toolsVersion="5.0">
<dependency name="repo_build" linkPath="../../_repo/deps/repo_build">
<package name="repo_build" version="0.40.0"/>
</dependency>
<dependency name="repo_ci" linkPath="../../_repo/deps/repo_ci">
<package name="repo_ci" version="0.5.1" />
</dependency>
<dependency name="repo_changelog" linkPath="../../_repo/deps/repo_changelog">
<package name="repo_changelog" version="0.3.0" />
</dependency>
<dependency name="repo_format" linkPath="../_repo/deps/repo_format">
<package name="repo_format" version="2.7.0" />
</dependency>
<dependency name="repo_kit_tools" linkPath="../../_repo/deps/repo_kit_tools">
<package name="repo_kit_tools" version="0.12.18"/>
</dependency>
<dependency name="repo_licensing" linkPath="../../_repo/deps/repo_licensing">.
<package name="repo_licensing" version="1.11.2" />
</dependency>
<dependency name="repo_man" linkPath="../../_repo/deps/repo_man">
<package name="repo_man" version="1.32.1"/>
</dependency>
<dependency name="repo_package" linkPath="../../_repo/deps/repo_package">
<package name="repo_package" version="5.8.5" />
</dependency>
<dependency name="repo_source" linkPath="../../_repo/deps/repo_source">
<package name="repo_source" version="0.4.2"/>
</dependency>
<dependency name="repo_test" linkPath="../../_repo/deps/repo_test">
<package name="repo_test" version="2.5.6"/>
</dependency>
</project>
| 1,448 | XML | 42.90909 | 80 | 0.649171 |
NVIDIA-Omniverse/kit-project-template/tools/deps/kit-sdk.packman.xml | <project toolsVersion="5.0">
<dependency name="kit_sdk_${config}" linkPath="../../kit" tags="${config} non-redist">
<package name="kit-kernel" version="105.1+release.127680.dd92291b.tc.${platform}.${config}"/>
</dependency>
</project>
| 243 | XML | 39.66666 | 97 | 0.666667 |
NVIDIA-Omniverse/kit-project-template/source/package/description.toml | # Description of the application for the Omniverse Launcher
name = "My App" # displayed application name
shortName = "My App" # displayed application name in smaller card and library view
version = "${version}" # version must be semantic
kind = "app" # enum of "app", "connector" and "experience" for now
latest = true # boolean for if this version is the latest version
slug = "my_app" # unique identifier for component, all lower case, persists between versions
productArea = "My Company" # displayed before application name in launcher
category = "Apps" # category of content
channel = "release" # 3 filter types [ "alpha", "beta", "release "]
enterpriseStatus = false # Set true if you want this package to show in enterprise launcher
# values for filtering content
tags = [
"Media & Entertainment",
"Manufacturing",
"Product Design",
"Scene Composition",
"Visualization",
"Rendering"
]
# string array, each line is a new line, keep lines under 256 char and keep lines under 4
description = [
"My App is an application to showcase how to build an Omniverse App. ",
"FEATURES:",
"- Small and simple.",
"- Easy to change."
]
# array of links for more info on product
[[links]]
title = "Release Notes"
url = "https://google.com"
[[links]]
title = "Documentation"
url = "https://google.com"
| 1,398 | TOML | 34.871794 | 104 | 0.67525 |
NVIDIA-Omniverse/kit-extension-sample-airoomgenerator/README.md | # AI Room Generator Extension Sample

### About
This extension allows user's to generate 3D content using Generative AI, ChatGPT. Providing an area in the stage and a prompt the user can generate a room configuration designed by ChatGPT. This in turn can help end users automatically generate and place objects within their scene, saving hours of time that would typically be required to create a complex scene.
### [README](exts/omni.example.airoomgenerator)
See the [README for this extension](exts/omni.example.airoomgenerator) to learn more about it including how to use it.
> This sample is for educational purposes. For production please consider best security practices and scalability.
## Adding This Extension
This folder is ready to be pushed to any git repository. Once pushed direct link to a git repository can be added to *Omniverse Kit* extension search paths.
Link might look like this: `git://github.com/NVIDIA-Omniverse/kit-extension-sample-airoomgenerator?branch=main&dir=exts`
Notice `exts` is repo subfolder with extensions. More information can be found in "Git URL as Extension Search Paths" section of developers manual.
To add a link to your *Omniverse Kit* based app go into: Extension Manager -> Gear Icon -> Extension Search Path
## Linking with an Omniverse app
If `app` folder link doesn't exist or broken it can be created again. For better developer experience it is recommended to create a folder link named `app` to the *Omniverse Kit* app installed from *Omniverse Launcher*. Convenience script to use is included.
Run:
```
> link_app.bat
```
If successful you should see `app` folder link in the root of this repo.
If multiple Omniverse apps is installed script will select recommended one. Or you can explicitly pass an app:
```
> link_app.bat --app create
```
You can also just pass a path to create link to:
```
> link_app.bat --path "C:/Users/bob/AppData/Local/ov/pkg/create-2021.3.4"
```
# Contributing
The source code for this repository is provided as-is and we are not accepting outside contributions.
| 2,140 | Markdown | 40.173076 | 363 | 0.775701 |
NVIDIA-Omniverse/kit-extension-sample-airoomgenerator/exts/omni.sample.deepsearchpicker/omni/sample/deepsearchpicker/style.py | # SPDX-FileCopyrightText: Copyright (c) 2023 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
# SPDX-License-Identifier: Apache-2.0
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import omni.ui as ui
from pathlib import Path
icons_path = Path(__file__).parent.parent.parent.parent / "icons"
gen_ai_style = {
"HStack": {
"margin": 3
},
"Button.Image::create": {"image_url": f"{icons_path}/plus.svg", "color": 0xFF00B976}
}
| 946 | Python | 32.821427 | 98 | 0.726216 |
NVIDIA-Omniverse/kit-extension-sample-airoomgenerator/exts/omni.sample.deepsearchpicker/omni/sample/deepsearchpicker/extension.py | # SPDX-FileCopyrightText: Copyright (c) 2023 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
# SPDX-License-Identifier: Apache-2.0
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import omni.ext
from .window import DeepSearchPickerWindow
# Any class derived from `omni.ext.IExt` in top level module (defined in `python.modules` of `extension.toml`) will be
# instantiated when extension gets enabled and `on_startup(ext_id)` will be called. Later when extension gets disabled
# on_shutdown() is called.
class MyExtension(omni.ext.IExt):
# ext_id is current extension id. It can be used with extension manager to query additional information, like where
# this extension is located on filesystem.
def on_startup(self, ext_id):
self._window = DeepSearchPickerWindow("DeepSearch Swap", width=300, height=300)
def on_shutdown(self):
self._window.destroy()
self._window = None
| 1,423 | Python | 44.935482 | 119 | 0.747013 |
NVIDIA-Omniverse/kit-extension-sample-airoomgenerator/exts/omni.sample.deepsearchpicker/omni/sample/deepsearchpicker/deep_search.py | # SPDX-FileCopyrightText: Copyright (c) 2023 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
# SPDX-License-Identifier: Apache-2.0
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from omni.kit.ngsearch.client import NGSearchClient
import carb
import asyncio
class deep_search():
async def query_items(queries, url: str, paths):
result = list(tuple())
for query in queries:
query_result = await deep_search._query_first(query, url, paths)
if query_result is not None:
result.append(query_result)
return result
async def _query_first(query: str, url: str, paths):
filtered_query = "ext:usd,usdz,usda path:"
for path in paths:
filtered_query = filtered_query + "\"" + str(path) + "\","
filtered_query = filtered_query[:-1]
filtered_query = filtered_query + " "
filtered_query = filtered_query + query
SearchResult = await NGSearchClient.get_instance().find2(
query=filtered_query, url=url)
if len(SearchResult.paths) > 0:
return (query, SearchResult.paths[0].uri)
else:
return None
async def query_all(query: str, url: str, paths):
filtered_query = "ext:usd,usdz,usda path:"
for path in paths:
filtered_query = filtered_query + "\"" + str(path) + "\","
filtered_query = filtered_query[:-1]
filtered_query = filtered_query + " "
filtered_query = filtered_query + query
return await NGSearchClient.get_instance().find2(query=filtered_query, url=url)
| 2,185 | Python | 32.121212 | 98 | 0.632494 |
NVIDIA-Omniverse/kit-extension-sample-airoomgenerator/exts/omni.sample.deepsearchpicker/omni/sample/deepsearchpicker/window.py | # SPDX-FileCopyrightText: Copyright (c) 2023 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
# SPDX-License-Identifier: Apache-2.0
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import omni.ui as ui
import omni.usd
import carb
from .style import gen_ai_style
from .deep_search import deep_search
import asyncio
from pxr import UsdGeom, Usd, Sdf, Gf
class DeepSearchPickerWindow(ui.Window):
def __init__(self, title: str, **kwargs) -> None:
super().__init__(title, **kwargs)
# Models
self.frame.set_build_fn(self._build_fn)
self._index = 0
self._query_results = None
self._selected_prim = None
self._prim_path_model = ui.SimpleStringModel()
def _build_fn(self):
async def replace_prim():
self._index = 0
ctx = omni.usd.get_context()
prim_paths = ctx.get_selection().get_selected_prim_paths()
if len(prim_paths) != 1:
carb.log_warn("You must select one and only one prim")
return
prim_path = prim_paths[0]
stage = ctx.get_stage()
self._selected_prim = stage.GetPrimAtPath(prim_path)
query = self._selected_prim.GetAttribute("DeepSearch:Query").Get()
prop_paths = ["/Projects/simready_content/common_assets/props/",
"/NVIDIA/Assets/Isaac/2022.2.1/Isaac/Robots/",
"/NVIDIA/Assets/Isaac/2022.1/NVIDIA/Assets/ArchVis/Residential/Furniture/"]
self._query_results = await deep_search.query_all(query, "omniverse://ov-simready/", paths=prop_paths)
self._prim_path_model.set_value(prim_path)
def increment_prim_index():
if self._query_results is None:
return
self._index = self._index + 1
if self._index >= len(self._query_results.paths):
self._index = 0
self.replace_reference()
def decrement_prim_index():
if self._query_results is None:
return
self._index = self._index - 1
if self._index <= 0:
self._index = len(self._query_results.paths) - 1
self.replace_reference()
with self.frame:
with ui.VStack(style=gen_ai_style):
with ui.HStack(height=0):
ui.Spacer()
ui.StringField(model=self._prim_path_model, width=365, height=30)
ui.Button(name="create", width=30, height=30, clicked_fn=lambda: asyncio.ensure_future(replace_prim()))
ui.Spacer()
with ui.HStack(height=0):
ui.Spacer()
ui.Button("<", width=200, clicked_fn=lambda: decrement_prim_index())
ui.Button(">", width=200, clicked_fn=lambda: increment_prim_index())
ui.Spacer()
def replace_reference(self):
references: Usd.references = self._selected_prim.GetReferences()
references.ClearReferences()
references.AddReference(
assetPath="omniverse://ov-simready" + self._query_results.paths[self._index].uri)
carb.log_info("Got it?")
def destroy(self):
super().destroy() | 3,815 | Python | 36.048543 | 123 | 0.589253 |
NVIDIA-Omniverse/kit-extension-sample-airoomgenerator/exts/omni.example.airoomgenerator/config/extension.toml | [package]
# Semantic Versioning is used: https://semver.org/
version = "1.0.0"
# The title and description fields are primarily for displaying extension info in UI
title = "AI Room Generator Sample"
description="Generates Rooms using ChatGPT"
# Path (relative to the root) or content of readme markdown file for UI.
readme = "docs/README.md"
# URL of the extension source repository.
repository = ""
# One of categories for UI.
category = "Example"
# Keywords for the extension
keywords = ["kit", "example"]
# Icon to show in the extension manager
icon = "data/preview_icon.png"
# Preview to show in the extension manager
preview_image = "data/preview.png"
# Use omni.ui to build simple UI
[dependencies]
"omni.kit.uiapp" = {}
"omni.kit.ngsearch" = {}
"omni.kit.window.popup_dialog" = {}
# Main python module this extension provides, it will be publicly available as "import company.hello.world".
[[python.module]]
name = "omni.example.airoomgenerator"
[[test]]
# Extra dependencies only to be used during test run
dependencies = [
"omni.kit.ui_test" # UI testing extension
]
| 1,091 | TOML | 24.999999 | 108 | 0.731439 |
NVIDIA-Omniverse/kit-extension-sample-airoomgenerator/exts/omni.example.airoomgenerator/omni/example/airoomgenerator/priminfo.py | # SPDX-FileCopyrightText: Copyright (c) 2023 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
# SPDX-License-Identifier: Apache-2.0
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from pxr import Usd, Gf
class PrimInfo:
# Class that stores the prim info
def __init__(self, prim: Usd.Prim, name: str = "") -> None:
self.prim = prim
self.child = prim.GetAllChildren()[0]
self.length = self.GetLengthOfPrim()
self.width = self.GetWidthOfPrim()
self.origin = self.GetPrimOrigin()
self.area_name = name
def GetLengthOfPrim(self) -> str:
# Returns the X value
attr = self.child.GetAttribute('xformOp:scale')
x_scale = attr.Get()[0]
return str(x_scale)
def GetWidthOfPrim(self) -> str:
# Returns the Z value
attr = self.child.GetAttribute('xformOp:scale')
z_scale = attr.Get()[2]
return str(z_scale)
def GetPrimOrigin(self) -> str:
attr = self.prim.GetAttribute('xformOp:translate')
origin = Gf.Vec3d(0,0,0)
if attr:
origin = attr.Get()
phrase = str(origin[0]) + ", " + str(origin[1]) + ", " + str(origin[2])
return phrase | 1,706 | Python | 36.108695 | 98 | 0.651817 |
NVIDIA-Omniverse/kit-extension-sample-airoomgenerator/exts/omni.example.airoomgenerator/omni/example/airoomgenerator/widgets.py | # SPDX-FileCopyrightText: Copyright (c) 2023 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
# SPDX-License-Identifier: Apache-2.0
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import omni.ui as ui
from omni.ui import color as cl
import asyncio
import omni
import carb
class ProgressBar:
def __init__(self):
self.progress_bar_window = None
self.left = None
self.right = None
self._build_fn()
async def play_anim_forever(self):
fraction = 0.0
while True:
fraction = (fraction + 0.01) % 1.0
self.left.width = ui.Fraction(fraction)
self.right.width = ui.Fraction(1.0-fraction)
await omni.kit.app.get_app().next_update_async()
def _build_fn(self):
with ui.VStack():
self.progress_bar_window = ui.HStack(height=0, visible=False)
with self.progress_bar_window:
ui.Label("Processing", width=0, style={"margin_width": 3})
self.left = ui.Spacer(width=ui.Fraction(0.0))
ui.Rectangle(width=50, style={"background_color": cl("#76b900")})
self.right = ui.Spacer(width=ui.Fraction(1.0))
def show_bar(self, to_show):
self.progress_bar_window.visible = to_show
| 1,770 | Python | 34.419999 | 98 | 0.655367 |
NVIDIA-Omniverse/kit-extension-sample-airoomgenerator/exts/omni.example.airoomgenerator/omni/example/airoomgenerator/chatgpt_apiconnect.py | # SPDX-FileCopyrightText: Copyright (c) 2023 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
# SPDX-License-Identifier: Apache-2.0
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import json
import carb
import aiohttp
import asyncio
from .prompts import system_input, user_input, assistant_input
from .deep_search import query_items
from .item_generator import place_greyboxes, place_deepsearch_results
async def chatGPT_call(prompt: str):
# Load your API key from an environment variable or secret management service
settings = carb.settings.get_settings()
apikey = settings.get_as_string("/persistent/exts/omni.example.airoomgenerator/APIKey")
my_prompt = prompt.replace("\n", " ")
# Send a request API
try:
parameters = {
"model": "gpt-3.5-turbo",
"messages": [
{"role": "system", "content": system_input},
{"role": "user", "content": user_input},
{"role": "assistant", "content": assistant_input},
{"role": "user", "content": my_prompt}
]
}
chatgpt_url = "https://api.openai.com/v1/chat/completions"
headers = {"Authorization": "Bearer %s" % apikey}
# Create a completion using the chatGPT model
async with aiohttp.ClientSession() as session:
async with session.post(chatgpt_url, headers=headers, json=parameters) as r:
response = await r.json()
text = response["choices"][0]["message"]['content']
except Exception as e:
carb.log_error("An error as occurred")
return None, str(e)
# Parse data that was given from API
try:
#convert string to object
data = json.loads(text)
except ValueError as e:
carb.log_error(f"Exception occurred: {e}")
return None, text
else:
# Get area_objects_list
object_list = data['area_objects_list']
return object_list, text
async def call_Generate(prim_info, prompt, use_chatgpt, use_deepsearch, response_label, progress_widget):
run_loop = asyncio.get_event_loop()
progress_widget.show_bar(True)
task = run_loop.create_task(progress_widget.play_anim_forever())
response = ""
#chain the prompt
area_name = prim_info.area_name.split("/World/Layout/")
concat_prompt = area_name[-1].replace("_", " ") + ", " + prim_info.length + "x" + prim_info.width + ", origin at (0.0, 0.0, 0.0), generate a list of appropriate items in the correct places. " + prompt
root_prim_path = "/World/Layout/GPT/"
if prim_info.area_name != "":
root_prim_path= prim_info.area_name + "/items/"
if use_chatgpt: #when calling the API
objects, response = await chatGPT_call(concat_prompt)
else: #when testing and you want to skip the API call
data = json.loads(assistant_input)
objects = data['area_objects_list']
if objects is None:
response_label.text = response
return
if use_deepsearch:
settings = carb.settings.get_settings()
nucleus_path = settings.get_as_string("/persistent/exts/omni.example.airoomgenerator/deepsearch_nucleus_path")
filter_path = settings.get_as_string("/persistent/exts/omni.example.airoomgenerator/filter_path")
filter_paths = filter_path.split(',')
queries = list()
for item in objects:
queries.append(item['object_name'])
query_result = await query_items(queries=queries, url=nucleus_path, paths=filter_paths)
if query_result is not None:
place_deepsearch_results(
gpt_results=objects,
query_result=query_result,
root_prim_path=root_prim_path)
else:
place_greyboxes(
gpt_results=objects,
root_prim_path=root_prim_path)
else:
place_greyboxes(
gpt_results=objects,
root_prim_path=root_prim_path)
task.cancel()
await asyncio.sleep(1)
response_label.text = response
progress_widget.show_bar(False)
| 4,729 | Python | 39.775862 | 204 | 0.623176 |
NVIDIA-Omniverse/kit-extension-sample-airoomgenerator/exts/omni.example.airoomgenerator/omni/example/airoomgenerator/style.py | # SPDX-FileCopyrightText: Copyright (c) 2023 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
# SPDX-License-Identifier: Apache-2.0
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import omni.ui as ui
from pathlib import Path
icons_path = Path(__file__).parent.parent.parent.parent / "icons"
gen_ai_style = {
"HStack": {
"margin": 3
},
"Button.Image::create": {"image_url": f"{icons_path}/plus.svg", "color": 0xFF00B976},
"Button.Image::properties": {"image_url": f"{icons_path}/cog.svg", "color": 0xFF989898},
"Line": {
"margin": 3
},
"Label": {
"margin_width": 5
}
}
guide = """
Step 1: Create a Floor
- You can draw a floor outline using the pencil tool. Right click in the viewport then `Create>BasicCurves>From Pencil`
- OR Create a prim and scale it to the size you want. i.e. Right click in the viewport then `Create>Mesh>Cube`.
- Next, with the floor selected type in a name into "Area Name". Make sure the area name is relative to the room you want to generate.
For example, if you inputted the name as "bedroom" ChatGPT will be prompted that the room is a bedroom.
- Then click the '+' button. This will generate the floor and add the option to our combo box.
Step 2: Prompt
- Type in a prompt that you want to send along to ChatGPT. This can be information about what is inside of the room.
For example, "generate a comfortable reception area that contains a front desk and an area for guest to sit down".
Step 3: Generate
- Select 'use ChatGPT' if you want to recieve a response from ChatGPT otherwise it will use a premade response.
- Select 'use Deepsearch' if you want to use the deepsearch functionality. (ENTERPRISE USERS ONLY)
When deepsearch is false it will spawn in cubes that greybox the scene.
- Hit Generate, after hitting generate it will start making the appropriate calls. Loading bar will be shown as api-calls are being made.
Step 4: More Rooms
- To add another room you can repeat Steps 1-3. To regenerate a previous room just select it from the 'Current Room' in the dropdown menu.
- The dropdown menu will remember the last prompt you used to generate the items.
- If you do not like the items it generated, you can hit the generate button until you are satisfied with the items.
""" | 2,792 | Python | 45.549999 | 138 | 0.731734 |
NVIDIA-Omniverse/kit-extension-sample-airoomgenerator/exts/omni.example.airoomgenerator/omni/example/airoomgenerator/prompts.py | # SPDX-FileCopyrightText: Copyright (c) 2023 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
# SPDX-License-Identifier: Apache-2.0
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
system_input='''You are an area generator expert. Given an area of a certain size, you can generate a list of items that are appropriate to that area, in the right place, and with a representative material.
You operate in a 3D Space. You work in a X,Y,Z coordinate system. X denotes width, Y denotes height, Z denotes depth. 0.0,0.0,0.0 is the default space origin.
You receive from the user the name of the area, the size of the area on X and Z axis in centimetres, the origin point of the area (which is at the center of the area).
You answer by only generating JSON files that contain the following information:
- area_name: name of the area
- X: coordinate of the area on X axis
- Y: coordinate of the area on Y axis
- Z: coordinate of the area on Z axis
- area_size_X: dimension in cm of the area on X axis
- area_size_Z: dimension in cm of the area on Z axis
- area_objects_list: list of all the objects in the area
For each object you need to store:
- object_name: name of the object
- X: coordinate of the object on X axis
- Y: coordinate of the object on Y axis
- Z: coordinate of the object on Z axis
- Length: dimension in cm of the object on X axis
- Width: dimension in cm of the object on Y axis
- Height: dimension in cm of the object on Z axis
- Material: a reasonable material of the object using an exact name from the following list: Plywood, Leather_Brown, Leather_Pumpkin, Leather_Black, Aluminum_Cast, Birch, Beadboard, Cardboard, Cloth_Black, Cloth_Gray, Concrete_Polished, Glazed_Glass, CorrugatedMetal, Cork, Linen_Beige, Linen_Blue, Linen_White, Mahogany, MDF, Oak, Plastic_ABS, Steel_Carbon, Steel_Stainless, Veneer_OU_Walnut, Veneer_UX_Walnut_Cherry, Veneer_Z5_Maple.
Each object name should include an appropriate adjective.
Keep in mind, objects should be disposed in the area to create the most meaningful layout possible, and they shouldn't overlap.
All objects must be within the bounds of the area size; Never place objects further than 1/2 the length or 1/2 the depth of the area from the origin.
Also keep in mind that the objects should be disposed all over the area in respect to the origin point of the area, and you can use negative values as well to display items correctly, since origin of the area is always at the center of the area.
Remember, you only generate JSON code, nothing else. It's very important.
'''
user_input="Warehouse, 1000x1000, origin at (0.0,0.0,0.0), generate a list of appropriate items in the correct places. Generate warehouse objects"
assistant_input='''{
"area_name": "Warehouse_Area",
"X": 0.0,
"Y": 0.0,
"Z": 0.0,
"area_size_X": 1000,
"area_size_Z": 1000,
"area_objects_list": [
{
"object_name": "Parts_Pallet_1",
"X": -150,
"Y": 0.0,
"Z": 250,
"Length": 100,
"Width": 100,
"Height": 10,
"Material": "Plywood"
},
{
"object_name": "Boxes_Pallet_2",
"X": -150,
"Y": 0.0,
"Z": 150,
"Length": 100,
"Width": 100,
"Height": 10,
"Material": "Plywood"
},
{
"object_name": "Industrial_Storage_Rack_1",
"X": -150,
"Y": 0.0,
"Z": 50,
"Length": 200,
"Width": 50,
"Height": 300,
"Material": "Steel_Carbon"
},
{
"object_name": "Empty_Pallet_3",
"X": -150,
"Y": 0.0,
"Z": -50,
"Length": 100,
"Width": 100,
"Height": 10,
"Material": "Plywood"
},
{
"object_name": "Yellow_Forklift_1",
"X": 50,
"Y": 0.0,
"Z": -50,
"Length": 200,
"Width": 100,
"Height": 250,
"Material": "Plastic_ABS"
},
{
"object_name": "Heavy_Duty_Forklift_2",
"X": 150,
"Y": 0.0,
"Z": -50,
"Length": 200,
"Width": 100,
"Height": 250,
"Material": "Steel_Stainless"
}
]
}'''
| 4,898 | Python | 37.880952 | 435 | 0.612903 |
NVIDIA-Omniverse/kit-extension-sample-airoomgenerator/exts/omni.example.airoomgenerator/omni/example/airoomgenerator/materials.py | # SPDX-FileCopyrightText: Copyright (c) 2023 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
# SPDX-License-Identifier: Apache-2.0
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
MaterialPresets = {
"Leather_Brown":
'http://omniverse-content-production.s3-us-west-2.amazonaws.com/Materials/Base/Textiles/Leather_Brown.mdl',
"Leather_Pumpkin_01":
'http://omniverse-content-production.s3-us-west-2.amazonaws.com/Materials/Base/Textiles/Leather_Pumpkin.mdl',
"Leather_Brown_02":
'http://omniverse-content-production.s3-us-west-2.amazonaws.com/Materials/Base/Textiles/Leather_Brown.mdl',
"Leather_Black_01":
'http://omniverse-content-production.s3-us-west-2.amazonaws.com/Materials/Base/Textiles/Leather_Black.mdl',
"Aluminum_cast":
'http://omniverse-content-production.s3-us-west-2.amazonaws.com/Materials/Base/Metals/Aluminum_Cast.mdl',
"Birch":
'http://omniverse-content-production.s3-us-west-2.amazonaws.com/Materials/Base/Wood/Birch.mdl',
"Beadboard":
'http://omniverse-content-production.s3-us-west-2.amazonaws.com/Materials/Base/Wood/Beadboard.mdl',
"Cardboard":
'http://omniverse-content-production.s3-us-west-2.amazonaws.com/Materials/Base/Wall_Board/Cardboard.mdl',
"Cloth_Black":
'http://omniverse-content-production.s3-us-west-2.amazonaws.com/Materials/Base/Textiles/Cloth_Black.mdl',
"Cloth_Gray":
'http://omniverse-content-production.s3-us-west-2.amazonaws.com/Materials/Base/Textiles/Cloth_Gray.mdl',
"Concrete_Polished":
'http://omniverse-content-production.s3-us-west-2.amazonaws.com/Materials/Base/Masonry/Concrete_Polished.mdl',
"Glazed_Glass":
'http://omniverse-content-production.s3-us-west-2.amazonaws.com/Materials/Base/Glass/Glazed_Glass.mdl',
"CorrugatedMetal":
'http://omniverse-content-production.s3-us-west-2.amazonaws.com/Materials/Base/Metals/CorrugatedMetal.mdl',
"Cork":
'http://omniverse-content-production.s3-us-west-2.amazonaws.com/Materials/Base/Wood/Cork.mdl',
"Linen_Beige":
'http://omniverse-content-production.s3-us-west-2.amazonaws.com/Materials/Base/Textiles/Linen_Beige.mdl',
"Linen_Blue":
'http://omniverse-content-production.s3-us-west-2.amazonaws.com/Materials/Base/Textiles/Linen_Blue.mdl',
"Linen_White":
'http://omniverse-content-production.s3-us-west-2.amazonaws.com/Materials/Base/Textiles/Linen_White.mdl',
"Mahogany":
'http://omniverse-content-production.s3-us-west-2.amazonaws.com/Materials/Base/Wood/Mahogany.mdl',
"MDF":
'http://omniverse-content-production.s3-us-west-2.amazonaws.com/Materials/Base/Wall_Board/MDF.mdl',
"Oak":
'http://omniverse-content-production.s3-us-west-2.amazonaws.com/Materials/Base/Wood/Oak.mdl',
"Plastic_ABS":
'http://omniverse-content-production.s3-us-west-2.amazonaws.com/Materials/Base/Plastics/Plastic_ABS.mdl',
"Steel_Carbon":
'http://omniverse-content-production.s3-us-west-2.amazonaws.com/Materials/Base/Metals/Steel_Carbon.mdl',
"Steel_Stainless":
'http://omniverse-content-production.s3-us-west-2.amazonaws.com/Materials/Base/Metals/Steel_Stainless.mdl',
"Veneer_OU_Walnut":
'http://omniverse-content-production.s3-us-west-2.amazonaws.com/Materials/Base/Plastics/Veneer_OU_Walnut.mdl',
"Veneer_UX_Walnut_Cherry":
'http://omniverse-content-production.s3-us-west-2.amazonaws.com/Materials/Base/Plastics/Veneer_UX_Walnut_Cherry.mdl',
"Veneer_Z5_Maple":
'http://omniverse-content-production.s3-us-west-2.amazonaws.com/Materials/Base/Plastics/Veneer_Z5_Maple.mdl',
"Plywood":
'http://omniverse-content-production.s3-us-west-2.amazonaws.com/Materials/Base/Wood/Plywood.mdl',
"Concrete_Rough_Dirty":
'http://omniverse-content-production.s3.us-west-2.amazonaws.com/Materials/vMaterials_2/Concrete/Concrete_Rough.mdl'
} | 4,323 | Python | 58.232876 | 121 | 0.743234 |
NVIDIA-Omniverse/kit-extension-sample-airoomgenerator/exts/omni.example.airoomgenerator/omni/example/airoomgenerator/utils.py | # SPDX-FileCopyrightText: Copyright (c) 2023 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
# SPDX-License-Identifier: Apache-2.0
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import omni.kit.commands
from pxr import Gf, Sdf, UsdGeom
from .materials import *
import carb
def CreateCubeFromCurve(curve_path: str, area_name: str = ""):
ctx = omni.usd.get_context()
stage = ctx.get_stage()
min_coords, max_coords = get_coords_from_bbox(curve_path)
x,y,z = get_bounding_box_dimensions(curve_path)
xForm_scale = Gf.Vec3d(x, 1, z)
cube_scale = Gf.Vec3d(0.01, 0.01, 0.01)
prim = stage.GetPrimAtPath(curve_path)
origin = prim.GetAttribute('xformOp:translate').Get()
if prim.GetTypeName() == "BasisCurves":
origin = Gf.Vec3d(min_coords[0]+x/2, 0, min_coords[2]+z/2)
area_path = '/World/Layout/Area'
if len(area_name) != 0:
area_path = '/World/Layout/' + area_name.replace(" ", "_")
new_area_path = omni.usd.get_stage_next_free_path(stage, area_path, False)
new_cube_xForm_path = new_area_path + "/" + "Floor"
new_cube_path = new_cube_xForm_path + "/" + "Cube"
# Create xForm to hold all items
item_container = create_prim(new_area_path)
set_transformTRS_attrs(item_container, translate=origin)
# Create Scale Xform for floor
xform = create_prim(new_cube_xForm_path)
set_transformTRS_attrs(xform, scale=xForm_scale)
# Create Floor Cube
omni.kit.commands.execute('CreateMeshPrimWithDefaultXform',
prim_type='Cube',
prim_path=new_cube_path,
select_new_prim=True
)
cube = stage.GetPrimAtPath(new_cube_path)
set_transformTRS_attrs(cube, scale=cube_scale)
cube.CreateAttribute("primvar:area_name", Sdf.ValueTypeNames.String, custom=True).Set(area_name)
omni.kit.commands.execute('DeletePrims',
paths=[curve_path],
destructive=False)
apply_material_to_prim('Concrete_Rough_Dirty', new_area_path)
return new_area_path
def apply_material_to_prim(material_name: str, prim_path: str):
ctx = omni.usd.get_context()
stage = ctx.get_stage()
looks_path = '/World/Looks/'
mat_path = looks_path + material_name
mat_prim = stage.GetPrimAtPath(mat_path)
if MaterialPresets.get(material_name, None) is not None:
if not mat_prim.IsValid():
omni.kit.commands.execute('CreateMdlMaterialPrimCommand',
mtl_url=MaterialPresets[material_name],
mtl_name=material_name,
mtl_path=mat_path)
omni.kit.commands.execute('BindMaterialCommand',
prim_path=prim_path,
material_path=mat_path)
def create_prim(prim_path, prim_type='Xform'):
ctx = omni.usd.get_context()
stage = ctx.get_stage()
prim = stage.DefinePrim(prim_path)
if prim_type == 'Xform':
xform = UsdGeom.Xform.Define(stage, prim_path)
else:
xform = UsdGeom.Cube.Define(stage, prim_path)
create_transformOps_for_xform(xform)
return prim
def create_transformOps_for_xform(xform):
xform.AddTranslateOp()
xform.AddRotateXYZOp()
xform.AddScaleOp()
def set_transformTRS_attrs(prim, translate: Gf.Vec3d = Gf.Vec3d(0,0,0), rotate: Gf.Vec3d=Gf.Vec3d(0,0,0), scale: Gf.Vec3d=Gf.Vec3d(1,1,1)):
prim.GetAttribute('xformOp:translate').Set(translate)
prim.GetAttribute('xformOp:rotateXYZ').Set(rotate)
prim.GetAttribute('xformOp:scale').Set(scale)
def get_bounding_box_dimensions(prim_path: str):
min_coords, max_coords = get_coords_from_bbox(prim_path)
length = max_coords[0] - min_coords[0]
width = max_coords[1] - min_coords[1]
height = max_coords[2] - min_coords[2]
return length, width, height
def get_coords_from_bbox(prim_path: str):
ctx = omni.usd.get_context()
bbox = ctx.compute_path_world_bounding_box(prim_path)
min_coords, max_coords = bbox
return min_coords, max_coords
def scale_object_if_needed(prim_path):
stage = omni.usd.get_context().get_stage()
length, width, height = get_bounding_box_dimensions(prim_path)
largest_dimension = max(length, width, height)
if largest_dimension < 10:
prim = stage.GetPrimAtPath(prim_path)
# HACK: All Get Attribute Calls need to check if the attribute exists and add it if it doesn't
if prim.IsValid():
scale_attr = prim.GetAttribute('xformOp:scale')
if scale_attr.IsValid():
current_scale = scale_attr.Get()
new_scale = (current_scale[0] * 100, current_scale[1] * 100, current_scale[2] * 100)
scale_attr.Set(new_scale)
carb.log_info(f"Scaled object by 100 times: {prim_path}")
else:
carb.log_info(f"Scale attribute not found for prim at path: {prim_path}")
else:
carb.log_info(f"Invalid prim at path: {prim_path}")
else:
carb.log_info(f"No scaling needed for object: {prim_path}") | 5,463 | Python | 38.594203 | 139 | 0.663738 |
NVIDIA-Omniverse/kit-extension-sample-airoomgenerator/exts/omni.example.airoomgenerator/omni/example/airoomgenerator/item_generator.py | # SPDX-FileCopyrightText: Copyright (c) 2023 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
# SPDX-License-Identifier: Apache-2.0
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#hotkey
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from pxr import Usd, Sdf, Gf
from .utils import scale_object_if_needed, apply_material_to_prim, create_prim, set_transformTRS_attrs
def place_deepsearch_results(gpt_results, query_result, root_prim_path):
index = 0
for item in query_result:
item_name = item[0]
item_path = item[1]
# Define Prim
prim_parent_path = root_prim_path + item_name.replace(" ", "_")
prim_path = prim_parent_path + "/" + item_name.replace(" ", "_")
parent_prim = create_prim(prim_parent_path)
next_prim = create_prim(prim_path)
# Add reference to USD Asset
references: Usd.references = next_prim.GetReferences()
# TODO: The query results should returnt he full path of the prim
references.AddReference(
assetPath="omniverse://ov-simready" + item_path)
# Add reference for future search refinement
config = next_prim.CreateAttribute("DeepSearch:Query", Sdf.ValueTypeNames.String)
config.Set(item_name)
# HACK: All "GetAttribute" calls should need to check if the attribute exists
# translate prim
next_object = gpt_results[index]
index = index + 1
x = next_object['X']
y = next_object['Y']
z = next_object['Z']
set_transformTRS_attrs(parent_prim, Gf.Vec3d(x,y,z), Gf.Vec3d(0,-90,-90), Gf.Vec3d(1.0,1.0,1.0))
scale_object_if_needed(prim_parent_path)
def place_greyboxes(gpt_results, root_prim_path):
index = 0
for item in gpt_results:
# Define Prim
prim_parent_path = root_prim_path + item['object_name'].replace(" ", "_")
prim_path = prim_parent_path + "/" + item['object_name'].replace(" ", "_")
# Define Dimensions and material
length = item['Length']/100
width = item['Width']/100
height = item['Height']/100
x = item['X']
y = item['Y']+height*100*.5 #shift bottom of object to y=0
z = item['Z']
material = item['Material']
# Create Prim
parent_prim = create_prim(prim_parent_path)
set_transformTRS_attrs(parent_prim)
prim = create_prim(prim_path, 'Cube')
set_transformTRS_attrs(prim, translate=Gf.Vec3d(x,y,z), scale=Gf.Vec3d(length, height, width))
prim.GetAttribute('extent').Set([(-50.0, -50.0, -50.0), (50.0, 50.0, 50.0)])
prim.GetAttribute('size').Set(100)
index = index + 1
# Add Attribute and Material
attr = prim.CreateAttribute("object_name", Sdf.ValueTypeNames.String)
attr.Set(item['object_name'])
apply_material_to_prim(material, prim_path)
| 3,365 | Python | 38.139534 | 104 | 0.63477 |
NVIDIA-Omniverse/kit-extension-sample-airoomgenerator/exts/omni.example.airoomgenerator/omni/example/airoomgenerator/window.py | # SPDX-FileCopyrightText: Copyright (c) 2023 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
# SPDX-License-Identifier: Apache-2.0
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import omni.ui as ui
import omni.usd
import carb
import asyncio
import omni.kit.commands
from omni.kit.window.popup_dialog.form_dialog import FormDialog
from .utils import CreateCubeFromCurve
from .style import gen_ai_style, guide
from .chatgpt_apiconnect import call_Generate
from .priminfo import PrimInfo
from pxr import Sdf
from .widgets import ProgressBar
class GenAIWindow(ui.Window):
def __init__(self, title: str, **kwargs) -> None:
super().__init__(title, **kwargs)
# Models
self._path_model = ui.SimpleStringModel()
self._prompt_model = ui.SimpleStringModel("generate warehouse objects")
self._area_name_model = ui.SimpleStringModel()
self._use_deepsearch = ui.SimpleBoolModel()
self._use_chatgpt = ui.SimpleBoolModel()
self._areas = []
self.response_log = None
self.current_index = -1
self.current_area = None
self._combo_changed_sub = None
self.frame.set_build_fn(self._build_fn)
def _build_fn(self):
with self.frame:
with ui.ScrollingFrame():
with ui.VStack(style=gen_ai_style):
with ui.HStack(height=0):
ui.Label("Content Generatation with ChatGPT", style={"font_size": 18})
ui.Button(name="properties", tooltip="Configure API Key and Nucleus Path", width=30, height=30, clicked_fn=lambda: self._open_settings())
with ui.CollapsableFrame("Getting Started Instructions", height=0, collapsed=True):
ui.Label(guide, word_wrap=True)
ui.Line()
with ui.HStack(height=0):
ui.Label("Area Name", width=ui.Percent(30))
ui.StringField(model=self._area_name_model)
ui.Button(name="create", width=30, height=30, clicked_fn=lambda: self._create_new_area(self.get_area_name()))
with ui.HStack(height=0):
ui.Label("Current Room", width=ui.Percent(30))
self._build_combo_box()
ui.Line()
with ui.HStack(height=ui.Percent(50)):
ui.Label("Prompt", width=0)
ui.StringField(model=self._prompt_model, multiline=True)
ui.Line()
self._build_ai_section()
def _save_settings(self, dialog):
values = dialog.get_values()
carb.log_info(values)
settings = carb.settings.get_settings()
settings.set_string("/persistent/exts/omni.example.airoomgenerator/APIKey", values["APIKey"])
settings.set_string("/persistent/exts/omni.example.airoomgenerator/deepsearch_nucleus_path", values["deepsearch_nucleus_path"])
settings.set_string("/persistent/exts/omni.example.airoomgenerator/path_filter", values["path_filter"])
dialog.hide()
def _open_settings(self):
settings = carb.settings.get_settings()
apikey_value = settings.get_as_string("/persistent/exts/omni.example.airoomgenerator/APIKey")
nucleus_path = settings.get_as_string("/persistent/exts/omni.example.airoomgenerator/deepsearch_nucleus_path")
path_filter = settings.get_as_string("/persistent/exts/omni.example.airoomgenerator/path_filter")
if apikey_value == "":
apikey_value = "Enter API Key Here"
if nucleus_path == "":
nucleus_path = "(ENTERPRISE ONLY) Enter Nucleus Path Here"
if path_filter == "":
path_filter = ""
field_defs = [
FormDialog.FieldDef("APIKey", "API Key: ", ui.StringField, apikey_value),
FormDialog.FieldDef("deepsearch_nucleus_path", "Nucleus Path: ", ui.StringField, nucleus_path),
FormDialog.FieldDef("path_filter", "Path Filter: ", ui.StringField, path_filter)
]
dialog = FormDialog(
title="Settings",
message="Your Settings: ",
field_defs = field_defs,
ok_handler=lambda dialog: self._save_settings(dialog))
dialog.show()
def _build_ai_section(self):
with ui.HStack(height=0):
ui.Spacer()
ui.Label("Use ChatGPT: ")
ui.CheckBox(model=self._use_chatgpt)
ui.Label("Use Deepsearch: ", tooltip="ENTERPRISE USERS ONLY")
ui.CheckBox(model=self._use_deepsearch)
ui.Spacer()
with ui.HStack(height=0):
ui.Spacer(width=ui.Percent(10))
ui.Button("Generate", height=40,
clicked_fn=lambda: self._generate())
ui.Spacer(width=ui.Percent(10))
self.progress = ProgressBar()
with ui.CollapsableFrame("ChatGPT Response / Log", height=0, collapsed=True):
self.response_log = ui.Label("", word_wrap=True)
def _build_combo_box(self):
self.combo_model = ui.ComboBox(self.current_index, *[str(x) for x in self._areas] ).model
def combo_changed(item_model, item):
index_value_model = item_model.get_item_value_model(item)
self.current_area = self._areas[index_value_model.as_int]
self.current_index = index_value_model.as_int
self.rebuild_frame()
self._combo_changed_sub = self.combo_model.subscribe_item_changed_fn(combo_changed)
def _create_new_area(self, area_name: str):
if area_name == "":
carb.log_warn("No area name provided")
return
new_area_name = CreateCubeFromCurve(self.get_prim_path(), area_name)
self._areas.append(new_area_name)
self.current_index = len(self._areas) - 1
index_value_model = self.combo_model.get_item_value_model()
index_value_model.set_value(self.current_index)
def rebuild_frame(self):
# we do want to update the area name and possibly last prompt?
area_name = self.current_area.split("/World/Layout/")
self._area_name_model.set_value(area_name[-1].replace("_", " "))
attr_prompt = self.get_prim().GetAttribute('genai:prompt')
if attr_prompt.IsValid():
self._prompt_model.set_value(attr_prompt.Get())
else:
self._prompt_model.set_value("")
self.frame.rebuild()
def _generate(self):
prim = self.get_prim()
attr = prim.GetAttribute('genai:prompt')
if not attr.IsValid():
attr = prim.CreateAttribute('genai:prompt', Sdf.ValueTypeNames.String)
attr.Set(self.get_prompt())
items_path = self.current_area + "/items"
ctx = omni.usd.get_context()
stage = ctx.get_stage()
if stage.GetPrimAtPath(items_path).IsValid():
omni.kit.commands.execute('DeletePrims',
paths=[items_path],
destructive=False)
# asyncio.ensure_future(self.progress.fill_bar(0,100))
run_loop = asyncio.get_event_loop()
run_loop.create_task(call_Generate(self.get_prim_info(),
self.get_prompt(),
self._use_chatgpt.as_bool,
self._use_deepsearch.as_bool,
self.response_log,
self.progress
))
# Returns a PrimInfo object containing the Length, Width, Origin and Area Name
def get_prim_info(self) -> PrimInfo:
prim = self.get_prim()
prim_info = None
if prim.IsValid():
prim_info = PrimInfo(prim, self.current_area)
return prim_info
# # Get the prim path specified
def get_prim_path(self):
ctx = omni.usd.get_context()
selection = ctx.get_selection().get_selected_prim_paths()
if len(selection) > 0:
return str(selection[0])
carb.log_warn("No Prim Selected")
return ""
# Get the area name specified
def get_area_name(self):
if self._area_name_model == "":
carb.log_warn("No Area Name Provided")
return self._area_name_model.as_string
# Get the prompt specified
def get_prompt(self):
if self._prompt_model == "":
carb.log_warn("No Prompt Provided")
return self._prompt_model.as_string
# Get the prim based on the Prim Path
def get_prim(self):
ctx = omni.usd.get_context()
stage = ctx.get_stage()
prim = stage.GetPrimAtPath(self.current_area)
if prim.IsValid() is None:
carb.log_warn("No valid prim in the scene")
return prim
def destroy(self):
super().destroy()
self._combo_changed_sub = None
self._path_model = None
self._prompt_model = None
self._area_name_model = None
self._use_deepsearch = None
self._use_chatgpt = None | 9,607 | Python | 41.892857 | 161 | 0.595503 |
NVIDIA-Omniverse/kit-extension-sample-airoomgenerator/exts/omni.example.airoomgenerator/docs/README.md | # AI Room Generator Sample Extension (omni.sample.airoomgenerator)

## Overview
The AI Room Generator Sample Extension allows users to generate 3D content to populate a room using Generative AI. The user will specify what area that defines the room and a prompt that will get passed to ChatGPT.
> NOTE: To enable the extension you will need to have ngsearch module. By default it is already avaliable in Omniverse USD Composer. If using Omniverse Code follow these [instructions](https://docs.omniverse.nvidia.com/prod_nucleus/prod_services/services/deepsearch/client/using_deepsearch_ui.html#using-deepsearch-beta-in-usd-composer) to get ngsearch
This Sample Extension utilizes Omniverse's [Deepsearch](https://docs.omniverse.nvidia.com/prod_nucleus/prod_services/services/deepsearch/overview.html) functionality to search for models within a nucleus server. (ENTERPRISE USERS ONLY)
## UI Overview

1. Settings (Cog Button)
- Where the user can input their API Key from [OpenAI](https://platform.openai.com/account/api-keys)
- Enterprise users can input their Deepsearch Enabled Nucleus Path
2. Area Name
- The name that will be applied to the Area once added.
3. Add Area (Plus Button)
- With an area selected and an Area Name provided, it will remove the selected object and spawn in a cube resembling the dimensions of the selected area prim.
4. Current Room
- By default this will be empty. As you add rooms this combo box will populate and allow you to switch between each generated room maintaining the prompt (if the room items have been generated). This allows users to adjust their prompt later for an already generated room.
5. Prompt
- The prompt that will be sent to ChatGPT.
- Here is an example prompt for a reception area:
- "This is the room where we meet our customers. Make sure there is a set of comfortable armchairs, a sofa, and a coffee table"
6. Use ChatGPT
- This enables the extension to call ChatGPT, otherwise it will use a default assistant prompt which will be the same every time.
7. Use Deepsearch (ENTERPRISE USERS ONLY)
- This enables the extension to use Deepsearch
8. Generate
- With a room selected and a prompt, this will send all the related information to ChatGPT. A progress bar will show up indicating if the response is still going.
9. ChatGPT Reponse / Log
- Once you have hit *Generate* this collapsable frame will contain the output recieved from ChatGPT. Here you can view the JSON data or if any issues arise with ChatGPT.
## How it works
### Getting information about the 3D Scene
Everything starts with the USD scene in Omniverse. Users can easily circle an area using the Pencil tool in Omniverse or create a cube and scale it in the scene, type in the kind of room/environment they want to generate - for example, a warehouse, or a reception room - and with one click that area is created.

### Creating the Prompt for ChatGPT
The ChatGPT prompt is composed of four pieces; system input, user input example, assistant output example, and user prompt.
Let’s start with the aspects of the prompt that tailor to the user’s scenario. This includes text that the user inputs plus data from the scene.
For example, if the user wants to create a reception room, they specify something like “This is the room where we meet our customers. Make sure there is a set of comfortable armchairs, a sofa and a coffee table”. Or, if they want to add a certain number of items they could add “make sure to include a minimum of 10 items”.
This text is combined with scene information like the size and name of the area where we will place items as the User Prompt.
### Passing the results from ChatGPT

The items from the ChatGPT JSON response are then parsed by the extension and passed to the Omnivere DeepSearch API. DeepSearch allows users to search 3D models stored within an Omniverse Nucleus server using natural language queries.
This means that even if we don’t know the exact file name of a model of a sofa, for example, we can retrieve it just by searching for “Comfortable Sofa” which is exactly what we got from ChatGPT.
DeepSearch understands natural language and by asking it for a “Comfortable Sofa” we get a list of items that our helpful AI librarian has decided are best suited from the selection of assets we have in our current asset library. It is surprisingly good at this and so we often can use the first item it returns, but of course we build in choice in case the user wants to select something from the list.
### When not using Deepsearch

For those who are not Enterprise users or users that want to use greyboxing, by default as long as `use Deepsearch` is turned off the extension will generate cube of various shapes and sizes to best suit the response from ChatGPT. | 4,975 | Markdown | 73.268656 | 404 | 0.776482 |
NVIDIA-Omniverse/AnariUsdDevice/UsdParameterizedObject.h | // Copyright 2020 The Khronos Group
// SPDX-License-Identifier: Apache-2.0
#pragma once
#include <map>
#include <string>
#include <cstring>
#include <cassert>
#include <algorithm>
#include <vector>
#include "UsdAnari.h"
#include "UsdSharedObjects.h"
#include "UsdMultiTypeParameter.h"
#include "helium/utility/IntrusivePtr.h"
#include "anari/frontend/type_utility.h"
class UsdDevice;
class UsdBridge;
// When deriving from UsdParameterizedObject<T>, define a a struct T::Data and
// a static void T::registerParams() that registers any member of T::Data using REGISTER_PARAMETER_MACRO()
template<typename T, typename D>
class UsdParameterizedObject
{
public:
struct UsdAnariDataTypeStore
{
ANARIDataType type0 = ANARI_UNKNOWN;
ANARIDataType type1 = ANARI_UNKNOWN;
ANARIDataType type2 = ANARI_UNKNOWN;
ANARIDataType singleType() const { return type0; }
bool isMultiType() const { return type1 != ANARI_UNKNOWN; }
bool typeMatches(ANARIDataType inType) const
{
return inType == type0 ||
(isMultiType() && (inType == type1 || inType == type2));
}
};
struct ParamTypeInfo
{
size_t dataOffset = 0; // offset of data, within paramDataSet D
size_t typeOffset = 0; // offset of type, from data
size_t size = 0; // Total size of data+type
UsdAnariDataTypeStore types;
};
using ParameterizedClassType = UsdParameterizedObject<T, D>;
using ParamContainer = std::map<std::string, ParamTypeInfo>;
void* getParam(const char* name, ANARIDataType& returnType)
{
// Check if name registered
typename ParamContainer::iterator it = registeredParams->find(name);
if (it != registeredParams->end())
{
const ParamTypeInfo& typeInfo = it->second;
void* destAddress = nullptr;
getParamTypeAndAddress(paramDataSets[paramWriteIdx], typeInfo,
returnType, destAddress);
return destAddress;
}
return nullptr;
}
protected:
helium::RefCounted** ptrToRefCountedPtr(void* address) { return reinterpret_cast<helium::RefCounted**>(address); }
ANARIDataType* toAnariDataTypePtr(void* address) { return reinterpret_cast<ANARIDataType*>(address); }
bool isRefCounted(ANARIDataType type) const { return anari::isObject(type) || type == ANARI_STRING; }
void safeRefInc(void* paramPtr) // Pointer to the parameter address which holds a helium::RefCounted*
{
helium::RefCounted** refCountedPP = ptrToRefCountedPtr(paramPtr);
if (*refCountedPP)
(*refCountedPP)->refInc(helium::RefType::INTERNAL);
}
void safeRefDec(void* paramPtr, ANARIDataType paramType) // Pointer to the parameter address which holds a helium::RefCounted*
{
helium::RefCounted** refCountedPP = ptrToRefCountedPtr(paramPtr);
if (*refCountedPP)
{
helium::RefCounted*& refCountedP = *refCountedPP;
#ifdef CHECK_MEMLEAKS
logDeallocationThroughDevice(allocDevice, refCountedP, paramType);
#endif
assert(refCountedP->useCount(helium::RefType::INTERNAL) > 0);
refCountedP->refDec(helium::RefType::INTERNAL);
refCountedP = nullptr; // Explicitly clear the pointer (see destructor)
}
}
void* paramAddress(D& paramData, const ParamTypeInfo& typeInfo)
{
return reinterpret_cast<char*>(¶mData) + typeInfo.dataOffset;
}
ANARIDataType paramType(void* paramAddress, const ParamTypeInfo& typeInfo)
{
if(typeInfo.types.isMultiType())
return *toAnariDataTypePtr(static_cast<char*>(paramAddress) + typeInfo.typeOffset);
else
return typeInfo.types.singleType();
}
void setMultiParamType(void* paramAddress, const ParamTypeInfo& typeInfo, ANARIDataType newType)
{
if(typeInfo.types.isMultiType())
*toAnariDataTypePtr(static_cast<char*>(paramAddress) + typeInfo.typeOffset) = newType;
}
void getParamTypeAndAddress(D& paramData, const ParamTypeInfo& typeInfo,
ANARIDataType& returnType, void*& returnAddress)
{
returnAddress = paramAddress(paramData, typeInfo);
returnType = paramType(returnAddress, typeInfo);
}
// Convenience function for usd-compatible parameters
void formatUsdName(UsdSharedString* nameStr)
{
char* name = const_cast<char*>(UsdSharedString::c_str(nameStr));
assert(strlen(name) > 0);
auto letter = [](unsigned c) { return ((c - 'A') < 26) || ((c - 'a') < 26); };
auto number = [](unsigned c) { return (c - '0') < 10; };
auto under = [](unsigned c) { return c == '_'; };
unsigned x = *name;
if (!letter(x) && !under(x)) { *name = '_'; }
x = *(++name);
while (x != '\0')
{
if(!letter(x) && !number(x) && !under(x))
*name = '_';
x = *(++name);
};
}
public:
UsdParameterizedObject()
{
static ParamContainer* reg = ParameterizedClassType::registerParams();
registeredParams = reg;
}
~UsdParameterizedObject()
{
// Manually decrease the references on all objects in the read and writeparam datasets
// (since the pointers are relinquished)
auto it = registeredParams->begin();
while (it != registeredParams->end())
{
const ParamTypeInfo& typeInfo = it->second;
ANARIDataType readParamType, writeParamType;
void* readParamAddress = nullptr;
void* writeParamAddress = nullptr;
getParamTypeAndAddress(paramDataSets[paramReadIdx], typeInfo,
readParamType, readParamAddress);
getParamTypeAndAddress(paramDataSets[paramWriteIdx], typeInfo,
writeParamType, writeParamAddress);
// Works even if two parameters point to the same object, as the object pointers are set to null
if(isRefCounted(readParamType))
safeRefDec(readParamAddress, readParamType);
if(isRefCounted(writeParamType))
safeRefDec(writeParamAddress, writeParamType);
++it;
}
}
const D& getReadParams() const { return paramDataSets[paramReadIdx]; }
D& getWriteParams() { return paramDataSets[paramWriteIdx]; }
protected:
void setParam(const char* name, ANARIDataType srcType, const void* rawSrc, UsdDevice* device)
{
#ifdef CHECK_MEMLEAKS
allocDevice = device;
#endif
if(srcType == ANARI_UNKNOWN)
{
reportStatusThroughDevice(UsdLogInfo(device, this, ANARI_OBJECT, nullptr), ANARI_SEVERITY_ERROR, ANARI_STATUS_INVALID_ARGUMENT,
"Attempting to set param %s with type %s", name, AnariTypeToString(srcType));
return;
}
else if(anari::isArray(srcType))
{
// Flatten the source type in case of array
srcType = ANARI_ARRAY;
}
// Check if name registered
typename ParamContainer::iterator it = registeredParams->find(name);
if (it != registeredParams->end())
{
const ParamTypeInfo& typeInfo = it->second;
// Check if type matches
if (typeInfo.types.typeMatches(srcType))
{
ANARIDataType destType;
void* destAddress = nullptr;
getParamTypeAndAddress(paramDataSets[paramWriteIdx], typeInfo,
destType, destAddress);
const void* srcAddress = rawSrc; //temporary src
size_t numBytes = anari::sizeOf(srcType); // Size is determined purely by source data
bool contentUpdate = srcType != destType; // Always do a content update if types differ (in case of multitype params)
// Update data for all the different types
if (srcType == ANARI_BOOL)
{
bool* destBool_p = reinterpret_cast<bool*>(destAddress);
bool srcBool = *(reinterpret_cast<const uint32_t*>(srcAddress));
contentUpdate = contentUpdate || (*destBool_p != srcBool);
*destBool_p = srcBool;
}
else
{
UsdSharedString* sharedStr = nullptr;
if (srcType == ANARI_STRING)
{
// Wrap strings to make them refcounted,
// from that point they are considered normal RefCounteds.
UsdSharedString* destStr = reinterpret_cast<UsdSharedString*>(*ptrToRefCountedPtr(destAddress));
const char* srcCstr = reinterpret_cast<const char*>(srcAddress);
contentUpdate = contentUpdate || !destStr || !strEquals(destStr->c_str(), srcCstr); // Note that execution of strEquals => (srcType == destType)
if(contentUpdate)
{
sharedStr = new UsdSharedString(srcCstr); // Remember to refdec
numBytes = sizeof(void*);
srcAddress = &sharedStr;
#ifdef CHECK_MEMLEAKS
logAllocationThroughDevice(allocDevice, sharedStr, ANARI_STRING);
#endif
}
}
else
contentUpdate = contentUpdate || bool(std::memcmp(destAddress, srcAddress, numBytes));
if(contentUpdate)
{
if(isRefCounted(destType))
safeRefDec(destAddress, destType);
std::memcpy(destAddress, srcAddress, numBytes);
if(isRefCounted(srcType))
safeRefInc(destAddress);
}
// If a string object has been created, decrease its public refcount (1 at creation)
if (sharedStr)
{
assert(sharedStr->useCount() == 2); // Single public and internal reference
sharedStr->refDec();
}
}
// Update the type for multitype params (so far only data has been updated)
if(contentUpdate)
setMultiParamType(destAddress, typeInfo, srcType);
if(!strEquals(name, "usd::time")) // Allow for re-use of object as reference at different timestep, without triggering a full re-commit of the referenced object
{
#ifdef TIME_BASED_CACHING
paramChanged = true; //For time-varying parameters, comparisons between content of potentially different timesteps is meaningless
#else
paramChanged = paramChanged || contentUpdate;
#endif
}
}
else
reportStatusThroughDevice(UsdLogInfo(device, this, ANARI_OBJECT, nullptr), ANARI_SEVERITY_ERROR, ANARI_STATUS_INVALID_ARGUMENT,
"Param %s is not of an accepted type. For example, use %s instead.", name, AnariTypeToString(typeInfo.types.type0));
}
}
void resetParam(const ParamTypeInfo& typeInfo)
{
size_t paramSize = typeInfo.size;
// Copy to existing write param location
ANARIDataType destType;
void* destAddress = nullptr;
getParamTypeAndAddress(paramDataSets[paramWriteIdx], typeInfo,
destType, destAddress);
// Create temporary default-constructed parameter set and find source param address ((multi-)type is of no concern)
D defaultParamData;
void* srcAddress = paramAddress(defaultParamData, typeInfo);
// Make sure to dec existing ptr, as it will be relinquished
if(isRefCounted(destType))
safeRefDec(destAddress, destType);
// Just replace contents of the whole parameter structure, single or multiparam
std::memcpy(destAddress, srcAddress, paramSize);
}
void resetParam(const char* name)
{
typename ParamContainer::iterator it = registeredParams->find(name);
if (it != registeredParams->end())
{
const ParamTypeInfo& typeInfo = it->second;
resetParam(typeInfo);
if(!strEquals(name, "usd::time"))
{
paramChanged = true;
}
}
}
void resetParams()
{
auto it = registeredParams->begin();
while (it != registeredParams->end())
{
resetParam(it->second);
++it;
}
paramChanged = true;
}
void transferWriteToReadParams()
{
// Make sure object references are removed for
// the overwritten readparams, and increased for the source writeparams
auto it = registeredParams->begin();
while (it != registeredParams->end())
{
const ParamTypeInfo& typeInfo = it->second;
ANARIDataType srcType, destType;
void* srcAddress = nullptr;
void* destAddress = nullptr;
getParamTypeAndAddress(paramDataSets[paramWriteIdx], typeInfo,
srcType, srcAddress);
getParamTypeAndAddress(paramDataSets[paramReadIdx], typeInfo,
destType, destAddress);
// SrcAddress and destAddress are not the same, but they may specifically contain the same object pointers.
// Branch out on that situation (may also be disabled, which results in a superfluous inc/dec)
if(std::memcmp(destAddress, srcAddress, typeInfo.size))
{
// First inc, then dec (in case branch is taken out and the pointed to object is the same)
if (isRefCounted(srcType))
safeRefInc(srcAddress);
if (isRefCounted(destType))
safeRefDec(destAddress, destType);
// Perform assignment immediately; there may be multiple parameters with the same object target,
// which will be branched out at the compare the second time around
std::memcpy(destAddress, srcAddress, typeInfo.size);
}
++it;
}
}
static ParamContainer* registerParams();
ParamContainer* registeredParams;
typedef T DerivedClassType;
typedef D DataType;
D paramDataSets[2];
constexpr static unsigned int paramReadIdx = 0;
constexpr static unsigned int paramWriteIdx = 1;
bool paramChanged = false;
#ifdef CHECK_MEMLEAKS
UsdDevice* allocDevice = nullptr;
#endif
};
#define DEFINE_PARAMETER_MAP(DefClass, Params) template<> UsdParameterizedObject<DefClass,DefClass::DataType>::ParamContainer* UsdParameterizedObject<DefClass,DefClass::DataType>::registerParams() { static ParamContainer registeredParams; Params return ®isteredParams; }
#define REGISTER_PARAMETER_MACRO(ParamName, ParamType, ParamData) \
registeredParams.emplace( std::make_pair<std::string, ParamTypeInfo>( \
std::string(ParamName), \
{offsetof(DataType, ParamData), 0, sizeof(DataType::ParamData), {ParamType, ANARI_UNKNOWN, ANARI_UNKNOWN}} \
)); \
static_assert(ParamType == anari::ANARITypeFor<decltype(DataType::ParamData)>::value, "ANARI type " #ParamType " of member '" #ParamData "' does not correspond to member type");
#define REGISTER_PARAMETER_MULTITYPE_MACRO(ParamName, ParamType0, ParamType1, ParamType2, ParamData) \
{ \
static_assert(ParamType0 == decltype(DataType::ParamData)::AnariType0, "MultiTypeParams registration: ParamType0 " #ParamType0 " of member '" #ParamData "' doesn't match AnariType0"); \
static_assert(ParamType1 == decltype(DataType::ParamData)::AnariType1, "MultiTypeParams registration: ParamType1 " #ParamType1 " of member '" #ParamData "' doesn't match AnariType1"); \
static_assert(ParamType2 == decltype(DataType::ParamData)::AnariType2, "MultiTypeParams registration: ParamType2 " #ParamType2 " of member '" #ParamData "' doesn't match AnariType2"); \
size_t dataOffset = offsetof(DataType, ParamData); \
size_t typeOffset = offsetof(DataType, ParamData.type); \
registeredParams.emplace( std::make_pair<std::string, ParamTypeInfo>( \
std::string(ParamName), \
{dataOffset, typeOffset - dataOffset, sizeof(DataType::ParamData), {ParamType0, ParamType1, ParamType2}} \
)); \
}
// Static assert explainer: gets the element type of the array via the decltype of *std::begin(), which in turn accepts an array
#define REGISTER_PARAMETER_ARRAY_MACRO(ParamName, ParamNameSuffix, ParamType, ParamData, NumEntries) \
{ \
using element_type_t = std::remove_reference_t<decltype(*std::begin(std::declval<decltype(DataType::ParamData)&>()))>; \
static_assert(ParamType == anari::ANARITypeFor<element_type_t>::value, "ANARI type " #ParamType " of member '" #ParamData "' does not correspond to member type"); \
static_assert(sizeof(decltype(DataType::ParamData)) == sizeof(element_type_t)*NumEntries, "Number of elements of member '" #ParamData "' does not correspond with member declaration."); \
size_t offset0 = offsetof(DataType, ParamData[0]); \
size_t offset1 = offsetof(DataType, ParamData[1]); \
size_t paramSize = offset1-offset0; \
for(int i = 0; i < NumEntries; ++i) \
{ \
registeredParams.emplace( std::make_pair<std::string, ParamTypeInfo>( \
ParamName + std::to_string(i) + ParamNameSuffix, \
{offset0+paramSize*i, 0, paramSize, {ParamType, ANARI_UNKNOWN, ANARI_UNKNOWN}} \
)); \
} \
}
| 16,145 | C | 35.947368 | 273 | 0.679282 |
NVIDIA-Omniverse/AnariUsdDevice/UsdRenderer.h | // Copyright 2020 The Khronos Group
// SPDX-License-Identifier: Apache-2.0
#pragma once
#include "UsdBaseObject.h"
#include "UsdParameterizedObject.h"
struct UsdRendererData
{
};
class UsdRenderer : public UsdParameterizedBaseObject<UsdRenderer, UsdRendererData>
{
public:
UsdRenderer();
~UsdRenderer();
void remove(UsdDevice* device) override {}
int getProperty(const char * name, ANARIDataType type, void * mem, uint64_t size, UsdDevice* device) override;
protected:
bool deferCommit(UsdDevice* device) override;
bool doCommitData(UsdDevice* device) override;
void doCommitRefs(UsdDevice* device) override {}
UsdBridge* usdBridge;
};
| 681 | C | 20.999999 | 114 | 0.737151 |
NVIDIA-Omniverse/AnariUsdDevice/UsdGeometry.h | // Copyright 2020 The Khronos Group
// SPDX-License-Identifier: Apache-2.0
#pragma once
#include "UsdBridgedBaseObject.h"
#include <memory>
#include <limits>
class UsdDataArray;
struct UsdBridgeMeshData;
static constexpr int MAX_ATTRIBS = 16;
enum class UsdGeometryComponents
{
POSITION = 0,
NORMAL,
COLOR,
INDEX,
SCALE,
ORIENTATION,
ID,
ATTRIBUTE0,
ATTRIBUTE1,
ATTRIBUTE2,
ATTRIBUTE3
};
struct UsdGeometryData
{
UsdSharedString* name = nullptr;
UsdSharedString* usdName = nullptr;
double timeStep = 0.0;
int timeVarying = 0xFFFFFFFF; // TimeVarying bits
const UsdDataArray* vertexPositions = nullptr;
const UsdDataArray* vertexNormals = nullptr;
const UsdDataArray* vertexColors = nullptr;
const UsdDataArray* vertexAttributes[MAX_ATTRIBS] = { nullptr };
const UsdDataArray* primitiveNormals = nullptr;
const UsdDataArray* primitiveColors = nullptr;
const UsdDataArray* primitiveAttributes[MAX_ATTRIBS] = { nullptr };
const UsdDataArray* primitiveIds = nullptr;
const UsdSharedString* attributeNames[MAX_ATTRIBS] = { nullptr };
const UsdDataArray* indices = nullptr;
// Spheres
const UsdDataArray* vertexRadii = nullptr;
float radiusConstant = 1.0f;
bool UseUsdGeomPoints =
#ifdef USE_USD_GEOM_POINTS
true;
#else
false;
#endif
// Cylinders
const UsdDataArray* primitiveRadii = nullptr;
// Curves
// Glyphs
const UsdDataArray* vertexScales = nullptr;
const UsdDataArray* primitiveScales = nullptr;
const UsdDataArray* vertexOrientations = nullptr;
const UsdDataArray* primitiveOrientations = nullptr;
UsdFloat3 scaleConstant = {1.0f, 1.0f, 1.0f};
UsdQuaternion orientationConstant;
UsdSharedString* shapeType = nullptr;
UsdGeometry* shapeGeometry = nullptr;
UsdFloatMat4 shapeTransform;
double shapeGeometryRefTimeStep = std::numeric_limits<float>::quiet_NaN();
};
struct UsdGeometryTempArrays;
class UsdGeometry : public UsdBridgedBaseObject<UsdGeometry, UsdGeometryData, UsdGeometryHandle, UsdGeometryComponents>
{
public:
enum GeomType
{
GEOM_UNKNOWN = 0,
GEOM_TRIANGLE,
GEOM_QUAD,
GEOM_SPHERE,
GEOM_CYLINDER,
GEOM_CONE,
GEOM_CURVE,
GEOM_GLYPH
};
typedef std::vector<UsdBridgeAttribute> AttributeArray;
typedef std::vector<std::vector<char>> AttributeDataArraysType;
UsdGeometry(const char* name, const char* type, UsdDevice* device);
~UsdGeometry();
void remove(UsdDevice* device) override;
void filterSetParam(const char *name,
ANARIDataType type,
const void *mem,
UsdDevice* device) override;
bool isInstanced() const
{
return geomType == GEOM_SPHERE
|| geomType == GEOM_CONE
|| geomType == GEOM_CYLINDER
|| geomType == GEOM_GLYPH;
}
static constexpr ComponentPair componentParamNames[] = {
ComponentPair(UsdGeometryComponents::POSITION, "position"),
ComponentPair(UsdGeometryComponents::NORMAL, "normal"),
ComponentPair(UsdGeometryComponents::COLOR, "color"),
ComponentPair(UsdGeometryComponents::INDEX, "index"),
ComponentPair(UsdGeometryComponents::SCALE, "scale"),
ComponentPair(UsdGeometryComponents::SCALE, "radius"),
ComponentPair(UsdGeometryComponents::ORIENTATION, "orientation"),
ComponentPair(UsdGeometryComponents::ID, "id"),
ComponentPair(UsdGeometryComponents::ATTRIBUTE0, "attribute0"),
ComponentPair(UsdGeometryComponents::ATTRIBUTE1, "attribute1"),
ComponentPair(UsdGeometryComponents::ATTRIBUTE2, "attribute2"),
ComponentPair(UsdGeometryComponents::ATTRIBUTE3, "attribute3")};
protected:
bool deferCommit(UsdDevice* device) override;
bool doCommitData(UsdDevice* device) override;
void doCommitRefs(UsdDevice* device) override;
void initializeGeomData(UsdBridgeMeshData& geomData);
void initializeGeomData(UsdBridgeInstancerData& geomData);
void initializeGeomData(UsdBridgeCurveData& geomData);
void initializeGeomRefData(UsdBridgeInstancerRefData& geomRefData);
bool checkArrayConstraints(const UsdDataArray* vertexArray, const UsdDataArray* primArray,
const char* paramName, UsdDevice* device, const char* debugName, int attribIndex = -1);
bool checkGeomParams(UsdDevice* device);
void updateGeomData(UsdDevice* device, UsdBridge* usdBridge, UsdBridgeMeshData& meshData, bool isNew);
void updateGeomData(UsdDevice* device, UsdBridge* usdBridge, UsdBridgeInstancerData& instancerData, bool isNew);
void updateGeomData(UsdDevice* device, UsdBridge* usdBridge, UsdBridgeCurveData& curveData, bool isNew);
template<typename UsdGeomType>
bool commitTemplate(UsdDevice* device);
void commitPrototypes(UsdBridge* usdBridge);
template<typename GeomDataType>
void setAttributeTimeVarying(typename GeomDataType::DataMemberId& timeVarying);
void syncAttributeArrays();
template<typename GeomDataType>
void copyAttributeArraysToData(GeomDataType& geomData);
void assignTempDataToAttributes(bool perPrimInterpolation);
GeomType geomType = GEOM_UNKNOWN;
bool protoShapeChanged = false; // Do not automatically commit shapes (the object may have been recreated onto an already existing USD prim)
std::unique_ptr<UsdGeometryTempArrays> tempArrays;
AttributeArray attributeArray;
}; | 5,365 | C | 29.83908 | 144 | 0.741473 |
NVIDIA-Omniverse/AnariUsdDevice/UsdMaterial.h | // Copyright 2020 The Khronos Group
// SPDX-License-Identifier: Apache-2.0
#pragma once
#include "UsdBridgedBaseObject.h"
#include "UsdBridgeNumerics.h"
#include "UsdDeviceUtils.h"
#include <limits>
class UsdSampler;
template<typename ValueType>
using UsdMaterialMultiTypeParameter = UsdMultiTypeParameter<ValueType, UsdSampler*, UsdSharedString*>;
enum class UsdMaterialDataComponents
{
COLOR = 0,
OPACITY,
EMISSIVE,
EMISSIVEFACTOR,
ROUGHNESS,
METALLIC,
IOR
};
struct UsdMaterialData
{
UsdSharedString* name = nullptr;
UsdSharedString* usdName = nullptr;
double timeStep = std::numeric_limits<float>::quiet_NaN();
int timeVarying = 0; // Bitmask indicating which attributes are time-varying.
// Standard parameters
UsdMaterialMultiTypeParameter<UsdFloat3> color = {{ 1.0f, 1.0f, 1.0f }, ANARI_FLOAT32_VEC3};
UsdMaterialMultiTypeParameter<float> opacity = {1.0f, ANARI_FLOAT32};
UsdSharedString* alphaMode = nullptr; // Timevarying state linked to opacity
float alphaCutoff = 0.5f; // Timevarying state linked to opacity
// Possible PBR parameters
UsdMaterialMultiTypeParameter<UsdFloat3> emissiveColor = {{ 1.0f, 1.0f, 1.0f }, ANARI_FLOAT32_VEC3};
UsdMaterialMultiTypeParameter<float> emissiveIntensity = {0.0f, ANARI_FLOAT32};
UsdMaterialMultiTypeParameter<float> roughness = {0.5f, ANARI_FLOAT32};
UsdMaterialMultiTypeParameter<float> metallic = {0.0f, ANARI_FLOAT32};
UsdMaterialMultiTypeParameter<float> ior = {1.0f, ANARI_FLOAT32};
double colorSamplerTimeStep = std::numeric_limits<float>::quiet_NaN();
double opacitySamplerTimeStep = std::numeric_limits<float>::quiet_NaN();
double emissiveSamplerTimeStep = std::numeric_limits<float>::quiet_NaN();
double emissiveIntensitySamplerTimeStep = std::numeric_limits<float>::quiet_NaN();
double roughnessSamplerTimeStep = std::numeric_limits<float>::quiet_NaN();
double metallicSamplerTimeStep = std::numeric_limits<float>::quiet_NaN();
double iorSamplerTimeStep = std::numeric_limits<float>::quiet_NaN();
};
class UsdMaterial : public UsdBridgedBaseObject<UsdMaterial, UsdMaterialData, UsdMaterialHandle, UsdMaterialDataComponents>
{
public:
using MaterialDMI = UsdBridgeMaterialData::DataMemberId;
UsdMaterial(const char* name, const char* type, UsdDevice* device);
~UsdMaterial();
void remove(UsdDevice* device) override;
bool isPerInstance() const { return perInstance; }
void updateBoundParameters(bool boundToInstance, UsdDevice* device);
static constexpr ComponentPair componentParamNames[] = {
ComponentPair(UsdMaterialDataComponents::COLOR, "color"),
ComponentPair(UsdMaterialDataComponents::COLOR, "baseColor"),
ComponentPair(UsdMaterialDataComponents::OPACITY, "opacity"),
ComponentPair(UsdMaterialDataComponents::EMISSIVE, "emissive"),
ComponentPair(UsdMaterialDataComponents::EMISSIVEFACTOR, "emissiveIntensity"),
ComponentPair(UsdMaterialDataComponents::ROUGHNESS, "roughness"),
ComponentPair(UsdMaterialDataComponents::METALLIC, "metallic"),
ComponentPair(UsdMaterialDataComponents::IOR, "ior")};
protected:
using MaterialInputAttribNamePair = std::pair<MaterialDMI, const char*>;
template<typename ValueType>
bool getMaterialInputSourceName(const UsdMaterialMultiTypeParameter<ValueType>& param,
MaterialDMI dataMemberId, UsdDevice* device, const UsdLogInfo& logInfo);
template<typename ValueType>
bool getSamplerRefData(const UsdMaterialMultiTypeParameter<ValueType>& param, double refTimeStep,
MaterialDMI dataMemberId, UsdDevice* device, const UsdLogInfo& logInfo);
template<typename ValueType>
void assignParameterToMaterialInput(
const UsdMaterialMultiTypeParameter<ValueType>& param,
UsdBridgeMaterialData::MaterialInput<ValueType>& matInput,
const UsdLogInfo& logInfo);
bool deferCommit(UsdDevice* device) override;
bool doCommitData(UsdDevice* device) override;
void doCommitRefs(UsdDevice* device) override;
void setMaterialTimeVarying(UsdBridgeMaterialData::DataMemberId& timeVarying);
bool isPbr = false;
bool perInstance = false; // Whether material is attached to a point instancer
bool instanceAttributeAttached = false; // Whether a value to any parameter has been set which in USD is different between per-instance and regular geometries
OptionalList<MaterialInputAttribNamePair> materialInputAttributes;
OptionalList<UsdSamplerHandle> samplerHandles;
OptionalList<UsdSamplerRefData> samplerRefDatas;
}; | 4,548 | C | 39.981982 | 162 | 0.769789 |
NVIDIA-Omniverse/AnariUsdDevice/UsdMaterial.cpp | // Copyright 2020 The Khronos Group
// SPDX-License-Identifier: Apache-2.0
#include "UsdMaterial.h"
#include "UsdAnari.h"
#include "UsdDevice.h"
#include "UsdSampler.h"
#include "UsdDataArray.h"
#define SamplerType ANARI_SAMPLER
using SamplerUsdType = AnariToUsdBridgedObject<SamplerType>::Type;
#define REGISTER_PARAMETER_MATERIAL_MULTITYPE_MACRO(ParamName, ParamType0, ParamData) \
REGISTER_PARAMETER_MULTITYPE_MACRO(ParamName, ParamType0, SamplerType, ANARI_STRING, ParamData)
DEFINE_PARAMETER_MAP(UsdMaterial,
REGISTER_PARAMETER_MACRO("name", ANARI_STRING, name)
REGISTER_PARAMETER_MACRO("usd::name", ANARI_STRING, usdName)
REGISTER_PARAMETER_MACRO("usd::time", ANARI_FLOAT64, timeStep)
REGISTER_PARAMETER_MACRO("usd::timeVarying", ANARI_INT32, timeVarying)
REGISTER_PARAMETER_MACRO("usd::time.sampler.color", ANARI_FLOAT64, colorSamplerTimeStep)
REGISTER_PARAMETER_MACRO("usd::time.sampler.baseColor", ANARI_FLOAT64, colorSamplerTimeStep)
REGISTER_PARAMETER_MACRO("usd::time.sampler.opacity", ANARI_FLOAT64, opacitySamplerTimeStep)
REGISTER_PARAMETER_MACRO("usd::time.sampler.emissive", ANARI_FLOAT64, emissiveSamplerTimeStep)
REGISTER_PARAMETER_MACRO("usd::time.sampler.emissiveIntensity", ANARI_FLOAT64, emissiveIntensitySamplerTimeStep)
REGISTER_PARAMETER_MACRO("usd::time.sampler.roughness", ANARI_FLOAT64, roughnessSamplerTimeStep)
REGISTER_PARAMETER_MACRO("usd::time.sampler.metallic", ANARI_FLOAT64, metallicSamplerTimeStep)
REGISTER_PARAMETER_MACRO("usd::time.sampler.ior", ANARI_FLOAT64, iorSamplerTimeStep)
REGISTER_PARAMETER_MATERIAL_MULTITYPE_MACRO("color", ANARI_FLOAT32_VEC3, color)
REGISTER_PARAMETER_MATERIAL_MULTITYPE_MACRO("baseColor", ANARI_FLOAT32_VEC3, color)
REGISTER_PARAMETER_MATERIAL_MULTITYPE_MACRO("opacity", ANARI_FLOAT32, opacity)
REGISTER_PARAMETER_MACRO("alphaMode", ANARI_STRING, alphaMode)
REGISTER_PARAMETER_MACRO("alphaCutoff", ANARI_FLOAT32, alphaCutoff)
REGISTER_PARAMETER_MATERIAL_MULTITYPE_MACRO("emissive", ANARI_FLOAT32_VEC3, emissiveColor)
REGISTER_PARAMETER_MATERIAL_MULTITYPE_MACRO("emissiveIntensity", ANARI_FLOAT32, emissiveIntensity)
REGISTER_PARAMETER_MATERIAL_MULTITYPE_MACRO("roughness", ANARI_FLOAT32, roughness)
REGISTER_PARAMETER_MATERIAL_MULTITYPE_MACRO("metallic", ANARI_FLOAT32, metallic)
REGISTER_PARAMETER_MATERIAL_MULTITYPE_MACRO("ior", ANARI_FLOAT32, ior)
)
constexpr UsdMaterial::ComponentPair UsdMaterial::componentParamNames[]; // Workaround for C++14's lack of inlining constexpr arrays
using DMI = UsdMaterial::MaterialDMI;
UsdMaterial::UsdMaterial(const char* name, const char* type, UsdDevice* device)
: BridgedBaseObjectType(ANARI_MATERIAL, name, device)
{
if (strEquals(type, "matte"))
{
isPbr = false;
}
else if (strEquals(type, "physicallyBased"))
{
isPbr = true;
}
else
{
device->reportStatus(this, ANARI_MATERIAL, ANARI_SEVERITY_ERROR, ANARI_STATUS_INVALID_ARGUMENT, "UsdMaterial '%s' intialization error: unknown material type", getName());
}
}
UsdMaterial::~UsdMaterial()
{
#ifdef OBJECT_LIFETIME_EQUALS_USD_LIFETIME
if(cachedBridge)
cachedBridge->DeleteMaterial(usdHandle);
#endif
}
void UsdMaterial::remove(UsdDevice* device)
{
applyRemoveFunc(device, &UsdBridge::DeleteMaterial);
}
template<typename ValueType>
bool UsdMaterial::getMaterialInputSourceName(const UsdMaterialMultiTypeParameter<ValueType>& param, MaterialDMI dataMemberId, UsdDevice* device, const UsdLogInfo& logInfo)
{
bool hasPositionAttrib = false;
UsdSharedString* anariAttribStr = nullptr;
param.Get(anariAttribStr);
const char* anariAttrib = UsdSharedString::c_str(anariAttribStr);
if(anariAttrib)
{
hasPositionAttrib = strEquals(anariAttrib, "objectPosition");
if( hasPositionAttrib && instanceAttributeAttached)
{
// In case of a per-instance specific attribute name, there can be only one change of the attribute name.
// Otherwise there is a risk of the material attribute being used for two differently named attributes.
reportStatusThroughDevice(logInfo, ANARI_SEVERITY_WARNING, ANARI_STATUS_INVALID_ARGUMENT,
"UsdMaterial '%s' binds one of its parameters to %s, but is transitively bound to both an instanced geometry (cones, spheres, cylinders) and regular geometry. \
This is incompatible with USD, which demands a differently bound name for those categories. \
Please create two different samplers and bind each to only one of both categories of geometry. \
The parameter value will be updated, but may therefore invalidate previous bindings to the objectPosition attribute.", logInfo.sourceName, "'objectPosition'");
}
const char* usdAttribName = AnariAttributeToUsdName(anariAttrib, perInstance, logInfo);
materialInputAttributes.push_back(UsdBridge::MaterialInputAttribName(dataMemberId, usdAttribName));
}
return hasPositionAttrib;
}
template<typename ValueType>
bool UsdMaterial::getSamplerRefData(const UsdMaterialMultiTypeParameter<ValueType>& param, double refTimeStep, MaterialDMI dataMemberId, UsdDevice* device, const UsdLogInfo& logInfo)
{
UsdSampler* sampler = nullptr;
param.Get(sampler);
if(sampler)
{
const UsdSamplerData& samplerParamData = sampler->getReadParams();
double worldTimeStep = device->getReadParams().timeStep;
double samplerObjTimeStep = samplerParamData.timeStep;
double samplerRefTime = selectRefTime(refTimeStep, samplerObjTimeStep, worldTimeStep);
// Reading child (sampler) data in the material has the consequence that the sampler's parameters as they were last committed are in effect "part of" the material parameter set, at this point of commit.
// So in case a sampler at a particular timestep is referenced from a material at two different world timesteps
// - ie. for this world timestep, a particular timestep of an image already committed and subsequently referenced at some other previous world timestep is reused -
// the user needs to make sure that not only the timestep is set correctly on the sampler for the commit (which is by itself lightweight, as it does not trigger a full commit),
// but also that the parameters read here have been re-set on the sampler to the values belonging to the referenced timestep, as if there is no USD representation of a sampler object.
// Setting those parameters will in turn trigger a full commit of the sampler object, which is in theory inefficient.
// However, in case of a sampler this is not a problem in practice; data transfer is only a concern when the filename is *not* set, at which point a relative file corresponding
// to the sampler timestep will be automatically chosen and set for the material, without the sampler object requiring any updates.
// In case a filename *is* set, only the filename is used and no data transfer/file io operations are performed.
//const char* imageUrl = UsdSharedString::c_str(samplerParamData.imageUrl); // not required anymore since all materials are a graph
int imageNumComponents = 4;
if(samplerParamData.imageData)
{
imageNumComponents = static_cast<int>(anari::componentsOf(samplerParamData.imageData->getType()));
}
UsdSamplerRefData samplerRefData = {imageNumComponents, samplerRefTime, dataMemberId};
samplerHandles.push_back(sampler->getUsdHandle());
samplerRefDatas.push_back(samplerRefData);
}
return false;
}
template<typename ValueType>
void UsdMaterial::assignParameterToMaterialInput(const UsdMaterialMultiTypeParameter<ValueType>& param,
UsdBridgeMaterialData::MaterialInput<ValueType>& matInput, const UsdLogInfo& logInfo)
{
param.Get(matInput.Value);
UsdSharedString* anariAttribStr = nullptr;
matInput.SrcAttrib = param.Get(anariAttribStr) ?
AnariAttributeToUsdName(anariAttribStr->c_str(), perInstance, logInfo) :
nullptr;
UsdSampler* sampler = nullptr;
matInput.Sampler = param.Get(sampler);
}
void UsdMaterial::updateBoundParameters(bool boundToInstance, UsdDevice* device)
{
UsdBridge* usdBridge = device->getUsdBridge();
const UsdMaterialData& paramData = getReadParams();
if(perInstance != boundToInstance)
{
UsdLogInfo logInfo = {device, this, ANARI_MATERIAL, getName()};
double worldTimeStep = device->getReadParams().timeStep;
double dataTimeStep = selectObjTime(paramData.timeStep, worldTimeStep);
// Fix up any parameters that have a geometry-type-dependent name set as source attribute
materialInputAttributes.clear();
bool hasPositionAttrib =
getMaterialInputSourceName(paramData.color, DMI::DIFFUSE, device, logInfo) ||
getMaterialInputSourceName(paramData.opacity, DMI::OPACITY, device, logInfo) ||
getMaterialInputSourceName(paramData.emissiveColor, DMI::EMISSIVECOLOR, device, logInfo) ||
getMaterialInputSourceName(paramData.emissiveIntensity, DMI::EMISSIVEINTENSITY, device, logInfo) ||
getMaterialInputSourceName(paramData.roughness, DMI::ROUGHNESS, device, logInfo) ||
getMaterialInputSourceName(paramData.metallic, DMI::METALLIC, device, logInfo) ||
getMaterialInputSourceName(paramData.ior, DMI::IOR, device, logInfo);
DMI timeVarying;
setMaterialTimeVarying(timeVarying);
// Fixup attribute name and type depending on the newly bound geometry
if(materialInputAttributes.size())
usdBridge->ChangeMaterialInputAttributes(usdHandle, materialInputAttributes.data(), materialInputAttributes.size(), dataTimeStep, timeVarying);
if(hasPositionAttrib)
instanceAttributeAttached = true; // As soon as any parameter is set to a position attribute, the geometry type for this material is 'locked-in'
perInstance = boundToInstance;
}
if(paramData.color.type == SamplerType)
{
UsdSampler* colorSampler = nullptr;
if (paramData.color.Get(colorSampler))
{
colorSampler->updateBoundParameters(boundToInstance, device);
}
}
}
bool UsdMaterial::deferCommit(UsdDevice* device)
{
//const UsdMaterialData& paramData = getReadParams();
//if(UsdObjectNotInitialized<SamplerUsdType>(paramData.color.type == SamplerType))
//{
// return true;
//}
return false;
}
bool UsdMaterial::doCommitData(UsdDevice* device)
{
UsdBridge* usdBridge = device->getUsdBridge();
if(!device->getReadParams().outputMaterial)
return false;
bool isNew = false;
if (!usdHandle.value)
isNew = usdBridge->CreateMaterial(getName(), usdHandle);
if (paramChanged || isNew)
{
const UsdMaterialData& paramData = getReadParams();
double worldTimeStep = device->getReadParams().timeStep;
double dataTimeStep = selectObjTime(paramData.timeStep, worldTimeStep);
UsdBridgeMaterialData matData;
matData.IsPbr = isPbr;
matData.AlphaMode = AnariToUsdAlphaMode(UsdSharedString::c_str(paramData.alphaMode));
matData.AlphaCutoff = paramData.alphaCutoff;
UsdLogInfo logInfo = {device, this, ANARI_MATERIAL, getName()};
assignParameterToMaterialInput(paramData.color, matData.Diffuse, logInfo);
assignParameterToMaterialInput(paramData.opacity, matData.Opacity, logInfo);
assignParameterToMaterialInput(paramData.emissiveColor, matData.Emissive, logInfo);
assignParameterToMaterialInput(paramData.emissiveIntensity, matData.EmissiveIntensity, logInfo);
assignParameterToMaterialInput(paramData.roughness, matData.Roughness, logInfo);
assignParameterToMaterialInput(paramData.metallic, matData.Metallic, logInfo);
assignParameterToMaterialInput(paramData.ior, matData.Ior, logInfo);
setMaterialTimeVarying(matData.TimeVarying);
usdBridge->SetMaterialData(usdHandle, matData, dataTimeStep);
paramChanged = false;
return paramData.color.type == SamplerType; // Only commit refs when material actually contains a texture (filename param from diffusemap is required)
}
return false;
}
void UsdMaterial::doCommitRefs(UsdDevice* device)
{
UsdBridge* usdBridge = device->getUsdBridge();
const UsdMaterialData& paramData = getReadParams();
double worldTimeStep = device->getReadParams().timeStep;
samplerHandles.clear();
samplerRefDatas.clear();
UsdLogInfo logInfo = {device, this, ANARI_MATERIAL, getName()};
getSamplerRefData(paramData.color, paramData.colorSamplerTimeStep, DMI::DIFFUSE, device, logInfo);
getSamplerRefData(paramData.opacity, paramData.opacitySamplerTimeStep, DMI::OPACITY, device, logInfo);
getSamplerRefData(paramData.emissiveColor, paramData.emissiveSamplerTimeStep, DMI::EMISSIVECOLOR, device, logInfo);
getSamplerRefData(paramData.emissiveIntensity, paramData.emissiveIntensitySamplerTimeStep, DMI::EMISSIVEINTENSITY, device, logInfo);
getSamplerRefData(paramData.roughness, paramData.roughnessSamplerTimeStep, DMI::ROUGHNESS, device, logInfo);
getSamplerRefData(paramData.metallic, paramData.metallicSamplerTimeStep, DMI::METALLIC, device, logInfo);
getSamplerRefData(paramData.ior, paramData.iorSamplerTimeStep, DMI::IOR, device, logInfo);
if(samplerHandles.size())
usdBridge->SetSamplerRefs(usdHandle, samplerHandles.data(), samplerHandles.size(), worldTimeStep, samplerRefDatas.data());
else
usdBridge->DeleteSamplerRefs(usdHandle, worldTimeStep);
}
void UsdMaterial::setMaterialTimeVarying(UsdBridgeMaterialData::DataMemberId& timeVarying)
{
timeVarying = DMI::ALL
& (isTimeVarying(CType::COLOR) ? DMI::ALL : ~DMI::DIFFUSE)
& (isTimeVarying(CType::OPACITY) ? DMI::ALL : ~DMI::OPACITY)
& (isTimeVarying(CType::EMISSIVE) ? DMI::ALL : ~DMI::EMISSIVECOLOR)
& (isTimeVarying(CType::EMISSIVEFACTOR) ? DMI::ALL : ~DMI::EMISSIVEINTENSITY)
& (isTimeVarying(CType::ROUGHNESS) ? DMI::ALL : ~DMI::ROUGHNESS)
& (isTimeVarying(CType::METALLIC) ? DMI::ALL : ~DMI::METALLIC)
& (isTimeVarying(CType::IOR) ? DMI::ALL : ~DMI::IOR);
} | 13,810 | C++ | 45.190635 | 207 | 0.767343 |
NVIDIA-Omniverse/AnariUsdDevice/UsdWorld.h | // Copyright 2020 The Khronos Group
// SPDX-License-Identifier: Apache-2.0
#pragma once
#include "UsdBridgedBaseObject.h"
class UsdDataArray;
enum class UsdWorldComponents
{
INSTANCES = 0,
SURFACES,
VOLUMES
};
struct UsdWorldData
{
UsdSharedString* name = nullptr;
UsdSharedString* usdName = nullptr;
int timeVarying = 0xFFFFFFFF; // Bitmask indicating which attributes are time-varying.
UsdDataArray* instances = nullptr;
UsdDataArray* surfaces = nullptr;
UsdDataArray* volumes = nullptr;
};
class UsdWorld : public UsdBridgedBaseObject<UsdWorld, UsdWorldData, UsdWorldHandle, UsdWorldComponents>
{
public:
UsdWorld(const char* name, UsdDevice* device);
~UsdWorld();
void remove(UsdDevice* device) override;
static constexpr ComponentPair componentParamNames[] = {
ComponentPair(UsdWorldComponents::INSTANCES, "instance"),
ComponentPair(UsdWorldComponents::SURFACES, "surface"),
ComponentPair(UsdWorldComponents::VOLUMES, "volume")};
protected:
bool deferCommit(UsdDevice* device) override;
bool doCommitData(UsdDevice* device) override;
void doCommitRefs(UsdDevice* device) override;
std::vector<UsdInstanceHandle> instanceHandles; // for convenience
std::vector<UsdSurfaceHandle> surfaceHandles; // for convenience
std::vector<UsdVolumeHandle> volumeHandles; // for convenience
}; | 1,375 | C | 26.519999 | 104 | 0.749818 |
NVIDIA-Omniverse/AnariUsdDevice/UsdLight.h | // Copyright 2020 The Khronos Group
// SPDX-License-Identifier: Apache-2.0
#pragma once
#include "UsdBridgedBaseObject.h"
struct UsdLightData
{
UsdSharedString* name = nullptr;
UsdSharedString* usdName = nullptr;
};
class UsdLight : public UsdBridgedBaseObject<UsdLight, UsdLightData, UsdLightHandle>
{
public:
UsdLight(const char* name,
UsdDevice* device);
~UsdLight();
void remove(UsdDevice* device) override;
protected:
bool deferCommit(UsdDevice* device) override;
bool doCommitData(UsdDevice* device) override;
void doCommitRefs(UsdDevice* device) override {}
};
| 612 | C | 20.892856 | 84 | 0.73366 |
NVIDIA-Omniverse/AnariUsdDevice/UsdFrame.cpp | // Copyright 2020 The Khronos Group
// SPDX-License-Identifier: Apache-2.0
#include "UsdFrame.h"
#include "UsdBridge/UsdBridge.h"
#include "UsdAnari.h"
#include "UsdDevice.h"
#include "anari/frontend/type_utility.h"
DEFINE_PARAMETER_MAP(UsdFrame,
REGISTER_PARAMETER_MACRO("world", ANARI_WORLD, world)
REGISTER_PARAMETER_MACRO("renderer", ANARI_RENDERER, renderer)
REGISTER_PARAMETER_MACRO("size", ANARI_UINT32_VEC2, size)
REGISTER_PARAMETER_MACRO("channel.color", ANARI_DATA_TYPE, color)
REGISTER_PARAMETER_MACRO("channel.depth", ANARI_DATA_TYPE, depth)
)
UsdFrame::UsdFrame(UsdBridge* bridge)
: UsdParameterizedBaseObject<UsdFrame, UsdFrameData>(ANARI_FRAME)
{
}
UsdFrame::~UsdFrame()
{
delete[] mappedColorMem;
delete[] mappedDepthMem;
}
bool UsdFrame::deferCommit(UsdDevice* device)
{
return false;
}
bool UsdFrame::doCommitData(UsdDevice* device)
{
return false;
}
const void* UsdFrame::mapBuffer(const char *channel,
uint32_t *width,
uint32_t *height,
ANARIDataType *pixelType)
{
const UsdFrameData& paramData = getReadParams();
*width = paramData.size.Data[0];
*height = paramData.size.Data[1];
*pixelType = ANARI_UNKNOWN;
if (strEquals(channel, "channel.color"))
{
mappedColorMem = ReserveBuffer(paramData.color);
*pixelType = paramData.color;
return mappedColorMem;
}
else if (strEquals(channel, "channel.depth"))
{
mappedDepthMem = ReserveBuffer(paramData.depth);
*pixelType = paramData.depth;
return mappedDepthMem;
}
*width = 0;
*height = 0;
return nullptr;
}
void UsdFrame::unmapBuffer(const char *channel)
{
if (strEquals(channel, "channel.color"))
{
delete[] mappedColorMem;
mappedColorMem = nullptr;
}
else if (strEquals(channel, "channel.depth"))
{
delete[] mappedDepthMem;
mappedDepthMem = nullptr;
}
}
char* UsdFrame::ReserveBuffer(ANARIDataType format)
{
const UsdFrameData& paramData = getReadParams();
size_t formatSize = anari::sizeOf(format);
size_t memSize = formatSize * paramData.size.Data[0] * paramData.size.Data[1];
return new char[memSize];
}
void UsdFrame::saveUsd(UsdDevice* device)
{
device->getUsdBridge()->SaveScene();
}
| 2,184 | C++ | 22 | 80 | 0.717491 |
NVIDIA-Omniverse/AnariUsdDevice/UsdSampler.h | // Copyright 2020 The Khronos Group
// SPDX-License-Identifier: Apache-2.0
#pragma once
#include "UsdBridgedBaseObject.h"
enum class UsdSamplerComponents
{
DATA = 0,
WRAPS,
WRAPT,
WRAPR
};
struct UsdSamplerData
{
UsdSharedString* name = nullptr;
UsdSharedString* usdName = nullptr;
double timeStep = 0.0;
int timeVarying = 0; // Bitmask indicating which attributes are time-varying.
const UsdDataArray* imageData = nullptr;
UsdSharedString* inAttribute = nullptr;
UsdSharedString* imageUrl = nullptr;
UsdSharedString* wrapS = nullptr;
UsdSharedString* wrapT = nullptr;
UsdSharedString* wrapR = nullptr;
};
class UsdSampler : public UsdBridgedBaseObject<UsdSampler, UsdSamplerData, UsdSamplerHandle, UsdSamplerComponents>
{
protected:
enum SamplerType
{
SAMPLER_UNKNOWN = 0,
SAMPLER_1D,
SAMPLER_2D,
SAMPLER_3D
};
public:
UsdSampler(const char* name, const char* type, UsdDevice* device);
~UsdSampler();
void remove(UsdDevice* device) override;
bool isPerInstance() const { return perInstance; }
void updateBoundParameters(bool boundToInstance, UsdDevice* device);
static constexpr ComponentPair componentParamNames[] = {
ComponentPair(CType::DATA, "image"),
ComponentPair(CType::DATA, "imageUrl"),
ComponentPair(CType::WRAPS, "wrapMode"),
ComponentPair(CType::WRAPS, "wrapMode1"),
ComponentPair(CType::WRAPT, "wrapMode2"),
ComponentPair(CType::WRAPR, "wrapMode3")};
protected:
bool deferCommit(UsdDevice* device) override;
bool doCommitData(UsdDevice* device) override;
void doCommitRefs(UsdDevice* device) override {}
void setSamplerTimeVarying(UsdBridgeSamplerData::DataMemberId& timeVarying);
SamplerType samplerType = SAMPLER_UNKNOWN;
bool perInstance = false; // Whether sampler is attached to a point instancer
bool instanceAttributeAttached = false; // Whether a value to inAttribute has been set which in USD is different between per-instance and regular geometries
}; | 2,050 | C | 27.486111 | 160 | 0.725854 |
NVIDIA-Omniverse/AnariUsdDevice/UsdInstance.h | // Copyright 2020 The Khronos Group
// SPDX-License-Identifier: Apache-2.0
#pragma once
#include "UsdBridgedBaseObject.h"
class UsdGroup;
enum class UsdInstanceComponents
{
GROUP = 0,
TRANSFORM
};
struct UsdInstanceData
{
UsdSharedString* name = nullptr;
UsdSharedString* usdName = nullptr;
int timeVarying = 0xFFFFFFFF; // Bitmask indicating which attributes are time-varying.
UsdGroup* group = nullptr;
UsdFloatMat4 transform;
};
class UsdInstance : public UsdBridgedBaseObject<UsdInstance, UsdInstanceData, UsdInstanceHandle, UsdInstanceComponents>
{
public:
UsdInstance(const char* name,
UsdDevice* device);
~UsdInstance();
void remove(UsdDevice* device) override;
static constexpr ComponentPair componentParamNames[] = {
ComponentPair(UsdInstanceComponents::GROUP, "group"),
ComponentPair(UsdInstanceComponents::TRANSFORM, "transform")};
protected:
bool deferCommit(UsdDevice* device) override;
bool doCommitData(UsdDevice* device) override;
void doCommitRefs(UsdDevice* device) override;
}; | 1,070 | C | 23.906976 | 119 | 0.750467 |
NVIDIA-Omniverse/AnariUsdDevice/UsdDataArray.h | // Copyright 2020 The Khronos Group
// SPDX-License-Identifier: Apache-2.0
#pragma once
#include "UsdBaseObject.h"
#include "UsdParameterizedObject.h"
#include "anari/frontend/anari_enums.h"
class UsdDevice;
struct UsdDataLayout
{
bool isDense() const { return byteStride1 == typeSize && byteStride2 == numItems1*byteStride1 && byteStride3 == numItems2*byteStride2; }
bool isOneDimensional() const { return numItems2 == 1 && numItems3 == 1; }
void copyDims(uint64_t dims[3]) const { std::memcpy(dims, &numItems1, sizeof(uint64_t)*3); }
void copyStride(int64_t stride[3]) const { std::memcpy(stride, &byteStride1, sizeof(int64_t)*3); }
uint64_t typeSize = 0;
uint64_t numItems1 = 0;
uint64_t numItems2 = 0;
uint64_t numItems3 = 0;
int64_t byteStride1 = 0;
int64_t byteStride2 = 0;
int64_t byteStride3 = 0;
};
struct UsdDataArrayParams
{
// Even though we are not dealing with a usd-backed object, the data array can still have an identifying name.
// The pointer can then be used as id for resources (plus defining their filenames) such as textures,
// so they can be shared and still removed during garbage collection (after an UsdAnari object has already been destroyed).
// The persistence reason is why these strings have to be added to the string list of the device on construction.
UsdSharedString* name = nullptr;
UsdSharedString* usdName = nullptr;
};
class UsdDataArray : public UsdParameterizedBaseObject<UsdDataArray, UsdDataArrayParams>
{
public:
UsdDataArray(const void *appMemory,
ANARIMemoryDeleter deleter,
const void *userData,
ANARIDataType dataType,
uint64_t numItems1,
int64_t byteStride1,
uint64_t numItems2,
int64_t byteStride2,
uint64_t numItems3,
int64_t byteStride3,
UsdDevice* device
);
UsdDataArray(ANARIDataType dataType,
uint64_t numItems1,
uint64_t numItems2,
uint64_t numItems3,
UsdDevice* device
);
~UsdDataArray();
void filterSetParam(const char *name,
ANARIDataType type,
const void *mem,
UsdDevice* device) override;
int getProperty(const char *name,
ANARIDataType type,
void *mem,
uint64_t size,
UsdDevice* device) override;
void commit(UsdDevice* device) override;
void remove(UsdDevice* device) override {}
void* map(UsdDevice* device);
void unmap(UsdDevice* device);
void privatize();
const char* getName() const override { return UsdSharedString::c_str(getReadParams().usdName); }
const void* getData() const { return data; }
ANARIDataType getType() const { return type; }
const UsdDataLayout& getLayout() const { return layout; }
size_t getDataSizeInBytes() const { return dataSizeInBytes; }
protected:
bool deferCommit(UsdDevice* device) override { return false; }
bool doCommitData(UsdDevice* device) override { return false; }
void doCommitRefs(UsdDevice* device) override {}
void setLayoutAndSize(uint64_t numItems1,
int64_t byteStride1,
uint64_t numItems2,
int64_t byteStride2,
uint64_t numItems3,
int64_t byteStride3);
bool CheckFormatting(UsdDevice* device);
// Ref manipulation on arrays of anariobjects
void incRef(const ANARIObject* anariObjects, uint64_t numAnariObjects);
void decRef(const ANARIObject* anariObjects, uint64_t numAnariObjects);
// Private memory management
void allocPrivateData();
void freePrivateData(bool mappedCopy = false);
void freePublicData(const void* appMemory);
void publicToPrivateData();
// Mapped memory management
void CreateMappedObjectCopy();
void TransferAndRemoveMappedObjectCopy();
const void* data = nullptr;
ANARIMemoryDeleter dataDeleter = nullptr;
const void* deleterUserData = nullptr;
ANARIDataType type;
UsdDataLayout layout;
size_t dataSizeInBytes;
bool isPrivate;
const void* mappedObjectCopy;
#ifdef CHECK_MEMLEAKS
UsdDevice* allocDevice;
#endif
}; | 4,032 | C | 30.263566 | 138 | 0.708829 |
NVIDIA-Omniverse/AnariUsdDevice/UsdDeviceQueries.h | // Copyright 2021 The Khronos Group
// SPDX-License-Identifier: Apache-2.0
// This file was generated by generate_queries.py
// Don't make changes to this directly
#include <anari/anari.h>
namespace anari {
namespace usd {
#define ANARI_INFO_required 0
#define ANARI_INFO_default 1
#define ANARI_INFO_minimum 2
#define ANARI_INFO_maximum 3
#define ANARI_INFO_description 4
#define ANARI_INFO_elementType 5
#define ANARI_INFO_value 6
#define ANARI_INFO_sourceExtension 7
#define ANARI_INFO_extension 8
#define ANARI_INFO_parameter 9
#define ANARI_INFO_channel 10
#define ANARI_INFO_use 11
const int extension_count = 17;
const char ** query_extensions();
const char ** query_object_types(ANARIDataType type);
const ANARIParameter * query_params(ANARIDataType type, const char *subtype);
const void * query_param_info_enum(ANARIDataType type, const char *subtype, const char *paramName, ANARIDataType paramType, int infoName, ANARIDataType infoType);
const void * query_param_info(ANARIDataType type, const char *subtype, const char *paramName, ANARIDataType paramType, const char *infoNameString, ANARIDataType infoType);
const void * query_object_info_enum(ANARIDataType type, const char *subtype, int infoName, ANARIDataType infoType);
const void * query_object_info(ANARIDataType type, const char *subtype, const char *infoNameString, ANARIDataType infoType);
}
}
| 1,368 | C | 41.781249 | 171 | 0.790205 |
NVIDIA-Omniverse/AnariUsdDevice/UsdDevice.h | // Copyright 2020 The Khronos Group
// SPDX-License-Identifier: Apache-2.0
#pragma once
#include "anari/backend/DeviceImpl.h"
#include "anari/backend/LibraryImpl.h"
#include "UsdBaseObject.h"
#include <vector>
#include <memory>
#ifdef _WIN32
#ifdef anari_library_usd_EXPORTS
#define USDDevice_INTERFACE __declspec(dllexport)
#else
#define USDDevice_INTERFACE __declspec(dllimport)
#endif
#endif
extern "C"
{
#ifdef WIN32
USDDevice_INTERFACE void __cdecl anari_library_usd_init();
#else
void anari_library_usd_init();
#endif
}
class UsdDevice;
class UsdDeviceInternals;
class UsdBaseObject;
class UsdVolume;
struct UsdDeviceData
{
UsdSharedString* hostName = nullptr;
UsdSharedString* outputPath = nullptr;
bool createNewSession = true;
bool outputBinary = false;
bool writeAtCommit = false;
double timeStep = 0.0;
bool outputMaterial = true;
bool outputPreviewSurfaceShader = true;
bool outputMdlShader = true;
};
class UsdDevice : public anari::DeviceImpl, public UsdParameterizedBaseObject<UsdDevice, UsdDeviceData>
{
public:
UsdDevice();
UsdDevice(ANARILibrary library);
~UsdDevice();
///////////////////////////////////////////////////////////////////////////
// Main virtual interface to accepting API calls
///////////////////////////////////////////////////////////////////////////
// Data Arrays ////////////////////////////////////////////////////////////
ANARIArray1D newArray1D(const void *appMemory,
ANARIMemoryDeleter deleter,
const void *userdata,
ANARIDataType,
uint64_t numItems1) override;
ANARIArray2D newArray2D(const void *appMemory,
ANARIMemoryDeleter deleter,
const void *userdata,
ANARIDataType,
uint64_t numItems1,
uint64_t numItems2) override;
ANARIArray3D newArray3D(const void *appMemory,
ANARIMemoryDeleter deleter,
const void *userdata,
ANARIDataType,
uint64_t numItems1,
uint64_t numItems2,
uint64_t numItems3) override;
void* mapArray(ANARIArray) override;
void unmapArray(ANARIArray) override;
// Renderable Objects /////////////////////////////////////////////////////
ANARILight newLight(const char *type) override { return nullptr; }
ANARICamera newCamera(const char *type) override;
ANARIGeometry newGeometry(const char *type);
ANARISpatialField newSpatialField(const char *type) override;
ANARISurface newSurface() override;
ANARIVolume newVolume(const char *type) override;
// Model Meta-Data ////////////////////////////////////////////////////////
ANARIMaterial newMaterial(const char *material_type) override;
ANARISampler newSampler(const char *type) override;
// Instancing /////////////////////////////////////////////////////////////
ANARIGroup newGroup() override;
ANARIInstance newInstance(const char *type) override;
// Top-level Worlds ///////////////////////////////////////////////////////
ANARIWorld newWorld() override;
// Query functions ////////////////////////////////////////////////////////
const char ** getObjectSubtypes(ANARIDataType objectType) override;
const void* getObjectInfo(ANARIDataType objectType,
const char* objectSubtype,
const char* infoName,
ANARIDataType infoType) override;
const void* getParameterInfo(ANARIDataType objectType,
const char* objectSubtype,
const char* parameterName,
ANARIDataType parameterType,
const char* infoName,
ANARIDataType infoType) override;
// Object + Parameter Lifetime Management /////////////////////////////////
void setParameter(ANARIObject object,
const char *name,
ANARIDataType type,
const void *mem) override;
void unsetParameter(ANARIObject object, const char *name) override;
void unsetAllParameters(ANARIObject o) override;
void* mapParameterArray1D(ANARIObject o,
const char* name,
ANARIDataType dataType,
uint64_t numElements1,
uint64_t *elementStride) override;
void* mapParameterArray2D(ANARIObject o,
const char* name,
ANARIDataType dataType,
uint64_t numElements1,
uint64_t numElements2,
uint64_t *elementStride) override;
void* mapParameterArray3D(ANARIObject o,
const char* name,
ANARIDataType dataType,
uint64_t numElements1,
uint64_t numElements2,
uint64_t numElements3,
uint64_t *elementStride) override;
void unmapParameterArray(ANARIObject o,
const char* name) override;
void commitParameters(ANARIObject object) override;
void release(ANARIObject _obj) override;
void retain(ANARIObject _obj) override;
// Object Query Interface /////////////////////////////////////////////////
int getProperty(ANARIObject object,
const char *name,
ANARIDataType type,
void *mem,
uint64_t size,
uint32_t mask) override;
// FrameBuffer Manipulation ///////////////////////////////////////////////
ANARIFrame newFrame() override;
const void *frameBufferMap(ANARIFrame fb,
const char *channel,
uint32_t *width,
uint32_t *height,
ANARIDataType *pixelType) override;
void frameBufferUnmap(ANARIFrame fb, const char *channel) override;
// Frame Rendering ////////////////////////////////////////////////////////
ANARIRenderer newRenderer(const char *type) override;
void renderFrame(ANARIFrame frame) override;
int frameReady(ANARIFrame, ANARIWaitMask) override { return 1; }
void discardFrame(ANARIFrame) override {}
// UsdParameterizedBaseObject interface ///////////////////////////////////////////////////////////
void filterSetParam(
const char *name,
ANARIDataType type,
const void *mem,
UsdDevice* device) override;
void filterResetParam(
const char *name) override;
void commit(UsdDevice* device) override;
void remove(UsdDevice* device) override {}
// USD Specific ///////////////////////////////////////////////////////////
bool isInitialized() { return getUsdBridge() != nullptr; }
UsdBridge* getUsdBridge();
bool nameExists(const char* name);
void addToCommitList(UsdBaseObject* object, bool commitData);
bool isFlushingCommitList() const { return lockCommitList; }
void addToVolumeList(UsdVolume* volume);
void removeFromVolumeList(UsdVolume* volume);
// Allows for selected strings to persist,
// so their pointers can be cached beyond their containing objects' lifetimes,
// to be used for garbage collecting resource files.
void addToResourceStringList(UsdSharedString* sharedString);
#ifdef CHECK_MEMLEAKS
// Memleak checking
void LogObjAllocation(const UsdBaseObject* ptr);
void LogObjDeallocation(const UsdBaseObject* ptr);
std::vector<const UsdBaseObject*> allocatedObjects;
void LogStrAllocation(const UsdSharedString* ptr);
void LogStrDeallocation(const UsdSharedString* ptr);
std::vector<const UsdSharedString*> allocatedStrings;
void LogRawAllocation(const void* ptr);
void LogRawDeallocation(const void* ptr);
std::vector<const void*> allocatedRawMemory;
#endif
void reportStatus(void* source,
ANARIDataType sourceType,
ANARIStatusSeverity severity,
ANARIStatusCode statusCode,
const char *format, ...);
void reportStatus(void* source,
ANARIDataType sourceType,
ANARIStatusSeverity severity,
ANARIStatusCode statusCode,
const char *format,
va_list& arglist);
protected:
UsdBaseObject* getBaseObjectPtr(ANARIObject object);
// UsdParameterizedBaseObject interface ///////////////////////////////////////////////////////////
bool deferCommit(UsdDevice* device) { return false; };
bool doCommitData(UsdDevice* device) { return false; };
void doCommitRefs(UsdDevice* device) {};
// USD Specific Cleanup /////////////////////////////////////////////////////////////
void clearCommitList();
void flushCommitList();
void clearDeviceParameters();
void clearResourceStringList();
void initializeBridge();
const char* makeUniqueName(const char* name);
ANARIArray CreateDataArray(const void *appMemory,
ANARIMemoryDeleter deleter,
const void *userData,
ANARIDataType dataType,
uint64_t numItems1,
int64_t byteStride1,
uint64_t numItems2,
int64_t byteStride2,
uint64_t numItems3,
int64_t byteStride3);
template<int typeInt>
void writeTypeToUsd();
void removePrimsFromUsd(bool onlyRemoveHandles = false);
std::unique_ptr<UsdDeviceInternals> internals;
bool bridgeInitAttempt = false;
// Using object pointers as basis for deferred commits; another option would be to traverse
// the bridge's internal cache handles, but a handle may map to multiple objects (with the same name)
// so that's not 1-1 with the effects of a non-deferred commit order.
using CommitListType = std::pair<helium::IntrusivePtr<UsdBaseObject>, bool>;
std::vector<CommitListType> commitList;
std::vector<UsdBaseObject*> removeList;
std::vector<UsdVolume*> volumeList; // Tracks all volumes to auto-commit when child fields have been committed
bool lockCommitList = false;
std::vector<helium::IntrusivePtr<UsdSharedString>> resourceStringList;
ANARIStatusCallback statusFunc = nullptr;
const void* statusUserData = nullptr;
ANARIStatusCallback userSetStatusFunc = nullptr;
const void* userSetStatusUserData = nullptr;
std::vector<char> lastStatusMessage;
};
| 9,712 | C | 30.031949 | 114 | 0.643637 |
NVIDIA-Omniverse/AnariUsdDevice/UsdCamera.h | // Copyright 2020 The Khronos Group
// SPDX-License-Identifier: Apache-2.0
#pragma once
#include "UsdBaseObject.h"
#include "UsdBridgedBaseObject.h"
enum class UsdCameraComponents
{
VIEW = 0,
PROJECTION
};
struct UsdCameraData
{
UsdSharedString* name = nullptr;
UsdSharedString* usdName = nullptr;
int timeVarying = 0xFFFFFFFF; // TimeVarying bits
UsdFloat3 position = {0.0f, 0.0f, 0.0f};
UsdFloat3 direction = {0.0f, 0.0f, -1.0f};
UsdFloat3 up = {0.0f, 1.0f, 0.0f};
UsdFloatBox2 imageRegion = {0.0f, 0.0f, 1.0f, 1.0f};
// perspective/orthographic
float aspect = 1.0f;
float near = 1.0f;
float far = 10000;
float fovy = M_PI/3.0f;
float height = 1.0f;
};
class UsdCamera : public UsdBridgedBaseObject<UsdCamera, UsdCameraData, UsdCameraHandle, UsdCameraComponents>
{
public:
UsdCamera(const char* name, const char* type, UsdDevice* device);
~UsdCamera();
void remove(UsdDevice* device) override;
enum CameraType
{
CAMERA_UNKNOWN = 0,
CAMERA_PERSPECTIVE,
CAMERA_ORTHOGRAPHIC
};
static constexpr ComponentPair componentParamNames[] = {
ComponentPair(UsdCameraComponents::VIEW, "view"),
ComponentPair(UsdCameraComponents::PROJECTION, "projection")};
protected:
bool deferCommit(UsdDevice* device) override;
bool doCommitData(UsdDevice* device) override;
void doCommitRefs(UsdDevice* device) override {}
void copyParameters(UsdBridgeCameraData& camData);
CameraType cameraType = CAMERA_UNKNOWN;
}; | 1,521 | C | 23.548387 | 109 | 0.702827 |
NVIDIA-Omniverse/AnariUsdDevice/UsdDeviceUtils.h | // Copyright 2020 The Khronos Group
// SPDX-License-Identifier: Apache-2.0
#pragma once
#include <vector>
#include <memory>
template<typename ValueType, typename ContainerType = std::vector<ValueType>>
struct OptionalList
{
void ensureList()
{
if(!list)
list = std::make_unique<ContainerType>();
}
void clear()
{
if(list)
list->resize(0);
}
void push_back(const ValueType& value)
{
ensureList();
list->push_back(value);
}
void emplace_back(const ValueType& value)
{
ensureList();
list->emplace_back(value);
}
const ValueType* data()
{
if(list)
return list->data();
return nullptr;
}
size_t size()
{
if(list)
return list->size();
return 0;
}
std::unique_ptr<ContainerType> list;
}; | 796 | C | 14.627451 | 77 | 0.614322 |
NVIDIA-Omniverse/AnariUsdDevice/UsdSurface.h | // Copyright 2020 The Khronos Group
// SPDX-License-Identifier: Apache-2.0
#pragma once
#include "UsdBridgedBaseObject.h"
#include <limits>
class UsdGeometry;
class UsdMaterial;
struct UsdSurfaceData
{
UsdSharedString* name = nullptr;
UsdSharedString* usdName = nullptr;
// No timevarying data: geometry and material reference always set over all timesteps
UsdGeometry* geometry = nullptr;
UsdMaterial* material = nullptr;
double geometryRefTimeStep = std::numeric_limits<float>::quiet_NaN();
double materialRefTimeStep = std::numeric_limits<float>::quiet_NaN();
};
class UsdSurface : public UsdBridgedBaseObject<UsdSurface, UsdSurfaceData, UsdSurfaceHandle>
{
public:
UsdSurface(const char* name, UsdDevice* device);
~UsdSurface();
void remove(UsdDevice* device) override;
protected:
bool deferCommit(UsdDevice* device) override;
bool doCommitData(UsdDevice* device) override;
void doCommitRefs(UsdDevice* device) override;
}; | 980 | C | 24.153846 | 92 | 0.753061 |
NVIDIA-Omniverse/AnariUsdDevice/UsdVolume.h | // Copyright 2020 The Khronos Group
// SPDX-License-Identifier: Apache-2.0
#pragma once
#include "UsdBridgedBaseObject.h"
#include <limits>
class UsdSpatialField;
class UsdDevice;
class UsdDataArray;
enum class UsdVolumeComponents
{
COLOR = 0,
OPACITY,
VALUERANGE
};
struct UsdVolumeData
{
UsdSharedString* name = nullptr;
UsdSharedString* usdName = nullptr;
int timeVarying = 0xFFFFFFFF; // Bitmask indicating which attributes are time-varying. (field reference always set over all timesteps)
UsdSpatialField* field = nullptr;
double fieldRefTimeStep = std::numeric_limits<float>::quiet_NaN();
bool preClassified = false;
//TF params
const UsdDataArray* color = nullptr;
const UsdDataArray* opacity = nullptr;
UsdFloatBox1 valueRange = { 0.0f, 1.0f };
float unitDistance = 1.0f;
};
class UsdVolume : public UsdBridgedBaseObject<UsdVolume, UsdVolumeData, UsdVolumeHandle, UsdVolumeComponents>
{
public:
UsdVolume(const char* name, UsdDevice* device);
~UsdVolume();
void remove(UsdDevice* device) override;
static constexpr ComponentPair componentParamNames[] = {
ComponentPair(UsdVolumeComponents::COLOR, "color"),
ComponentPair(UsdVolumeComponents::OPACITY, "opacity"),
ComponentPair(UsdVolumeComponents::VALUERANGE, "valueRange")};
protected:
bool deferCommit(UsdDevice* device) override;
bool doCommitData(UsdDevice* device) override;
void doCommitRefs(UsdDevice* device) override {}
bool CheckTfParams(UsdDevice* device);
bool UpdateVolume(UsdDevice* device, const char* debugName);
UsdSpatialField* prevField = nullptr;
UsdDevice* usdDevice = nullptr;
}; | 1,669 | C | 25.507936 | 136 | 0.742361 |
NVIDIA-Omniverse/AnariUsdDevice/UsdDataArray.cpp | // Copyright 2020 The Khronos Group
// SPDX-License-Identifier: Apache-2.0
#include "UsdDataArray.h"
#include "UsdDevice.h"
#include "UsdAnari.h"
#include "anari/frontend/type_utility.h"
DEFINE_PARAMETER_MAP(UsdDataArray,
REGISTER_PARAMETER_MACRO("name", ANARI_STRING, name)
REGISTER_PARAMETER_MACRO("usd::name", ANARI_STRING, usdName)
)
#define TO_OBJ_PTR reinterpret_cast<const ANARIObject*>
UsdDataArray::UsdDataArray(const void *appMemory,
ANARIMemoryDeleter deleter,
const void *userData,
ANARIDataType dataType,
uint64_t numItems1,
int64_t byteStride1,
uint64_t numItems2,
int64_t byteStride2,
uint64_t numItems3,
int64_t byteStride3,
UsdDevice* device
)
: UsdParameterizedBaseObject<UsdDataArray, UsdDataArrayParams>(ANARI_ARRAY)
, data(appMemory)
, dataDeleter(deleter)
, deleterUserData(userData)
, type(dataType)
, isPrivate(false)
#ifdef CHECK_MEMLEAKS
, allocDevice(device)
#endif
{
setLayoutAndSize(numItems1, byteStride1, numItems2, byteStride2, numItems3, byteStride3);
if (CheckFormatting(device))
{
// Make sure to incref all anari objects in case of object array
if (anari::isObject(type))
{
incRef(TO_OBJ_PTR(data), layout.numItems1);
}
}
}
UsdDataArray::UsdDataArray(ANARIDataType dataType, uint64_t numItems1, uint64_t numItems2, uint64_t numItems3, UsdDevice* device)
: UsdParameterizedBaseObject<UsdDataArray, UsdDataArrayParams>(ANARI_ARRAY)
, type(dataType)
, isPrivate(true)
#ifdef CHECK_MEMLEAKS
, allocDevice(device)
#endif
{
setLayoutAndSize(numItems1, 0, numItems2, 0, numItems3, 0);
if (CheckFormatting(device))
{
allocPrivateData();
}
}
UsdDataArray::~UsdDataArray()
{
// Decref anari objects in case of object array
if (anari::isObject(type))
{
decRef(TO_OBJ_PTR(data), layout.numItems1);
}
if (isPrivate)
{
freePrivateData();
}
else
{
freePublicData(data);
}
}
void UsdDataArray::filterSetParam(const char *name,
ANARIDataType type,
const void *mem,
UsdDevice* device)
{
if(setNameParam(name, type, mem, device))
device->addToResourceStringList(getWriteParams().usdName); //Name is kept for the lifetime of the device (to allow using pointer for caching resource's names)
}
int UsdDataArray::getProperty(const char * name, ANARIDataType type, void * mem, uint64_t size, UsdDevice* device)
{
int nameResult = getNameProperty(name, type, mem, size, device);
return nameResult;
}
void UsdDataArray::commit(UsdDevice* device)
{
if (anari::isObject(type) && (layout.numItems2 != 1 || layout.numItems3 != 1))
device->reportStatus(this, ANARI_ARRAY, ANARI_SEVERITY_ERROR, ANARI_STATUS_INVALID_ARGUMENT,
"UsdDataArray only supports one-dimensional ANARI_OBJECT arrays");
UsdParameterizedBaseObject<UsdDataArray, UsdDataArrayParams>::commit(device);
}
void * UsdDataArray::map(UsdDevice * device)
{
if (anari::isObject(type))
{
CreateMappedObjectCopy();
}
return const_cast<void *>(data);
}
void UsdDataArray::unmap(UsdDevice * device)
{
if (anari::isObject(type))
{
TransferAndRemoveMappedObjectCopy();
}
}
void UsdDataArray::privatize()
{
if(!isPrivate)
{
publicToPrivateData();
isPrivate = true;
}
}
void UsdDataArray::setLayoutAndSize(uint64_t numItems1,
int64_t byteStride1,
uint64_t numItems2,
int64_t byteStride2,
uint64_t numItems3,
int64_t byteStride3)
{
size_t typeSize = anari::sizeOf(type);
if (byteStride1 == 0)
byteStride1 = typeSize;
if (byteStride2 == 0)
byteStride2 = byteStride1 * numItems1;
if (byteStride3 == 0)
byteStride3 = byteStride2 * numItems2;
dataSizeInBytes = byteStride3 * numItems3 - (byteStride1 - typeSize);
layout = { typeSize, numItems1, numItems2, numItems3, byteStride1, byteStride2, byteStride3 };
}
bool UsdDataArray::CheckFormatting(UsdDevice* device)
{
if (anari::isObject(type))
{
if (!layout.isDense() || !layout.isOneDimensional())
{
device->reportStatus(this, ANARI_ARRAY, ANARI_SEVERITY_ERROR, ANARI_STATUS_INVALID_ARGUMENT, "UsdDataArray construction failed: arrays with object type have to be one dimensional and without stride.");
layout.numItems1 = layout.numItems2 = layout.numItems3 = 0;
data = nullptr;
type = ANARI_UNKNOWN;
return false;
}
}
return true;
}
void UsdDataArray::incRef(const ANARIObject* anariObjects, uint64_t numAnariObjects)
{
for (int i = 0; i < numAnariObjects; ++i)
{
const UsdBaseObject* baseObj = (reinterpret_cast<const UsdBaseObject*>(anariObjects[i]));
if (baseObj)
baseObj->refInc(helium::RefType::INTERNAL);
}
}
void UsdDataArray::decRef(const ANARIObject* anariObjects, uint64_t numAnariObjects)
{
for (int i = 0; i < numAnariObjects; ++i)
{
const UsdBaseObject* baseObj = (reinterpret_cast<const UsdBaseObject*>(anariObjects[i]));
#ifdef CHECK_MEMLEAKS
allocDevice->LogObjDeallocation(baseObj);
#endif
if (baseObj)
{
assert(baseObj->useCount(helium::RefType::INTERNAL) > 0);
baseObj->refDec(helium::RefType::INTERNAL);
}
}
}
void UsdDataArray::allocPrivateData()
{
// Alloc the owned memory
char* newData = new char[dataSizeInBytes];
memset(newData, 0, dataSizeInBytes);
data = newData;
#ifdef CHECK_MEMLEAKS
allocDevice->LogRawAllocation(newData);
#endif
}
void UsdDataArray::freePrivateData(bool mappedCopy)
{
const void*& memToFree = mappedCopy ? mappedObjectCopy : data;
#ifdef CHECK_MEMLEAKS
allocDevice->LogRawDeallocation(memToFree);
#endif
// Deallocate owned memory
delete[](char*)memToFree;
memToFree = nullptr;
}
void UsdDataArray::freePublicData(const void* appMemory)
{
if (dataDeleter)
{
dataDeleter(deleterUserData, appMemory);
dataDeleter = nullptr;
}
}
void UsdDataArray::publicToPrivateData()
{
// Alloc private dest, copy appMemory src to it
const void* appMemory = data;
allocPrivateData();
std::memcpy(const_cast<void *>(data), appMemory, dataSizeInBytes); // In case of object array, Refcount 'transfers' to the copy (splits off user-managed public refcount)
// Delete appMemory if appropriate
freePublicData(appMemory);
// No refcount modification necessary, public refcount managed by user
}
void UsdDataArray::CreateMappedObjectCopy()
{
// Move the original array to a different spot and allocate new memory for the mapped object array.
mappedObjectCopy = data;
allocPrivateData();
// Transfer contents over to new memory, keep old one for managing references later on.
std::memcpy(const_cast<void *>(data), mappedObjectCopy, dataSizeInBytes);
}
void UsdDataArray::TransferAndRemoveMappedObjectCopy()
{
const ANARIObject* newAnariObjects = TO_OBJ_PTR(data);
const ANARIObject* oldAnariObjects = TO_OBJ_PTR(mappedObjectCopy);
uint64_t numAnariObjects = layout.numItems1;
// First, increase reference counts of all objects that different in the new object array
for (int i = 0; i < numAnariObjects; ++i)
{
const UsdBaseObject* newObj = (reinterpret_cast<const UsdBaseObject*>(newAnariObjects[i]));
const UsdBaseObject* oldObj = (reinterpret_cast<const UsdBaseObject*>(oldAnariObjects[i]));
if (newObj != oldObj && newObj)
newObj->refInc(helium::RefType::INTERNAL);
}
// Then, decrease reference counts of all objects that are different in the original array (which will delete those that not referenced anymore)
for (int i = 0; i < numAnariObjects; ++i)
{
const UsdBaseObject* newObj = (reinterpret_cast<const UsdBaseObject*>(newAnariObjects[i]));
const UsdBaseObject* oldObj = (reinterpret_cast<const UsdBaseObject*>(oldAnariObjects[i]));
if (newObj != oldObj && oldObj)
{
#ifdef CHECK_MEMLEAKS
allocDevice->LogObjDeallocation(oldObj);
#endif
oldObj->refDec(helium::RefType::INTERNAL);
}
}
// Release the mapped object copy's allocated memory
freePrivateData(true);
}
| 7,904 | C++ | 26.258621 | 207 | 0.721407 |
NVIDIA-Omniverse/AnariUsdDevice/UsdInstance.cpp | // Copyright 2020 The Khronos Group
// SPDX-License-Identifier: Apache-2.0
#include "UsdInstance.h"
#include "UsdAnari.h"
#include "UsdDevice.h"
#include "UsdGroup.h"
#define GroupType ANARI_GROUP
using GroupUsdType = AnariToUsdBridgedObject<GroupType>::Type;
DEFINE_PARAMETER_MAP(UsdInstance,
REGISTER_PARAMETER_MACRO("name", ANARI_STRING, name)
REGISTER_PARAMETER_MACRO("usd::name", ANARI_STRING, usdName)
REGISTER_PARAMETER_MACRO("usd::timeVarying", ANARI_INT32, timeVarying)
REGISTER_PARAMETER_MACRO("group", GroupType, group)
REGISTER_PARAMETER_MACRO("transform", ANARI_FLOAT32_MAT4, transform)
)
constexpr UsdInstance::ComponentPair UsdInstance::componentParamNames[]; // Workaround for C++14's lack of inlining constexpr arrays
UsdInstance::UsdInstance(const char* name,
UsdDevice* device)
: BridgedBaseObjectType(ANARI_INSTANCE, name, device)
{
}
UsdInstance::~UsdInstance()
{
#ifdef OBJECT_LIFETIME_EQUALS_USD_LIFETIME
if(cachedBridge)
cachedBridge->DeleteInstance(usdHandle);
#endif
}
void UsdInstance::remove(UsdDevice* device)
{
applyRemoveFunc(device, &UsdBridge::DeleteInstance);
}
bool UsdInstance::deferCommit(UsdDevice* device)
{
const UsdInstanceData& paramData = getReadParams();
if(UsdObjectNotInitialized<GroupUsdType>(paramData.group))
{
return true;
}
return false;
}
bool UsdInstance::doCommitData(UsdDevice* device)
{
UsdBridge* usdBridge = device->getUsdBridge();
const char* instanceName = getName();
bool isNew = false;
if (!usdHandle.value)
isNew = usdBridge->CreateInstance(instanceName, usdHandle);
if (paramChanged || isNew)
{
doCommitRefs(device); // Perform immediate commit of refs - no params from children required
paramChanged = false;
}
return false;
}
void UsdInstance::doCommitRefs(UsdDevice* device)
{
UsdBridge* usdBridge = device->getUsdBridge();
const UsdInstanceData& paramData = getReadParams();
double timeStep = device->getReadParams().timeStep;
bool groupTimeVarying = isTimeVarying(UsdInstanceComponents::GROUP);
bool transformTimeVarying = isTimeVarying(UsdInstanceComponents::TRANSFORM);
if (paramData.group)
{
usdBridge->SetGroupRef(usdHandle, paramData.group->getUsdHandle(), groupTimeVarying, timeStep);
}
else
{
usdBridge->DeleteGroupRef(usdHandle, groupTimeVarying, timeStep);
}
usdBridge->SetInstanceTransform(usdHandle, paramData.transform.Data, transformTimeVarying, timeStep);
} | 2,456 | C++ | 25.706521 | 132 | 0.757329 |
NVIDIA-Omniverse/AnariUsdDevice/UsdGeometry.cpp | // Copyright 2020 The Khronos Group
// SPDX-License-Identifier: Apache-2.0
#include "UsdGeometry.h"
#include "UsdAnari.h"
#include "UsdDataArray.h"
#include "UsdDevice.h"
#include "UsdBridgeUtils.h"
#include "anari/frontend/type_utility.h"
#include <cmath>
DEFINE_PARAMETER_MAP(UsdGeometry,
REGISTER_PARAMETER_MACRO("name", ANARI_STRING, name)
REGISTER_PARAMETER_MACRO("usd::name", ANARI_STRING, usdName)
REGISTER_PARAMETER_MACRO("usd::time", ANARI_FLOAT64, timeStep)
REGISTER_PARAMETER_MACRO("usd::timeVarying", ANARI_INT32, timeVarying)
REGISTER_PARAMETER_MACRO("usd::time.shapeGeometry", ANARI_FLOAT64, shapeGeometryRefTimeStep)
REGISTER_PARAMETER_MACRO("usd::useUsdGeomPoints", ANARI_BOOL, UseUsdGeomPoints)
REGISTER_PARAMETER_MACRO("primitive.index", ANARI_ARRAY, indices)
REGISTER_PARAMETER_MACRO("primitive.normal", ANARI_ARRAY, primitiveNormals)
REGISTER_PARAMETER_MACRO("primitive.color", ANARI_ARRAY, primitiveColors)
REGISTER_PARAMETER_MACRO("primitive.radius", ANARI_ARRAY, primitiveRadii)
REGISTER_PARAMETER_MACRO("primitive.scale", ANARI_ARRAY, primitiveScales)
REGISTER_PARAMETER_MACRO("primitive.orientation", ANARI_ARRAY, primitiveOrientations)
REGISTER_PARAMETER_ARRAY_MACRO("primitive.attribute", "", ANARI_ARRAY, primitiveAttributes, MAX_ATTRIBS)
REGISTER_PARAMETER_MACRO("primitive.id", ANARI_ARRAY, primitiveIds)
REGISTER_PARAMETER_MACRO("vertex.position", ANARI_ARRAY, vertexPositions)
REGISTER_PARAMETER_MACRO("vertex.normal", ANARI_ARRAY, vertexNormals)
REGISTER_PARAMETER_MACRO("vertex.color", ANARI_ARRAY, vertexColors)
REGISTER_PARAMETER_MACRO("vertex.radius", ANARI_ARRAY, vertexRadii)
REGISTER_PARAMETER_MACRO("vertex.scale", ANARI_ARRAY, vertexScales)
REGISTER_PARAMETER_MACRO("vertex.orientation", ANARI_ARRAY, vertexOrientations)
REGISTER_PARAMETER_ARRAY_MACRO("vertex.attribute", "", ANARI_ARRAY, vertexAttributes, MAX_ATTRIBS)
REGISTER_PARAMETER_ARRAY_MACRO("usd::attribute", ".name", ANARI_STRING, attributeNames, MAX_ATTRIBS)
REGISTER_PARAMETER_MACRO("radius", ANARI_FLOAT32, radiusConstant)
REGISTER_PARAMETER_MACRO("scale", ANARI_FLOAT32_VEC3, scaleConstant)
REGISTER_PARAMETER_MACRO("orientation", ANARI_FLOAT32_QUAT_IJKW, orientationConstant)
REGISTER_PARAMETER_MACRO("shapeType", ANARI_STRING, shapeType)
REGISTER_PARAMETER_MACRO("shapeGeometry", ANARI_GEOMETRY, shapeGeometry)
REGISTER_PARAMETER_MACRO("shapeTransform", ANARI_FLOAT32_MAT4, shapeTransform)
) // See .h for usage.
constexpr UsdGeometry::ComponentPair UsdGeometry::componentParamNames[]; // Workaround for C++14's lack of inlining constexpr arrays
struct UsdGeometryTempArrays
{
UsdGeometryTempArrays(const UsdGeometry::AttributeArray& attributes)
: Attributes(attributes)
{}
std::vector<int> CurveLengths;
std::vector<float> PointsArray;
std::vector<float> NormalsArray;
std::vector<float> RadiiArray;
std::vector<float> ScalesArray;
std::vector<float> OrientationsArray;
std::vector<int64_t> IdsArray;
std::vector<int64_t> InvisIdsArray;
std::vector<char> ColorsArray; // generic byte array
ANARIDataType ColorsArrayType;
UsdGeometry::AttributeDataArraysType AttributeDataArrays;
const UsdGeometry::AttributeArray& Attributes;
void resetColorsArray(size_t numElements, ANARIDataType type)
{
ColorsArray.resize(numElements*anari::sizeOf(type));
ColorsArrayType = type;
}
void reserveColorsArray(size_t numElements)
{
ColorsArray.reserve(numElements*anari::sizeOf(ColorsArrayType));
}
size_t expandColorsArray(size_t numElements)
{
size_t startByte = ColorsArray.size();
size_t typeSize = anari::sizeOf(ColorsArrayType);
ColorsArray.resize(startByte+numElements*typeSize);
return startByte/typeSize;
}
void copyToColorsArray(const void* source, size_t srcIdx, size_t destIdx, size_t numElements)
{
size_t typeSize = anari::sizeOf(ColorsArrayType);
size_t srcStart = srcIdx*typeSize;
size_t dstStart = destIdx*typeSize;
size_t numBytes = numElements*typeSize;
assert(dstStart+numBytes <= ColorsArray.size());
memcpy(ColorsArray.data()+dstStart, reinterpret_cast<const char*>(source)+srcStart, numBytes);
}
void resetAttributeDataArray(size_t attribIdx, size_t numElements)
{
if(Attributes[attribIdx].Data)
{
uint32_t eltSize = Attributes[attribIdx].EltSize;
AttributeDataArrays[attribIdx].resize(numElements*eltSize);
}
else
AttributeDataArrays[attribIdx].resize(0);
}
void reserveAttributeDataArray(size_t attribIdx, size_t numElements)
{
if(Attributes[attribIdx].Data)
{
uint32_t eltSize = Attributes[attribIdx].EltSize;
AttributeDataArrays[attribIdx].reserve(numElements*eltSize);
}
}
size_t expandAttributeDataArray(size_t attribIdx, size_t numElements)
{
if(Attributes[attribIdx].Data)
{
uint32_t eltSize = Attributes[attribIdx].EltSize;
size_t startByte = AttributeDataArrays[attribIdx].size();
AttributeDataArrays[attribIdx].resize(startByte+numElements*eltSize);
return startByte/eltSize;
}
return 0;
}
void copyToAttributeDataArray(size_t attribIdx, size_t srcIdx, size_t destIdx, size_t numElements)
{
if(Attributes[attribIdx].Data)
{
uint32_t eltSize = Attributes[attribIdx].EltSize;
const void* attribSrc = reinterpret_cast<const char*>(Attributes[attribIdx].Data) + srcIdx*eltSize;
size_t dstStart = destIdx*eltSize;
size_t numBytes = numElements*eltSize;
assert(dstStart+numBytes <= AttributeDataArrays[attribIdx].size());
void* attribDest = &AttributeDataArrays[attribIdx][dstStart];
memcpy(attribDest, attribSrc, numElements*eltSize);
}
}
};
namespace
{
struct UsdGeometryDebugData
{
UsdDevice* device = nullptr;
UsdGeometry* geometry = nullptr;
const char* debugName = nullptr;
};
UsdGeometry::GeomType GetGeomType(const char* type)
{
UsdGeometry::GeomType geomType;
if (strEquals(type, "sphere"))
geomType = UsdGeometry::GEOM_SPHERE;
else if (strEquals(type, "cylinder"))
geomType = UsdGeometry::GEOM_CYLINDER;
else if (strEquals(type, "cone"))
geomType = UsdGeometry::GEOM_CONE;
else if (strEquals(type, "curve"))
geomType = UsdGeometry::GEOM_CURVE;
else if(strEquals(type, "triangle"))
geomType = UsdGeometry::GEOM_TRIANGLE;
else if (strEquals(type, "quad"))
geomType = UsdGeometry::GEOM_QUAD;
else if (strEquals(type, "glyph"))
geomType = UsdGeometry::GEOM_GLYPH;
else
geomType = UsdGeometry::GEOM_UNKNOWN;
return geomType;
}
uint64_t GetNumberOfPrims(bool hasIndices, const UsdDataLayout& indexLayout, UsdGeometry::GeomType geomType)
{
if(geomType == UsdGeometry::GEOM_CURVE)
return indexLayout.numItems1 - 1;
else if(hasIndices)
return indexLayout.numItems1;
int perPrimVertexCount = 1;
switch(geomType)
{
case UsdGeometry::GEOM_CYLINDER:
case UsdGeometry::GEOM_CONE:
perPrimVertexCount = 2;
break;
case UsdGeometry::GEOM_TRIANGLE:
perPrimVertexCount = 3;
break;
case UsdGeometry::GEOM_QUAD:
perPrimVertexCount = 4;
break;
default: break;
};
return indexLayout.numItems1 / perPrimVertexCount;
}
bool isBitSet(int value, int bit)
{
return (bool)(value & (1 << bit));
}
size_t getIndex(const void* indices, ANARIDataType type, size_t elt)
{
size_t result;
switch (type)
{
case ANARI_INT32:
case ANARI_INT32_VEC2:
result = (reinterpret_cast<const int*>(indices))[elt];
break;
case ANARI_UINT32:
case ANARI_UINT32_VEC2:
result = (reinterpret_cast<const uint32_t*>(indices))[elt];
break;
case ANARI_INT64:
case ANARI_INT64_VEC2:
result = (reinterpret_cast<const int64_t*>(indices))[elt];
break;
case ANARI_UINT64:
case ANARI_UINT64_VEC2:
result = (reinterpret_cast<const uint64_t*>(indices))[elt];
break;
default:
result = 0;
break;
}
return result;
}
void getValues1(const void* vertices, ANARIDataType type, size_t idx, float* result)
{
if (type == ANARI_FLOAT32)
{
const float* vertf = reinterpret_cast<const float*>(vertices);
result[0] = vertf[idx];
}
else if (type == ANARI_FLOAT64)
{
const double* vertd = reinterpret_cast<const double*>(vertices);
result[0] = (float)vertd[idx];
}
}
void getValues2(const void* vertices, ANARIDataType type, size_t idx, float* result)
{
if (type == ANARI_FLOAT32_VEC2)
{
const float* vertf = reinterpret_cast<const float*>(vertices);
result[0] = vertf[idx * 2];
result[1] = vertf[idx * 2 + 1];
}
else if (type == ANARI_FLOAT64_VEC2)
{
const double* vertd = reinterpret_cast<const double*>(vertices);
result[0] = (float)vertd[idx * 2];
result[1] = (float)vertd[idx * 2 + 1];
}
}
void getValues3(const void* vertices, ANARIDataType type, size_t idx, float* result)
{
if (type == ANARI_FLOAT32_VEC3)
{
const float* vertf = reinterpret_cast<const float*>(vertices);
result[0] = vertf[idx * 3];
result[1] = vertf[idx * 3 + 1];
result[2] = vertf[idx * 3 + 2];
}
else if (type == ANARI_FLOAT64_VEC3)
{
const double* vertd = reinterpret_cast<const double*>(vertices);
result[0] = (float)vertd[idx * 3];
result[1] = (float)vertd[idx * 3 + 1];
result[2] = (float)vertd[idx * 3 + 2];
}
}
void getValues4(const void* vertices, ANARIDataType type, size_t idx, float* result)
{
if (type == ANARI_FLOAT32_VEC4)
{
const float* vertf = reinterpret_cast<const float*>(vertices);
result[0] = vertf[idx * 4];
result[1] = vertf[idx * 4 + 1];
result[2] = vertf[idx * 4 + 2];
result[3] = vertf[idx * 4 + 3];
}
else if (type == ANARI_FLOAT64_VEC4)
{
const double* vertd = reinterpret_cast<const double*>(vertices);
result[0] = (float)vertd[idx * 4];
result[1] = (float)vertd[idx * 4 + 1];
result[2] = (float)vertd[idx * 4 + 2];
result[3] = (float)vertd[idx * 4 + 3];
}
}
void generateIndexedSphereData(const UsdGeometryData& paramData, const UsdGeometry::AttributeArray& attributeArray, UsdGeometryTempArrays* tempArrays)
{
if (paramData.indices)
{
auto& attribDataArrays = tempArrays->AttributeDataArrays;
assert(attribDataArrays.size() == attributeArray.size());
uint64_t numVertices = paramData.vertexPositions->getLayout().numItems1;
ANARIDataType scaleType = paramData.vertexScales ? paramData.vertexScales->getType()
: (paramData.primitiveScales ? paramData.primitiveScales->getType() : ANARI_UNKNOWN);
size_t scaleComps = anari::componentsOf(scaleType);
bool perPrimNormals = !paramData.vertexNormals && paramData.primitiveNormals;
bool perPrimRadii = !paramData.vertexRadii && paramData.primitiveRadii;
bool perPrimScales = !paramData.vertexScales && paramData.primitiveScales;
bool perPrimColors = !paramData.vertexColors && paramData.primitiveColors;
bool perPrimOrientations = !paramData.vertexOrientations && paramData.primitiveOrientations;
ANARIDataType colorType = perPrimColors ? paramData.primitiveColors->getType() : ANARI_UINT8; // Vertex colors aren't reordered
// Effectively only has to reorder if the source array is perPrim, otherwise this function effectively falls through and the source array is assigned directly at parent scope.
tempArrays->NormalsArray.resize(perPrimNormals ? numVertices*3 : 0);
tempArrays->RadiiArray.resize(perPrimScales ? numVertices : 0);
tempArrays->ScalesArray.resize(perPrimScales ? numVertices*scaleComps : 0);
tempArrays->OrientationsArray.resize(perPrimOrientations ? numVertices*4 : 0);
tempArrays->IdsArray.resize(numVertices, -1); // Always filled, since indices implies necessity for invisibleIds, and therefore also an Id array
tempArrays->resetColorsArray(perPrimColors ? numVertices : 0, colorType);
for(size_t attribIdx = 0; attribIdx < attribDataArrays.size(); ++attribIdx)
{
tempArrays->resetAttributeDataArray(attribIdx, attributeArray[attribIdx].PerPrimData ? numVertices : 0);
}
const void* indices = paramData.indices->getData();
uint64_t numIndices = paramData.indices->getLayout().numItems1;
ANARIDataType indexType = paramData.indices->getType();
int64_t maxId = -1;
for (uint64_t primIdx = 0; primIdx < numIndices; ++primIdx)
{
size_t vertIdx = getIndex(indices, indexType, primIdx);
// Normals
if (perPrimNormals)
{
float* normalsDest = &tempArrays->NormalsArray[vertIdx * 3];
getValues3(paramData.primitiveNormals->getData(), paramData.primitiveNormals->getType(), primIdx, normalsDest);
}
// Orientations
if (perPrimOrientations)
{
float* orientsDest = &tempArrays->OrientationsArray[vertIdx*4];
getValues4(paramData.primitiveOrientations->getData(), paramData.primitiveOrientations->getType(), primIdx, orientsDest);
}
// Radii
if (perPrimRadii)
{
float* radiiDest = &tempArrays->RadiiArray[vertIdx];
getValues1(paramData.primitiveRadii->getData(), paramData.primitiveRadii->getType(), primIdx, radiiDest);
}
// Scales
if (perPrimScales)
{
float* scalesDest = &tempArrays->ScalesArray[vertIdx*scaleComps];
if(scaleComps == 1)
getValues1(paramData.primitiveScales->getData(), paramData.primitiveScales->getType(), primIdx, scalesDest);
else if(scaleComps == 3)
getValues3(paramData.primitiveScales->getData(), paramData.primitiveScales->getType(), primIdx, scalesDest);
}
// Colors
if (perPrimColors)
{
assert(primIdx < paramData.primitiveColors->getLayout().numItems1);
tempArrays->copyToColorsArray(paramData.primitiveColors->getData(), primIdx, vertIdx, 1);
}
// Attributes
for(size_t attribIdx = 0; attribIdx < attribDataArrays.size(); ++attribIdx)
{
if(attributeArray[attribIdx].PerPrimData)
{
tempArrays->copyToAttributeDataArray(attribIdx, primIdx, vertIdx, 1);
}
}
// Ids
if (paramData.primitiveIds)
{
int64_t id = static_cast<int64_t>(getIndex(paramData.primitiveIds->getData(), paramData.primitiveIds->getType(), primIdx));
tempArrays->IdsArray[vertIdx] = id;
if (id > maxId)
maxId = id;
}
else
{
int64_t id = static_cast<int64_t>(vertIdx);
maxId = tempArrays->IdsArray[vertIdx] = id;
}
}
// Assign unused ids to untouched vertices, then add those ids to invisible array
tempArrays->InvisIdsArray.resize(0);
tempArrays->InvisIdsArray.reserve(numVertices);
for (uint64_t vertIdx = 0; vertIdx < numVertices; ++vertIdx)
{
if (tempArrays->IdsArray[vertIdx] == -1)
{
tempArrays->IdsArray[vertIdx] = ++maxId;
tempArrays->InvisIdsArray.push_back(maxId);
}
}
}
}
void convertLinesToSticks(const UsdGeometryData& paramData, const UsdGeometry::AttributeArray& attributeArray, UsdGeometryTempArrays* tempArrays)
{
// Converts arrays of vertex endpoint 2-tuples (optionally obtained via index 2-tuples) into center vertices with correct seglengths.
auto& attribDataArrays = tempArrays->AttributeDataArrays;
assert(attribDataArrays.size() == attributeArray.size());
const UsdDataArray* vertexArray = paramData.vertexPositions;
uint64_t numVertices = vertexArray->getLayout().numItems1;
const void* vertices = vertexArray->getData();
ANARIDataType vertexType = vertexArray->getType();
const UsdDataArray* indexArray = paramData.indices;
uint64_t numSticks = indexArray ? indexArray->getLayout().numItems1 : numVertices/2;
uint64_t numIndices = numSticks * 2; // Indices are 2-element vectors in ANARI
const void* indices = indexArray ? indexArray->getData() : nullptr;
ANARIDataType indexType = indexArray ? indexArray->getType() : ANARI_UINT32;
tempArrays->PointsArray.resize(numSticks * 3);
tempArrays->ScalesArray.resize(numSticks * 3); // Scales are always present
tempArrays->OrientationsArray.resize(numSticks * 4);
tempArrays->IdsArray.resize(paramData.primitiveIds ? numSticks : 0);
// Only reorder per-vertex arrays, per-prim is already in order of the output stick center vertices
ANARIDataType colorType = paramData.vertexColors ? paramData.vertexColors->getType() : ANARI_UINT8;
tempArrays->resetColorsArray(paramData.vertexColors ? numSticks : 0, colorType);
for(size_t attribIdx = 0; attribIdx < attribDataArrays.size(); ++attribIdx)
{
tempArrays->resetAttributeDataArray(attribIdx, !attributeArray[attribIdx].PerPrimData ? numSticks : 0);
}
for (size_t i = 0; i < numIndices; i += 2)
{
size_t primIdx = i / 2;
size_t vertIdx0 = indices ? getIndex(indices, indexType, i) : i;
size_t vertIdx1 = indices ? getIndex(indices, indexType, i + 1) : i + 1;
assert(vertIdx0 < numVertices);
assert(vertIdx1 < numVertices);
float point0[3], point1[3];
getValues3(vertices, vertexType, vertIdx0, point0);
getValues3(vertices, vertexType, vertIdx1, point1);
tempArrays->PointsArray[primIdx * 3] = (point0[0] + point1[0]) * 0.5f;
tempArrays->PointsArray[primIdx * 3 + 1] = (point0[1] + point1[1]) * 0.5f;
tempArrays->PointsArray[primIdx * 3 + 2] = (point0[2] + point1[2]) * 0.5f;
float scaleVal = paramData.radiusConstant;
if (paramData.vertexRadii)
{
getValues1(paramData.vertexRadii->getData(), paramData.vertexRadii->getType(), vertIdx0, &scaleVal);
}
else if (paramData.primitiveRadii)
{
getValues1(paramData.primitiveRadii->getData(), paramData.primitiveRadii->getType(), primIdx, &scaleVal);
}
float segDir[3] = {
point1[0] - point0[0],
point1[1] - point0[1],
point1[2] - point0[2],
};
float segLength = sqrtf(segDir[0] * segDir[0] + segDir[1] * segDir[1] + segDir[2] * segDir[2]);
tempArrays->ScalesArray[primIdx * 3] = scaleVal;
tempArrays->ScalesArray[primIdx * 3 + 1] = scaleVal;
tempArrays->ScalesArray[primIdx * 3 + 2] = segLength * 0.5f;
// Rotation
// USD shapes are always lengthwise-oriented along the z axis
usdbridgenumerics::DirectionToQuaternionZ(segDir, segLength, tempArrays->OrientationsArray.data() + primIdx*4);
//Colors
if (paramData.vertexColors)
{
assert(vertIdx0 < paramData.vertexColors->getLayout().numItems1);
tempArrays->copyToColorsArray(paramData.vertexColors->getData(), vertIdx0, primIdx, 1);
}
// Attributes
for(size_t attribIdx = 0; attribIdx < attribDataArrays.size(); ++attribIdx)
{
if(!attributeArray[attribIdx].PerPrimData)
{
tempArrays->copyToAttributeDataArray(attribIdx, vertIdx0, primIdx, 1);
}
}
// Ids
if (paramData.primitiveIds)
{
tempArrays->IdsArray[primIdx] = (int64_t)getIndex(paramData.primitiveIds->getData(), paramData.primitiveIds->getType(), primIdx);
}
}
}
void pushVertex(const UsdGeometryData& paramData, const UsdGeometry::AttributeArray& attributeArray, UsdGeometryTempArrays* tempArrays,
const void* vertices, ANARIDataType vertexType,
bool hasNormals, bool hasColors, bool hasRadii,
size_t segStart, size_t primIdx)
{
auto& attribDataArrays = tempArrays->AttributeDataArrays;
float point[3];
getValues3(vertices, vertexType, segStart, point);
tempArrays->PointsArray.push_back(point[0]);
tempArrays->PointsArray.push_back(point[1]);
tempArrays->PointsArray.push_back(point[2]);
// Normals
if (hasNormals)
{
float normals[3];
if (paramData.vertexNormals)
{
getValues3(paramData.vertexNormals->getData(), paramData.vertexNormals->getType(), segStart, normals);
}
else if (paramData.primitiveNormals)
{
getValues3(paramData.primitiveNormals->getData(), paramData.primitiveNormals->getType(), primIdx, normals);
}
tempArrays->NormalsArray.push_back(normals[0]);
tempArrays->NormalsArray.push_back(normals[1]);
tempArrays->NormalsArray.push_back(normals[2]);
}
// Radii
if (hasRadii)
{
float radii;
if (paramData.vertexRadii)
{
getValues1(paramData.vertexRadii->getData(), paramData.vertexRadii->getType(), segStart, &radii);
}
else if (paramData.primitiveRadii)
{
getValues1(paramData.primitiveRadii->getData(), paramData.primitiveRadii->getType(), primIdx, &radii);
}
tempArrays->ScalesArray.push_back(radii);
}
// Colors
if (hasColors)
{
size_t destIdx = tempArrays->expandColorsArray(1);
if (paramData.vertexColors)
{
tempArrays->copyToColorsArray(paramData.vertexColors->getData(), segStart, destIdx, 1);
}
else if (paramData.primitiveColors)
{
tempArrays->copyToColorsArray(paramData.primitiveColors->getData(), primIdx, destIdx, 1);
}
}
// Attributes
for(size_t attribIdx = 0; attribIdx < attribDataArrays.size(); ++attribIdx)
{
size_t srcIdx = attributeArray[attribIdx].PerPrimData ? primIdx : segStart;
size_t destIdx = tempArrays->expandAttributeDataArray(attribIdx, 1);
tempArrays->copyToAttributeDataArray(attribIdx, srcIdx, destIdx, 1);
}
}
#define PUSH_VERTEX(x, y) \
pushVertex(paramData, attributeArray, tempArrays, \
vertices, vertexType, \
hasNormals, hasColors, hasRadii, \
x, y)
void reorderCurveGeometry(const UsdGeometryData& paramData, const UsdGeometry::AttributeArray& attributeArray, UsdGeometryTempArrays* tempArrays)
{
auto& attribDataArrays = tempArrays->AttributeDataArrays;
assert(attribDataArrays.size() == attributeArray.size());
const UsdDataArray* vertexArray = paramData.vertexPositions;
uint64_t numVertices = vertexArray->getLayout().numItems1;
const void* vertices = vertexArray->getData();
ANARIDataType vertexType = vertexArray->getType();
const UsdDataArray* indexArray = paramData.indices;
uint64_t numSegments = indexArray ? indexArray->getLayout().numItems1 : numVertices-1;
const void* indices = indexArray ? indexArray->getData() : nullptr;
ANARIDataType indexType = indexArray ? indexArray->getType() : ANARI_UINT32;
uint64_t maxNumVerts = numSegments*2;
tempArrays->CurveLengths.resize(0);
tempArrays->PointsArray.resize(0);
tempArrays->PointsArray.reserve(maxNumVerts * 3); // Conservative max number of points
bool hasNormals = paramData.vertexNormals || paramData.primitiveNormals;
if (hasNormals)
{
tempArrays->NormalsArray.resize(0);
tempArrays->NormalsArray.reserve(maxNumVerts * 3);
}
bool hasColors = paramData.vertexColors || paramData.primitiveColors;
if (hasColors)
{
tempArrays->resetColorsArray(0, paramData.vertexColors ? paramData.vertexColors->getType() : paramData.primitiveColors->getType());
tempArrays->reserveColorsArray(maxNumVerts);
}
bool hasRadii = paramData.vertexRadii || paramData.primitiveRadii;
if (hasRadii)
{
tempArrays->ScalesArray.resize(0);
tempArrays->ScalesArray.reserve(maxNumVerts);
}
for(size_t attribIdx = 0; attribIdx < attribDataArrays.size(); ++attribIdx)
{
tempArrays->resetAttributeDataArray(attribIdx, 0);
tempArrays->reserveAttributeDataArray(attribIdx, maxNumVerts);
}
size_t prevSegEnd = 0;
int curveLength = 0;
for (size_t primIdx = 0; primIdx < numSegments; ++primIdx)
{
size_t segStart = indices ? getIndex(indices, indexType, primIdx) : primIdx;
if (primIdx != 0 && prevSegEnd != segStart)
{
PUSH_VERTEX(prevSegEnd, primIdx - 1);
curveLength += 1;
tempArrays->CurveLengths.push_back(curveLength);
curveLength = 0;
}
assert(segStart+1 < numVertices); // begin and end vertex should be in range
PUSH_VERTEX(segStart, primIdx);
curveLength += 1;
prevSegEnd = segStart + 1;
}
if (curveLength != 0)
{
PUSH_VERTEX(prevSegEnd, numSegments - 1);
curveLength += 1;
tempArrays->CurveLengths.push_back(curveLength);
}
}
template<typename T>
void setInstancerDataArray(const char* arrayName, const UsdDataArray* vertArray, const UsdDataArray* primArray, const std::vector<T>& tmpArray, UsdBridgeType tmpArrayType,
void const*& instancerDataArray, UsdBridgeType& instancerDataArrayType, const UsdGeometryData& paramData, const UsdGeometryDebugData& dbgData)
{
// Normals
if (paramData.indices && tmpArray.size())
{
instancerDataArray = tmpArray.data();
instancerDataArrayType = tmpArrayType;
}
else
{
const UsdDataArray* normals = vertArray;
if (normals)
{
instancerDataArray = normals->getData();
instancerDataArrayType = AnariToUsdBridgeType(normals->getType());
}
else if(primArray)
{
dbgData.device->reportStatus(dbgData.geometry, ANARI_GEOMETRY, ANARI_SEVERITY_ERROR, ANARI_STATUS_INVALID_ARGUMENT,
"UsdGeometry '%s' primitive.%s not transferred: per-primitive arrays provided without setting primitive.index", dbgData.debugName, arrayName);
}
}
}
}
UsdGeometry::UsdGeometry(const char* name, const char* type, UsdDevice* device)
: BridgedBaseObjectType(ANARI_GEOMETRY, name, device)
{
bool createTempArrays = false;
geomType = GetGeomType(type);
if(isInstanced() || geomType == GEOM_CURVE)
createTempArrays = true;
if(geomType == GEOM_UNKNOWN)
device->reportStatus(this, ANARI_GEOMETRY, ANARI_SEVERITY_ERROR, ANARI_STATUS_INVALID_ARGUMENT, "UsdGeometry '%s' construction failed: type %s not supported", getName(), type);
if(createTempArrays)
tempArrays = std::make_unique<UsdGeometryTempArrays>(attributeArray);
}
UsdGeometry::~UsdGeometry()
{
#ifdef OBJECT_LIFETIME_EQUALS_USD_LIFETIME
if(cachedBridge)
cachedBridge->DeleteGeometry(usdHandle);
#endif
}
void UsdGeometry::remove(UsdDevice* device)
{
applyRemoveFunc(device, &UsdBridge::DeleteGeometry);
}
void UsdGeometry::filterSetParam(const char *name,
ANARIDataType type,
const void *mem,
UsdDevice* device)
{
if(geomType == GEOM_GLYPH && strEquals(name, "shapeType") || strEquals(name, "shapeGeometry") || strEquals(name, "shapeTransform"))
protoShapeChanged = true;
if(usdHandle.value && strEquals(name, "usd::useUsdGeomPoints"))
{
device->reportStatus(this, ANARI_GEOMETRY, ANARI_SEVERITY_WARNING, ANARI_STATUS_INVALID_ARGUMENT, "UsdGeometry '%s' filterSetParam failed: 'usd::useUsdGeomPoints' parameter cannot be changed after the first commit", getName());
return;
}
BridgedBaseObjectType::filterSetParam(name, type, mem, device);
}
template<typename GeomDataType>
void UsdGeometry::setAttributeTimeVarying(typename GeomDataType::DataMemberId& timeVarying)
{
typedef typename GeomDataType::DataMemberId DMI;
const UsdGeometryData& paramData = getReadParams();
static constexpr int attribStartBit = static_cast<int>(UsdGeometryComponents::ATTRIBUTE0);
for(size_t attribIdx = 0; attribIdx < attributeArray.size(); ++attribIdx)
{
DMI attributeId = DMI::ATTRIBUTE0 + attribIdx;
timeVarying = timeVarying &
(isBitSet(paramData.timeVarying, attribStartBit+(int)attribIdx) ? DMI::ALL : ~attributeId);
}
}
void UsdGeometry::syncAttributeArrays()
{
const UsdGeometryData& paramData = getReadParams();
// Find the max index of the last attribute that still contains an array
int attribCount = 0;
for(int i = 0; i < MAX_ATTRIBS; ++i)
{
if(paramData.primitiveAttributes[i] != nullptr || paramData.vertexAttributes[i] != nullptr)
attribCount = i+1;
}
// Set the attribute arrays and related info, resize temporary attribute array data for reordering
if(attribCount)
{
attributeArray.resize(attribCount);
for(int i = 0; i < attribCount; ++i)
{
const UsdDataArray* attribArray = paramData.vertexAttributes[i] ? paramData.vertexAttributes[i] : paramData.primitiveAttributes[i];
if (attribArray)
{
attributeArray[i].Data = attribArray->getData();
attributeArray[i].DataType = AnariToUsdBridgeType(attribArray->getType());
attributeArray[i].PerPrimData = paramData.vertexAttributes[i] ? false : true;
attributeArray[i].EltSize = static_cast<uint32_t>(anari::sizeOf(attribArray->getType()));
attributeArray[i].Name = UsdSharedString::c_str(paramData.attributeNames[i]);
}
else
{
attributeArray[i].Data = nullptr;
attributeArray[i].DataType = UsdBridgeType::UNDEFINED;
}
}
if(tempArrays)
tempArrays->AttributeDataArrays.resize(attribCount);
}
}
template<typename GeomDataType>
void UsdGeometry::copyAttributeArraysToData(GeomDataType& geomData)
{
geomData.Attributes = attributeArray.data();
geomData.NumAttributes = static_cast<uint32_t>(attributeArray.size());
}
void UsdGeometry::assignTempDataToAttributes(bool perPrimInterpolation)
{
const AttributeDataArraysType& attribDataArrays = tempArrays->AttributeDataArrays;
assert(attributeArray.size() == attribDataArrays.size());
for(size_t attribIdx = 0; attribIdx < attribDataArrays.size(); ++attribIdx)
{
if(attribDataArrays[attribIdx].size()) // Always > 0 if attributeArray[attribIdx].Data is set
attributeArray[attribIdx].Data = attribDataArrays[attribIdx].data();
attributeArray[attribIdx].PerPrimData = perPrimInterpolation; // Already converted to per-vertex (or per-prim)
}
}
void UsdGeometry::initializeGeomData(UsdBridgeMeshData& geomData)
{
typedef UsdBridgeMeshData::DataMemberId DMI;
const UsdGeometryData& paramData = getReadParams();
geomData.TimeVarying = DMI::ALL
& (isTimeVarying(CType::POSITION) ? DMI::ALL : ~DMI::POINTS)
& (isTimeVarying(CType::NORMAL) ? DMI::ALL : ~DMI::NORMALS)
& (isTimeVarying(CType::COLOR) ? DMI::ALL : ~DMI::COLORS)
& (isTimeVarying(CType::INDEX) ? DMI::ALL : ~DMI::INDICES);
setAttributeTimeVarying<UsdBridgeMeshData>(geomData.TimeVarying);
geomData.FaceVertexCount = geomType == GEOM_QUAD ? 4 : 3;
}
void UsdGeometry::initializeGeomData(UsdBridgeInstancerData& geomData)
{
typedef UsdBridgeInstancerData::DataMemberId DMI;
const UsdGeometryData& paramData = getReadParams();
geomData.TimeVarying = DMI::ALL
& (isTimeVarying(CType::POSITION) ? DMI::ALL : ~DMI::POINTS)
& (( ((geomType == GEOM_CYLINDER || geomType == GEOM_CONE)
&& (isTimeVarying(CType::NORMAL) || isTimeVarying(CType::POSITION) || isTimeVarying(CType::INDEX)))
|| ((geomType == GEOM_GLYPH) && isTimeVarying(CType::ORIENTATION))
) ? DMI::ALL : ~DMI::ORIENTATIONS)
& (isTimeVarying(CType::SCALE) ? DMI::ALL : ~DMI::SCALES)
& (isTimeVarying(CType::INDEX) ? DMI::ALL : ~DMI::INVISIBLEIDS)
& (isTimeVarying(CType::COLOR) ? DMI::ALL : ~DMI::COLORS)
& (isTimeVarying(CType::ID) ? DMI::ALL : ~DMI::INSTANCEIDS)
& ~DMI::SHAPEINDICES; // Shapeindices are always the same, and USD clients typically do not support timevarying shapes
setAttributeTimeVarying<UsdBridgeInstancerData>(geomData.TimeVarying);
geomData.UseUsdGeomPoints = geomType == GEOM_SPHERE && paramData.UseUsdGeomPoints;
}
void UsdGeometry::initializeGeomData(UsdBridgeCurveData& geomData)
{
typedef UsdBridgeCurveData::DataMemberId DMI;
const UsdGeometryData& paramData = getReadParams();
// Turn off what is not timeVarying
geomData.TimeVarying = DMI::ALL
& (isTimeVarying(CType::POSITION) ? DMI::ALL : ~DMI::POINTS)
& (isTimeVarying(CType::NORMAL) ? DMI::ALL : ~DMI::NORMALS)
& (isTimeVarying(CType::SCALE) ? DMI::ALL : ~DMI::SCALES)
& (isTimeVarying(CType::COLOR) ? DMI::ALL : ~DMI::COLORS)
& ((isTimeVarying(CType::POSITION) || isTimeVarying(CType::INDEX)) ? DMI::ALL : ~DMI::CURVELENGTHS);
setAttributeTimeVarying<UsdBridgeCurveData>(geomData.TimeVarying);
}
void UsdGeometry::initializeGeomRefData(UsdBridgeInstancerRefData& geomRefData)
{
const UsdGeometryData& paramData = getReadParams();
// The anari side currently only supports only one shape, so just set DefaultShape
bool isGlyph = geomType == GEOM_GLYPH;
if(isGlyph && paramData.shapeGeometry)
geomRefData.DefaultShape = UsdBridgeInstancerRefData::SHAPE_MESH;
else
{
UsdGeometry::GeomType defaultShape = (isGlyph && paramData.shapeType) ? GetGeomType(paramData.shapeType->c_str()) : geomType;
switch (defaultShape)
{
case GEOM_CYLINDER:
geomRefData.DefaultShape = UsdBridgeInstancerRefData::SHAPE_CYLINDER;
break;
case GEOM_CONE:
geomRefData.DefaultShape = UsdBridgeInstancerRefData::SHAPE_CONE;
break;
default:
geomRefData.DefaultShape = UsdBridgeInstancerRefData::SHAPE_SPHERE;
break;
};
}
geomRefData.ShapeTransform = paramData.shapeTransform;
}
bool UsdGeometry::checkArrayConstraints(const UsdDataArray* vertexArray, const UsdDataArray* primArray,
const char* paramName, UsdDevice* device, const char* debugName, int attribIndex)
{
const UsdGeometryData& paramData = getReadParams();
UsdLogInfo logInfo(device, this, ANARI_GEOMETRY, debugName);
const UsdDataArray* vertices = paramData.vertexPositions;
const UsdDataLayout& vertLayout = vertices->getLayout();
const UsdDataArray* indices = paramData.indices;
const UsdDataLayout& indexLayout = indices ? indices->getLayout() : vertLayout;
const UsdDataLayout& perVertLayout = vertexArray ? vertexArray->getLayout() : vertLayout;
const UsdDataLayout& perPrimLayout = primArray ? primArray->getLayout() : indexLayout;
const UsdDataLayout& attrLayout = vertexArray ? perVertLayout : perPrimLayout;
if (!AssertOneDimensional(attrLayout, logInfo, paramName)
|| !AssertNoStride(attrLayout, logInfo, paramName)
)
{
return false;
}
if (vertexArray && vertexArray->getLayout().numItems1 < vertLayout.numItems1)
{
if(attribIndex == -1)
device->reportStatus(this, ANARI_GEOMETRY, ANARI_SEVERITY_ERROR, ANARI_STATUS_INVALID_ARGUMENT, "UsdGeometry '%s' commit failed: all 'vertex.X' array elements should at least be the size of vertex.positions", debugName);
else
device->reportStatus(this, ANARI_GEOMETRY, ANARI_SEVERITY_ERROR, ANARI_STATUS_INVALID_ARGUMENT, "UsdGeometry '%s' commit failed: all 'vertex.attribute%i' array elements should at least be the size of vertex.positions", debugName, attribIndex);
return false;
}
uint64_t numPrims = GetNumberOfPrims(indices, indexLayout, geomType);
if (primArray && primArray->getLayout().numItems1 < numPrims)
{
if(attribIndex == -1)
device->reportStatus(this, ANARI_GEOMETRY, ANARI_SEVERITY_ERROR, ANARI_STATUS_INVALID_ARGUMENT, "UsdGeometry '%s' commit failed: size of 'primitive.X' array too small", debugName);
else
device->reportStatus(this, ANARI_GEOMETRY, ANARI_SEVERITY_ERROR, ANARI_STATUS_INVALID_ARGUMENT, "UsdGeometry '%s' commit failed: size of 'primitive.attribute%i' array too small", debugName, attribIndex);
return false;
}
return true;
}
bool UsdGeometry::checkGeomParams(UsdDevice* device)
{
const UsdGeometryData& paramData = getReadParams();
const char* debugName = getName();
bool success = true;
success = success && checkArrayConstraints(paramData.vertexPositions, nullptr, "vertex.position", device, debugName);
success = success && checkArrayConstraints(nullptr, paramData.indices, "primitive.index", device, debugName);
success = success && checkArrayConstraints(paramData.vertexNormals, paramData.primitiveNormals, "vertex/primitive.normal", device, debugName);
for(int i = 0; i < MAX_ATTRIBS; ++i)
success = success && checkArrayConstraints(paramData.vertexAttributes[i], paramData.primitiveAttributes[i], "vertex/primitive.attribute", device, debugName, i);
success = success && checkArrayConstraints(paramData.vertexColors, paramData.primitiveColors, "vertex/primitive.color", device, debugName);
success = success && checkArrayConstraints(paramData.vertexRadii, paramData.primitiveRadii, "vertex/primitive.radius", device, debugName);
success = success && checkArrayConstraints(paramData.vertexScales, paramData.primitiveScales, "vertex/primitive.scale", device, debugName);
success = success && checkArrayConstraints(paramData.vertexOrientations, paramData.primitiveOrientations, "vertex/primitive.orientation", device, debugName);
success = success && checkArrayConstraints(nullptr, paramData.primitiveIds, "primitive.id", device, debugName);
if (!success)
return false;
ANARIDataType vertType = paramData.vertexPositions->getType();
if (vertType != ANARI_FLOAT32_VEC3 && vertType != ANARI_FLOAT64_VEC3)
{
device->reportStatus(this, ANARI_GEOMETRY, ANARI_SEVERITY_ERROR, ANARI_STATUS_INVALID_ARGUMENT, "UsdGeometry '%s' commit failed: 'vertex.position' parameter should be of type ANARI_FLOAT32_VEC3 or ANARI_FLOAT64_VEC3.", debugName);
return false;
}
if (paramData.indices)
{
ANARIDataType indexType = paramData.indices->getType();
UsdBridgeType flattenedType = AnariToUsdBridgeType_Flattened(indexType);
if( (geomType == GEOM_TRIANGLE || geomType == GEOM_QUAD) &&
(flattenedType == UsdBridgeType::UINT || flattenedType == UsdBridgeType::ULONG || flattenedType == UsdBridgeType::LONG))
{
static bool reported = false; // Hardcode this to show only once to make sure developers get to see it, without spamming the console.
if(!reported)
{
device->reportStatus(this, ANARI_GEOMETRY, ANARI_SEVERITY_WARNING, ANARI_STATUS_INVALID_ARGUMENT, "UsdGeometry '%s' has 'primitive.index' of type other than ANARI_INT32, which may result in an overflow for FaceVertexIndicesAttr of UsdGeomMesh.", debugName);
reported = true;
}
}
if (geomType == GEOM_SPHERE || geomType == GEOM_CURVE || geomType == GEOM_GLYPH)
{
if(geomType == GEOM_SPHERE && paramData.UseUsdGeomPoints)
device->reportStatus(this, ANARI_GEOMETRY, ANARI_SEVERITY_WARNING, ANARI_STATUS_INVALID_ARGUMENT, "UsdGeometry '%s' is a sphere geometry with indices, but the usd::useUsdGeomPoints parameter is not set, so all vertices will show as spheres.", debugName);
if (indexType != ANARI_INT32 && indexType != ANARI_UINT32 && indexType != ANARI_INT64 && indexType != ANARI_UINT64)
{
device->reportStatus(this, ANARI_GEOMETRY, ANARI_SEVERITY_ERROR, ANARI_STATUS_INVALID_ARGUMENT, "UsdGeometry '%s' commit failed: 'primitive.index' parameter should be of type ANARI_(U)INT32/64.", debugName);
return false;
}
}
else if (geomType == GEOM_CYLINDER || geomType == GEOM_CONE)
{
if (indexType != ANARI_UINT32_VEC2 && indexType != ANARI_INT32_VEC2 && indexType != ANARI_UINT64_VEC2 && indexType != ANARI_INT64_VEC2)
{
device->reportStatus(this, ANARI_GEOMETRY, ANARI_SEVERITY_ERROR, ANARI_STATUS_INVALID_ARGUMENT, "UsdGeometry '%s' commit failed: 'primitive.index' parameter should be of type ANARI_(U)INT_VEC2.", debugName);
return false;
}
}
else if (geomType == GEOM_TRIANGLE)
{
if (indexType != ANARI_UINT32_VEC3 && indexType != ANARI_INT32_VEC3 && indexType != ANARI_UINT64_VEC3 && indexType != ANARI_INT64_VEC3)
{
device->reportStatus(this, ANARI_GEOMETRY, ANARI_SEVERITY_ERROR, ANARI_STATUS_INVALID_ARGUMENT, "UsdGeometry '%s' commit failed: 'primitive.index' parameter should be of type ANARI_(U)INT_VEC3.", debugName);
return false;
}
}
else if (geomType == GEOM_QUAD)
{
if (indexType != ANARI_UINT32_VEC4 && indexType != ANARI_INT32_VEC4 && indexType != ANARI_UINT64_VEC4 && indexType != ANARI_INT64_VEC4)
{
device->reportStatus(this, ANARI_GEOMETRY, ANARI_SEVERITY_ERROR, ANARI_STATUS_INVALID_ARGUMENT, "UsdGeometry '%s' commit failed: 'primitive.index' parameter should be of type ANARI_(U)INT_VEC4.", debugName);
return false;
}
}
}
const UsdDataArray* normals = paramData.vertexNormals ? paramData.vertexNormals : paramData.primitiveNormals;
if (normals)
{
ANARIDataType arrayType = normals->getType();
if (arrayType != ANARI_FLOAT32_VEC3 && arrayType != ANARI_FLOAT64_VEC3)
{
device->reportStatus(this, ANARI_GEOMETRY, ANARI_SEVERITY_ERROR, ANARI_STATUS_INVALID_ARGUMENT, "UsdGeometry '%s' commit failed: 'vertex/primitive.normal' parameter should be of type ANARI_FLOAT32_VEC3 or ANARI_FLOAT64_VEC3.", debugName);
return false;
}
}
const UsdDataArray* colors = paramData.vertexColors ? paramData.vertexColors : paramData.primitiveColors;
if (colors)
{
ANARIDataType arrayType = colors->getType();
if ((int)arrayType < (int)ANARI_INT8 || (int)arrayType > (int)ANARI_UFIXED8_R_SRGB)
{
device->reportStatus(this, ANARI_GEOMETRY, ANARI_SEVERITY_ERROR, ANARI_STATUS_INVALID_ARGUMENT, "UsdGeometry '%s' commit failed: 'vertex/primitive.color' parameter should be of Color type (see ANARI standard)", debugName);
return false;
}
}
const UsdDataArray* radii = paramData.vertexRadii ? paramData.vertexRadii : paramData.primitiveRadii;
if (radii)
{
ANARIDataType arrayType = radii->getType();
if (arrayType != ANARI_FLOAT32 && arrayType != ANARI_FLOAT64)
{
device->reportStatus(this, ANARI_GEOMETRY, ANARI_SEVERITY_ERROR, ANARI_STATUS_INVALID_ARGUMENT, "UsdGeometry '%s' commit failed: 'vertex/primitive.radius' parameter should be of type ANARI_FLOAT32 or ANARI_FLOAT64.", debugName);
return false;
}
}
const UsdDataArray* scales = paramData.vertexScales ? paramData.vertexScales : paramData.primitiveScales;
if (scales)
{
ANARIDataType arrayType = scales->getType();
if (arrayType != ANARI_FLOAT32 && arrayType != ANARI_FLOAT64 && arrayType != ANARI_FLOAT32_VEC3 && arrayType != ANARI_FLOAT64_VEC3)
{
device->reportStatus(this, ANARI_GEOMETRY, ANARI_SEVERITY_ERROR, ANARI_STATUS_INVALID_ARGUMENT, "UsdGeometry '%s' commit failed: 'vertex/primitive.scale' parameter should be of type ANARI_FLOAT32(_VEC3) or ANARI_FLOAT64(_VEC3).", debugName);
return false;
}
}
const UsdDataArray* orientations = paramData.vertexOrientations ? paramData.vertexOrientations : paramData.primitiveOrientations;
if (orientations)
{
ANARIDataType arrayType = orientations->getType();
if (arrayType != ANARI_FLOAT32_QUAT_IJKW)
{
device->reportStatus(this, ANARI_GEOMETRY, ANARI_SEVERITY_ERROR, ANARI_STATUS_INVALID_ARGUMENT, "UsdGeometry '%s' commit failed: 'vertex/primitive.orientation' parameter should be of type ANARI_FLOAT32_QUAT_IJKW.", debugName);
return false;
}
}
if (paramData.primitiveIds)
{
ANARIDataType idType = paramData.primitiveIds->getType();
if (idType != ANARI_INT32 && idType != ANARI_UINT32 && idType != ANARI_INT64 && idType != ANARI_UINT64)
{
device->reportStatus(this, ANARI_GEOMETRY, ANARI_SEVERITY_ERROR, ANARI_STATUS_INVALID_ARGUMENT, "UsdGeometry '%s' commit failed: 'primitive.id' parameter should be of type ANARI_(U)INT or ANARI_(U)LONG.", debugName);
return false;
}
}
return true;
}
void UsdGeometry::updateGeomData(UsdDevice* device, UsdBridge* usdBridge, UsdBridgeMeshData& meshData, bool isNew)
{
const UsdGeometryData& paramData = getReadParams();
const UsdDataArray* vertices = paramData.vertexPositions;
meshData.NumPoints = vertices->getLayout().numItems1;
meshData.Points = vertices->getData();
meshData.PointsType = AnariToUsdBridgeType(vertices->getType());
const UsdDataArray* normals = paramData.vertexNormals ? paramData.vertexNormals : paramData.primitiveNormals;
if (normals)
{
meshData.Normals = normals->getData();
meshData.NormalsType = AnariToUsdBridgeType(normals->getType());
meshData.PerPrimNormals = paramData.vertexNormals ? false : true;
}
const UsdDataArray* colors = paramData.vertexColors ? paramData.vertexColors : paramData.primitiveColors;
if (colors)
{
meshData.Colors = colors->getData();
meshData.ColorsType = AnariToUsdBridgeType(colors->getType());
meshData.PerPrimColors = paramData.vertexColors ? false : true;
}
const UsdDataArray* indices = paramData.indices;
if (indices)
{
ANARIDataType indexType = indices->getType();
meshData.NumIndices = indices->getLayout().numItems1 * anari::componentsOf(indexType);
meshData.Indices = indices->getData();
meshData.IndicesType = AnariToUsdBridgeType_Flattened(indexType);
}
else
{
meshData.NumIndices = meshData.NumPoints; // Vertices are implicitly indexed consecutively (FaceVertexCount determines how many prims)
}
//meshData.UpdatesToPerform = Still to be implemented
double worldTimeStep = device->getReadParams().timeStep;
double dataTimeStep = selectObjTime(paramData.timeStep, worldTimeStep);
usdBridge->SetGeometryData(usdHandle, meshData, dataTimeStep);
}
void UsdGeometry::updateGeomData(UsdDevice* device, UsdBridge* usdBridge, UsdBridgeInstancerData& instancerData, bool isNew)
{
const UsdGeometryData& paramData = getReadParams();
const char* debugName = getName();
if (geomType == GEOM_SPHERE || geomType == GEOM_GLYPH)
{
// A paramData.indices (primitive-indexed spheres) array, is not supported in USD, also duplicate spheres make no sense.
// Instead, Ids/InvisibleIds are assigned to emulate sparsely indexed spheres (sourced from paramData.primitiveIds if available),
// with the per-vertex arrays remaining intact. Any per-prim arrays are explicitly converted to per-vertex via the tempArrays.
generateIndexedSphereData(paramData, attributeArray, tempArrays.get());
const UsdDataArray* vertices = paramData.vertexPositions;
instancerData.NumPoints = vertices->getLayout().numItems1;
instancerData.Points = vertices->getData();
instancerData.PointsType = AnariToUsdBridgeType(vertices->getType());
UsdGeometryDebugData dbgData = { device, this, debugName };
// Orientations
// are a bit extended beyond the spec: even spheres can set them, and the use of normals is also supported
if(paramData.vertexOrientations || paramData.primitiveOrientations)
{
setInstancerDataArray("orientation", paramData.vertexOrientations, paramData.primitiveOrientations, tempArrays->OrientationsArray, UsdBridgeType::FLOAT4,
instancerData.Orientations, instancerData.OrientationsType,
paramData, dbgData);
}
else
{
setInstancerDataArray("normal", paramData.vertexNormals, paramData.primitiveNormals, tempArrays->NormalsArray, UsdBridgeType::FLOAT3,
instancerData.Orientations, instancerData.OrientationsType,
paramData, dbgData);
}
// Scales
if(geomType == GEOM_SPHERE)
{
setInstancerDataArray("radius", paramData.vertexRadii, paramData.primitiveRadii,
tempArrays->RadiiArray, UsdBridgeType::FLOAT,
instancerData.Scales, instancerData.ScalesType,
paramData, dbgData);
}
else
{
size_t numTmpScales = tempArrays->ScalesArray.size();
bool scalarScale = (numTmpScales == instancerData.NumPoints);
assert(!numTmpScales || scalarScale || numTmpScales == instancerData.NumPoints*3);
setInstancerDataArray("scale", paramData.vertexScales, paramData.primitiveScales,
tempArrays->ScalesArray, scalarScale ? UsdBridgeType::FLOAT : UsdBridgeType::FLOAT3,
instancerData.Scales, instancerData.ScalesType,
paramData, dbgData);
}
// Colors
setInstancerDataArray("color", paramData.vertexColors, paramData.primitiveColors,
tempArrays->ColorsArray, AnariToUsdBridgeType(tempArrays->ColorsArrayType),
instancerData.Colors, instancerData.ColorsType,
paramData, dbgData);
// Attributes
// By default, syncAttributeArrays and initializeGeomData already set up instancerData.Attributes
// Just set attributeArray's data to tempArrays where necessary
if(paramData.indices)
{
// Type remains the same, everything per-vertex (as explained above)
assignTempDataToAttributes(false);
}
else
{
// Check whether any perprim attributes exist
for(size_t attribIdx = 0; attribIdx < attributeArray.size(); ++attribIdx)
{
if(attributeArray[attribIdx].Data && attributeArray[attribIdx].PerPrimData)
{
attributeArray[attribIdx].Data = nullptr;
device->reportStatus(this, ANARI_GEOMETRY, ANARI_SEVERITY_ERROR, ANARI_STATUS_INVALID_ARGUMENT,
"UsdGeometry '%s' primitive.attribute%i not transferred: per-primitive arrays provided without setting primitive.index", debugName, static_cast<int>(attribIdx));
}
}
}
// Ids
if (paramData.indices && tempArrays->IdsArray.size())
{
instancerData.InstanceIds = tempArrays->IdsArray.data();
instancerData.InstanceIdsType = UsdBridgeType::LONG;
}
else
{
const UsdDataArray* ids = paramData.primitiveIds;
if (ids)
{
instancerData.InstanceIds = ids->getData();
instancerData.InstanceIdsType = AnariToUsdBridgeType(ids->getType());
}
}
// Invisible Ids
if (paramData.indices && tempArrays->InvisIdsArray.size())
{
instancerData.InvisibleIds = tempArrays->InvisIdsArray.data();
instancerData.InvisibleIdsType = UsdBridgeType::LONG;
instancerData.NumInvisibleIds = tempArrays->InvisIdsArray.size();
}
for(int i = 0; i < 3; ++i)
instancerData.Scale.Data[i] = (geomType == GEOM_SPHERE) ? paramData.radiusConstant : paramData.scaleConstant.Data[i];
instancerData.Orientation = paramData.orientationConstant;
}
else
{
convertLinesToSticks(paramData, attributeArray, tempArrays.get());
instancerData.NumPoints = tempArrays->PointsArray.size()/3;
if (instancerData.NumPoints > 0)
{
instancerData.Points = tempArrays->PointsArray.data();
instancerData.PointsType = UsdBridgeType::FLOAT3;
instancerData.Scales = tempArrays->ScalesArray.data();
instancerData.ScalesType = UsdBridgeType::FLOAT3;
instancerData.Orientations = tempArrays->OrientationsArray.data();
instancerData.OrientationsType = UsdBridgeType::FLOAT4;
// Colors
if (tempArrays->ColorsArray.size())
{
instancerData.Colors = tempArrays->ColorsArray.data();
instancerData.ColorsType = AnariToUsdBridgeType(tempArrays->ColorsArrayType);
}
else if(const UsdDataArray* colors = paramData.primitiveColors)
{ // Per-primitive color array corresponds to per-vertex stick output
instancerData.Colors = colors->getData();
instancerData.ColorsType = AnariToUsdBridgeType(colors->getType());
}
// Attributes
assignTempDataToAttributes(false);
// Ids
if (tempArrays->IdsArray.size())
{
instancerData.InstanceIds = tempArrays->IdsArray.data();
instancerData.InstanceIdsType = UsdBridgeType::LONG;
}
}
}
double worldTimeStep = device->getReadParams().timeStep;
double dataTimeStep = selectObjTime(paramData.timeStep, worldTimeStep);
usdBridge->SetGeometryData(usdHandle, instancerData, dataTimeStep);
if(isNew && geomType != GEOM_GLYPH && !instancerData.UseUsdGeomPoints)
commitPrototypes(usdBridge); // Also initialize the prototype shape on the instancer geom
}
void UsdGeometry::updateGeomData(UsdDevice* device, UsdBridge* usdBridge, UsdBridgeCurveData& curveData, bool isNew)
{
const UsdGeometryData& paramData = getReadParams();
reorderCurveGeometry(paramData, attributeArray, tempArrays.get());
curveData.NumPoints = tempArrays->PointsArray.size() / 3;
if (curveData.NumPoints > 0)
{
curveData.Points = tempArrays->PointsArray.data();
curveData.PointsType = UsdBridgeType::FLOAT3;
curveData.CurveLengths = tempArrays->CurveLengths.data();
curveData.NumCurveLengths = tempArrays->CurveLengths.size();
if (tempArrays->NormalsArray.size())
{
curveData.Normals = tempArrays->NormalsArray.data();
curveData.NormalsType = UsdBridgeType::FLOAT3;
}
curveData.PerPrimNormals = false;// Always vertex colored as per reorderCurveGeometry. One entry per whole curve would be useless
// Attributes
assignTempDataToAttributes(false);
// Copy colors
if (tempArrays->ColorsArray.size())
{
curveData.Colors = tempArrays->ColorsArray.data();
curveData.ColorsType = AnariToUsdBridgeType(tempArrays->ColorsArrayType);
}
curveData.PerPrimColors = false; // Always vertex colored as per reorderCurveGeometry. One entry per whole curve would be useless
// Assign scales
if (tempArrays->ScalesArray.size())
{
curveData.Scales = tempArrays->ScalesArray.data();
curveData.ScalesType = UsdBridgeType::FLOAT;
}
curveData.UniformScale = paramData.radiusConstant;
}
double worldTimeStep = device->getReadParams().timeStep;
double dataTimeStep = selectObjTime(paramData.timeStep, worldTimeStep);
usdBridge->SetGeometryData(usdHandle, curveData, dataTimeStep);
}
template<typename UsdGeomType>
bool UsdGeometry::commitTemplate(UsdDevice* device)
{
UsdBridge* usdBridge = device->getUsdBridge();
const UsdGeometryData& paramData = getReadParams();
const char* debugName = getName();
UsdGeomType geomData;
syncAttributeArrays();
initializeGeomData(geomData);
copyAttributeArraysToData(geomData);
bool isNew = false;
if (!usdHandle.value)
{
isNew = usdBridge->CreateGeometry(debugName, usdHandle, geomData);
}
if (paramChanged || isNew)
{
if (paramData.vertexPositions)
{
if(checkGeomParams(device))
updateGeomData(device, usdBridge, geomData, isNew);
}
else
{
device->reportStatus(this, ANARI_GEOMETRY, ANARI_SEVERITY_ERROR, ANARI_STATUS_INVALID_ARGUMENT, "UsdGeometry '%s' commit failed: missing 'vertex.position'.", debugName);
}
paramChanged = false;
}
return isNew;
}
void UsdGeometry::commitPrototypes(UsdBridge* usdBridge)
{
UsdBridgeInstancerRefData instancerRefData;
initializeGeomRefData(instancerRefData);
usdBridge->SetPrototypeData(usdHandle, instancerRefData);
}
bool UsdGeometry::deferCommit(UsdDevice* device)
{
return false;
}
bool UsdGeometry::doCommitData(UsdDevice* device)
{
if(geomType == GEOM_UNKNOWN)
return false;
bool isNew = false;
switch (geomType)
{
case GEOM_TRIANGLE: isNew = commitTemplate<UsdBridgeMeshData>(device); break;
case GEOM_QUAD: isNew = commitTemplate<UsdBridgeMeshData>(device); break;
case GEOM_SPHERE: isNew = commitTemplate<UsdBridgeInstancerData>(device); break;
case GEOM_CYLINDER: isNew = commitTemplate<UsdBridgeInstancerData>(device); break;
case GEOM_CONE: isNew = commitTemplate<UsdBridgeInstancerData>(device); break;
case GEOM_GLYPH: isNew = commitTemplate<UsdBridgeInstancerData>(device); break;
case GEOM_CURVE: isNew = commitTemplate<UsdBridgeCurveData>(device); break;
default: break;
}
return geomType == GEOM_GLYPH && (isNew || protoShapeChanged); // Defer commit of prototypes until the geometry refs are in place
}
void UsdGeometry::doCommitRefs(UsdDevice* device)
{
assert(geomType == GEOM_GLYPH && protoShapeChanged);
UsdBridge* usdBridge = device->getUsdBridge();
const UsdGeometryData& paramData = getReadParams();
double worldTimeStep = device->getReadParams().timeStep;
// Make sure the references are updated on the Bridge side.
if (paramData.shapeGeometry)
{
double geomObjTimeStep = paramData.shapeGeometry->getReadParams().timeStep;
UsdGeometryHandle protoGeomHandle = paramData.shapeGeometry->getUsdHandle();
size_t numHandles = 1;
double protoTimestep = selectRefTime(paramData.shapeGeometryRefTimeStep, geomObjTimeStep, worldTimeStep);
usdBridge->SetPrototypeRefs(usdHandle,
&protoGeomHandle,
numHandles,
worldTimeStep,
&protoTimestep
);
}
else
{
usdBridge->DeletePrototypeRefs(usdHandle, worldTimeStep);
}
// Now set the prototype relations to the reference paths (Bridge uses paths from SetPrototypeRefs)
commitPrototypes(usdBridge);
protoShapeChanged = false;
}
| 56,898 | C++ | 38.431046 | 265 | 0.704049 |
NVIDIA-Omniverse/AnariUsdDevice/UsdGroup.cpp | // Copyright 2020 The Khronos Group
// SPDX-License-Identifier: Apache-2.0
#include "UsdGroup.h"
#include "UsdAnari.h"
#include "UsdDataArray.h"
#include "UsdDevice.h"
#include "UsdSurface.h"
#include "UsdVolume.h"
#define SurfaceType ANARI_SURFACE
#define VolumeType ANARI_VOLUME
using SurfaceUsdType = AnariToUsdBridgedObject<SurfaceType>::Type;
using VolumeUsdType = AnariToUsdBridgedObject<VolumeType>::Type;
DEFINE_PARAMETER_MAP(UsdGroup,
REGISTER_PARAMETER_MACRO("name", ANARI_STRING, name)
REGISTER_PARAMETER_MACRO("usd::name", ANARI_STRING, usdName)
REGISTER_PARAMETER_MACRO("usd::timeVarying", ANARI_INT32, timeVarying)
REGISTER_PARAMETER_MACRO("surface", ANARI_ARRAY, surfaces)
REGISTER_PARAMETER_MACRO("volume", ANARI_ARRAY, volumes)
)
constexpr UsdGroup::ComponentPair UsdGroup::componentParamNames[]; // Workaround for C++14's lack of inlining constexpr arrays
UsdGroup::UsdGroup(const char* name,
UsdDevice* device)
: BridgedBaseObjectType(ANARI_GROUP, name, device)
{
}
UsdGroup::~UsdGroup()
{
#ifdef OBJECT_LIFETIME_EQUALS_USD_LIFETIME
if(cachedBridge)
cachedBridge->DeleteGroup(usdHandle);
#endif
}
void UsdGroup::remove(UsdDevice* device)
{
applyRemoveFunc(device, &UsdBridge::DeleteGroup);
}
bool UsdGroup::deferCommit(UsdDevice* device)
{
const UsdGroupData& paramData = getReadParams();
if(UsdObjectNotInitialized<SurfaceUsdType>(paramData.surfaces) ||
UsdObjectNotInitialized<VolumeUsdType>(paramData.volumes))
{
return true;
}
return false;
}
bool UsdGroup::doCommitData(UsdDevice* device)
{
UsdBridge* usdBridge = device->getUsdBridge();
bool isNew = false;
if (!usdHandle.value)
isNew = usdBridge->CreateGroup(getName(), usdHandle);
if (paramChanged || isNew)
{
doCommitRefs(device); // Perform immediate commit of refs - no params from children required
paramChanged = false;
}
return false;
}
void UsdGroup::doCommitRefs(UsdDevice* device)
{
UsdBridge* usdBridge = device->getUsdBridge();
const UsdGroupData& paramData = getReadParams();
double timeStep = device->getReadParams().timeStep;
UsdLogInfo logInfo(device, this, ANARI_GROUP, this->getName());
bool surfacesTimeVarying = isTimeVarying(UsdGroupComponents::SURFACES);
bool volumesTimeVarying = isTimeVarying(UsdGroupComponents::VOLUMES);
ManageRefArray<SurfaceType, ANARISurface, UsdSurface>(usdHandle, paramData.surfaces, surfacesTimeVarying, timeStep,
surfaceHandles, &UsdBridge::SetSurfaceRefs, &UsdBridge::DeleteSurfaceRefs,
usdBridge, logInfo, "UsdGroup commit failed: 'surface' array elements should be of type ANARI_SURFACE");
ManageRefArray<VolumeType, ANARIVolume, UsdVolume>(usdHandle, paramData.volumes, volumesTimeVarying, timeStep,
volumeHandles, &UsdBridge::SetVolumeRefs, &UsdBridge::DeleteVolumeRefs,
usdBridge, logInfo, "UsdGroup commit failed: 'volume' array elements should be of type ANARI_VOLUME");
} | 2,925 | C++ | 30.462365 | 126 | 0.764103 |
NVIDIA-Omniverse/AnariUsdDevice/UsdFrame.h | // Copyright 2020 The Khronos Group
// SPDX-License-Identifier: Apache-2.0
#pragma once
#include "UsdBaseObject.h"
#include "UsdParameterizedObject.h"
class UsdRenderer;
class UsdWorld;
struct UsdFrameData
{
UsdWorld* world = nullptr;
UsdRenderer* renderer = nullptr;
UsdUint2 size = {0, 0};
ANARIDataType color = ANARI_UNKNOWN;
ANARIDataType depth = ANARI_UNKNOWN;
};
class UsdFrame : public UsdParameterizedBaseObject<UsdFrame, UsdFrameData>
{
public:
UsdFrame(UsdBridge* bridge);
~UsdFrame();
void remove(UsdDevice* device) override {}
const void* mapBuffer(const char* channel,
uint32_t *width,
uint32_t *height,
ANARIDataType *pixelType);
void unmapBuffer(const char* channel);
void saveUsd(UsdDevice* device);
protected:
bool deferCommit(UsdDevice* device) override;
bool doCommitData(UsdDevice* device) override;
void doCommitRefs(UsdDevice* device) override {}
char* ReserveBuffer(ANARIDataType format);
char* mappedColorMem = nullptr;
char* mappedDepthMem = nullptr;
};
| 1,070 | C | 21.787234 | 74 | 0.718692 |
NVIDIA-Omniverse/AnariUsdDevice/UsdCamera.cpp | // Copyright 2020 The Khronos Group
// SPDX-License-Identifier: Apache-2.0
#include "UsdCamera.h"
#include "UsdAnari.h"
#include "UsdDataArray.h"
#include "UsdDevice.h"
DEFINE_PARAMETER_MAP(UsdCamera,
REGISTER_PARAMETER_MACRO("name", ANARI_STRING, name)
REGISTER_PARAMETER_MACRO("usd::name", ANARI_STRING, usdName)
REGISTER_PARAMETER_MACRO("usd::timeVarying", ANARI_INT32, timeVarying)
REGISTER_PARAMETER_MACRO("position", ANARI_FLOAT32_VEC3, position)
REGISTER_PARAMETER_MACRO("direction", ANARI_FLOAT32_VEC3, direction)
REGISTER_PARAMETER_MACRO("up", ANARI_FLOAT32_VEC3, up)
REGISTER_PARAMETER_MACRO("imageRegion", ANARI_FLOAT32_BOX2, imageRegion)
REGISTER_PARAMETER_MACRO("aspect", ANARI_FLOAT32, aspect)
REGISTER_PARAMETER_MACRO("near", ANARI_FLOAT32, near)
REGISTER_PARAMETER_MACRO("far", ANARI_FLOAT32, far)
REGISTER_PARAMETER_MACRO("fovy", ANARI_FLOAT32, fovy)
REGISTER_PARAMETER_MACRO("height", ANARI_FLOAT32, height)
)
constexpr UsdCamera::ComponentPair UsdCamera::componentParamNames[]; // Workaround for C++14's lack of inlining constexpr arrays
UsdCamera::UsdCamera(const char* name, const char* type, UsdDevice* device)
: BridgedBaseObjectType(ANARI_CAMERA, name, device)
{
if(strEquals(type, "perspective"))
cameraType = CAMERA_PERSPECTIVE;
else if(strEquals(type, "orthographic"))
cameraType = CAMERA_ORTHOGRAPHIC;
}
UsdCamera::~UsdCamera()
{
#ifdef OBJECT_LIFETIME_EQUALS_USD_LIFETIME
if(cachedBridge)
cachedBridge->DeleteGroup(usdHandle);
#endif
}
void UsdCamera::remove(UsdDevice* device)
{
applyRemoveFunc(device, &UsdBridge::DeleteCamera);
}
bool UsdCamera::deferCommit(UsdDevice* device)
{
return false;
}
void UsdCamera::copyParameters(UsdBridgeCameraData& camData)
{
typedef UsdBridgeCameraData::DataMemberId DMI;
const UsdCameraData& paramData = getReadParams();
camData.Position = paramData.position;
camData.Direction = paramData.direction;
camData.Up = paramData.up;
camData.ImageRegion = paramData.imageRegion;
camData.Aspect = paramData.aspect;
camData.Near = paramData.near;
camData.Far = paramData.far;
camData.Fovy = paramData.fovy;
camData.Height = paramData.height;
camData.TimeVarying = DMI::ALL
& (isTimeVarying(CType::VIEW) ? DMI::ALL : ~DMI::VIEW)
& (isTimeVarying(CType::PROJECTION) ? DMI::ALL : ~DMI::PROJECTION);
}
bool UsdCamera::doCommitData(UsdDevice* device)
{
UsdBridge* usdBridge = device->getUsdBridge();
const UsdCameraData& paramData = getReadParams();
double timeStep = device->getReadParams().timeStep;
bool isNew = false;
if (!usdHandle.value)
isNew = usdBridge->CreateCamera(getName(), usdHandle);
if (paramChanged || isNew)
{
UsdBridgeCameraData camData;
copyParameters(camData);
usdBridge->SetCameraData(usdHandle, camData, timeStep);
paramChanged = false;
}
return false;
} | 2,864 | C++ | 29.478723 | 128 | 0.745461 |
NVIDIA-Omniverse/AnariUsdDevice/UsdBaseObject.h | // Copyright 2020 The Khronos Group
// SPDX-License-Identifier: Apache-2.0
#pragma once
#include "helium/utility/IntrusivePtr.h"
#include "UsdCommonMacros.h"
#include "UsdParameterizedObject.h"
class UsdDevice;
// Base parameterized class without being derived as such - nontemplated to allow for polymorphic use
class UsdBaseObject : public helium::RefCounted
{
public:
// If device != 0, the object is added to the commit list
UsdBaseObject(ANARIDataType t, UsdDevice* device = nullptr);
virtual void filterSetParam(
const char *name,
ANARIDataType type,
const void *mem,
UsdDevice* device) = 0;
virtual void filterResetParam(
const char *name) = 0;
virtual void resetAllParams() = 0;
virtual void* getParameter(const char* name, ANARIDataType& returnType) = 0;
virtual int getProperty(const char *name,
ANARIDataType type,
void *mem,
uint64_t size,
UsdDevice* device) = 0;
virtual void commit(UsdDevice* device) = 0;
virtual void remove(UsdDevice* device) = 0; // Remove any committed data and refs
ANARIDataType getType() const { return type; }
protected:
virtual bool deferCommit(UsdDevice* device) = 0; // Returns whether data commit has to be deferred
virtual bool doCommitData(UsdDevice* device) = 0; // Data commit, execution can be immediate, returns whether doCommitRefs has to be performed
virtual void doCommitRefs(UsdDevice* device) = 0; // For updates with dependencies on referenced object's data, is always executed deferred
ANARIDataType type;
friend class UsdDevice;
};
// Templated base implementation of parameterized object
template<typename T, typename D>
class UsdParameterizedBaseObject : public UsdBaseObject, public UsdParameterizedObject<T, D>
{
public:
typedef UsdParameterizedObject<T, D> ParamClass;
UsdParameterizedBaseObject(ANARIDataType t, UsdDevice* device = nullptr)
: UsdBaseObject(t, device)
{}
void filterSetParam(
const char *name,
ANARIDataType type,
const void *mem,
UsdDevice* device) override
{
ParamClass::setParam(name, type, mem, device);
}
void filterResetParam(
const char *name) override
{
ParamClass::resetParam(name);
}
void resetAllParams() override
{
ParamClass::resetParams();
}
void* getParameter(const char* name, ANARIDataType& returnType) override
{
return ParamClass::getParam(name, returnType);
}
int getProperty(const char *name,
ANARIDataType type,
void *mem,
uint64_t size,
UsdDevice* device) override
{
return 0;
}
void commit(UsdDevice* device) override
{
ParamClass::transferWriteToReadParams();
UsdBaseObject::commit(device);
}
// Convenience functions for commonly used name property
virtual const char* getName() const { return ""; }
protected:
// Convenience functions for commonly used name property
bool setNameParam(const char *name,
ANARIDataType type,
const void *mem,
UsdDevice* device)
{
const char* objectName = static_cast<const char*>(mem);
if (type == ANARI_STRING)
{
if (strEquals(name, "name"))
{
if (!objectName || strEquals(objectName, ""))
{
reportStatusThroughDevice(UsdLogInfo(device, this, ANARI_OBJECT, nullptr), ANARI_SEVERITY_WARNING, ANARI_STATUS_NO_ERROR,
"%s: ANARI object %s cannot be an empty string, using auto-generated name instead.", getName(), "name");
}
else
{
ParamClass::setParam(name, type, mem, device);
ParamClass::setParam("usd::name", type, mem, device);
this->formatUsdName(this->getWriteParams().usdName);
}
return true;
}
else if (strEquals(name, "usd::name"))
{
reportStatusThroughDevice(UsdLogInfo(device, this, ANARI_OBJECT, nullptr), ANARI_SEVERITY_WARNING, ANARI_STATUS_NO_ERROR,
"%s parameter '%s' cannot be set, only read with getProperty().", getName(), "usd::name");
return true;
}
}
return false;
}
int getNameProperty(const char *name,
ANARIDataType type,
void *mem,
uint64_t size,
UsdDevice* device)
{
if (type == ANARI_STRING && strEquals(name, "usd::name"))
{
snprintf((char*)mem, size, "%s", UsdSharedString::c_str(this->getReadParams().usdName));
return 1;
}
else if (type == ANARI_UINT64 && strEquals(name, "usd::name.size"))
{
if (Assert64bitStringLengthProperty(size, UsdLogInfo(device, this, ANARI_ARRAY, this->getName()), "usd::name.size"))
{
uint64_t nameLen = this->getReadParams().usdName ? strlen(this->getReadParams().usdName->c_str())+1 : 0;
memcpy(mem, &nameLen, size);
}
return 1;
}
return 0;
}
}; | 5,007 | C | 29.168675 | 146 | 0.641901 |
NVIDIA-Omniverse/AnariUsdDevice/UsdAnari.h | // Copyright 2020 The Khronos Group
// SPDX-License-Identifier: Apache-2.0
#pragma once
#include "UsdBridgeData.h"
#include "UsdCommonMacros.h"
#include "anari/frontend/anari_enums.h"
#include "anari/anari_cpp/Traits.h"
#include <cstring>
class UsdDevice;
class UsdDataArray;
class UsdFrame;
class UsdGeometry;
class UsdGroup;
class UsdInstance;
class UsdLight;
class UsdMaterial;
class UsdRenderer;
class UsdSurface;
class UsdSampler;
class UsdSpatialField;
class UsdVolume;
class UsdWorld;
class UsdCamera;
class UsdSharedString;
class UsdBaseObject;
struct UsdDataLayout;
namespace anari
{
ANARI_TYPEFOR_SPECIALIZATION(UsdUint2, ANARI_UINT32_VEC2);
ANARI_TYPEFOR_SPECIALIZATION(UsdFloat2, ANARI_FLOAT32_VEC2);
ANARI_TYPEFOR_SPECIALIZATION(UsdFloat3, ANARI_FLOAT32_VEC3);
ANARI_TYPEFOR_SPECIALIZATION(UsdFloat4, ANARI_FLOAT32_VEC4);
ANARI_TYPEFOR_SPECIALIZATION(UsdQuaternion, ANARI_FLOAT32_QUAT_IJKW);
ANARI_TYPEFOR_SPECIALIZATION(UsdFloatMat4, ANARI_FLOAT32_MAT4);
ANARI_TYPEFOR_SPECIALIZATION(UsdFloatBox1, ANARI_FLOAT32_BOX1);
ANARI_TYPEFOR_SPECIALIZATION(UsdFloatBox2, ANARI_FLOAT32_BOX2);
ANARI_TYPEFOR_SPECIALIZATION(UsdSharedString*, ANARI_STRING);
ANARI_TYPEFOR_SPECIALIZATION(UsdDataArray*, ANARI_ARRAY);
ANARI_TYPEFOR_SPECIALIZATION(UsdFrame*, ANARI_FRAME);
ANARI_TYPEFOR_SPECIALIZATION(UsdGeometry*, ANARI_GEOMETRY);
ANARI_TYPEFOR_SPECIALIZATION(UsdGroup*, ANARI_GROUP);
ANARI_TYPEFOR_SPECIALIZATION(UsdInstance*, ANARI_INSTANCE);
ANARI_TYPEFOR_SPECIALIZATION(UsdLight*, ANARI_LIGHT);
ANARI_TYPEFOR_SPECIALIZATION(UsdMaterial*, ANARI_MATERIAL);
ANARI_TYPEFOR_SPECIALIZATION(UsdRenderer*, ANARI_RENDERER);
ANARI_TYPEFOR_SPECIALIZATION(UsdSampler*, ANARI_SAMPLER);
ANARI_TYPEFOR_SPECIALIZATION(UsdSpatialField*, ANARI_SPATIAL_FIELD);
ANARI_TYPEFOR_SPECIALIZATION(UsdSurface*, ANARI_SURFACE);
ANARI_TYPEFOR_SPECIALIZATION(UsdVolume*, ANARI_VOLUME);
ANARI_TYPEFOR_SPECIALIZATION(UsdWorld*, ANARI_WORLD);
}
// Shared convenience functions
namespace
{
inline bool strEquals(const char* arg0, const char* arg1)
{
return strcmp(arg0, arg1) == 0;
}
template <typename T>
inline void writeToVoidP(void *_p, T v)
{
T *p = (T *)_p;
*p = v;
}
}
// Standard log info
struct UsdLogInfo
{
UsdLogInfo(UsdDevice* dev, void* src, ANARIDataType srcType, const char* srcName)
: device(dev)
, source(src)
, sourceType(srcType)
, sourceName(srcName)
{}
UsdDevice* device = nullptr;
void* source = nullptr;
ANARIDataType sourceType = ANARI_VOID_POINTER;
const char* sourceName = nullptr;
};
void reportStatusThroughDevice(const UsdLogInfo& logInfo, ANARIStatusSeverity severity, ANARIStatusCode statusCode,
const char *format, const char* firstArg, const char* secondArg); // In case #include <UsdDevice.h> is undesired
#ifdef CHECK_MEMLEAKS
void logAllocationThroughDevice(UsdDevice* device, const void* ptr, ANARIDataType ptrType);
void logDeallocationThroughDevice(UsdDevice* device, const void* ptr, ANARIDataType ptrType);
#endif
// Anari <=> USD conversions
UsdBridgeType AnariToUsdBridgeType(ANARIDataType anariType);
UsdBridgeType AnariToUsdBridgeType_Flattened(ANARIDataType anariType);
const char* AnariTypeToString(ANARIDataType anariType);
const char* AnariAttributeToUsdName(const char* param, bool perInstance, const UsdLogInfo& logInfo);
UsdBridgeMaterialData::AlphaModes AnariToUsdAlphaMode(const char* alphaMode);
ANARIStatusSeverity UsdBridgeLogLevelToAnariSeverity(UsdBridgeLogLevel level);
bool Assert64bitStringLengthProperty(uint64_t size, const UsdLogInfo& logInfo, const char* propName);
bool AssertOneDimensional(const UsdDataLayout& layout, const UsdLogInfo& logInfo, const char* arrayName);
bool AssertNoStride(const UsdDataLayout& layout, const UsdLogInfo& logInfo, const char* arrayName);
bool AssertArrayType(UsdDataArray* dataArray, ANARIDataType dataType, const UsdLogInfo& logInfo, const char* errorMessage);
// Template definitions
template<typename AnariType>
class AnariToUsdObject {};
template<int AnariType>
class AnariToUsdBridgedObject {};
template<int AnariType>
class AnariToUsdBaseObject {};
#define USDBRIDGE_DEFINE_OBJECT_MAPPING(AnariType, UsdType) \
template<>\
class AnariToUsdObject<AnariType>\
{\
public:\
using Type = UsdType;\
};
#define USDBRIDGE_DEFINE_BASE_OBJECT_MAPPING(AnariType, UsdType) \
template<>\
class AnariToUsdBaseObject<(int)AnariType>\
{\
public:\
using Type = UsdType;\
};
#define USDBRIDGE_DEFINE_BRIDGED_OBJECT_MAPPING(AnariType, UsdType)\
template<>\
class AnariToUsdBridgedObject<(int)AnariType>\
{\
public:\
using Type = UsdType;\
};\
template<>\
class AnariToUsdBaseObject<(int)AnariType>\
{\
public:\
using Type = UsdType;\
};
USDBRIDGE_DEFINE_OBJECT_MAPPING(ANARIObject, UsdBaseObject)
USDBRIDGE_DEFINE_OBJECT_MAPPING(ANARIDevice, UsdDevice)
USDBRIDGE_DEFINE_OBJECT_MAPPING(ANARIArray, UsdDataArray)
USDBRIDGE_DEFINE_OBJECT_MAPPING(ANARIArray1D, UsdDataArray)
USDBRIDGE_DEFINE_OBJECT_MAPPING(ANARIArray2D, UsdDataArray)
USDBRIDGE_DEFINE_OBJECT_MAPPING(ANARIArray3D, UsdDataArray)
USDBRIDGE_DEFINE_OBJECT_MAPPING(ANARIFrame, UsdFrame)
USDBRIDGE_DEFINE_OBJECT_MAPPING(ANARIGeometry, UsdGeometry)
USDBRIDGE_DEFINE_OBJECT_MAPPING(ANARIGroup, UsdGroup)
USDBRIDGE_DEFINE_OBJECT_MAPPING(ANARIInstance, UsdInstance)
USDBRIDGE_DEFINE_OBJECT_MAPPING(ANARILight, UsdLight)
USDBRIDGE_DEFINE_OBJECT_MAPPING(ANARIMaterial, UsdMaterial)
USDBRIDGE_DEFINE_OBJECT_MAPPING(ANARISampler, UsdSampler)
USDBRIDGE_DEFINE_OBJECT_MAPPING(ANARISurface, UsdSurface)
USDBRIDGE_DEFINE_OBJECT_MAPPING(ANARIRenderer, UsdRenderer)
USDBRIDGE_DEFINE_OBJECT_MAPPING(ANARISpatialField, UsdSpatialField)
USDBRIDGE_DEFINE_OBJECT_MAPPING(ANARIVolume, UsdVolume)
USDBRIDGE_DEFINE_OBJECT_MAPPING(ANARIWorld, UsdWorld)
USDBRIDGE_DEFINE_OBJECT_MAPPING(ANARICamera, UsdCamera)
USDBRIDGE_DEFINE_BASE_OBJECT_MAPPING(ANARI_DEVICE, UsdDevice)
USDBRIDGE_DEFINE_BASE_OBJECT_MAPPING(ANARI_ARRAY, UsdDataArray)
USDBRIDGE_DEFINE_BASE_OBJECT_MAPPING(ANARI_ARRAY1D, UsdDataArray)
USDBRIDGE_DEFINE_BASE_OBJECT_MAPPING(ANARI_ARRAY2D, UsdDataArray)
USDBRIDGE_DEFINE_BASE_OBJECT_MAPPING(ANARI_ARRAY3D, UsdDataArray)
USDBRIDGE_DEFINE_BASE_OBJECT_MAPPING(ANARI_FRAME, UsdFrame)
USDBRIDGE_DEFINE_BASE_OBJECT_MAPPING(ANARI_RENDERER, UsdRenderer)
USDBRIDGE_DEFINE_BRIDGED_OBJECT_MAPPING(ANARI_GEOMETRY, UsdGeometry)
USDBRIDGE_DEFINE_BRIDGED_OBJECT_MAPPING(ANARI_GROUP, UsdGroup)
USDBRIDGE_DEFINE_BRIDGED_OBJECT_MAPPING(ANARI_INSTANCE, UsdInstance)
USDBRIDGE_DEFINE_BRIDGED_OBJECT_MAPPING(ANARI_LIGHT, UsdLight)
USDBRIDGE_DEFINE_BRIDGED_OBJECT_MAPPING(ANARI_MATERIAL, UsdMaterial)
USDBRIDGE_DEFINE_BRIDGED_OBJECT_MAPPING(ANARI_SURFACE, UsdSurface)
USDBRIDGE_DEFINE_BRIDGED_OBJECT_MAPPING(ANARI_SAMPLER, UsdSampler)
USDBRIDGE_DEFINE_BRIDGED_OBJECT_MAPPING(ANARI_SPATIAL_FIELD, UsdSpatialField)
USDBRIDGE_DEFINE_BRIDGED_OBJECT_MAPPING(ANARI_VOLUME, UsdVolume)
USDBRIDGE_DEFINE_BRIDGED_OBJECT_MAPPING(ANARI_WORLD, UsdWorld)
USDBRIDGE_DEFINE_BRIDGED_OBJECT_MAPPING(ANARI_CAMERA, UsdCamera)
template<typename AnariType>
typename AnariToUsdObject<AnariType>::Type* AnariToUsdObjectPtr(AnariType object) { return (typename AnariToUsdObject<AnariType>::Type*) object; }
| 7,214 | C | 36.38342 | 146 | 0.804963 |
NVIDIA-Omniverse/AnariUsdDevice/UsdWorld.cpp | // Copyright 2020 The Khronos Group
// SPDX-License-Identifier: Apache-2.0
#include "UsdWorld.h"
#include "UsdAnari.h"
#include "UsdInstance.h"
#include "UsdSurface.h"
#include "UsdVolume.h"
#include "UsdDevice.h"
#include "UsdDataArray.h"
#include "UsdGroup.h"
#define InstanceType ANARI_INSTANCE
#define SurfaceType ANARI_SURFACE
#define VolumeType ANARI_VOLUME
using InstanceUsdType = AnariToUsdBridgedObject<InstanceType>::Type;
using SurfaceUsdType = AnariToUsdBridgedObject<SurfaceType>::Type;
using VolumeUsdType = AnariToUsdBridgedObject<VolumeType>::Type;
DEFINE_PARAMETER_MAP(UsdWorld,
REGISTER_PARAMETER_MACRO("name", ANARI_STRING, name)
REGISTER_PARAMETER_MACRO("usd::name", ANARI_STRING, usdName)
REGISTER_PARAMETER_MACRO("usd::timeVarying", ANARI_INT32, timeVarying)
REGISTER_PARAMETER_MACRO("instance", ANARI_ARRAY, instances)
REGISTER_PARAMETER_MACRO("surface", ANARI_ARRAY, surfaces)
REGISTER_PARAMETER_MACRO("volume", ANARI_ARRAY, volumes)
)
constexpr UsdWorld::ComponentPair UsdWorld::componentParamNames[]; // Workaround for C++14's lack of inlining constexpr arrays
UsdWorld::UsdWorld(const char* name, UsdDevice* device)
: BridgedBaseObjectType(ANARI_WORLD, name, device)
{
}
UsdWorld::~UsdWorld()
{
#ifdef OBJECT_LIFETIME_EQUALS_USD_LIFETIME
if(cachedBridge)
cachedBridge->DeleteWorld(usdHandle);
#endif
}
void UsdWorld::remove(UsdDevice* device)
{
applyRemoveFunc(device, &UsdBridge::DeleteWorld);
}
bool UsdWorld::deferCommit(UsdDevice* device)
{
const UsdWorldData& paramData = getReadParams();
if(UsdObjectNotInitialized<InstanceUsdType>(paramData.instances) ||
UsdObjectNotInitialized<SurfaceUsdType>(paramData.surfaces) ||
UsdObjectNotInitialized<VolumeUsdType>(paramData.volumes))
{
return true;
}
return false;
}
bool UsdWorld::doCommitData(UsdDevice* device)
{
UsdBridge* usdBridge = device->getUsdBridge();
const char* objName = getName();
bool isNew = false;
if(!usdHandle.value)
isNew = usdBridge->CreateWorld(objName, usdHandle);
if (paramChanged || isNew)
{
doCommitRefs(device); // Perform immediate commit of refs - no params from children required
paramChanged = false;
}
return false;
}
void UsdWorld::doCommitRefs(UsdDevice* device)
{
UsdBridge* usdBridge = device->getUsdBridge();
const UsdWorldData& paramData = getReadParams();
double timeStep = device->getReadParams().timeStep;
const char* objName = getName();
bool instancesTimeVarying = isTimeVarying(UsdWorldComponents::INSTANCES);
bool surfacesTimeVarying = isTimeVarying(UsdWorldComponents::SURFACES);
bool volumesTimeVarying = isTimeVarying(UsdWorldComponents::VOLUMES);
UsdLogInfo logInfo(device, this, ANARI_WORLD, this->getName());
ManageRefArray<InstanceType, ANARIInstance, UsdInstance>(usdHandle, paramData.instances, instancesTimeVarying, timeStep,
instanceHandles, &UsdBridge::SetInstanceRefs, &UsdBridge::DeleteInstanceRefs,
usdBridge, logInfo, "UsdWorld commit failed: 'instance' array elements should be of type ANARI_INSTANCE");
ManageRefArray<SurfaceType, ANARISurface, UsdSurface>(usdHandle, paramData.surfaces, surfacesTimeVarying, timeStep,
surfaceHandles, &UsdBridge::SetSurfaceRefs, &UsdBridge::DeleteSurfaceRefs,
usdBridge, logInfo, "UsdGroup commit failed: 'surface' array elements should be of type ANARI_SURFACE");
ManageRefArray<VolumeType, ANARIVolume, UsdVolume>(usdHandle, paramData.volumes, volumesTimeVarying, timeStep,
volumeHandles, &UsdBridge::SetVolumeRefs, &UsdBridge::DeleteVolumeRefs,
usdBridge, logInfo, "UsdGroup commit failed: 'volume' array elements should be of type ANARI_VOLUME");
} | 3,668 | C++ | 33.289719 | 126 | 0.771538 |
NVIDIA-Omniverse/AnariUsdDevice/UsdSurface.cpp | // Copyright 2020 The Khronos Group
// SPDX-License-Identifier: Apache-2.0
#include "UsdSurface.h"
#include "UsdAnari.h"
#include "UsdDevice.h"
#include "UsdMaterial.h"
#include "UsdGeometry.h"
#define GeometryType ANARI_GEOMETRY
#define MaterialType ANARI_MATERIAL
using GeometryUsdType = AnariToUsdBridgedObject<GeometryType>::Type;
using MaterialUsdType = AnariToUsdBridgedObject<MaterialType>::Type;
DEFINE_PARAMETER_MAP(UsdSurface,
REGISTER_PARAMETER_MACRO("name", ANARI_STRING, name)
REGISTER_PARAMETER_MACRO("usd::name", ANARI_STRING, usdName)
REGISTER_PARAMETER_MACRO("usd::time.geometry", ANARI_FLOAT64, geometryRefTimeStep)
REGISTER_PARAMETER_MACRO("usd::time.material", ANARI_FLOAT64, materialRefTimeStep)
REGISTER_PARAMETER_MACRO("geometry", GeometryType, geometry)
REGISTER_PARAMETER_MACRO("material", MaterialType, material)
)
UsdSurface::UsdSurface(const char* name, UsdDevice* device)
: BridgedBaseObjectType(ANARI_SURFACE, name, device)
{
}
UsdSurface::~UsdSurface()
{
#ifdef OBJECT_LIFETIME_EQUALS_USD_LIFETIME
// Given that the object is destroyed, none of its references to other objects
// has to be updated anymore.
if(cachedBridge)
cachedBridge->DeleteSurface(usdHandle);
#endif
}
void UsdSurface::remove(UsdDevice* device)
{
applyRemoveFunc(device, &UsdBridge::DeleteSurface);
}
bool UsdSurface::deferCommit(UsdDevice* device)
{
// Given that all handles/data are used in doCommitRefs, which is always executed deferred, we don't need to check for initialization
//const UsdSurfaceData& paramData = getReadParams();
//if(UsdObjectNotInitialized<GeometryUsdType>(paramData.geometry) || UsdObjectNotInitialized<MaterialUsdType>(paramData.material))
//{
// return true;
//}
return false;
}
bool UsdSurface::doCommitData(UsdDevice* device)
{
UsdBridge* usdBridge = device->getUsdBridge();
bool isNew = false;
if (!usdHandle.value)
isNew = usdBridge->CreateSurface(getName(), usdHandle);
if (paramChanged || isNew)
{
paramChanged = false;
return true; // In this case a doCommitRefs is required, with data (timesteps, handles) from children
}
return false;
}
void UsdSurface::doCommitRefs(UsdDevice* device)
{
UsdBridge* usdBridge = device->getUsdBridge();
const UsdSurfaceData& paramData = getReadParams();
double worldTimeStep = device->getReadParams().timeStep;
// Make sure the references are updated on the Bridge side.
if (paramData.geometry)
{
double geomObjTimeStep = paramData.geometry->getReadParams().timeStep;
if(device->getReadParams().outputMaterial && paramData.material)
{
double matObjTimeStep = paramData.material->getReadParams().timeStep;
// The geometry to which a material binds has an effect on attribute reader (geom primvar) names, and output types
paramData.material->updateBoundParameters(paramData.geometry->isInstanced(), device);
usdBridge->SetGeometryMaterialRef(usdHandle,
paramData.geometry->getUsdHandle(),
paramData.material->getUsdHandle(),
worldTimeStep,
selectRefTime(paramData.geometryRefTimeStep, geomObjTimeStep, worldTimeStep),
selectRefTime(paramData.materialRefTimeStep, matObjTimeStep, worldTimeStep)
);
}
else
{
usdBridge->SetGeometryRef(usdHandle,
paramData.geometry->getUsdHandle(),
worldTimeStep,
selectRefTime(paramData.geometryRefTimeStep, geomObjTimeStep, worldTimeStep)
);
usdBridge->DeleteMaterialRef(usdHandle, worldTimeStep);
}
}
else
{
usdBridge->DeleteGeometryRef(usdHandle, worldTimeStep);
if (!paramData.material && device->getReadParams().outputMaterial)
{
usdBridge->DeleteMaterialRef(usdHandle, worldTimeStep);
}
}
} | 3,776 | C++ | 30.475 | 135 | 0.739142 |
NVIDIA-Omniverse/AnariUsdDevice/UsdCommonMacros.h | // Copyright 2020 The Khronos Group
// SPDX-License-Identifier: Apache-2.0
#pragma once
#include "UsdBridge/Common/UsdBridgeMacros.h"
//#define OBJECT_LIFETIME_EQUALS_USD_LIFETIME
#ifndef NDEBUG
// This is now handled in CMake
//#define CHECK_MEMLEAKS //asserts at ~UsdDevice() if memleak found
#endif
| 306 | C | 20.92857 | 67 | 0.761438 |
NVIDIA-Omniverse/AnariUsdDevice/UsdVolume.cpp | // Copyright 2020 The Khronos Group
// SPDX-License-Identifier: Apache-2.0
#include "UsdVolume.h"
#include "UsdAnari.h"
#include "UsdDevice.h"
#include "UsdSpatialField.h"
#include "UsdDataArray.h"
DEFINE_PARAMETER_MAP(UsdVolume,
REGISTER_PARAMETER_MACRO("name", ANARI_STRING, name)
REGISTER_PARAMETER_MACRO("usd::name", ANARI_STRING, usdName)
REGISTER_PARAMETER_MACRO("usd::timeVarying", ANARI_INT32, timeVarying)
REGISTER_PARAMETER_MACRO("usd::preClassified", ANARI_BOOL, preClassified)
REGISTER_PARAMETER_MACRO("usd::time.value", ANARI_FLOAT64, fieldRefTimeStep)
REGISTER_PARAMETER_MACRO("value", ANARI_SPATIAL_FIELD, field)
REGISTER_PARAMETER_MACRO("color", ANARI_ARRAY, color)
REGISTER_PARAMETER_MACRO("opacity", ANARI_ARRAY, opacity)
REGISTER_PARAMETER_MACRO("valueRange", ANARI_FLOAT32_BOX1, valueRange)
REGISTER_PARAMETER_MACRO("unitDistance", ANARI_FLOAT32, unitDistance)
)
constexpr UsdVolume::ComponentPair UsdVolume::componentParamNames[]; // Workaround for C++14's lack of inlining constexpr arrays
namespace
{
void GatherTfData(const UsdVolumeData& paramData, UsdBridgeTfData& tfData)
{
// Get transfer function data
const UsdDataArray* tfColor = paramData.color;
const UsdDataArray* tfOpacity = paramData.opacity;
UsdBridgeType tfColorType = AnariToUsdBridgeType(tfColor->getType());
UsdBridgeType tfOpacityType = AnariToUsdBridgeType(tfOpacity->getType());
// Write to struct
tfData.TfColors = tfColor->getData();
tfData.TfColorsType = tfColorType;
tfData.TfNumColors = (int)(tfColor->getLayout().numItems1);
tfData.TfOpacities = tfOpacity->getData();
tfData.TfOpacitiesType = tfOpacityType;
tfData.TfNumOpacities = (int)(tfOpacity->getLayout().numItems1);
tfData.TfValueRange[0] = paramData.valueRange.Data[0];
tfData.TfValueRange[1] = paramData.valueRange.Data[1];
}
}
UsdVolume::UsdVolume(const char* name, UsdDevice* device)
: BridgedBaseObjectType(ANARI_VOLUME, name, device)
, usdDevice(device)
{
usdDevice->addToVolumeList(this);
}
UsdVolume::~UsdVolume()
{
usdDevice->removeFromVolumeList(this);
#ifdef OBJECT_LIFETIME_EQUALS_USD_LIFETIME
// Given that the object is destroyed, none of its references to other objects
// has to be updated anymore.
if(cachedBridge)
cachedBridge->DeleteVolume(usdHandle);
#endif
}
void UsdVolume::remove(UsdDevice* device)
{
applyRemoveFunc(device, &UsdBridge::DeleteVolume);
}
bool UsdVolume::CheckTfParams(UsdDevice* device)
{
const UsdVolumeData& paramData = getReadParams();
const char* debugName = getName();
UsdLogInfo logInfo(device, this, ANARI_VOLUME, debugName);
// Only perform data(type) checks, data upload along with field in UsdVolume::commit()
const UsdDataArray* tfColor = paramData.color;
if (paramData.color == nullptr)
{
device->reportStatus(this, ANARI_VOLUME, ANARI_SEVERITY_ERROR, ANARI_STATUS_INVALID_ARGUMENT,
"UsdVolume '%s' commit failed: transferfunction color array not set.", debugName);
return false;
}
const UsdDataArray* tfOpacity = paramData.opacity;
if (tfOpacity == nullptr)
{
device->reportStatus(this, ANARI_VOLUME, ANARI_SEVERITY_ERROR, ANARI_STATUS_INVALID_ARGUMENT,
"UsdVolume '%s' commit failed: transferfunction opacity not set.", debugName);
return false;
}
if (!AssertOneDimensional(tfColor->getLayout(), logInfo, "tfColor"))
{
device->reportStatus(this, ANARI_VOLUME, ANARI_SEVERITY_ERROR, ANARI_STATUS_INVALID_ARGUMENT,
"UsdVolume '%s' commit failed: transferfunction color array not one-dimensional.", debugName);
return false;
}
if (!AssertOneDimensional(tfOpacity->getLayout(), logInfo, "tfOpacity"))
{
device->reportStatus(this, ANARI_VOLUME, ANARI_SEVERITY_ERROR, ANARI_STATUS_INVALID_ARGUMENT,
"UsdVolume '%s' commit failed: transferfunction opacity array not one-dimensional.", debugName);
return false;
}
if (paramData.preClassified && tfColor->getType() != ANARI_FLOAT32_VEC3)
{
device->reportStatus(this, ANARI_VOLUME, ANARI_SEVERITY_ERROR, ANARI_STATUS_INVALID_ARGUMENT,
"UsdVolume '%s' commit failed: transferfunction color array needs to be of type ANARI_FLOAT32_VEC3 when preClassified is set.", debugName);
return false;
}
if (tfOpacity->getType() != ANARI_FLOAT32)
{
device->reportStatus(this, ANARI_VOLUME, ANARI_SEVERITY_ERROR, ANARI_STATUS_INVALID_ARGUMENT,
"UsdVolume '%s' commit failed: transferfunction opacity array needs to be of type ANARI_FLOAT32.", debugName);
return false;
}
if (tfColor->getLayout().numItems1 != tfOpacity->getLayout().numItems1)
{
device->reportStatus(this, ANARI_VOLUME, ANARI_SEVERITY_WARNING, ANARI_STATUS_INVALID_ARGUMENT,
"UsdVolume '%s' commit warning: transferfunction output merges colors and opacities into one array, so they should contain the same number of elements.", debugName);
}
return true;
}
bool UsdVolume::UpdateVolume(UsdDevice* device, const char* debugName)
{
UsdBridge* usdBridge = device->getUsdBridge();
const UsdVolumeData& paramData = getReadParams();
UsdSpatialField* field = paramData.field;
if (!CheckTfParams(device))
return false;
// Get field data
const UsdSpatialFieldData& fieldParams = field->getReadParams();
const UsdDataArray* fieldDataArray = fieldParams.data;
if(!fieldDataArray) return false; // Enforced in field commit()
const UsdDataLayout& posLayout = fieldDataArray->getLayout();
UsdBridgeType fieldDataType = AnariToUsdBridgeType(fieldDataArray->getType());
//Set bridge volumedata
UsdBridgeVolumeData volumeData;
volumeData.Data = fieldDataArray->getData();
volumeData.DataType = fieldDataType;
size_t* elts = volumeData.NumElements;
float* ori = volumeData.Origin;
float* celldims = volumeData.CellDimensions;
elts[0] = posLayout.numItems1; elts[1] = posLayout.numItems2; elts[2] = posLayout.numItems3;
ori[0] = fieldParams.gridOrigin[0]; ori[1] = fieldParams.gridOrigin[1]; ori[2] = fieldParams.gridOrigin[2];
celldims[0] = fieldParams.gridSpacing[0]; celldims[1] = fieldParams.gridSpacing[1]; celldims[2] = fieldParams.gridSpacing[2];
GatherTfData(paramData, volumeData.TfData);
// Set whether we want to output source data or preclassified colored volumes
volumeData.preClassified = paramData.preClassified;
typedef UsdBridgeVolumeData::DataMemberId DMI;
volumeData.TimeVarying = DMI::ALL
& (field->isTimeVarying(UsdSpatialFieldComponents::DATA) ? DMI::ALL : ~DMI::DATA)
& (isTimeVarying(CType::COLOR) ? DMI::ALL : ~DMI::TFCOLORS)
& (isTimeVarying(CType::OPACITY) ? DMI::ALL : ~DMI::TFOPACITIES)
& (isTimeVarying(CType::VALUERANGE) ? DMI::ALL : ~DMI::TFVALUERANGE);
double worldTimeStep = device->getReadParams().timeStep;
double fieldTimeStep = selectRefTime(paramData.fieldRefTimeStep, fieldParams.timeStep, worldTimeStep); // use the link time, as there is no such thing as separate field data
usdBridge->SetSpatialFieldData(field->getUsdHandle(), volumeData, fieldTimeStep);
return true;
}
bool UsdVolume::deferCommit(UsdDevice* device)
{
// The spatial field may not yet have been committed, but the volume reads data from its params during commit. So always defer until flushing of commit list.
return !device->isFlushingCommitList();
}
bool UsdVolume::doCommitData(UsdDevice* device)
{
const UsdVolumeData& paramData = getReadParams();
UsdBridge* usdBridge = device->getUsdBridge();
bool isNew = false;
if (!usdHandle.value)
isNew = usdBridge->CreateVolume(getName(), usdHandle);
const char* debugName = getName();
if (prevField != paramData.field)
{
double worldTimeStep = device->getReadParams().timeStep;
// Make sure the references are updated on the Bridge side.
if (paramData.field)
{
const UsdSpatialFieldData& fieldParams = paramData.field->getReadParams();
usdBridge->SetSpatialFieldRef(usdHandle,
paramData.field->getUsdHandle(),
worldTimeStep,
selectRefTime(paramData.fieldRefTimeStep, fieldParams.timeStep, worldTimeStep)
);
}
else
{
usdBridge->DeleteSpatialFieldRef(usdHandle, worldTimeStep);
}
prevField = paramData.field;
}
// Regardless of whether tf param changes, field params or the vol reference itself, UpdateVolume is required.
if (paramChanged || paramData.field->paramChanged)
{
if(paramData.field)
{
UpdateVolume(device, debugName);
paramChanged = false;
paramData.field->paramChanged = false;
}
else
{
device->reportStatus(this, ANARI_VOLUME, ANARI_SEVERITY_ERROR, ANARI_STATUS_INVALID_ARGUMENT,
"UsdVolume '%s' commit failed: field reference missing.", debugName);
}
}
return false;
} | 8,778 | C++ | 35.127572 | 175 | 0.733424 |
NVIDIA-Omniverse/AnariUsdDevice/UsdBridgedBaseObject.h | // Copyright 2020 The Khronos Group
// SPDX-License-Identifier: Apache-2.0
#pragma once
#include "UsdBaseObject.h"
#include "UsdBridge/UsdBridge.h"
#include "UsdDevice.h"
#include "UsdDataArray.h"
#include <cmath>
#include <utility>
enum class UsdEmptyComponents
{
};
template<typename T, typename D, typename H, typename C = UsdEmptyComponents>
class UsdBridgedBaseObject : public UsdParameterizedBaseObject<T, D>
{
protected:
using CType = C;
// Timevarying helper functions (classes workaround to allow for partial specialization)
template<typename IT, typename ID, typename IH, typename IC>
class TimeVaryingClass
{
public:
bool findTimeVarying(const char* name, IC& component)
{
for(auto& cmpName : IT::componentParamNames)
{
if(strEquals(name, cmpName.second))
{
component = cmpName.first;
return true;
}
}
return false;
}
void setTimeVarying(UsdBridgedBaseObject<IT,ID,IH,IC>* bridgedObj, IC component, bool value)
{
ID& params = bridgedObj->getWriteParams();
int bit = (1 << static_cast<int>(component));
params.timeVarying = value ? (params.timeVarying | bit) : (params.timeVarying & ~bit);
}
};
template<typename IT, typename ID, typename IH>
class TimeVaryingClass<IT, ID, IH, UsdEmptyComponents>
{
public:
bool findTimeVarying(const char* name, UsdEmptyComponents& component)
{
return false;
}
void setTimeVarying(UsdBridgedBaseObject<IT,ID,IH,UsdEmptyComponents>* bridgedObj, UsdEmptyComponents component, bool value)
{
}
};
bool setTimeVaryingParam(const char *name,
ANARIDataType type,
const void *mem,
UsdDevice* device)
{
static const char* paramName = "usd::timeVarying.";
bool value = *(reinterpret_cast<const uint32_t*>(mem));
if (type == ANARI_BOOL)
{
if (strcmp(name, paramName) > 0)
{
const char* secondPart = name + strlen(paramName);
C component;
TimeVaryingClass<T,D,H,C> timevarHelper;
if(timevarHelper.findTimeVarying(secondPart, component))
{
timevarHelper.setTimeVarying(this, component, value);
return true;
}
}
}
return false;
}
bool isTimeVarying(C component) const
{
const D& params = this->getReadParams();
return params.timeVarying & (1 << static_cast<int>(component));
}
bool setRemovePrimParam(const char *name,
ANARIDataType type,
const void *mem,
UsdDevice* device)
{
if (type == ANARI_BOOL)
{
if (strcmp(name, "usd::removePrim") == 0)
{
removePrim = true;
return true;
}
}
return false;
}
public:
using ComponentPair = std::pair<C, const char*>; // Used to define a componentParamNames
UsdBridgedBaseObject(ANARIDataType t, const char* name, UsdDevice* device)
: UsdParameterizedBaseObject<T, D>(t, device)
, uniqueName(name)
{
}
H getUsdHandle() const { return usdHandle; }
const char* getName() const override { return this->getReadParams().usdName ? this->getReadParams().usdName->c_str() : uniqueName; }
void filterSetParam(const char *name,
ANARIDataType type,
const void *mem,
UsdDevice* device) override
{
if(!this->setTimeVaryingParam(name, type, mem, device))
if (!this->setNameParam(name, type, mem, device))
if(!this->setRemovePrimParam(name, type, mem, device))
this->setParam(name, type, mem, device);
}
int getProperty(const char *name,
ANARIDataType type,
void *mem,
uint64_t size,
UsdDevice* device) override
{
int nameResult = this->getNameProperty(name, type, mem, size, device);
if(!nameResult)
{
UsdBridge* usdBridge = device->getUsdBridge();
if(!usdBridge)
{
reportStatusThroughDevice(UsdLogInfo(device, this, ANARI_OBJECT, nullptr), ANARI_SEVERITY_WARNING, ANARI_STATUS_NO_ERROR,
"%s parameter '%s' cannot be read with getProperty(); it requires a succesful device parameter commit.", getName(), name);
}
if (type == ANARI_STRING && strEquals(name, "usd::primPath"))
{
const char* primPath = usdBridge->GetPrimPath(&usdHandle);
snprintf((char*)mem, size, "%s", primPath);
return 1;
}
else if (type == ANARI_UINT64 && strEquals(name, "usd::primPath.size"))
{
if (Assert64bitStringLengthProperty(size, UsdLogInfo(device, this, ANARI_OBJECT, this->getName()), "usd::primPath.size"))
{
const char* primPath = usdBridge->GetPrimPath(&usdHandle);
uint64_t nameLen = strlen(primPath)+1;
memcpy(mem, &nameLen, size);
}
return 1;
}
}
return nameResult;
}
virtual void commit(UsdDevice* device) override
{
#ifdef OBJECT_LIFETIME_EQUALS_USD_LIFETIME
cachedBridge = device->getUsdBridge();
#endif
UsdParameterizedBaseObject<T, D>::commit(device);
}
double selectObjTime(double objTimeStep, double worldTimeStep)
{
return
#ifdef VALUE_CLIP_RETIMING
!std::isnan(objTimeStep) ? objTimeStep :
#endif
worldTimeStep;
}
double selectRefTime(double refTimeStep, double objTimeStep, double worldTimeStep)
{
return
#ifdef VALUE_CLIP_RETIMING
!std::isnan(refTimeStep) ? refTimeStep :
(!std::isnan(objTimeStep) ? objTimeStep : worldTimeStep);
#else
worldTimeStep;
#endif
}
bool getRemovePrim() const { return removePrim; }
protected:
typedef UsdBridgedBaseObject<T,D,H,C> BridgedBaseObjectType;
typedef void (UsdBridge::*UsdBridgeMemFn)(H handle);
void applyRemoveFunc(UsdDevice* device, UsdBridgeMemFn func)
{
UsdBridge* usdBridge = device->getUsdBridge();
if(usdBridge && usdHandle.value)
(usdBridge->*func)(usdHandle);
}
const char* uniqueName;
H usdHandle;
bool removePrim = false;
#ifdef OBJECT_LIFETIME_EQUALS_USD_LIFETIME
UsdBridge* cachedBridge = nullptr;
#endif
};
template<typename T, typename D, typename H, typename C>
inline bool UsdObjectNotInitialized(const UsdBridgedBaseObject<T,D,H,C>* obj)
{
return obj && !obj->getUsdHandle().value;
}
template<typename T>
inline bool UsdObjectNotInitialized(UsdDataArray* objects)
{
if (!objects)
return false;
bool notInitialized = false;
if(anari::isObject(objects->getType()))
{
const T* const * object = reinterpret_cast<const T* const *>(objects->getData());
uint64_t numObjects = objects->getLayout().numItems1;
for(int i = 0; i < numObjects; ++i)
{
notInitialized = notInitialized || UsdObjectNotInitialized(object[i]);
}
}
return notInitialized;
} | 7,017 | C | 27.644898 | 136 | 0.629899 |
NVIDIA-Omniverse/AnariUsdDevice/UsdGroup.h | // Copyright 2020 The Khronos Group
// SPDX-License-Identifier: Apache-2.0
#pragma once
#include "UsdBridgedBaseObject.h"
#include "UsdBridge.h"
class UsdDevice;
class UsdDataArray;
enum class UsdGroupComponents
{
SURFACES = 0,
VOLUMES
};
struct UsdGroupData
{
UsdSharedString* name = nullptr;
UsdSharedString* usdName = nullptr;
int timeVarying = 0xFFFFFFFF; // Bitmask indicating which attributes are time-varying.
UsdDataArray* surfaces = nullptr;
UsdDataArray* volumes = nullptr;
};
class UsdGroup : public UsdBridgedBaseObject<UsdGroup, UsdGroupData, UsdGroupHandle, UsdGroupComponents>
{
public:
UsdGroup(const char* name, UsdDevice* device);
~UsdGroup();
void remove(UsdDevice* device) override;
static constexpr ComponentPair componentParamNames[] = {
ComponentPair(UsdGroupComponents::SURFACES, "surface"),
ComponentPair(UsdGroupComponents::VOLUMES, "volume")};
protected:
bool deferCommit(UsdDevice* device) override;
bool doCommitData(UsdDevice* device) override;
void doCommitRefs(UsdDevice* device) override;
std::vector<UsdSurfaceHandle> surfaceHandles; // for convenience
std::vector<UsdVolumeHandle> volumeHandles; // for convenience
};
typedef void (UsdBridge::*SetRefFunc)(UsdGroupHandle, const UsdSurfaceHandle*, uint64_t, bool, double);
template<int ChildAnariTypeEnum, typename ChildAnariType, typename ChildUsdType,
typename ParentHandleType, typename ChildHandleType>
void ManageRefArray(ParentHandleType parentHandle, UsdDataArray* childArray, bool refsTimeVarying, double timeStep, std::vector<ChildHandleType>& tempChildHandles,
void (UsdBridge::*SetRefFunc)(ParentHandleType, const ChildHandleType*, uint64_t, bool, double), void (UsdBridge::*DeleteRefFunc)(ParentHandleType, bool, double),
UsdBridge* usdBridge, UsdLogInfo& logInfo, const char* typeErrorMsg)
{
bool validRefs = AssertArrayType(childArray, ChildAnariTypeEnum, logInfo, typeErrorMsg);
if(validRefs)
{
if (childArray)
{
const ChildAnariType* children = reinterpret_cast<const ChildAnariType*>(childArray->getData());
uint64_t numChildren = childArray->getLayout().numItems1;
tempChildHandles.resize(numChildren);
for (uint64_t i = 0; i < numChildren; ++i)
{
const ChildUsdType* usdChild = reinterpret_cast<const ChildUsdType*>(children[i]);
tempChildHandles[i] = usdChild->getUsdHandle();
}
(usdBridge->*SetRefFunc)(parentHandle, tempChildHandles.data(), numChildren, refsTimeVarying, timeStep);
}
else
{
(usdBridge->*DeleteRefFunc)(parentHandle, refsTimeVarying, timeStep);
}
}
} | 2,658 | C | 32.2375 | 165 | 0.743416 |
NVIDIA-Omniverse/AnariUsdDevice/UsdLibrary.cpp | // Copyright 2023 The Khronos Group
// SPDX-License-Identifier: Apache-2.0
#include "UsdDevice.h"
#include "anari/backend/LibraryImpl.h"
#ifndef USDDevice_INTERFACE
#define USDDevice_INTERFACE
#endif
namespace anari {
namespace usd {
const char **query_extensions();
struct UsdLibrary : public anari::LibraryImpl {
UsdLibrary(void *lib, ANARIStatusCallback defaultStatusCB,
const void *statusCBPtr);
ANARIDevice newDevice(const char *subtype) override;
const char **getDeviceExtensions(const char *deviceType) override;
};
// Definitions ////////////////////////////////////////////////////////////////
UsdLibrary::UsdLibrary(void *lib, ANARIStatusCallback defaultStatusCB,
const void *statusCBPtr)
: anari::LibraryImpl(lib, defaultStatusCB, statusCBPtr) {}
ANARIDevice UsdLibrary::newDevice(const char * /*subtype*/) {
return (ANARIDevice) new UsdDevice(this_library());
}
const char **UsdLibrary::getDeviceExtensions(const char * /*deviceType*/) {
return query_extensions();
}
} // namespace usd
} // namespace anari
// Define library entrypoint //////////////////////////////////////////////////
extern "C" USDDevice_INTERFACE
ANARI_DEFINE_LIBRARY_ENTRYPOINT(usd, handle, scb, scbPtr) {
return (ANARILibrary) new anari::usd::UsdLibrary(handle, scb, scbPtr);
}
| 1,328 | C++ | 27.276595 | 79 | 0.670934 |
NVIDIA-Omniverse/AnariUsdDevice/UsdAnari.cpp | #include "UsdAnari.h"
#include "UsdDevice.h"
#include "UsdDataArray.h"
#include "anari/frontend/type_utility.h"
UsdBridgeType AnariToUsdBridgeType(ANARIDataType anariType)
{
switch (anariType)
{
case ANARI_UINT8: return UsdBridgeType::UCHAR;
case ANARI_UINT8_VEC2: return UsdBridgeType::UCHAR2;
case ANARI_UINT8_VEC3: return UsdBridgeType::UCHAR3;
case ANARI_UINT8_VEC4: return UsdBridgeType::UCHAR4;
case ANARI_INT8: return UsdBridgeType::CHAR;
case ANARI_INT8_VEC2: return UsdBridgeType::CHAR2;
case ANARI_INT8_VEC3: return UsdBridgeType::CHAR3;
case ANARI_INT8_VEC4: return UsdBridgeType::CHAR4;
case ANARI_UFIXED8: return UsdBridgeType::UCHAR;
case ANARI_UFIXED8_VEC2: return UsdBridgeType::UCHAR2;
case ANARI_UFIXED8_VEC3: return UsdBridgeType::UCHAR3;
case ANARI_UFIXED8_VEC4: return UsdBridgeType::UCHAR4;
case ANARI_FIXED8: return UsdBridgeType::CHAR;
case ANARI_FIXED8_VEC2: return UsdBridgeType::CHAR2;
case ANARI_FIXED8_VEC3: return UsdBridgeType::CHAR3;
case ANARI_FIXED8_VEC4: return UsdBridgeType::CHAR4;
case ANARI_UFIXED8_R_SRGB: return UsdBridgeType::UCHAR_SRGB_R;
case ANARI_UFIXED8_RA_SRGB: return UsdBridgeType::UCHAR_SRGB_RA;
case ANARI_UFIXED8_RGB_SRGB: return UsdBridgeType::UCHAR_SRGB_RGB;
case ANARI_UFIXED8_RGBA_SRGB: return UsdBridgeType::UCHAR_SRGB_RGBA;
case ANARI_UINT16: return UsdBridgeType::USHORT;
case ANARI_UINT16_VEC2: return UsdBridgeType::USHORT2;
case ANARI_UINT16_VEC3: return UsdBridgeType::USHORT3;
case ANARI_UINT16_VEC4: return UsdBridgeType::USHORT4;
case ANARI_INT16: return UsdBridgeType::SHORT;
case ANARI_INT16_VEC2: return UsdBridgeType::SHORT2;
case ANARI_INT16_VEC3: return UsdBridgeType::SHORT3;
case ANARI_INT16_VEC4: return UsdBridgeType::SHORT4;
case ANARI_UFIXED16: return UsdBridgeType::USHORT;
case ANARI_UFIXED16_VEC2: return UsdBridgeType::USHORT2;
case ANARI_UFIXED16_VEC3: return UsdBridgeType::USHORT3;
case ANARI_UFIXED16_VEC4: return UsdBridgeType::USHORT4;
case ANARI_FIXED16: return UsdBridgeType::SHORT;
case ANARI_FIXED16_VEC2: return UsdBridgeType::SHORT2;
case ANARI_FIXED16_VEC3: return UsdBridgeType::SHORT3;
case ANARI_FIXED16_VEC4: return UsdBridgeType::SHORT4;
case ANARI_UINT32: return UsdBridgeType::UINT;
case ANARI_UINT32_VEC2: return UsdBridgeType::UINT2;
case ANARI_UINT32_VEC3: return UsdBridgeType::UINT3;
case ANARI_UINT32_VEC4: return UsdBridgeType::UINT4;
case ANARI_INT32: return UsdBridgeType::INT;
case ANARI_INT32_VEC2: return UsdBridgeType::INT2;
case ANARI_INT32_VEC3: return UsdBridgeType::INT3;
case ANARI_INT32_VEC4: return UsdBridgeType::INT4;
case ANARI_UFIXED32: return UsdBridgeType::UINT;
case ANARI_UFIXED32_VEC2: return UsdBridgeType::UINT2;
case ANARI_UFIXED32_VEC3: return UsdBridgeType::UINT3;
case ANARI_UFIXED32_VEC4: return UsdBridgeType::UINT4;
case ANARI_FIXED32: return UsdBridgeType::INT;
case ANARI_FIXED32_VEC2: return UsdBridgeType::INT2;
case ANARI_FIXED32_VEC3: return UsdBridgeType::INT3;
case ANARI_FIXED32_VEC4: return UsdBridgeType::INT4;
case ANARI_UINT64: return UsdBridgeType::ULONG;
case ANARI_UINT64_VEC2: return UsdBridgeType::ULONG2;
case ANARI_UINT64_VEC3: return UsdBridgeType::ULONG3;
case ANARI_UINT64_VEC4: return UsdBridgeType::ULONG4;
case ANARI_INT64: return UsdBridgeType::LONG;
case ANARI_INT64_VEC2: return UsdBridgeType::LONG2;
case ANARI_INT64_VEC3: return UsdBridgeType::LONG3;
case ANARI_INT64_VEC4: return UsdBridgeType::LONG4;
case ANARI_FLOAT32: return UsdBridgeType::FLOAT;
case ANARI_FLOAT32_VEC2: return UsdBridgeType::FLOAT2;
case ANARI_FLOAT32_VEC3: return UsdBridgeType::FLOAT3;
case ANARI_FLOAT32_VEC4: return UsdBridgeType::FLOAT4;
case ANARI_FLOAT64: return UsdBridgeType::DOUBLE;
case ANARI_FLOAT64_VEC2: return UsdBridgeType::DOUBLE2;
case ANARI_FLOAT64_VEC3: return UsdBridgeType::DOUBLE3;
case ANARI_FLOAT64_VEC4: return UsdBridgeType::DOUBLE4;
case ANARI_INT32_BOX1: return UsdBridgeType::INT_PAIR;
case ANARI_INT32_BOX2: return UsdBridgeType::INT_PAIR2;
case ANARI_INT32_BOX3: return UsdBridgeType::INT_PAIR3;
case ANARI_INT32_BOX4: return UsdBridgeType::INT_PAIR4;
case ANARI_FLOAT32_BOX1: return UsdBridgeType::FLOAT_PAIR;
case ANARI_FLOAT32_BOX2: return UsdBridgeType::FLOAT_PAIR2;
case ANARI_FLOAT32_BOX3: return UsdBridgeType::FLOAT_PAIR3;
case ANARI_FLOAT32_BOX4: return UsdBridgeType::FLOAT_PAIR4;
case ANARI_UINT64_REGION1: return UsdBridgeType::ULONG_PAIR;
case ANARI_UINT64_REGION2: return UsdBridgeType::ULONG_PAIR2;
case ANARI_UINT64_REGION3: return UsdBridgeType::ULONG_PAIR3;
case ANARI_UINT64_REGION4: return UsdBridgeType::ULONG_PAIR4;
case ANARI_FLOAT32_MAT2: return UsdBridgeType::FLOAT_MAT2;
case ANARI_FLOAT32_MAT3: return UsdBridgeType::FLOAT_MAT3;
case ANARI_FLOAT32_MAT4: return UsdBridgeType::FLOAT_MAT4;
case ANARI_FLOAT32_MAT2x3: return UsdBridgeType::FLOAT_MAT2x3;
case ANARI_FLOAT32_MAT3x4: return UsdBridgeType::FLOAT_MAT3x4;
case ANARI_FLOAT32_QUAT_IJKW: return UsdBridgeType::FLOAT4;
default: return UsdBridgeType::UNDEFINED;
}
}
UsdBridgeType AnariToUsdBridgeType_Flattened(ANARIDataType anariType)
{
switch (anariType)
{
case ANARI_UINT8: return UsdBridgeType::UCHAR;
case ANARI_UINT8_VEC2: return UsdBridgeType::UCHAR;
case ANARI_UINT8_VEC3: return UsdBridgeType::UCHAR;
case ANARI_UINT8_VEC4: return UsdBridgeType::UCHAR;
case ANARI_INT8: return UsdBridgeType::CHAR;
case ANARI_INT8_VEC2: return UsdBridgeType::CHAR;
case ANARI_INT8_VEC3: return UsdBridgeType::CHAR;
case ANARI_INT8_VEC4: return UsdBridgeType::CHAR;
case ANARI_UFIXED8: return UsdBridgeType::UCHAR;
case ANARI_UFIXED8_VEC2: return UsdBridgeType::UCHAR;
case ANARI_UFIXED8_VEC3: return UsdBridgeType::UCHAR;
case ANARI_UFIXED8_VEC4: return UsdBridgeType::UCHAR;
case ANARI_FIXED8: return UsdBridgeType::CHAR;
case ANARI_FIXED8_VEC2: return UsdBridgeType::CHAR;
case ANARI_FIXED8_VEC3: return UsdBridgeType::CHAR;
case ANARI_FIXED8_VEC4: return UsdBridgeType::CHAR;
case ANARI_UFIXED8_R_SRGB: return UsdBridgeType::UCHAR_SRGB_R;
case ANARI_UFIXED8_RA_SRGB: return UsdBridgeType::UCHAR_SRGB_R;
case ANARI_UFIXED8_RGB_SRGB: return UsdBridgeType::UCHAR_SRGB_R;
case ANARI_UFIXED8_RGBA_SRGB: return UsdBridgeType::UCHAR_SRGB_R;
case ANARI_UINT16: return UsdBridgeType::USHORT;
case ANARI_UINT16_VEC2: return UsdBridgeType::USHORT;
case ANARI_UINT16_VEC3: return UsdBridgeType::USHORT;
case ANARI_UINT16_VEC4: return UsdBridgeType::USHORT;
case ANARI_INT16: return UsdBridgeType::SHORT;
case ANARI_INT16_VEC2: return UsdBridgeType::SHORT;
case ANARI_INT16_VEC3: return UsdBridgeType::SHORT;
case ANARI_INT16_VEC4: return UsdBridgeType::SHORT;
case ANARI_UFIXED16: return UsdBridgeType::USHORT;
case ANARI_UFIXED16_VEC2: return UsdBridgeType::USHORT;
case ANARI_UFIXED16_VEC3: return UsdBridgeType::USHORT;
case ANARI_UFIXED16_VEC4: return UsdBridgeType::USHORT;
case ANARI_FIXED16: return UsdBridgeType::SHORT;
case ANARI_FIXED16_VEC2: return UsdBridgeType::SHORT;
case ANARI_FIXED16_VEC3: return UsdBridgeType::SHORT;
case ANARI_FIXED16_VEC4: return UsdBridgeType::SHORT;
case ANARI_UINT32: return UsdBridgeType::UINT;
case ANARI_UINT32_VEC2: return UsdBridgeType::UINT;
case ANARI_UINT32_VEC3: return UsdBridgeType::UINT;
case ANARI_UINT32_VEC4: return UsdBridgeType::UINT;
case ANARI_INT32: return UsdBridgeType::INT;
case ANARI_INT32_VEC2: return UsdBridgeType::INT;
case ANARI_INT32_VEC3: return UsdBridgeType::INT;
case ANARI_INT32_VEC4: return UsdBridgeType::INT;
case ANARI_UFIXED32: return UsdBridgeType::UINT;
case ANARI_UFIXED32_VEC2: return UsdBridgeType::UINT;
case ANARI_UFIXED32_VEC3: return UsdBridgeType::UINT;
case ANARI_UFIXED32_VEC4: return UsdBridgeType::UINT;
case ANARI_FIXED32: return UsdBridgeType::INT;
case ANARI_FIXED32_VEC2: return UsdBridgeType::INT;
case ANARI_FIXED32_VEC3: return UsdBridgeType::INT;
case ANARI_FIXED32_VEC4: return UsdBridgeType::INT;
case ANARI_UINT64: return UsdBridgeType::ULONG;
case ANARI_UINT64_VEC2: return UsdBridgeType::ULONG;
case ANARI_UINT64_VEC3: return UsdBridgeType::ULONG;
case ANARI_UINT64_VEC4: return UsdBridgeType::ULONG;
case ANARI_INT64: return UsdBridgeType::LONG;
case ANARI_INT64_VEC2: return UsdBridgeType::LONG;
case ANARI_INT64_VEC3: return UsdBridgeType::LONG;
case ANARI_INT64_VEC4: return UsdBridgeType::LONG;
case ANARI_FLOAT32: return UsdBridgeType::FLOAT;
case ANARI_FLOAT32_VEC2: return UsdBridgeType::FLOAT;
case ANARI_FLOAT32_VEC3: return UsdBridgeType::FLOAT;
case ANARI_FLOAT32_VEC4: return UsdBridgeType::FLOAT;
case ANARI_FLOAT64: return UsdBridgeType::DOUBLE;
case ANARI_FLOAT64_VEC2: return UsdBridgeType::DOUBLE;
case ANARI_FLOAT64_VEC3: return UsdBridgeType::DOUBLE;
case ANARI_FLOAT64_VEC4: return UsdBridgeType::DOUBLE;
case ANARI_INT32_BOX1: return UsdBridgeType::INT;
case ANARI_INT32_BOX2: return UsdBridgeType::INT;
case ANARI_INT32_BOX3: return UsdBridgeType::INT;
case ANARI_INT32_BOX4: return UsdBridgeType::INT;
case ANARI_FLOAT32_BOX1: return UsdBridgeType::FLOAT;
case ANARI_FLOAT32_BOX2: return UsdBridgeType::FLOAT;
case ANARI_FLOAT32_BOX3: return UsdBridgeType::FLOAT;
case ANARI_FLOAT32_BOX4: return UsdBridgeType::FLOAT;
case ANARI_UINT64_REGION1: return UsdBridgeType::ULONG;
case ANARI_UINT64_REGION2: return UsdBridgeType::ULONG;
case ANARI_UINT64_REGION3: return UsdBridgeType::ULONG;
case ANARI_UINT64_REGION4: return UsdBridgeType::ULONG;
case ANARI_FLOAT32_MAT2: return UsdBridgeType::FLOAT;
case ANARI_FLOAT32_MAT3: return UsdBridgeType::FLOAT;
case ANARI_FLOAT32_MAT4: return UsdBridgeType::FLOAT;
case ANARI_FLOAT32_MAT2x3: return UsdBridgeType::FLOAT;
case ANARI_FLOAT32_MAT3x4: return UsdBridgeType::FLOAT;
default: return UsdBridgeType::UNDEFINED;
}
}
template<int T>
struct AnariTypeStringConverter : public anari::ANARITypeProperties<T>
{
const char* operator()(){ return anari::ANARITypeProperties<T>::enum_name; }
};
const char* AnariTypeToString(ANARIDataType anariType)
{
return anari::anariTypeInvoke<const char*, AnariTypeStringConverter>(anariType);
}
const char* AnariAttributeToUsdName(const char* param, bool perInstance, const UsdLogInfo& logInfo)
{
if(strEquals(param, "worldPosition")
|| strEquals(param, "worldNormal"))
{
reportStatusThroughDevice(logInfo, ANARI_SEVERITY_ERROR, ANARI_STATUS_INVALID_ARGUMENT,
"UsdSampler '%s' inAttribute %s not supported, use inTransform parameter on object-space attribute instead.", logInfo.sourceName, param);
}
if(strEquals(param, "objectPosition"))
{
if(perInstance)
return "positions";
else
return "points";
}
else if(strEquals(param, "objectNormal"))
{
return "normals";
}
//else if(!strncmp(param, "attribute", 9))
//{
// return param;
//}
return param; // The generic case just returns the param itself
}
UsdBridgeMaterialData::AlphaModes AnariToUsdAlphaMode(const char* alphaMode)
{
if(alphaMode)
{
if(strEquals(alphaMode, "blend"))
{
return UsdBridgeMaterialData::AlphaModes::BLEND;
}
else if(strEquals(alphaMode, "mask"))
{
return UsdBridgeMaterialData::AlphaModes::MASK;
}
}
return UsdBridgeMaterialData::AlphaModes::NONE;
}
ANARIStatusSeverity UsdBridgeLogLevelToAnariSeverity(UsdBridgeLogLevel level)
{
ANARIStatusSeverity severity = ANARI_SEVERITY_INFO;
switch (level)
{
case UsdBridgeLogLevel::STATUS: severity = ANARI_SEVERITY_INFO; break;
case UsdBridgeLogLevel::WARNING: severity = ANARI_SEVERITY_WARNING; break;
case UsdBridgeLogLevel::ERR: severity = ANARI_SEVERITY_ERROR; break;
default: severity = ANARI_SEVERITY_INFO; break;
}
return severity;
}
void reportStatusThroughDevice(const UsdLogInfo& logInfo, ANARIStatusSeverity severity, ANARIStatusCode statusCode,
const char *format, const char* firstArg, const char* secondArg)
{
if(logInfo.device)
logInfo.device->reportStatus(logInfo.source, logInfo.sourceType, severity, statusCode, format, firstArg, secondArg);
}
#ifdef CHECK_MEMLEAKS
void logAllocationThroughDevice(UsdDevice* device, const void* ptr, ANARIDataType ptrType)
{
if(anari::isObject(ptrType))
device->LogObjAllocation((const UsdBaseObject*)ptr);
else if(ptrType == ANARI_STRING)
device->LogStrAllocation((const UsdSharedString*)ptr);
else
device->LogRawAllocation(ptr);
}
void logDeallocationThroughDevice(UsdDevice* device, const void* ptr, ANARIDataType ptrType)
{
if(anari::isObject(ptrType))
device->LogObjDeallocation((const UsdBaseObject*)ptr);
else if(ptrType == ANARI_STRING)
device->LogStrDeallocation((const UsdSharedString*)ptr);
else
device->LogRawDeallocation(ptr);
}
#endif
bool Assert64bitStringLengthProperty(uint64_t size, const UsdLogInfo& logInfo, const char* name)
{
if (size != sizeof(uint64_t) && logInfo.device)
{
logInfo.device->reportStatus(logInfo.source, ANARI_OBJECT, ANARI_SEVERITY_ERROR, ANARI_STATUS_INVALID_ARGUMENT,
"On object '%s', getProperty() on %s, size parameter differs from sizeof(uint64_t)", logInfo.sourceName, name);
return false;
}
return true;
}
bool AssertOneDimensional(const UsdDataLayout& layout, const UsdLogInfo& logInfo, const char* arrayName)
{
if (!layout.isOneDimensional() && logInfo.device)
{
logInfo.device->reportStatus(logInfo.source, logInfo.sourceType, ANARI_SEVERITY_ERROR, ANARI_STATUS_INVALID_ARGUMENT, "On object '%s', '%s' array has to be 1-dimensional.", logInfo.sourceName, arrayName);
return false;
}
return true;
}
bool AssertNoStride(const UsdDataLayout& layout, const UsdLogInfo& logInfo, const char* arrayName)
{
if (!layout.isDense() && logInfo.device)
{
logInfo.device->reportStatus(logInfo.source, logInfo.sourceType, ANARI_SEVERITY_ERROR, ANARI_STATUS_INVALID_ARGUMENT, "On object '%s', '%s' layout strides should all be 0.", logInfo.sourceName, arrayName);
return false;
}
return true;
}
bool AssertArrayType(UsdDataArray* dataArray, ANARIDataType dataType, const UsdLogInfo& logInfo, const char* errorMessage)
{
if (dataArray && dataArray->getType() != dataType && logInfo.device)
{
logInfo.device->reportStatus(logInfo.source, logInfo.sourceType, ANARI_SEVERITY_ERROR, ANARI_STATUS_INVALID_ARGUMENT, "On object '%s', '%s'", logInfo.sourceName, errorMessage);
return false;
}
return true;
} | 14,507 | C++ | 39.638655 | 209 | 0.766044 |
NVIDIA-Omniverse/AnariUsdDevice/UsdSpatialField.cpp | // Copyright 2020 The Khronos Group
// SPDX-License-Identifier: Apache-2.0
#include "UsdSpatialField.h"
#include "UsdAnari.h"
#include "UsdDataArray.h"
#include "UsdDevice.h"
#include "UsdVolume.h"
#include <algorithm>
DEFINE_PARAMETER_MAP(UsdSpatialField,
REGISTER_PARAMETER_MACRO("name", ANARI_STRING, name)
REGISTER_PARAMETER_MACRO("usd::name", ANARI_STRING, usdName)
REGISTER_PARAMETER_MACRO("usd::time", ANARI_FLOAT64, timeStep)
REGISTER_PARAMETER_MACRO("usd::timeVarying", ANARI_INT32, timeVarying)
REGISTER_PARAMETER_MACRO("data", ANARI_ARRAY, data)
REGISTER_PARAMETER_MACRO("spacing", ANARI_FLOAT32_VEC3, gridSpacing)
REGISTER_PARAMETER_MACRO("origin", ANARI_FLOAT32_VEC3, gridOrigin)
) // See .h for usage.
constexpr UsdSpatialField::ComponentPair UsdSpatialField::componentParamNames[]; // Workaround for C++14's lack of inlining constexpr arrays
UsdSpatialField::UsdSpatialField(const char* name, const char* type, UsdDevice* device)
: BridgedBaseObjectType(ANARI_SPATIAL_FIELD, name, device)
{
}
UsdSpatialField::~UsdSpatialField()
{
#ifdef OBJECT_LIFETIME_EQUALS_USD_LIFETIME
if(cachedBridge)
cachedBridge->DeleteSpatialField(usdHandle);
#endif
}
void UsdSpatialField::remove(UsdDevice* device)
{
applyRemoveFunc(device, &UsdBridge::DeleteSpatialField);
}
bool UsdSpatialField::deferCommit(UsdDevice* device)
{
// Always defer until flushing of commit list, to give parent volumes the possibility to detect which of its child fields have been committed,
// such that those volumes with committed children are also automatically committed.
return !device->isFlushingCommitList();
}
bool UsdSpatialField::doCommitData(UsdDevice* device)
{
UsdBridge* usdBridge = device->getUsdBridge();
const UsdSpatialFieldData& paramData = getReadParams();
const char* debugName = getName();
UsdLogInfo logInfo(device, this, ANARI_SPATIAL_FIELD, debugName);
bool isNew = false;
if(!usdHandle.value)
isNew = usdBridge->CreateSpatialField(debugName, usdHandle);
// Only perform type checks, actual data gets uploaded during UsdVolume::commit()
const UsdDataArray* fieldDataArray = paramData.data;
if (!fieldDataArray)
{
device->reportStatus(this, ANARI_SPATIAL_FIELD, ANARI_SEVERITY_ERROR, ANARI_STATUS_INVALID_OPERATION,
"UsdSpatialField '%s' commit failed: data missing.", debugName);
return false;
}
const UsdDataLayout& dataLayout = fieldDataArray->getLayout();
if (!AssertNoStride(dataLayout, logInfo, "data"))
return false;
switch (fieldDataArray->getType())
{
case ANARI_INT8:
case ANARI_UINT8:
case ANARI_INT16:
case ANARI_UINT16:
case ANARI_INT32:
case ANARI_UINT32:
case ANARI_INT64:
case ANARI_UINT64:
case ANARI_FLOAT32:
case ANARI_FLOAT64:
break;
default:
device->reportStatus(this, ANARI_SPATIAL_FIELD, ANARI_SEVERITY_ERROR, ANARI_STATUS_INVALID_ARGUMENT,
"UsdSpatialField '%s' commit failed: incompatible data type.", debugName);
return false;
}
// Make sure that parameters are set a first time
paramChanged = paramChanged || isNew;
return false;
} | 3,105 | C++ | 30.693877 | 144 | 0.750725 |
NVIDIA-Omniverse/AnariUsdDevice/UsdSpatialField.h | // Copyright 2020 The Khronos Group
// SPDX-License-Identifier: Apache-2.0
#pragma once
#include "UsdBridgedBaseObject.h"
class UsdDataArray;
class UsdVolume;
enum class UsdSpatialFieldComponents
{
DATA = 0 // includes spacing and origin
};
struct UsdSpatialFieldData
{
UsdSharedString* name = nullptr;
UsdSharedString* usdName = nullptr;
double timeStep = 0.0;
int timeVarying = 0xFFFFFFFF; // Bitmask indicating which attributes are time-varying.
const UsdDataArray* data = nullptr;
float gridSpacing[3] = {1.0f, 1.0f, 1.0f};
float gridOrigin[3] = {1.0f, 1.0f, 1.0f};
//int filter = 0;
//int gradientFilter = 0;
};
class UsdSpatialField : public UsdBridgedBaseObject<UsdSpatialField, UsdSpatialFieldData, UsdSpatialFieldHandle, UsdSpatialFieldComponents>
{
public:
UsdSpatialField(const char* name, const char* type, UsdDevice* device);
~UsdSpatialField();
void remove(UsdDevice* device) override;
friend class UsdVolume;
static constexpr ComponentPair componentParamNames[] = {
ComponentPair(UsdSpatialFieldComponents::DATA, "data")};
protected:
bool deferCommit(UsdDevice* device) override;
bool doCommitData(UsdDevice* device) override;
void doCommitRefs(UsdDevice* device) override {}
void toBridge(UsdDevice* device, const char* debugName);
}; | 1,335 | C | 24.692307 | 139 | 0.734831 |
NVIDIA-Omniverse/AnariUsdDevice/UsdSampler.cpp | // Copyright 2020 The Khronos Group
// SPDX-License-Identifier: Apache-2.0
#include "UsdSampler.h"
#include "UsdAnari.h"
#include "UsdDevice.h"
#include "UsdDataArray.h"
DEFINE_PARAMETER_MAP(UsdSampler,
REGISTER_PARAMETER_MACRO("name", ANARI_STRING, name)
REGISTER_PARAMETER_MACRO("usd::name", ANARI_STRING, usdName)
REGISTER_PARAMETER_MACRO("usd::time", ANARI_FLOAT64, timeStep)
REGISTER_PARAMETER_MACRO("usd::timeVarying", ANARI_INT32, timeVarying)
REGISTER_PARAMETER_MACRO("usd::imageUrl", ANARI_STRING, imageUrl)
REGISTER_PARAMETER_MACRO("inAttribute", ANARI_STRING, inAttribute)
REGISTER_PARAMETER_MACRO("image", ANARI_ARRAY, imageData)
REGISTER_PARAMETER_MACRO("wrapMode", ANARI_STRING, wrapS)
REGISTER_PARAMETER_MACRO("wrapMode1", ANARI_STRING, wrapS)
REGISTER_PARAMETER_MACRO("wrapMode2", ANARI_STRING, wrapT)
REGISTER_PARAMETER_MACRO("wrapMode3", ANARI_STRING, wrapR)
)
constexpr UsdSampler::ComponentPair UsdSampler::componentParamNames[]; // Workaround for C++14's lack of inlining constexpr arrays
namespace
{
UsdBridgeSamplerData::WrapMode ANARIToUsdBridgeWrapMode(const char* anariWrapMode)
{
UsdBridgeSamplerData::WrapMode usdWrapMode = UsdBridgeSamplerData::WrapMode::BLACK;
if(anariWrapMode)
{
if (strEquals(anariWrapMode, "clampToEdge"))
{
usdWrapMode = UsdBridgeSamplerData::WrapMode::CLAMP;
}
else if (strEquals(anariWrapMode, "repeat"))
{
usdWrapMode = UsdBridgeSamplerData::WrapMode::REPEAT;
}
else if (strEquals(anariWrapMode, "mirrorRepeat"))
{
usdWrapMode = UsdBridgeSamplerData::WrapMode::MIRROR;
}
}
return usdWrapMode;
}
}
UsdSampler::UsdSampler(const char* name, const char* type, UsdDevice* device)
: BridgedBaseObjectType(ANARI_SAMPLER, name, device)
{
if (strEquals(type, "image1D"))
samplerType = SAMPLER_1D;
else if (strEquals(type, "image2D"))
samplerType = SAMPLER_2D;
else if (strEquals(type, "image3D"))
samplerType = SAMPLER_3D;
else
device->reportStatus(this, ANARI_SAMPLER, ANARI_SEVERITY_ERROR, ANARI_STATUS_INVALID_ARGUMENT, "UsdSampler '%s' construction failed: type %s not supported", getName(), name);
}
UsdSampler::~UsdSampler()
{
#ifdef OBJECT_LIFETIME_EQUALS_USD_LIFETIME
if(cachedBridge)
cachedBridge->DeleteSampler(usdHandle);
#endif
}
void UsdSampler::remove(UsdDevice* device)
{
applyRemoveFunc(device, &UsdBridge::DeleteSampler);
}
void UsdSampler::updateBoundParameters(bool boundToInstance, UsdDevice* device)
{
UsdBridge* usdBridge = device->getUsdBridge();
if(!usdHandle.value)
return;
if(perInstance != boundToInstance)
{
// Fix up the position attribute
const UsdSamplerData& paramData = getReadParams();
const char* inAttribName = UsdSharedString::c_str(paramData.inAttribute);
if(inAttribName && strEquals(inAttribName, "objectPosition"))
{
// In case of a per-instance specific attribute name, there can be only one change of the attribute name.
UsdLogInfo logInfo(device, this, ANARI_SAMPLER, getName());
if(instanceAttributeAttached)
{
reportStatusThroughDevice(logInfo, ANARI_SEVERITY_WARNING, ANARI_STATUS_INVALID_ARGUMENT,
"UsdSampler '%s' binds its inAttribute parameter to %s, but is transitively bound to both an instanced geometry (cones, spheres, cylinders) and regular geometry. \
This is incompatible with USD, which demands a differently bound name for those categories. \
Please create two different samplers and bind each to only one of both categories of geometry. \
The inAttribute value will be updated, but may therefore invalidate previous bindings to the objectPosition attribute.", logInfo.sourceName, "'objectPosition'");
}
instanceAttributeAttached = true;
const char* usdAttribName = AnariAttributeToUsdName(inAttribName, perInstance, logInfo);
double worldTimeStep = device->getReadParams().timeStep;
double dataTimeStep = selectObjTime(paramData.timeStep, worldTimeStep);
UsdBridgeSamplerData::DataMemberId timeVarying;
setSamplerTimeVarying(timeVarying);
usdBridge->ChangeInAttribute(usdHandle, usdAttribName, dataTimeStep, timeVarying);
}
perInstance = boundToInstance;
}
}
bool UsdSampler::deferCommit(UsdDevice* device)
{
return false;
}
bool UsdSampler::doCommitData(UsdDevice* device)
{
UsdBridge* usdBridge = device->getUsdBridge();
if(!device->getReadParams().outputMaterial ||
samplerType == SAMPLER_UNKNOWN)
return false;
const UsdSamplerData& paramData = getReadParams();
UsdBridgeSamplerData::SamplerType type =
(samplerType == SAMPLER_1D ? UsdBridgeSamplerData::SamplerType::SAMPLER_1D :
(samplerType == SAMPLER_2D ? UsdBridgeSamplerData::SamplerType::SAMPLER_2D :
UsdBridgeSamplerData::SamplerType::SAMPLER_3D
)
);
bool isNew = false;
if (!usdHandle.value)
isNew = usdBridge->CreateSampler(getName(), usdHandle, type);
if (paramChanged || isNew)
{
if (paramData.inAttribute && (std::strlen(UsdSharedString::c_str(paramData.inAttribute)) > 0)
&& (paramData.imageUrl || paramData.imageData))
{
bool supportedImage = true;
int numComponents = 0;
if(paramData.imageData)
{
numComponents = static_cast<int>(anari::componentsOf(paramData.imageData->getType()));
if(numComponents > 4)
device->reportStatus(this, ANARI_SAMPLER, ANARI_SEVERITY_WARNING, ANARI_STATUS_INVALID_ARGUMENT,
"UsdSampler '%s' image data has more than 4 components. Anything above the 4th component will be ignored.", paramData.imageData->getName());
}
if(supportedImage)
{
UsdLogInfo logInfo(device, this, ANARI_SAMPLER, getName());
UsdBridgeSamplerData samplerData;
samplerData.Type = type;
double worldTimeStep = device->getReadParams().timeStep;
double dataTimeStep = selectObjTime(paramData.timeStep, worldTimeStep);
samplerData.InAttribute = AnariAttributeToUsdName(UsdSharedString::c_str(paramData.inAttribute), perInstance, logInfo);
if(paramData.imageUrl)
{
samplerData.ImageUrl = UsdSharedString::c_str(paramData.imageUrl);
}
if(paramData.imageData)
{
samplerData.Data = paramData.imageData->getData();
samplerData.ImageName = paramData.imageData->getName();
samplerData.ImageNumComponents = numComponents;
samplerData.DataType = AnariToUsdBridgeType(paramData.imageData->getType());
paramData.imageData->getLayout().copyDims(samplerData.ImageDims);
paramData.imageData->getLayout().copyStride(samplerData.ImageStride);
}
samplerData.WrapS = ANARIToUsdBridgeWrapMode(UsdSharedString::c_str(paramData.wrapS));
samplerData.WrapT = ANARIToUsdBridgeWrapMode(UsdSharedString::c_str(paramData.wrapT));
samplerData.WrapR = ANARIToUsdBridgeWrapMode(UsdSharedString::c_str(paramData.wrapR));
setSamplerTimeVarying(samplerData.TimeVarying);
usdBridge->SetSamplerData(usdHandle, samplerData, dataTimeStep);
}
}
else
{
device->reportStatus(this, ANARI_SAMPLER, ANARI_SEVERITY_ERROR, ANARI_STATUS_INVALID_ARGUMENT,
"UsdSampler '%s' commit failed: missing either the 'inAttribute', or both the 'image' and 'usd::imageUrl' parameter", getName());
}
paramChanged = false;
}
return false;
}
void UsdSampler::setSamplerTimeVarying(UsdBridgeSamplerData::DataMemberId& timeVarying)
{
typedef UsdBridgeSamplerData::DataMemberId DMI;
timeVarying = DMI::ALL
& (isTimeVarying(CType::DATA) ? DMI::ALL : ~DMI::DATA)
& (isTimeVarying(CType::WRAPS) ? DMI::ALL : ~DMI::WRAPS)
& (isTimeVarying(CType::WRAPT) ? DMI::ALL : ~DMI::WRAPT)
& (isTimeVarying(CType::WRAPR) ? DMI::ALL : ~DMI::WRAPR);
}
| 7,952 | C++ | 35.649769 | 178 | 0.709633 |
NVIDIA-Omniverse/AnariUsdDevice/UsdMultiTypeParameter.h | // Copyright 2020 The Khronos Group
// SPDX-License-Identifier: Apache-2.0
#pragma once
#include "UsdAnari.h"
#include "anari/anari_cpp/Traits.h"
template<typename T0, typename T1, typename T2>
struct UsdMultiTypeParameter
{
static constexpr int AnariType0 = anari::ANARITypeFor<T0>::value;
static constexpr int AnariType1 = anari::ANARITypeFor<T1>::value;
static constexpr int AnariType2 = anari::ANARITypeFor<T2>::value;
union DataUnion
{
T0 type0;
T1 type1;
T2 type2;
};
DataUnion data;
ANARIDataType type;
// Helper functions
T0& Get(T0& arg) const
{
if(AnariType0 == type) { arg = data.type0; }
return arg;
}
T1& Get(T1& arg) const
{
if(AnariType1 == type) { arg = data.type1; }
return arg;
}
T2& Get(T2& arg) const
{
if(AnariType2 == type) { arg = data.type2; }
return arg;
}
};
| 876 | C | 17.659574 | 67 | 0.64726 |
NVIDIA-Omniverse/AnariUsdDevice/UsdLight.cpp | // Copyright 2020 The Khronos Group
// SPDX-License-Identifier: Apache-2.0
#include "UsdLight.h"
#include "UsdAnari.h"
#include "UsdDevice.h"
DEFINE_PARAMETER_MAP(UsdLight,
REGISTER_PARAMETER_MACRO("name", ANARI_STRING, name)
REGISTER_PARAMETER_MACRO("usd::name", ANARI_STRING, usdName)
)
UsdLight::UsdLight(const char* name, UsdDevice* device)
: BridgedBaseObjectType(ANARI_LIGHT, name, device)
{}
UsdLight::~UsdLight()
{}
void UsdLight::remove(UsdDevice* device)
{
//applyRemoveFunc(device, &UsdBridge::DeleteLight);
}
bool UsdLight::deferCommit(UsdDevice* device)
{
return false;
}
bool UsdLight::doCommitData(UsdDevice* device)
{
return false;
} | 672 | C++ | 19.393939 | 62 | 0.735119 |
NVIDIA-Omniverse/AnariUsdDevice/UsdDevice.cpp | // Copyright 2020 The Khronos Group
// SPDX-License-Identifier: Apache-2.0
#include "UsdDevice.h"
#include "UsdBridgedBaseObject.h"
#include "UsdDataArray.h"
#include "UsdGeometry.h"
#include "UsdSpatialField.h"
#include "UsdSurface.h"
#include "UsdVolume.h"
#include "UsdInstance.h"
#include "UsdGroup.h"
#include "UsdMaterial.h"
#include "UsdSampler.h"
#include "UsdWorld.h"
#include "UsdRenderer.h"
#include "UsdFrame.h"
#include "UsdLight.h"
#include "UsdCamera.h"
#include "UsdDeviceQueries.h"
#include <cstdarg>
#include <cstdio>
#include <set>
#include <memory>
#include <sstream>
#include <algorithm>
#include <limits>
static char deviceName[] = "usd";
class UsdDeviceInternals
{
public:
UsdDeviceInternals()
{
}
bool CreateNewBridge(const UsdDeviceData& deviceParams, UsdBridgeLogCallback bridgeStatusFunc, void* userData)
{
if (bridge.get())
bridge->CloseSession();
UsdBridgeSettings bridgeSettings = {
UsdSharedString::c_str(deviceParams.hostName),
outputLocation.c_str(),
deviceParams.createNewSession,
deviceParams.outputBinary,
deviceParams.outputPreviewSurfaceShader,
deviceParams.outputMdlShader
};
bridge = std::make_unique<UsdBridge>(bridgeSettings);
bridge->SetExternalSceneStage(externalSceneStage);
bridge->SetEnableSaving(this->enableSaving);
bridgeStatusFunc(UsdBridgeLogLevel::STATUS, userData, "Initializing UsdBridge Session");
bool createSuccess = bridge->OpenSession(bridgeStatusFunc, userData);
if (!createSuccess)
{
bridge = nullptr;
bridgeStatusFunc(UsdBridgeLogLevel::STATUS, userData, "UsdBridge Session initialization failed.");
}
else
{
bridgeStatusFunc(UsdBridgeLogLevel::STATUS, userData, "UsdBridge Session initialization successful.");
}
return createSuccess;
}
std::string outputLocation;
bool enableSaving = true;
std::unique_ptr<UsdBridge> bridge;
SceneStagePtr externalSceneStage{nullptr};
std::set<std::string> uniqueNames;
};
//---- Make sure to update clearDeviceParameters() on refcounted objects
DEFINE_PARAMETER_MAP(UsdDevice,
REGISTER_PARAMETER_MACRO("usd::serialize.hostName", ANARI_STRING, hostName)
REGISTER_PARAMETER_MACRO("usd::serialize.location", ANARI_STRING, outputPath)
REGISTER_PARAMETER_MACRO("usd::serialize.newSession", ANARI_BOOL, createNewSession)
REGISTER_PARAMETER_MACRO("usd::serialize.outputBinary", ANARI_BOOL, outputBinary)
REGISTER_PARAMETER_MACRO("usd::time", ANARI_FLOAT64, timeStep)
REGISTER_PARAMETER_MACRO("usd::writeAtCommit", ANARI_BOOL, writeAtCommit)
REGISTER_PARAMETER_MACRO("usd::output.material", ANARI_BOOL, outputMaterial)
REGISTER_PARAMETER_MACRO("usd::output.previewSurfaceShader", ANARI_BOOL, outputPreviewSurfaceShader)
REGISTER_PARAMETER_MACRO("usd::output.mdlShader", ANARI_BOOL, outputMdlShader)
)
void UsdDevice::clearDeviceParameters()
{
filterResetParam("usd::serialize.hostName");
filterResetParam("usd::serialize.location");
transferWriteToReadParams();
}
//----
UsdDevice::UsdDevice()
: UsdParameterizedBaseObject<UsdDevice, UsdDeviceData>(ANARI_DEVICE)
, internals(std::make_unique<UsdDeviceInternals>())
{}
UsdDevice::UsdDevice(ANARILibrary library)
: DeviceImpl(library)
, UsdParameterizedBaseObject<UsdDevice, UsdDeviceData>(ANARI_DEVICE)
, internals(std::make_unique<UsdDeviceInternals>())
{}
UsdDevice::~UsdDevice()
{
// Make sure no more references are held before cleaning up the device (and checking for memleaks)
clearCommitList();
clearDeviceParameters(); // Release device parameters with object references
clearResourceStringList(); // Do the same for resource string references
//internals->bridge->SaveScene(); //Uncomment to test cleanup of usd files.
#ifdef CHECK_MEMLEAKS
if(!allocatedObjects.empty() || !allocatedStrings.empty() || !allocatedRawMemory.empty())
{
std::stringstream errstream;
errstream << "USD Device memleak reported for: ";
for(auto ptr : allocatedObjects)
errstream << "Object ptr: 0x" << std::hex << ptr << " of type: " << std::dec << ptr->getType() << "; ";
for(auto ptr : allocatedStrings)
errstream << "String ptr: 0x" << std::hex << ptr << " with content: " << std::dec << ptr->c_str() << "; ";
for(auto ptr : allocatedRawMemory)
errstream << "Raw ptr: 0x" << std::hex << ptr << std::dec << "; ";
reportStatus(this, ANARI_DEVICE, ANARI_SEVERITY_ERROR, ANARI_STATUS_INVALID_OPERATION, errstream.str().c_str());
}
else
{
reportStatus(this, ANARI_DEVICE, ANARI_SEVERITY_INFO, ANARI_STATUS_NO_ERROR, "Reference memleak check complete, no issues found.");
}
assert(allocatedObjects.empty());
#endif
}
void UsdDevice::reportStatus(void* source,
ANARIDataType sourceType,
ANARIStatusSeverity severity,
ANARIStatusCode statusCode,
const char *format, ...)
{
va_list arglist;
va_start(arglist, format);
reportStatus(source, sourceType, severity, statusCode, format, arglist);
va_end(arglist);
}
static void reportBridgeStatus(UsdBridgeLogLevel level, void* device, const char *message)
{
ANARIStatusSeverity severity = UsdBridgeLogLevelToAnariSeverity(level);
va_list arglist;
((UsdDevice*)device)->reportStatus(nullptr, ANARI_UNKNOWN, severity, ANARI_STATUS_NO_ERROR, message, arglist);
}
void UsdDevice::reportStatus(void* source,
ANARIDataType sourceType,
ANARIStatusSeverity severity,
ANARIStatusCode statusCode,
const char *format,
va_list& arglist)
{
va_list arglist_copy;
va_copy(arglist_copy, arglist);
int count = std::vsnprintf(nullptr, 0, format, arglist);
lastStatusMessage.resize(count + 1);
std::vsnprintf(lastStatusMessage.data(), count + 1, format, arglist_copy);
va_end(arglist_copy);
if (statusFunc != nullptr)
{
statusFunc(
statusUserData,
(ANARIDevice)this,
(ANARIObject)source,
sourceType,
severity,
statusCode,
lastStatusMessage.data());
}
}
void UsdDevice::filterSetParam(
const char *name,
ANARIDataType type,
const void *mem,
UsdDevice* device)
{
if (strEquals(name, "usd::garbageCollect"))
{
// Perform garbage collection on usd objects (needs to move into the user interface)
if(internals->bridge)
internals->bridge->GarbageCollect();
}
else if(strEquals(name, "usd::removeUnusedNames"))
{
internals->uniqueNames.clear();
}
else if (strEquals(name, "usd::connection.logVerbosity")) // 0 <= verbosity <= 4, with 4 being the loudest
{
if(type == ANARI_INT32)
UsdBridge::SetConnectionLogVerbosity(*(reinterpret_cast<const int*>(mem)));
}
else if(strEquals(name, "usd::sceneStage"))
{
if(type == ANARI_VOID_POINTER)
internals->externalSceneStage = const_cast<void *>(mem);
}
else if (strEquals(name, "usd::enableSaving"))
{
if(type == ANARI_BOOL)
{
internals->enableSaving = *(reinterpret_cast<const bool*>(mem));
if(internals->bridge)
internals->bridge->SetEnableSaving(internals->enableSaving);
}
}
else if (strEquals(name, "statusCallback") && type == ANARI_STATUS_CALLBACK)
{
userSetStatusFunc = (ANARIStatusCallback)mem;
}
else if (strEquals(name, "statusCallbackUserData") && type == ANARI_VOID_POINTER)
{
userSetStatusUserData = const_cast<void *>(mem);
}
else
{
setParam(name, type, mem, this);
}
}
void UsdDevice::filterResetParam(const char * name)
{
if (strEquals(name, "statusCallback"))
{
userSetStatusFunc = nullptr;
}
else if (strEquals(name, "statusCallbackUserData"))
{
userSetStatusUserData = nullptr;
}
else if (!strEquals(name, "usd::garbageCollect")
&& !strEquals(name, "usd::removeUnusedNames"))
{
resetParam(name);
}
}
void UsdDevice::commit(UsdDevice* device)
{
transferWriteToReadParams();
if(!bridgeInitAttempt)
{
initializeBridge();
}
else
{
const UsdDeviceData& paramData = getReadParams();
internals->bridge->UpdateBeginEndTime(paramData.timeStep);
}
}
void UsdDevice::initializeBridge()
{
const UsdDeviceData& paramData = getReadParams();
bridgeInitAttempt = true;
statusFunc = userSetStatusFunc ? userSetStatusFunc : defaultStatusCallback();
statusUserData = userSetStatusUserData ? userSetStatusUserData : defaultStatusCallbackUserPtr();
if(paramData.outputPath)
internals->outputLocation = paramData.outputPath->c_str();
if(internals->outputLocation.empty()) {
auto *envLocation = getenv("ANARI_USD_SERIALIZE_LOCATION");
if (envLocation) {
internals->outputLocation = envLocation;
reportStatus(this, ANARI_DEVICE, ANARI_SEVERITY_INFO, ANARI_STATUS_NO_ERROR,
"Usd Device parameter 'usd::serialize.location' using ANARI_USD_SERIALIZE_LOCATION value");
}
}
if (internals->outputLocation.empty())
{
reportStatus(this, ANARI_DEVICE, ANARI_SEVERITY_WARNING, ANARI_STATUS_INVALID_ARGUMENT,
"Usd Device parameter 'usd::serialize.location' not set, defaulting to './'");
internals->outputLocation = "./";
}
if (!internals->CreateNewBridge(paramData, &reportBridgeStatus, this))
{
reportStatus(this, ANARI_DEVICE, ANARI_SEVERITY_ERROR, ANARI_STATUS_UNKNOWN_ERROR, "Usd Bridge failed to load");
}
}
ANARIArray UsdDevice::CreateDataArray(const void *appMemory,
ANARIMemoryDeleter deleter,
const void *userData,
ANARIDataType dataType,
uint64_t numItems1,
int64_t byteStride1,
uint64_t numItems2,
int64_t byteStride2,
uint64_t numItems3,
int64_t byteStride3)
{
if (!appMemory)
{
UsdDataArray* object = new UsdDataArray(dataType, numItems1, numItems2, numItems3, this);
#ifdef CHECK_MEMLEAKS
LogObjAllocation(object);
#endif
return (ANARIArray)(object);
}
else
{
UsdDataArray* object = new UsdDataArray(appMemory, deleter, userData,
dataType, numItems1, byteStride1, numItems2, byteStride2, numItems3, byteStride3,
this);
#ifdef CHECK_MEMLEAKS
LogObjAllocation(object);
#endif
return (ANARIArray)(object);
}
}
ANARIArray1D UsdDevice::newArray1D(const void *appMemory,
ANARIMemoryDeleter deleter,
const void *userData,
ANARIDataType type,
uint64_t numItems)
{
return (ANARIArray1D)CreateDataArray(appMemory, deleter, userData,
type, numItems, 0, 1, 0, 1, 0);
}
ANARIArray2D UsdDevice::newArray2D(const void *appMemory,
ANARIMemoryDeleter deleter,
const void *userData,
ANARIDataType type,
uint64_t numItems1,
uint64_t numItems2)
{
return (ANARIArray2D)CreateDataArray(appMemory, deleter, userData,
type, numItems1, 0, numItems2, 0, 1, 0);
}
ANARIArray3D UsdDevice::newArray3D(const void *appMemory,
ANARIMemoryDeleter deleter,
const void *userData,
ANARIDataType type,
uint64_t numItems1,
uint64_t numItems2,
uint64_t numItems3)
{
return (ANARIArray3D)CreateDataArray(appMemory, deleter, userData,
type, numItems1, 0, numItems2, 0, numItems3, 0);
}
void * UsdDevice::mapArray(ANARIArray array)
{
return array ? AnariToUsdObjectPtr(array)->map(this) : nullptr;
}
void UsdDevice::unmapArray(ANARIArray array)
{
if(array)
AnariToUsdObjectPtr(array)->unmap(this);
}
ANARISampler UsdDevice::newSampler(const char *type)
{
const char* name = makeUniqueName("Sampler");
UsdSampler* object = new UsdSampler(name, type, this);
#ifdef CHECK_MEMLEAKS
LogObjAllocation(object);
#endif
return (ANARISampler)(object);
}
ANARIMaterial UsdDevice::newMaterial(const char *material_type)
{
const char* name = makeUniqueName("Material");
UsdMaterial* object = new UsdMaterial(name, material_type, this);
#ifdef CHECK_MEMLEAKS
LogObjAllocation(object);
#endif
return (ANARIMaterial)(object);
}
ANARIGeometry UsdDevice::newGeometry(const char *type)
{
const char* name = makeUniqueName("Geometry");
UsdGeometry* object = new UsdGeometry(name, type, this);
#ifdef CHECK_MEMLEAKS
LogObjAllocation(object);
#endif
return (ANARIGeometry)(object);
}
ANARISpatialField UsdDevice::newSpatialField(const char * type)
{
const char* name = makeUniqueName("SpatialField");
UsdSpatialField* object = new UsdSpatialField(name, type, this);
#ifdef CHECK_MEMLEAKS
LogObjAllocation(object);
#endif
return (ANARISpatialField)(object);
}
ANARISurface UsdDevice::newSurface()
{
const char* name = makeUniqueName("Surface");
UsdSurface* object = new UsdSurface(name, this);
#ifdef CHECK_MEMLEAKS
LogObjAllocation(object);
#endif
return (ANARISurface)(object);
}
ANARIVolume UsdDevice::newVolume(const char *type)
{
const char* name = makeUniqueName("Volume");
UsdVolume* object = new UsdVolume(name, this);
#ifdef CHECK_MEMLEAKS
LogObjAllocation(object);
#endif
return (ANARIVolume)(object);
}
ANARIGroup UsdDevice::newGroup()
{
const char* name = makeUniqueName("Group");
UsdGroup* object = new UsdGroup(name, this);
#ifdef CHECK_MEMLEAKS
LogObjAllocation(object);
#endif
return (ANARIGroup)(object);
}
ANARIInstance UsdDevice::newInstance(const char */*type*/)
{
const char* name = makeUniqueName("Instance");
UsdInstance* object = new UsdInstance(name, this);
#ifdef CHECK_MEMLEAKS
LogObjAllocation(object);
#endif
return (ANARIInstance)(object);
}
ANARIWorld UsdDevice::newWorld()
{
const char* name = makeUniqueName("World");
UsdWorld* object = new UsdWorld(name, this);
#ifdef CHECK_MEMLEAKS
LogObjAllocation(object);
#endif
return (ANARIWorld)(object);
}
ANARICamera UsdDevice::newCamera(const char *type)
{
const char* name = makeUniqueName("Camera");
UsdCamera* object = new UsdCamera(name, type, this);
#ifdef CHECK_MEMLEAKS
LogObjAllocation(object);
#endif
return (ANARICamera)(object);
}
const char **UsdDevice::getObjectSubtypes(ANARIDataType objectType)
{
return anari::usd::query_object_types(objectType);
}
const void *UsdDevice::getObjectInfo(ANARIDataType objectType,
const char *objectSubtype,
const char *infoName,
ANARIDataType infoType)
{
return anari::usd::query_object_info(
objectType, objectSubtype, infoName, infoType);
}
const void *UsdDevice::getParameterInfo(ANARIDataType objectType,
const char *objectSubtype,
const char *parameterName,
ANARIDataType parameterType,
const char *infoName,
ANARIDataType infoType)
{
return anari::usd::query_param_info(objectType,
objectSubtype,
parameterName,
parameterType,
infoName,
infoType);
}
ANARIRenderer UsdDevice::newRenderer(const char *type)
{
UsdRenderer* object = new UsdRenderer();
#ifdef CHECK_MEMLEAKS
LogObjAllocation(object);
#endif
return (ANARIRenderer)(object);
}
UsdBridge* UsdDevice::getUsdBridge()
{
return internals->bridge.get();
}
void UsdDevice::renderFrame(ANARIFrame frame)
{
// Always commit device changes if not initialized, otherwise no conversion can be performed.
if(!bridgeInitAttempt)
initializeBridge();
if(!isInitialized())
return;
flushCommitList();
internals->bridge->ResetResourceUpdateState(); // Reset the modified flags for committed shared resources
if(frame)
AnariToUsdObjectPtr(frame)->saveUsd(this);
}
const char* UsdDevice::makeUniqueName(const char* name)
{
std::string proposedBaseName(name);
proposedBaseName.append("_");
int postFix = 0;
std::string proposedName = proposedBaseName + std::to_string(postFix);
auto empRes = internals->uniqueNames.emplace(proposedName);
while (!empRes.second)
{
++postFix;
proposedName = proposedBaseName + std::to_string(postFix);
empRes = internals->uniqueNames.emplace(proposedName);
}
return empRes.first->c_str();
}
bool UsdDevice::nameExists(const char* name)
{
return internals->uniqueNames.find(name) != internals->uniqueNames.end();
}
void UsdDevice::addToCommitList(UsdBaseObject* object, bool commitData)
{
if(!object)
return;
if(lockCommitList)
{
this->reportStatus(object, object->getType(), ANARI_SEVERITY_FATAL_ERROR, ANARI_STATUS_INVALID_OPERATION,
"Usd device internal error; addToCommitList called while list is locked");
}
else
{
auto it = std::find_if(commitList.begin(), commitList.end(),
[&object](const CommitListType& entry) -> bool { return entry.first.ptr == object; });
if(it == commitList.end())
commitList.emplace_back(CommitListType(object, commitData));
}
}
void UsdDevice::clearCommitList()
{
removePrimsFromUsd(true); // removeList pointers are taken from commitlist
#ifdef CHECK_MEMLEAKS
for(auto& commitEntry : commitList)
{
LogObjDeallocation(commitEntry.first.ptr);
}
#endif
commitList.resize(0);
}
void UsdDevice::flushCommitList()
{
// Automatically perform a new commitdata/commitrefs on volumes which are not committed,
// but for which their (readdata) spatial field is in commitlist. (to update the previous commit)
for(UsdVolume* volume : volumeList)
{
const UsdVolumeData& readParams = volume->getReadParams();
if(readParams.field)
{
//volume not in commitlist
auto volEntry = std::find_if(commitList.begin(), commitList.end(),
[&volume](const CommitListType& entry) -> bool { return entry.first.ptr == volume; });
if(volEntry == commitList.end())
{
auto fieldEntry = std::find_if(commitList.begin(), commitList.end(),
[&readParams](const CommitListType& entry) -> bool { return entry.first.ptr == readParams.field; });
// spatialfield from readParams is in commit list
if(fieldEntry != commitList.end())
{
UsdBaseObject* baseObject = static_cast<UsdBaseObject*>(volume);
bool commitRefs = baseObject->doCommitData(this);
if(commitRefs)
baseObject->doCommitRefs(this);
}
}
}
}
lockCommitList = true;
writeTypeToUsd<(int)ANARI_SAMPLER>();
writeTypeToUsd<(int)ANARI_SPATIAL_FIELD>();
writeTypeToUsd<(int)ANARI_GEOMETRY>();
writeTypeToUsd<(int)ANARI_LIGHT>();
writeTypeToUsd<(int)ANARI_MATERIAL>();
writeTypeToUsd<(int)ANARI_SURFACE>();
writeTypeToUsd<(int)ANARI_VOLUME>();
writeTypeToUsd<(int)ANARI_GROUP>();
writeTypeToUsd<(int)ANARI_INSTANCE>();
writeTypeToUsd<(int)ANARI_WORLD>();
writeTypeToUsd<(int)ANARI_CAMERA>();
removePrimsFromUsd();
clearCommitList();
lockCommitList = false;
}
void UsdDevice::addToVolumeList(UsdVolume* volume)
{
auto it = std::find(volumeList.begin(), volumeList.end(), volume);
if(it == volumeList.end())
volumeList.emplace_back(volume);
}
void UsdDevice::addToResourceStringList(UsdSharedString* string)
{
resourceStringList.push_back(helium::IntrusivePtr<UsdSharedString>(string));
}
void UsdDevice::clearResourceStringList()
{
resourceStringList.resize(0);
}
void UsdDevice::removeFromVolumeList(UsdVolume* volume)
{
auto it = std::find(volumeList.begin(), volumeList.end(), volume);
if(it == volumeList.end())
{
*it = volumeList.back();
volumeList.pop_back();
}
}
template<int typeInt>
void UsdDevice::writeTypeToUsd()
{
for(auto objCommitPair : commitList)
{
auto object = objCommitPair.first;
bool commitData = objCommitPair.second;
if((int)object->getType() == typeInt)
{
using ObjectType = typename AnariToUsdBridgedObject<typeInt>::Type;
ObjectType* typedObj = reinterpret_cast<ObjectType*>(object.ptr);
if(!object->deferCommit(this))
{
bool commitRefs = true;
if(commitData)
commitRefs = object->doCommitData(this);
if(commitRefs)
object->doCommitRefs(this);
}
else
{
this->reportStatus(object.ptr, object->getType(), ANARI_SEVERITY_ERROR, ANARI_STATUS_INVALID_OPERATION,
"User forgot to at least once commit an ANARI child object of parent object '%s'", typedObj->getName());
}
if(typedObj->getRemovePrim())
{
removeList.push_back(object.ptr); // Just raw pointer, removeList is purged upon commitList clear
}
}
}
}
void UsdDevice::removePrimsFromUsd(bool onlyRemoveHandles)
{
if(!onlyRemoveHandles)
{
for(auto baseObj : removeList)
{
baseObj->remove(this);
}
}
removeList.resize(0);
}
int UsdDevice::getProperty(ANARIObject object,
const char *name,
ANARIDataType type,
void *mem,
uint64_t size,
uint32_t mask)
{
if ((void *)object == (void *)this)
{
if (strEquals(name, "version") && type == ANARI_INT32)
{
writeToVoidP(mem, DEVICE_VERSION_BUILD);
return 1;
}
if (strEquals(name, "version.major") && type == ANARI_INT32)
{
writeToVoidP(mem, DEVICE_VERSION_MAJOR);
return 1;
}
if (strEquals(name, "version.minor") && type == ANARI_INT32)
{
writeToVoidP(mem, DEVICE_VERSION_MINOR);
return 1;
}
if (strEquals(name, "version.patch") && type == ANARI_INT32)
{
writeToVoidP(mem, DEVICE_VERSION_PATCH);
return 1;
}
if (strEquals(name, "version.name") && type == ANARI_STRING)
{
snprintf((char*)mem, size, "%s", DEVICE_VERSION_NAME);
return 1;
}
else if (strEquals(name, "version.name.size") && type == ANARI_UINT64)
{
if (Assert64bitStringLengthProperty(size, UsdLogInfo(this, this, ANARI_DEVICE, "UsdDevice"), "version.name.size"))
{
uint64_t nameLen = strlen(DEVICE_VERSION_NAME)+1;
memcpy(mem, &nameLen, size);
}
return 1;
}
else if (strEquals(name, "geometryMaxIndex") && type == ANARI_UINT64)
{
uint64_t maxIndex = std::numeric_limits<uint64_t>::max(); // Only restricted to int for UsdGeomMesh: GetFaceVertexIndicesAttr() takes a VtArray<int>
writeToVoidP(mem, maxIndex);
return 1;
}
else if (strEquals(name, "extension") && type == ANARI_STRING_LIST)
{
writeToVoidP(mem, anari::usd::query_extensions());
return 1;
}
}
else if(object)
return AnariToUsdObjectPtr(object)->getProperty(name, type, mem, size, this);
return 0;
}
ANARIFrame UsdDevice::newFrame()
{
UsdFrame* object = new UsdFrame(internals->bridge.get());
#ifdef CHECK_MEMLEAKS
LogObjAllocation(object);
#endif
return (ANARIFrame)(object);
}
const void * UsdDevice::frameBufferMap(
ANARIFrame fb,
const char *channel,
uint32_t *width,
uint32_t *height,
ANARIDataType *pixelType)
{
if (fb)
return AnariToUsdObjectPtr(fb)->mapBuffer(channel, width, height, pixelType);
return nullptr;
}
void UsdDevice::frameBufferUnmap(ANARIFrame fb, const char *channel)
{
if (fb)
return AnariToUsdObjectPtr(fb)->unmapBuffer(channel);
}
UsdBaseObject* UsdDevice::getBaseObjectPtr(ANARIObject object)
{
return handleIsDevice(object) ? this : (UsdBaseObject*)object;
}
void UsdDevice::setParameter(ANARIObject object,
const char *name,
ANARIDataType type,
const void *mem)
{
if(object)
getBaseObjectPtr(object)->filterSetParam(name, type, mem, this);
}
void UsdDevice::unsetParameter(ANARIObject object, const char * name)
{
if(object)
getBaseObjectPtr(object)->filterResetParam(name);
}
void UsdDevice::unsetAllParameters(ANARIObject object)
{
if(object)
getBaseObjectPtr(object)->resetAllParams();
}
void *UsdDevice::mapParameterArray1D(ANARIObject object,
const char *name,
ANARIDataType dataType,
uint64_t numElements1,
uint64_t *elementStride)
{
auto array = newArray1D(nullptr, nullptr, nullptr, dataType, numElements1);
setParameter(object, name, ANARI_ARRAY1D, &array);
*elementStride = anari::sizeOf(dataType);
AnariToUsdObjectPtr(array)->refDec(helium::RefType::PUBLIC);
return mapArray(array);
}
void *UsdDevice::mapParameterArray2D(ANARIObject object,
const char *name,
ANARIDataType dataType,
uint64_t numElements1,
uint64_t numElements2,
uint64_t *elementStride)
{
auto array = newArray2D(nullptr, nullptr, nullptr, dataType, numElements1, numElements2);
setParameter(object, name, ANARI_ARRAY2D, &array);
*elementStride = anari::sizeOf(dataType);
AnariToUsdObjectPtr(array)->refDec(helium::RefType::PUBLIC);
return mapArray(array);
}
void *UsdDevice::mapParameterArray3D(ANARIObject object,
const char *name,
ANARIDataType dataType,
uint64_t numElements1,
uint64_t numElements2,
uint64_t numElements3,
uint64_t *elementStride)
{
auto array = newArray3D(nullptr,
nullptr,
nullptr,
dataType,
numElements1,
numElements2,
numElements3);
setParameter(object, name, ANARI_ARRAY3D, &array);
*elementStride = anari::sizeOf(dataType);
AnariToUsdObjectPtr(array)->refDec(helium::RefType::PUBLIC);
return mapArray(array);
}
void UsdDevice::unmapParameterArray(ANARIObject object, const char *name)
{
if(!object)
return;
ANARIDataType paramType = ANARI_UNKNOWN;
void* paramAddress = getBaseObjectPtr(object)->getParameter(name, paramType);
if(paramAddress && paramType == ANARI_ARRAY)
{
auto arrayAddress = (ANARIArray*)paramAddress;
if(*arrayAddress)
AnariToUsdObjectPtr(*arrayAddress)->unmap(this);
}
}
void UsdDevice::release(ANARIObject object)
{
if(!object)
return;
UsdBaseObject* baseObject = getBaseObjectPtr(object);
bool privatizeArray = baseObject->getType() == ANARI_ARRAY
&& baseObject->useCount(helium::RefType::INTERNAL) > 0
&& baseObject->useCount(helium::RefType::PUBLIC) == 1;
#ifdef CHECK_MEMLEAKS
if(!handleIsDevice(object))
LogObjDeallocation(baseObject);
#endif
if (baseObject)
baseObject->refDec(helium::RefType::PUBLIC);
if (privatizeArray)
AnariToUsdObjectPtr((ANARIArray)object)->privatize();
}
void UsdDevice::retain(ANARIObject object)
{
if(object)
getBaseObjectPtr(object)->refInc(helium::RefType::PUBLIC);
}
void UsdDevice::commitParameters(ANARIObject object)
{
if(object)
getBaseObjectPtr(object)->commit(this);
}
#ifdef CHECK_MEMLEAKS
namespace
{
template<typename T>
void SharedLogDeallocation(const T* ptr, std::vector<const T*>& allocations, UsdDevice* device)
{
if (ptr)
{
auto it = std::find(allocations.begin(), allocations.end(), ptr);
if(it == allocations.end())
{
std::stringstream errstream;
errstream << "USD Device release of nonexisting or already released/deleted object: 0x" << std::hex << ptr;
device->reportStatus(device, ANARI_DEVICE, ANARI_SEVERITY_FATAL_ERROR, ANARI_STATUS_INVALID_OPERATION, errstream.str().c_str());
}
if(ptr->useCount() == 1)
{
assert(it != allocations.end());
allocations.erase(it);
}
}
}
}
void UsdDevice::LogObjAllocation(const UsdBaseObject* ptr)
{
allocatedObjects.push_back(ptr);
}
void UsdDevice::LogObjDeallocation(const UsdBaseObject* ptr)
{
SharedLogDeallocation(ptr, allocatedObjects, this);
}
void UsdDevice::LogStrAllocation(const UsdSharedString* ptr)
{
allocatedStrings.push_back(ptr);
}
void UsdDevice::LogStrDeallocation(const UsdSharedString* ptr)
{
SharedLogDeallocation(ptr, allocatedStrings, this);
}
void UsdDevice::LogRawAllocation(const void* ptr)
{
allocatedRawMemory.push_back(ptr);
}
void UsdDevice::LogRawDeallocation(const void* ptr)
{
if (ptr)
{
auto it = std::find(allocatedRawMemory.begin(), allocatedRawMemory.end(), ptr);
if(it == allocatedRawMemory.end())
{
std::stringstream errstream;
errstream << "USD Device release of nonexisting or already released/deleted raw memory: 0x" << std::hex << ptr;
reportStatus(this, ANARI_DEVICE, ANARI_SEVERITY_FATAL_ERROR, ANARI_STATUS_INVALID_OPERATION, errstream.str().c_str());
}
else
allocatedRawMemory.erase(it);
}
}
#endif
| 27,549 | C++ | 25.695736 | 154 | 0.705652 |
NVIDIA-Omniverse/AnariUsdDevice/UsdRenderer.cpp | // Copyright 2020 The Khronos Group
// SPDX-License-Identifier: Apache-2.0
#include "UsdRenderer.h"
#include "UsdBridge/UsdBridge.h"
#include "UsdAnari.h"
#include "UsdDevice.h"
#include "UsdDeviceQueries.h"
DEFINE_PARAMETER_MAP(UsdRenderer,
)
UsdRenderer::UsdRenderer()
: UsdParameterizedBaseObject<UsdRenderer, UsdRendererData>(ANARI_RENDERER)
{
}
UsdRenderer::~UsdRenderer()
{
}
int UsdRenderer::getProperty(const char * name, ANARIDataType type, void * mem, uint64_t size, UsdDevice* device)
{
if (strEquals(name, "extension") && type == ANARI_STRING_LIST)
{
writeToVoidP(mem, anari::usd::query_extensions());
return 1;
}
return 0;
}
bool UsdRenderer::deferCommit(UsdDevice* device)
{
return false;
}
bool UsdRenderer::doCommitData(UsdDevice* device)
{
return false;
}
| 803 | C++ | 18.142857 | 113 | 0.728518 |
NVIDIA-Omniverse/AnariUsdDevice/UsdSharedObjects.h | // Copyright 2020 The Khronos Group
// SPDX-License-Identifier: Apache-2.0
#pragma once
#include "helium/utility/IntrusivePtr.h"
#include "UsdCommonMacros.h"
#include <string>
template<typename BaseType, typename InitType>
class UsdRefCountWrapped : public helium::RefCounted
{
public:
UsdRefCountWrapped(InitType i)
: data(i)
{}
BaseType data;
};
class UsdSharedString : public UsdRefCountWrapped<std::string, const char*>
{
public:
UsdSharedString(const char* cStr)
: UsdRefCountWrapped<std::string, const char*>(cStr)
{}
static const char* c_str(const UsdSharedString* string) { return string ? string->c_str() : nullptr; }
const char* c_str() const { return data.c_str(); }
}; | 733 | C | 22.677419 | 106 | 0.699864 |
NVIDIA-Omniverse/AnariUsdDevice/UsdBaseObject.cpp | // Copyright 2020 The Khronos Group
// SPDX-License-Identifier: Apache-2.0
#include "UsdBaseObject.h"
#include "UsdDevice.h"
UsdBaseObject::UsdBaseObject(ANARIDataType t, UsdDevice* device)
: type(t)
{
// The object will not be committed (as in, user-written write params will not be set to read params),
// but handles will be initialized and the object with its default data/refs will be written out to USD
// (but only if the prim wasn't yet written to USD before, see 'isNew' in doCommit implementations).
if(device)
device->addToCommitList(this, true);
}
void UsdBaseObject::commit(UsdDevice* device)
{
bool deferDataCommit = !device->isInitialized() || !device->getReadParams().writeAtCommit || deferCommit(device);
if(!deferDataCommit)
{
bool commitRefs = doCommitData(device);
if(commitRefs)
device->addToCommitList(this, false); // Commit refs, but no more data
}
else
device->addToCommitList(this, true); // Commit data and refs
}
| 1,008 | C++ | 33.793102 | 115 | 0.709325 |
NVIDIA-Omniverse/AnariUsdDevice/examples/anariTutorial_usd.c | // Copyright 2021 NVIDIA Corporation
// SPDX-License-Identifier: Apache-2.0
#include <errno.h>
#include <assert.h>
#include <stdint.h>
#include <stdio.h>
#ifdef _WIN32
#include <malloc.h>
#else
#include <alloca.h>
#endif
#include "anari/anari.h"
// stb_image
#include "stb_image_write.h"
#include "anariTutorial_usd_common.h"
typedef enum TestType
{
TEST_MESH,
TEST_CONES,
TEST_GLYPHS
} TestType_t;
typedef struct TestParameters
{
int writeAtCommit;
int useVertexColors;
int useTexture;
int useIndices;
int isTransparent;
TestType_t testType;
int useGlyphMesh;
} TestParameters_t;
typedef struct TexData
{
uint8_t* textureData;
uint8_t* opacityTextureData;
int textureSize[2];
} TexData_t;
float transform[16] = {
3.0f, 0.0f, 0.0f, 0.0f,
0.0f, 3.0f, 0.0f, 0.0f,
0.0f, 0.0f, 3.0f, 0.0f,
2.0f, 3.0f, 4.0f, 1.0f };
// triangle mesh data
float vertex[] = { -1.0f,
-1.0f,
3.0f,
-1.0f,
1.0f,
3.0f,
1.0f,
-1.0f,
3.0f,
0.1f,
0.1f,
0.3f };
float normal[] = { 0.0f,
0.0f,
1.0f,
0.0f,
1.0f,
0.0f,
0.0f,
1.0f,
0.0f,
1.0f,
0.0f,
0.0f
};
float color[] = { 0.0f,
0.0f,
0.9f,
1.0f,
0.8f,
0.8f,
0.8f,
1.0f,
0.8f,
0.8f,
0.8f,
1.0f,
0.0f,
0.9f,
0.0f,
1.0f };
float opacities[] = {
0.5f,
1.0f};
float texcoord[] = {
0.0f,
0.0f,
1.0f,
0.0f,
1.0f,
1.0f,
0.0f,
1.0f };
int32_t index[] = { 0, 1, 2, 2, 1, 3 };
float protoVertex[] = {-3.0f,
-1.0f,
-1.0f,
3.0f,
-1.0f,
-1.0f,
-3.0f,
1.0f,
-1.0f,
3.0f,
1.0f,
-1.0f,
-3.0f,
-1.0f,
1.0f,
3.0f,
-1.0f,
1.0f,
-3.0f,
1.0f,
1.0f,
3.0f,
1.0f,
1.0f};
float protoColor[] = {0.0f,
0.0f,
0.9f,
1.0f,
0.8f,
0.8f,
0.8f,
1.0f,
0.8f,
0.8f,
0.8f,
1.0f,
0.0f,
0.9f,
0.0f,
1.0f,
0.0f,
0.0f,
0.9f,
1.0f,
0.8f,
0.8f,
0.8f,
1.0f,
0.8f,
0.8f,
0.8f,
1.0f,
0.0f,
0.9f,
0.0f,
1.0f};
int32_t protoIndex[] = {0, 1, 2, 2, 1, 3, 2, 3, 4, 4, 3, 5, 4, 5, 6, 6, 5, 7, 6, 7, 0, 0, 7, 1};
float protoTransform[16] = {
0.75f, 0.0f, 0.0f, 0.0f,
0.0f, 1.5f, 0.0f, 0.0f,
0.0f, 0.0f, 1.0f, 0.0f,
0.0f, 0.0f, 0.0f, 1.0f };
float kd[] = { 0.0f, 0.0f, 1.0f };
ANARIInstance createMeshInstance(ANARIDevice dev, TestParameters_t testParams, TexData_t testData)
{
int useVertexColors = testParams.useVertexColors;
int useTexture = testParams.useTexture;
int isTransparent = testParams.isTransparent;
// create and setup mesh
ANARIGeometry mesh = anariNewGeometry(dev, "triangle");
anariSetParameter(dev, mesh, "name", ANARI_STRING, "tutorialMesh");
ANARIArray1D array = anariNewArray1D(dev, vertex, 0, 0, ANARI_FLOAT32_VEC3, 4);
anariCommitParameters(dev, array);
anariSetParameter(dev, mesh, "vertex.position", ANARI_ARRAY, &array);
anariRelease(dev, array); // we are done using this handle
array = anariNewArray1D(dev, normal, 0, 0, ANARI_FLOAT32_VEC3, 4);
anariCommitParameters(dev, array);
anariSetParameter(dev, mesh, "vertex.normal", ANARI_ARRAY, &array);
anariRelease(dev, array);
// Set the vertex colors
if (useVertexColors)
{
array = anariNewArray1D(dev, color, 0, 0, ANARI_FLOAT32_VEC4, 4);
anariCommitParameters(dev, array);
anariSetParameter(dev, mesh, "vertex.color", ANARI_ARRAY, &array);
anariRelease(dev, array);
}
array = anariNewArray1D(dev, texcoord, 0, 0, ANARI_FLOAT32_VEC2, 4);
anariCommitParameters(dev, array);
anariSetParameter(dev, mesh, "vertex.attribute0", ANARI_ARRAY, &array);
anariRelease(dev, array);
anariSetParameter(dev, mesh, "usd::attribute0.name", ANARI_STRING, "customTexcoordName");
if(isTransparent)
{
array = anariNewArray1D(dev, opacities, 0, 0, ANARI_FLOAT32, 2);
anariCommitParameters(dev, array);
anariSetParameter(dev, mesh, "primitive.attribute1", ANARI_ARRAY, &array);
anariRelease(dev, array);
}
array = anariNewArray1D(dev, index, 0, 0, ANARI_INT32_VEC3, 2);
anariCommitParameters(dev, array);
anariSetParameter(dev, mesh, "primitive.index", ANARI_ARRAY, &array);
anariRelease(dev, array);
anariCommitParameters(dev, mesh);
// Create a sampler
ANARISampler sampler = 0;
if(useTexture)
{
sampler = anariNewSampler(dev, "image2D");
anariSetParameter(dev, sampler, "name", ANARI_STRING, "tutorialSampler");
anariSetParameter(dev, sampler, "inAttribute", ANARI_STRING, "customTexcoordName");
anariSetParameter(dev, sampler, "wrapMode1", ANARI_STRING, wrapS);
anariSetParameter(dev, sampler, "wrapMode2", ANARI_STRING, wrapT);
array = anariNewArray2D(dev, testData.textureData, 0, 0, ANARI_UINT8_VEC3, testData.textureSize[0], testData.textureSize[1]); // Make sure this matches numTexComponents
//anariSetParameter(dev, sampler, "usd::imageUrl", ANARI_STRING, texFile);
anariSetParameter(dev, sampler, "image", ANARI_ARRAY, &array);
anariCommitParameters(dev, sampler);
anariRelease(dev, array);
}
ANARISampler opacitySampler = 0;
if(isTransparent && useTexture)
{
opacitySampler = anariNewSampler(dev, "image2D");
anariSetParameter(dev, opacitySampler, "name", ANARI_STRING, "tutorialSamplerOpacity");
anariSetParameter(dev, opacitySampler, "inAttribute", ANARI_STRING, "customTexcoordName");
anariSetParameter(dev, opacitySampler, "wrapMode1", ANARI_STRING, wrapS);
anariSetParameter(dev, opacitySampler, "wrapMode2", ANARI_STRING, wrapT);
array = anariNewArray2D(dev, testData.opacityTextureData, 0, 0, ANARI_UINT8, testData.textureSize[0], testData.textureSize[1]);
anariSetParameter(dev, opacitySampler, "image", ANARI_ARRAY, &array);
anariCommitParameters(dev, opacitySampler);
anariRelease(dev, array);
}
// Create a material
ANARIMaterial mat = anariNewMaterial(dev, "matte");
anariSetParameter(dev, mat, "name", ANARI_STRING, "tutorialMaterial");
if (useVertexColors)
anariSetParameter(dev, mat, "color", ANARI_STRING, "color");
else if(useTexture)
anariSetParameter(dev, mat, "color", ANARI_SAMPLER, &sampler);
else
anariSetParameter(dev, mat, "color", ANARI_FLOAT32_VEC3, kd);
float opacityConstant = isTransparent ? 0.65f : 1.0f;
if(isTransparent)
{
anariSetParameter(dev, mat, "alphaMode", ANARI_STRING, "blend");
if(useVertexColors)
anariSetParameter(dev, mat, "opacity", ANARI_STRING, "attribute1");
else if(useTexture)
anariSetParameter(dev, mat, "opacity", ANARI_SAMPLER, &opacitySampler);
else
anariSetParameter(dev, mat, "opacity", ANARI_FLOAT32, &opacityConstant);
}
else
{
anariSetParameter(dev, mat, "opacity", ANARI_FLOAT32, &opacityConstant);
}
int timevaryEmissive = 1; // Set emissive to timevarying (should appear in material stage under primstages/)
anariSetParameter(dev, mat, "usd::timeVarying.emissive", ANARI_BOOL, &timevaryEmissive);
anariCommitParameters(dev, mat);
anariRelease(dev, sampler);
anariRelease(dev, opacitySampler);
// put the mesh into a surface
ANARISurface surface = anariNewSurface(dev);
anariSetParameter(dev, surface, "name", ANARI_STRING, "tutorialSurface");
anariSetParameter(dev, surface, "geometry", ANARI_GEOMETRY, &mesh);
anariSetParameter(dev, surface, "material", ANARI_MATERIAL, &mat);
anariCommitParameters(dev, surface);
anariRelease(dev, mesh);
anariRelease(dev, mat);
// put the surface into a group
ANARIGroup group = anariNewGroup(dev);
anariSetParameter(dev, group, "name", ANARI_STRING, "tutorialGroup");
array = anariNewArray1D(dev, &surface, 0, 0, ANARI_SURFACE, 1);
anariCommitParameters(dev, array);
anariSetParameter(dev, group, "surface", ANARI_ARRAY, &array);
anariCommitParameters(dev, group);
anariRelease(dev, surface);
anariRelease(dev, array);
// put the group into an instance (give the group a world transform)
ANARIInstance instance = anariNewInstance(dev, "transform");
anariSetParameter(dev, instance, "name", ANARI_STRING, "tutorialInstance");
anariSetParameter(dev, instance, "transform", ANARI_FLOAT32_MAT4, transform);
anariSetParameter(dev, instance, "group", ANARI_GROUP, &group);
anariRelease(dev, group);
return instance;
}
ANARIInstance createConesInstance(ANARIDevice dev, TestParameters_t testParams, GridData_t testData)
{
// create and setup geom
ANARIGeometry cones = anariNewGeometry(dev, "cone");
anariSetParameter(dev, cones, "name", ANARI_STRING, "tutorialMesh");
int sizeX = testData.gridSize[0], sizeY = testData.gridSize[1];
int numVertices = sizeX*sizeY;
// Create a snake pattern through the vertices
int numIndexTuples = sizeY*sizeX-1;
int* indices = (int*)malloc(2*(numIndexTuples+1)*sizeof(int)); // Extra space for a dummy tuple
int vertIdxTo = 0;
for(int i = 0; i < sizeX; ++i)
{
for(int j = 0; j < sizeY; ++j)
{
int vertIdxFrom = vertIdxTo;
vertIdxTo = vertIdxFrom + ((j == sizeY-1) ? sizeY : ((i%2) ? -1 : 1));
int idxAddr = 2*(sizeY*i+j);
indices[idxAddr] = vertIdxFrom;
indices[idxAddr+1] = vertIdxTo;
}
}
ANARIArray1D array = anariNewArray1D(dev, testData.gridVertex, 0, 0, ANARI_FLOAT32_VEC3, numVertices);
anariCommitParameters(dev, array);
anariSetParameter(dev, cones, "vertex.position", ANARI_ARRAY, &array);
anariRelease(dev, array); // we are done using this handle
if(testParams.useIndices)
{
array = anariNewArray1D(dev, indices, 0, 0, ANARI_INT32_VEC2, numIndexTuples);
anariCommitParameters(dev, array);
anariSetParameter(dev, cones, "primitive.index", ANARI_ARRAY, &array);
anariRelease(dev, array);
}
// Set the vertex colors
if (testParams.useVertexColors)
{
array = anariNewArray1D(dev, testData.gridColor, 0, 0, ANARI_FLOAT32_VEC3, numVertices);
anariCommitParameters(dev, array);
anariSetParameter(dev, cones, "vertex.color", ANARI_ARRAY, &array);
anariRelease(dev, array);
}
if(testParams.isTransparent)
{
array = anariNewArray1D(dev, testData.gridOpacity, 0, 0, ANARI_FLOAT32, numVertices);
anariCommitParameters(dev, array);
anariSetParameter(dev, cones, "vertex.attribute0", ANARI_ARRAY, &array);
anariRelease(dev, array);
}
// Use per-primitive radii when not using indices, to test that codepath too
array = anariNewArray1D(dev, testData.gridRadius, 0, 0, ANARI_FLOAT32, testParams.useIndices ? numVertices : numVertices/2); // per-primitive is half the vertex count
anariCommitParameters(dev, array);
anariSetParameter(dev, cones, testParams.useIndices ? "vertex.radius" : "primitive.radius", ANARI_ARRAY, &array);
anariRelease(dev, array);
anariCommitParameters(dev, cones);
// Create a material
ANARIMaterial mat = anariNewMaterial(dev, "matte");
anariSetParameter(dev, mat, "name", ANARI_STRING, "tutorialMaterial");
if (testParams.useVertexColors)
anariSetParameter(dev, mat, "color", ANARI_STRING, "color");
else
anariSetParameter(dev, mat, "color", ANARI_FLOAT32_VEC3, kd);
float opacityConstant = testParams.isTransparent ? 0.65f : 1.0f;
if(testParams.isTransparent)
{
anariSetParameter(dev, mat, "alphaMode", ANARI_STRING, "blend");
if(testParams.useVertexColors)
anariSetParameter(dev, mat, "opacity", ANARI_STRING, "attribute1");
else
anariSetParameter(dev, mat, "opacity", ANARI_FLOAT32, &opacityConstant);
}
else
{
anariSetParameter(dev, mat, "opacity", ANARI_FLOAT32, &opacityConstant);
}
anariCommitParameters(dev, mat);
// put the mesh into a surface
ANARISurface surface = anariNewSurface(dev);
anariSetParameter(dev, surface, "name", ANARI_STRING, "tutorialSurface");
anariSetParameter(dev, surface, "geometry", ANARI_GEOMETRY, &cones);
anariSetParameter(dev, surface, "material", ANARI_MATERIAL, &mat);
anariCommitParameters(dev, surface);
anariRelease(dev, cones);
anariRelease(dev, mat);
// put the surface into a group
ANARIGroup group = anariNewGroup(dev);
anariSetParameter(dev, group, "name", ANARI_STRING, "tutorialGroup");
array = anariNewArray1D(dev, &surface, 0, 0, ANARI_SURFACE, 1);
anariCommitParameters(dev, array);
anariSetParameter(dev, group, "surface", ANARI_ARRAY, &array);
anariCommitParameters(dev, group);
anariRelease(dev, surface);
anariRelease(dev, array);
// put the group into an instance (give the group a world transform)
ANARIInstance instance = anariNewInstance(dev, "transform");
anariSetParameter(dev, instance, "name", ANARI_STRING, "tutorialInstance");
anariSetParameter(dev, instance, "group", ANARI_GROUP, &group);
anariRelease(dev, group);
free(indices);
return instance;
}
ANARIInstance createGlyphsInstance(ANARIDevice dev, TestParameters_t testParams, GridData_t testData)
{
int sizeX = testData.gridSize[0], sizeY = testData.gridSize[1];
int numVertices = sizeX*sizeY;
ANARIArray1D array;
ANARIGeometry protoMesh;
// The prototype mesh (instanced geometry)
if(testParams.useGlyphMesh)
{
protoMesh = anariNewGeometry(dev, "triangle");
anariSetParameter(dev, protoMesh, "name", ANARI_STRING, "tutorialProtoMesh");
array = anariNewArray1D(dev, protoVertex, 0, 0, ANARI_FLOAT32_VEC3, 8);
anariCommitParameters(dev, array);
anariSetParameter(dev, protoMesh, "vertex.position", ANARI_ARRAY, &array);
anariRelease(dev, array); // we are done using this handle
if (testParams.useVertexColors)
{
array = anariNewArray1D(dev, protoColor, 0, 0, ANARI_FLOAT32_VEC4, 8);
anariCommitParameters(dev, array);
anariSetParameter(dev, protoMesh, "vertex.color", ANARI_ARRAY, &array);
anariRelease(dev, array);
}
array = anariNewArray1D(dev, protoIndex, 0, 0, ANARI_INT32_VEC3, 8);
anariCommitParameters(dev, array);
anariSetParameter(dev, protoMesh, "primitive.index", ANARI_ARRAY, &array);
anariRelease(dev, array);
anariCommitParameters(dev, protoMesh);
}
// The glyph geometry
ANARIGeometry glyphs = anariNewGeometry(dev, "glyph");
if(testParams.useGlyphMesh)
anariSetParameter(dev, glyphs, "shapeGeometry", ANARI_GEOMETRY, &protoMesh);
else
anariSetParameter(dev, glyphs, "shapeType", ANARI_STRING, "cylinder");
anariSetParameter(dev, glyphs, "shapeTransform", ANARI_FLOAT32_MAT4, protoTransform);
if(testParams.useGlyphMesh)
anariRelease(dev, protoMesh);
array = anariNewArray1D(dev, testData.gridVertex, 0, 0, ANARI_FLOAT32_VEC3, numVertices);
anariCommitParameters(dev, array);
anariSetParameter(dev, glyphs, "vertex.position", ANARI_ARRAY, &array);
anariRelease(dev, array); // we are done using this handle
if (testParams.useVertexColors)
{
array = anariNewArray1D(dev, testData.gridColor, 0, 0, ANARI_FLOAT32_VEC3, numVertices);
anariCommitParameters(dev, array);
anariSetParameter(dev, glyphs, "vertex.color", ANARI_ARRAY, &array);
anariRelease(dev, array);
}
array = anariNewArray1D(dev, testData.gridRadius, 0, 0, ANARI_FLOAT32, numVertices);
anariCommitParameters(dev, array);
anariSetParameter(dev, glyphs, "vertex.scale", ANARI_ARRAY, &array);
anariRelease(dev, array);
array = anariNewArray1D(dev, testData.gridOrientation, 0, 0, ANARI_FLOAT32_QUAT_IJKW, numVertices);
anariCommitParameters(dev, array);
anariSetParameter(dev, glyphs, "vertex.orientation", ANARI_ARRAY, &array);
anariRelease(dev, array);
anariCommitParameters(dev, glyphs);
// Create a material
ANARIMaterial mat = anariNewMaterial(dev, "matte");
anariSetParameter(dev, mat, "name", ANARI_STRING, "tutorialMaterial");
if (testParams.useVertexColors)
anariSetParameter(dev, mat, "color", ANARI_STRING, "color");
else
anariSetParameter(dev, mat, "color", ANARI_FLOAT32_VEC3, kd);
float opacityConstant = testParams.isTransparent ? 0.65f : 1.0f;
if(testParams.isTransparent)
{
anariSetParameter(dev, mat, "alphaMode", ANARI_STRING, "blend");
if(testParams.useVertexColors)
anariSetParameter(dev, mat, "opacity", ANARI_STRING, "attribute1");
else
anariSetParameter(dev, mat, "opacity", ANARI_FLOAT32, &opacityConstant);
}
else
{
anariSetParameter(dev, mat, "opacity", ANARI_FLOAT32, &opacityConstant);
}
anariCommitParameters(dev, mat);
// put the mesh into a surface
ANARISurface surface = anariNewSurface(dev);
anariSetParameter(dev, surface, "name", ANARI_STRING, "tutorialSurface");
anariSetParameter(dev, surface, "geometry", ANARI_GEOMETRY, &glyphs);
anariSetParameter(dev, surface, "material", ANARI_MATERIAL, &mat);
anariCommitParameters(dev, surface);
anariRelease(dev, glyphs);
anariRelease(dev, mat);
// put the surface into a group
ANARIGroup group = anariNewGroup(dev);
anariSetParameter(dev, group, "name", ANARI_STRING, "tutorialGroup");
array = anariNewArray1D(dev, &surface, 0, 0, ANARI_SURFACE, 1);
anariCommitParameters(dev, array);
anariSetParameter(dev, group, "surface", ANARI_ARRAY, &array);
anariCommitParameters(dev, group);
anariRelease(dev, surface);
anariRelease(dev, array);
// put the group into an instance (give the group a world transform)
ANARIInstance instance = anariNewInstance(dev, "transform");
anariSetParameter(dev, instance, "name", ANARI_STRING, "tutorialInstance");
anariSetParameter(dev, instance, "group", ANARI_GROUP, &group);
anariRelease(dev, group);
return instance;
}
void doTest(TestParameters_t testParams)
{
printf("\n\n-------------- Starting new test iteration \n\n");
printf("Parameters: writeatcommit %d, useVertexColors %d, useTexture %d, transparent %d, geom type %s \n",
testParams.writeAtCommit, testParams.useVertexColors, testParams.useTexture, testParams.isTransparent,
((testParams.testType == TEST_MESH) ? "mesh" : ((testParams.testType == TEST_CONES) ? "cones" : "glyphs")));
stbi_flip_vertically_on_write(1);
// image sizes
int frameSize[2] = { 1024, 768 };
int textureSize[2] = { 256, 256 };
int gridSize[2] = { 100, 100 };
uint8_t* textureData = 0;
int numTexComponents = 3;
textureData = generateTexture(textureSize, numTexComponents);
uint8_t* opacityTextureData = 0;
opacityTextureData = generateTexture(textureSize, 1);
GridData_t gridData;
createSineWaveGrid(gridSize, &gridData);
TexData_t texData;
texData.textureData = textureData;
texData.opacityTextureData = opacityTextureData;
texData.textureSize[0] = textureSize[0];
texData.textureSize[1] = textureSize[1];
// camera
float cam_pos[] = { 0.f, 0.f, 0.f };
float cam_up[] = { 0.f, 1.f, 0.f };
float cam_view[] = { 0.1f, 0.f, 1.f };
printf("initialize ANARI...");
ANARILibrary lib = anariLoadLibrary(g_libraryType, statusFunc, NULL);
ANARIDevice dev = anariNewDevice(lib, "usd");
if (!dev) {
printf("\n\nERROR: could not load device '%s'\n", "usd");
return;
}
int outputBinary = 0;
int outputOmniverse = 0;
int connLogVerbosity = 0;
int outputMaterial = 1;
int outputPreviewSurface = 1;
int outputMdl = 1;
anariSetParameter(dev, dev, "usd::connection.logVerbosity", ANARI_INT32, &connLogVerbosity);
if (outputOmniverse)
{
anariSetParameter(dev, dev, "usd::serialize.hostName", ANARI_STRING, "localhost");
anariSetParameter(dev, dev, "usd::serialize.location", ANARI_STRING, "/Users/test/anari");
}
anariSetParameter(dev, dev, "usd::serialize.outputBinary", ANARI_BOOL, &outputBinary);
anariSetParameter(dev, dev, "usd::output.material", ANARI_BOOL, &outputMaterial);
anariSetParameter(dev, dev, "usd::output.previewSurfaceShader", ANARI_BOOL, &outputPreviewSurface);
anariSetParameter(dev, dev, "usd::output.mdlShader", ANARI_BOOL, &outputMdl);
anariSetParameter(dev, dev, "usd::writeAtCommit", ANARI_BOOL, &testParams.writeAtCommit);
// commit device
anariCommitParameters(dev, dev);
printf("done!\n");
printf("setting up camera...");
// create and setup camera
ANARICamera camera = anariNewCamera(dev, "perspective");
float aspect = frameSize[0] / (float)frameSize[1];
anariSetParameter(dev, camera, "aspect", ANARI_FLOAT32, &aspect);
anariSetParameter(dev, camera, "position", ANARI_FLOAT32_VEC3, cam_pos);
anariSetParameter(dev, camera, "direction", ANARI_FLOAT32_VEC3, cam_view);
anariSetParameter(dev, camera, "up", ANARI_FLOAT32_VEC3, cam_up);
anariCommitParameters(dev, camera); // commit each object to indicate mods are done
printf("done!\n");
printf("setting up scene...");
ANARIWorld world = anariNewWorld(dev);
ANARIInstance instance;
switch(testParams.testType)
{
case TEST_MESH:
instance = createMeshInstance(dev, testParams, texData);
break;
case TEST_CONES:
instance = createConesInstance(dev, testParams, gridData);
break;
case TEST_GLYPHS:
instance = createGlyphsInstance(dev, testParams, gridData);
break;
default:
break;
};
if(!instance)
return;
anariCommitParameters(dev, instance);
// create and setup light for Ambient Occlusion
ANARILight light = anariNewLight(dev, "ambient");
anariSetParameter(dev, light, "name", ANARI_STRING, "tutorialLight");
anariCommitParameters(dev, light);
ANARIArray1D array = anariNewArray1D(dev, &light, 0, 0, ANARI_LIGHT, 1);
anariCommitParameters(dev, array);
anariSetParameter(dev, world, "light", ANARI_ARRAY, &array);
anariRelease(dev, light);
anariRelease(dev, array);
// put the instance in the world
anariSetParameter(dev, world, "name", ANARI_STRING, "tutorialWorld");
array = anariNewArray1D(dev, &instance, 0, 0, ANARI_INSTANCE, 1);
anariCommitParameters(dev, array);
anariSetParameter(dev, world, "instance", ANARI_ARRAY, &array);
anariRelease(dev, instance);
anariRelease(dev, array);
anariCommitParameters(dev, world);
printf("done!\n");
// print out world bounds
float worldBounds[6];
if (anariGetProperty(dev,
world,
"bounds",
ANARI_FLOAT32_BOX3,
worldBounds,
sizeof(worldBounds),
ANARI_WAIT)) {
printf("\nworld bounds: ({%f, %f, %f}, {%f, %f, %f}\n\n",
worldBounds[0],
worldBounds[1],
worldBounds[2],
worldBounds[3],
worldBounds[4],
worldBounds[5]);
}
else {
printf("\nworld bounds not returned\n\n");
}
printf("setting up renderer...");
// create renderer
ANARIRenderer renderer =
anariNewRenderer(dev, "pathtracer"); // choose path tracing renderer
// complete setup of renderer
float bgColor[4] = { 1.f, 1.f, 1.f, 1.f }; // white
anariSetParameter(dev, renderer, "backgroundColor", ANARI_FLOAT32_VEC4, bgColor);
anariCommitParameters(dev, renderer);
// create and setup frame
ANARIFrame frame = anariNewFrame(dev);
ANARIDataType colFormat = ANARI_UFIXED8_RGBA_SRGB;
ANARIDataType depthFormat = ANARI_FLOAT32;
anariSetParameter(dev, frame, "size", ANARI_UINT32_VEC2, frameSize);
anariSetParameter(dev, frame, "channel.color", ANARI_DATA_TYPE, &colFormat);
anariSetParameter(dev, frame, "channel.depth", ANARI_DATA_TYPE, &depthFormat);
anariSetParameter(dev, frame, "renderer", ANARI_RENDERER, &renderer);
anariSetParameter(dev, frame, "camera", ANARI_CAMERA, &camera);
anariSetParameter(dev, frame, "world", ANARI_WORLD, &world);
anariCommitParameters(dev, frame);
printf("rendering frame...");
// render one frame
anariRenderFrame(dev, frame);
anariFrameReady(dev, frame, ANARI_WAIT);
printf("done!\n");
printf("\ncleaning up objects...");
// final cleanups
anariRelease(dev, renderer);
anariRelease(dev, camera);
anariRelease(dev, frame);
anariRelease(dev, world);
anariRelease(dev, dev);
anariUnloadLibrary(lib);
freeTexture(textureData);
freeSineWaveGrid(&gridData);
printf("done!\n");
}
int main(int argc, const char **argv)
{
TestParameters_t testParams;
testParams.testType = TEST_MESH;
testParams.writeAtCommit = 0;
testParams.isTransparent = 0;
// Test standard flow with textures
testParams.useVertexColors = 0;
testParams.useTexture = 1;
doTest(testParams);
// With vertex colors
testParams.useVertexColors = 1;
testParams.useTexture = 0;
doTest(testParams);
// With color constant
testParams.useVertexColors = 0;
testParams.useTexture = 0;
doTest(testParams);
// Transparency
testParams.useVertexColors = 0;
testParams.useTexture = 0;
testParams.isTransparent = 1;
doTest(testParams);
// Transparency (vertex)
testParams.useVertexColors = 1;
testParams.useTexture = 0;
doTest(testParams);
// Transparency (sampler)
testParams.useVertexColors = 0;
testParams.useTexture = 1;
doTest(testParams);
// Test immediate mode writing
testParams.writeAtCommit = 1;
testParams.useVertexColors = 0;
testParams.useTexture = 1;
testParams.isTransparent = 0;
doTest(testParams);
// Cones tests
testParams.testType = TEST_CONES;
testParams.writeAtCommit = 0;
testParams.useTexture = 0;
testParams.useIndices = 0;
// With vertex colors
testParams.useVertexColors = 1;
doTest(testParams);
// With color constant
testParams.useVertexColors = 0;
doTest(testParams);
// Using indices (and vertex colors)
testParams.useIndices = 1;
testParams.useVertexColors = 1;
doTest(testParams);
// Glyphs tests
testParams.testType = TEST_GLYPHS;
testParams.writeAtCommit = 0;
testParams.useTexture = 0;
testParams.useIndices = 0;
testParams.useGlyphMesh = 0;
// With vertex colors
testParams.useVertexColors = 1;
doTest(testParams);
// With color constant
testParams.useVertexColors = 0;
doTest(testParams);
// Using indices (and vertex colors)
testParams.useGlyphMesh = 1;
doTest(testParams);
return 0;
}
| 25,558 | C | 29.069412 | 172 | 0.698294 |
NVIDIA-Omniverse/AnariUsdDevice/examples/anariTutorial_usd_recreate.c | // Copyright 2021 NVIDIA Corporation
// SPDX-License-Identifier: Apache-2.0
#include <errno.h>
#include <stdint.h>
#include <stdio.h>
#ifdef _WIN32
#include <malloc.h>
#else
#include <alloca.h>
#endif
#include "anari/anari.h"
// stb_image
#include "stb_image_write.h"
#include "anariTutorial_usd_common.h"
int main(int argc, const char **argv)
{
stbi_flip_vertically_on_write(1);
// image size
int frameSize[2] = { 1024, 768 };
int textureSize[2] = { 256, 256 };
uint8_t* textureData = 0;
int numTexComponents = 3;
textureData = generateTexture(textureSize, numTexComponents);
// camera
float cam_pos[] = {0.f, 0.f, 0.f};
float cam_up[] = {0.f, 1.f, 0.f};
float cam_view[] = {0.1f, 0.f, 1.f};
float transform[16] = {
3.0f, 0.0f, 0.0f, 0.0f,
0.0f, 3.0f, 0.0f, 0.0f,
0.0f, 0.0f, 3.0f, 0.0f,
2.0f, 3.0f, 4.0f, 1.0f };
// triangle mesh data
float vertex[] = {-1.0f,
-1.0f,
3.0f,
-1.0f,
1.0f,
3.0f,
1.0f,
-1.0f,
3.0f,
0.1f,
0.1f,
0.3f};
float normal[] = { 0.0f,
0.0f,
1.0f,
0.0f,
1.0f,
0.0f,
0.0f,
1.0f,
0.0f,
1.0f,
0.0f,
0.0f
};
float color[] = {0.0f,
0.0f,
0.9f,
1.0f,
0.8f,
0.8f,
0.8f,
1.0f,
0.8f,
0.8f,
0.8f,
1.0f,
0.0f,
0.9f,
0.0f,
1.0f};
float texcoord[] = {
0.0f,
0.0f,
1.0f,
0.0f,
1.0f,
1.0f,
0.0f,
1.0f };
float sphereSizes[] = { 0.1f,
2.0f,
0.3f,
0.05f };
int32_t index[] = {0, 1, 2, 2, 1, 3};
float kd[] = { 0.0f, 0.0f, 1.0f };
for(int anariPass = 0; anariPass < 2; ++anariPass)
{
printf("initialize ANARI...");
ANARILibrary lib = anariLoadLibrary(g_libraryType, statusFunc, NULL);
ANARIDevice dev = anariNewDevice(lib, "usd");
if (!dev) {
printf("\n\nERROR: could not load device '%s'\n", "usd");
return 1;
}
int outputBinary = 0;
int outputOmniverse = 0;
int connLogVerbosity = 0;
int outputMaterial = 1;
int createNewSession = (anariPass == 0) ? 1 : 0;
int useVertexColors = (anariPass == 0);
int useTexture = 1;
anariSetParameter(dev, dev, "usd::connection.logVerbosity", ANARI_INT32, &connLogVerbosity);
if (outputOmniverse)
{
anariSetParameter(dev, dev, "usd::serialize.hostName", ANARI_STRING, "ov-test");
anariSetParameter(dev, dev, "usd::serialize.location", ANARI_STRING, "/Users/test/anari");
}
anariSetParameter(dev, dev, "usd::serialize.outputBinary", ANARI_BOOL, &outputBinary);
anariSetParameter(dev, dev, "usd::serialize.newSession", ANARI_BOOL, &createNewSession);
anariSetParameter(dev, dev, "usd::output.material", ANARI_BOOL, &outputMaterial);
// commit device
anariCommitParameters(dev, dev);
printf("done!\n");
printf("setting up camera...");
// create and setup camera
ANARICamera camera = anariNewCamera(dev, "perspective");
float aspect = frameSize[0] / (float)frameSize[1];
anariSetParameter(dev, camera, "aspect", ANARI_FLOAT32, &aspect);
anariSetParameter(dev, camera, "position", ANARI_FLOAT32_VEC3, cam_pos);
anariSetParameter(dev, camera, "direction", ANARI_FLOAT32_VEC3, cam_view);
anariSetParameter(dev, camera, "up", ANARI_FLOAT32_VEC3, cam_up);
int deleteCam = 1;
if(anariPass == 0)
anariSetParameter(dev, camera, "usd::removePrim", ANARI_BOOL, &deleteCam);
anariCommitParameters(dev, camera); // commit each object to indicate mods are done
printf("done!\n");
printf("setting up scene...");
ANARIWorld world = anariNewWorld(dev);
// create and setup mesh
ANARIGeometry mesh = anariNewGeometry(dev, "triangle");
anariSetParameter(dev, mesh, "name", ANARI_STRING, "tutorialMesh");
ANARIArray1D array = anariNewArray1D(dev, vertex, 0, 0, ANARI_FLOAT32_VEC3, 4);
anariCommitParameters(dev, array);
anariSetParameter(dev, mesh, "vertex.position", ANARI_ARRAY, &array);
anariRelease(dev, array); // we are done using this handle
array = anariNewArray1D(dev, normal, 0, 0, ANARI_FLOAT32_VEC3, 4);
anariCommitParameters(dev, array);
anariSetParameter(dev, mesh, "vertex.normal", ANARI_ARRAY, &array);
anariRelease(dev, array);
// Set the vertex colors
if (useVertexColors)
{
array = anariNewArray1D(dev, color, 0, 0, ANARI_FLOAT32_VEC4, 4);
anariCommitParameters(dev, array);
anariSetParameter(dev, mesh, "vertex.color", ANARI_ARRAY, &array);
anariRelease(dev, array);
}
array = anariNewArray1D(dev, texcoord, 0, 0, ANARI_FLOAT32_VEC2, 4);
anariCommitParameters(dev, array);
anariSetParameter(dev, mesh, "vertex.attribute0", ANARI_ARRAY, &array);
anariRelease(dev, array);
//array = anariNewArray1D(dev, sphereSizes, 0, 0, ANARI_FLOAT32, 4);
//anariCommitParameters(dev, array);
//anariSetParameter(dev, mesh, "vertex.radius", ANARI_ARRAY, &array);
//anariRelease(dev, array);
array = anariNewArray1D(dev, index, 0, 0, ANARI_INT32_VEC3, 2);
anariCommitParameters(dev, array);
anariSetParameter(dev, mesh, "primitive.index", ANARI_ARRAY, &array);
anariRelease(dev, array);
anariCommitParameters(dev, mesh);
ANARIMaterial mat;
// The second iteration should not create samplers/materials and not add it to the surface,
// so the material prim itself will remain untouched in the pre-existing stage,
// while its reference will be removed from the newly committed surface prim
if(anariPass == 0)
{
mat = anariNewMaterial(dev, "matte");
ANARISampler sampler = anariNewSampler(dev, "image2D");
// Create a sampler
anariSetParameter(dev, sampler, "name", ANARI_STRING, "tutorialSampler");
//anariSetParameter(dev, sampler, "usd::imageUrl", ANARI_STRING, texFile);
array = anariNewArray2D(dev, textureData, 0, 0, ANARI_UINT8_VEC3, textureSize[0], textureSize[1]); // Make sure this matches numTexComponents
anariSetParameter(dev, sampler, "image", ANARI_ARRAY, &array);
anariSetParameter(dev, sampler, "inAttribute", ANARI_STRING, "attribute0");
anariSetParameter(dev, sampler, "wrapMode1", ANARI_STRING, wrapS);
anariSetParameter(dev, sampler, "wrapMode2", ANARI_STRING, wrapT);
anariCommitParameters(dev, sampler);
anariRelease(dev, array);
// Create a material
anariSetParameter(dev, mat, "name", ANARI_STRING, "tutorialMaterial");
float opacity = 1.0f;
if (useVertexColors)
anariSetParameter(dev, mat, "color", ANARI_STRING, "color");
else if(useTexture)
anariSetParameter(dev, mat, "color", ANARI_SAMPLER, &sampler);
else
anariSetParameter(dev, mat, "color", ANARI_FLOAT32_VEC3, kd);
anariSetParameter(dev, mat, "opacity", ANARI_FLOAT32, &opacity);
anariCommitParameters(dev, mat);
anariRelease(dev, sampler);
}
// put the mesh into a surface
ANARISurface surface = anariNewSurface(dev);
anariSetParameter(dev, surface, "name", ANARI_STRING, "tutorialSurface");
anariSetParameter(dev, surface, "geometry", ANARI_GEOMETRY, &mesh);
if (anariPass == 0)
anariSetParameter(dev, surface, "material", ANARI_MATERIAL, &mat);
anariCommitParameters(dev, surface);
anariRelease(dev, mesh);
if (anariPass == 0)
anariRelease(dev, mat);
// put the surface into a group
ANARIGroup group = anariNewGroup(dev);
anariSetParameter(dev, group, "name", ANARI_STRING, "tutorialGroup");
array = anariNewArray1D(dev, &surface, 0, 0, ANARI_SURFACE, 1);
anariCommitParameters(dev, array);
anariSetParameter(dev, group, "surface", ANARI_ARRAY, &array);
anariCommitParameters(dev, group);
anariRelease(dev, surface);
anariRelease(dev, array);
// put the group into an instance (give the group a world transform)
ANARIInstance instance = anariNewInstance(dev, "transform");
anariSetParameter(dev, instance, "name", ANARI_STRING, "tutorialInstance");
anariSetParameter(dev, instance, "transform", ANARI_FLOAT32_MAT4, transform);
anariSetParameter(dev, instance, "group", ANARI_GROUP, &group);
anariRelease(dev, group);
// create and setup light for Ambient Occlusion
ANARILight light = anariNewLight(dev, "ambient");
anariSetParameter(dev, light, "name", ANARI_STRING, "tutorialLight");
anariCommitParameters(dev, light);
array = anariNewArray1D(dev, &light, 0, 0, ANARI_LIGHT, 1);
anariCommitParameters(dev, array);
anariSetParameter(dev, world, "light", ANARI_ARRAY, &array);
anariRelease(dev, light);
anariRelease(dev, array);
anariCommitParameters(dev, instance);
// put the instance in the world
anariSetParameter(dev, world, "name", ANARI_STRING, "tutorialWorld");
array = anariNewArray1D(dev, &instance, 0, 0, ANARI_INSTANCE, 1);
anariCommitParameters(dev, array);
anariSetParameter(dev, world, "instance", ANARI_ARRAY, &array);
anariRelease(dev, instance);
anariRelease(dev, array);
anariCommitParameters(dev, world);
printf("done!\n");
// print out world bounds
float worldBounds[6];
if (anariGetProperty(dev,
world,
"bounds",
ANARI_FLOAT32_BOX3,
worldBounds,
sizeof(worldBounds),
ANARI_WAIT)) {
printf("\nworld bounds: ({%f, %f, %f}, {%f, %f, %f}\n\n",
worldBounds[0],
worldBounds[1],
worldBounds[2],
worldBounds[3],
worldBounds[4],
worldBounds[5]);
}
else {
printf("\nworld bounds not returned\n\n");
}
printf("setting up renderer...");
// create renderer
ANARIRenderer renderer =
anariNewRenderer(dev, "pathtracer"); // choose path tracing renderer
// complete setup of renderer
float bgColor[4] = { 1.f, 1.f, 1.f, 1.f }; // white
anariSetParameter(dev, renderer, "backgroundColor", ANARI_FLOAT32_VEC4, bgColor);
anariCommitParameters(dev, renderer);
// create and setup frame
ANARIFrame frame = anariNewFrame(dev);
ANARIDataType colFormat = ANARI_UFIXED8_RGBA_SRGB;
ANARIDataType depthFormat = ANARI_FLOAT32;
anariSetParameter(dev, frame, "size", ANARI_UINT32_VEC2, frameSize);
anariSetParameter(dev, frame, "channel.color", ANARI_DATA_TYPE, &colFormat);
anariSetParameter(dev, frame, "channel.depth", ANARI_DATA_TYPE, &depthFormat);
anariSetParameter(dev, frame, "renderer", ANARI_RENDERER, &renderer);
anariSetParameter(dev, frame, "camera", ANARI_CAMERA, &camera);
anariSetParameter(dev, frame, "world", ANARI_WORLD, &world);
anariCommitParameters(dev, frame);
printf("rendering frame...");
// render one frame
anariRenderFrame(dev, frame);
anariFrameReady(dev, frame, ANARI_WAIT);
printf("done!\n");
printf("\ncleaning up objects...");
// final cleanups
anariRelease(dev, renderer);
anariRelease(dev, camera);
anariRelease(dev, frame);
anariRelease(dev, world);
anariRelease(dev, dev);
anariUnloadLibrary(lib);
printf("done!\n");
for(int vIdx = 0; vIdx < sizeof(vertex)/sizeof(float); ++vIdx)
{
vertex[vIdx] += 1.0f;
}
}
freeTexture(textureData);
return 0;
}
| 11,313 | C | 30.254144 | 147 | 0.644745 |
NVIDIA-Omniverse/AnariUsdDevice/examples/anariTutorial_usd.cpp | // Copyright 2021 NVIDIA Corporation
// SPDX-License-Identifier: Apache-2.0
#include <errno.h>
#include <stdint.h>
#include <stdio.h>
#include <array>
// anari
#define ANARI_EXTENSION_UTILITY_IMPL
#include "anari/anari_cpp.hpp"
#include "anari/anari_cpp/ext/std.h"
// stb_image
#include "stb_image_write.h"
using uvec2 = std::array<unsigned int, 2>;
using ivec3 = std::array<int, 3>;
using vec3 = std::array<float, 3>;
using vec4 = std::array<float, 4>;
using box3 = std::array<vec3, 2>;
void statusFunc(const void *userData,
ANARIDevice device,
ANARIObject source,
ANARIDataType sourceType,
ANARIStatusSeverity severity,
ANARIStatusCode code,
const char *message)
{
(void)userData;
(void)device;
(void)source;
(void)sourceType;
(void)code;
if (severity == ANARI_SEVERITY_FATAL_ERROR) {
fprintf(stderr, "[FATAL] %s\n", message);
} else if (severity == ANARI_SEVERITY_ERROR) {
fprintf(stderr, "[ERROR] %s\n", message);
} else if (severity == ANARI_SEVERITY_WARNING) {
fprintf(stderr, "[WARN ] %s\n", message);
} else if (severity == ANARI_SEVERITY_PERFORMANCE_WARNING) {
fprintf(stderr, "[PERF ] %s\n", message);
} else if (severity == ANARI_SEVERITY_INFO) {
fprintf(stderr, "[INFO ] %s\n", message);
} else if (severity == ANARI_SEVERITY_DEBUG) {
fprintf(stderr, "[DEBUG] %s\n", message);
}
}
int main(int argc, const char **argv)
{
(void)argc;
(void)argv;
stbi_flip_vertically_on_write(1);
// image size
uvec2 imgSize = {1024 /*width*/, 768 /*height*/};
// camera
vec3 cam_pos = {0.f, 0.f, 0.f};
vec3 cam_up = {0.f, 1.f, 0.f};
vec3 cam_view = {0.1f, 0.f, 1.f};
// triangle mesh array
vec3 vertex[] = {{-1.0f, -1.0f, 3.0f},
{-1.0f, 1.0f, 3.0f},
{1.0f, -1.0f, 3.0f},
{0.1f, 0.1f, 0.3f}};
vec4 color[] = {{0.9f, 0.0f, 0.0f, 1.0f},
{0.8f, 0.8f, 0.8f, 1.0f},
{0.8f, 0.8f, 0.8f, 1.0f},
{0.0f, 0.9f, 0.0f, 1.0f}};
ivec3 index[] = {{0, 1, 2}, {1, 2, 3}};
printf("initialize ANARI...");
anari::Library lib = anari::loadLibrary("usd", statusFunc);
anari::Extensions extensions =
anari::extension::getDeviceExtensionStruct(lib, "default");
if (!extensions.ANARI_KHR_GEOMETRY_TRIANGLE)
printf("WARNING: device doesn't support ANARI_KHR_GEOMETRY_TRIANGLE\n");
if (!extensions.ANARI_KHR_CAMERA_PERSPECTIVE)
printf("WARNING: device doesn't support ANARI_KHR_CAMERA_PERSPECTIVE\n");
if (!extensions.ANARI_KHR_LIGHT_DIRECTIONAL)
printf("WARNING: device doesn't support ANARI_KHR_LIGHT_DIRECTIONAL\n");
if (!extensions.ANARI_KHR_MATERIAL_MATTE)
printf("WARNING: device doesn't support ANARI_KHR_MATERIAL_MATTE\n");
ANARIDevice d = anariNewDevice(lib, "default");
printf("done!\n");
printf("setting up camera...");
// create and setup camera
auto camera = anari::newObject<anari::Camera>(d, "perspective");
anari::setParameter(
d, camera, "aspect", (float)imgSize[0] / (float)imgSize[1]);
anari::setParameter(d, camera, "position", cam_pos);
anari::setParameter(d, camera, "direction", cam_view);
anari::setParameter(d, camera, "up", cam_up);
anari::commitParameters(
d, camera); // commit objects to indicate setting parameters is done
printf("done!\n");
printf("setting up scene...");
// The world to be populated with renderable objects
auto world = anari::newObject<anari::World>(d);
// create and setup surface and mesh
auto mesh = anari::newObject<anari::Geometry>(d, "triangle");
anari::setAndReleaseParameter(
d, mesh, "vertex.position", anari::newArray1D(d, vertex, 4));
anari::setAndReleaseParameter(
d, mesh, "vertex.color", anari::newArray1D(d, color, 4));
anari::setAndReleaseParameter(
d, mesh, "primitive.index", anari::newArray1D(d, index, 2));
anari::commitParameters(d, mesh);
auto mat = anari::newObject<anari::Material>(d, "matte");
anari::setParameter(d, mat, "color", "color");
anari::commitParameters(d, mat);
// put the mesh into a surface
auto surface = anari::newObject<anari::Surface>(d);
anari::setAndReleaseParameter(d, surface, "geometry", mesh);
anari::setAndReleaseParameter(d, surface, "material", mat);
anari::commitParameters(d, surface);
// put the surface directly onto the world
anari::setAndReleaseParameter(
d, world, "surface", anari::newArray1D(d, &surface));
anari::release(d, surface);
// create and setup light
auto light = anari::newObject<anari::Light>(d, "directional");
anari::commitParameters(d, light);
anari::setAndReleaseParameter(
d, world, "light", anari::newArray1D(d, &light));
anari::release(d, light);
anari::commitParameters(d, world);
printf("done!\n");
// print out world bounds
box3 worldBounds;
if (anari::getProperty(d, world, "bounds", worldBounds, ANARI_WAIT)) {
printf("\nworld bounds: ({%f, %f, %f}, {%f, %f, %f}\n\n",
worldBounds[0][0],
worldBounds[0][1],
worldBounds[0][2],
worldBounds[1][0],
worldBounds[1][1],
worldBounds[1][2]);
} else {
printf("\nworld bounds not returned\n\n");
}
printf("setting up renderer...");
// create renderer
auto renderer = anari::newObject<anari::Renderer>(d, "default");
// objects can be named for easier identification in debug output etc.
anari::setParameter(d, renderer, "name", "MainRenderer");
printf("done!\n");
// complete setup of renderer
vec4 bgColor = {1.f, 1.f, 1.f, 1.f};
anari::setParameter(d, renderer, "backgroundColor", bgColor); // white
anari::commitParameters(d, renderer);
// create and setup frame
auto frame = anari::newObject<anari::Frame>(d);
anari::setParameter(d, frame, "size", imgSize);
anari::setParameter(d, frame, "channel.color", ANARI_UFIXED8_RGBA_SRGB);
anari::setAndReleaseParameter(d, frame, "renderer", renderer);
anari::setAndReleaseParameter(d, frame, "camera", camera);
anari::setAndReleaseParameter(d, frame, "world", world);
anari::commitParameters(d, frame);
printf("rendering out USD objects via anari::renderFrame()...");
// render one frame
anari::render(d, frame);
anari::wait(d, frame);
printf("done!\n");
printf("\ncleaning up objects...");
// final cleanups
anari::release(d, frame);
anari::release(d, d);
anari::unloadLibrary(lib);
printf("done!\n");
return 0;
}
| 6,357 | C++ | 29.27619 | 77 | 0.654554 |
NVIDIA-Omniverse/AnariUsdDevice/examples/anariTutorial_usd_common.h | // Copyright 2021 NVIDIA Corporation
// SPDX-License-Identifier: Apache-2.0
#pragma once
#include <math.h>
#define PI 3.14159265
const char *g_libraryType = "usd";
#ifdef _WIN32
const char* texFile = "d:/models/texture.png";
#else
const char* texFile = "/home/<username>/models/texture.png"; // Point this to any png
#endif
const char* wrapS = "repeat";
const char* wrapT = "repeat";
/******************************************************************/
void statusFunc(const void *userData,
ANARIDevice device,
ANARIObject source,
ANARIDataType sourceType,
ANARIStatusSeverity severity,
ANARIStatusCode code,
const char *message)
{
(void)userData;
if (severity == ANARI_SEVERITY_FATAL_ERROR)
{
fprintf(stderr, "[FATAL] %s\n", message);
}
else if (severity == ANARI_SEVERITY_ERROR)
{
fprintf(stderr, "[ERROR] %s\n", message);
}
else if (severity == ANARI_SEVERITY_WARNING)
{
fprintf(stderr, "[WARN ] %s\n", message);
}
else if (severity == ANARI_SEVERITY_PERFORMANCE_WARNING)
{
fprintf(stderr, "[PERF ] %s\n", message);
}
else if (severity == ANARI_SEVERITY_INFO)
{
fprintf(stderr, "[INFO ] %s\n", message);
}
else if (severity == ANARI_SEVERITY_DEBUG)
{
fprintf(stderr, "[DEBUG] %s\n", message);
}
}
void writePNG(const char *fileName, ANARIDevice d, ANARIFrame frame)
{
uint32_t size[2] = {0, 0};
ANARIDataType type = ANARI_UNKNOWN;
uint32_t *pixel = (uint32_t *)anariMapFrame(d, frame, "channel.color", &size[0], &size[1], &type);
if (type == ANARI_UFIXED8_RGBA_SRGB)
stbi_write_png(fileName, size[0], size[1], 4, pixel, 4 * size[0]);
else
printf("Incorrectly returned color buffer pixel type, image not saved.\n");
anariUnmapFrame(d, frame, "channel.color");
}
uint8_t touint8t(float val)
{
return (uint8_t)floorf((val + 1.0f)*127.5f); // 0.5*255
}
uint8_t* generateTexture(int* size, int numComps)
{
uint8_t* texData = (uint8_t*)malloc(size[0]*size[1]*numComps);
for(int i = 0; i < size[0]; ++i)
{
for(int j = 0; j < size[1]; ++j)
{
int pixIdx = i*size[1]+j;
int offset = pixIdx*numComps;
float rVal = sin((float)i/size[0] * 2.0f * PI);
float gVal = cos((float)i/size[0] * 8.0f * PI);
float bVal = cos((float)j/size[1] * 20.0f * PI);
texData[offset] = touint8t(rVal);
if(numComps >= 2)
texData[offset+1] = touint8t(gVal);
if(numComps >= 3)
texData[offset+2] = touint8t(bVal);
if(numComps == 4)
texData[offset+3] = 255;
}
}
return texData;
}
void freeTexture(uint8_t* data)
{
free(data);
}
typedef struct GridData
{
float* gridVertex;
float* gridColor;
float* gridOpacity;
float* gridRadius;
float* gridOrientation;
int gridSize[2];
} GridData_t;
void createSineWaveGrid(int* size, GridData_t* gridData)
{
int baseSize = size[0]*size[1]*sizeof(float);
float* vertData = (float*)malloc(baseSize*3);
float* colorData = (float*)malloc(baseSize*3);
float* opacityData = (float*)malloc(baseSize);
float* radiusData = (float*)malloc(baseSize);
float* orientData = (float*)malloc(baseSize*4);
for(int i = 0; i < size[0]; ++i)
{
for(int j = 0; j < size[1]; ++j)
{
int vertIdx = i*size[1]+j;
int vertAddr = vertIdx*3;
float iFrac = (float)i/size[0];
float jFrac = (float)j/size[1];
// Vertex
float amp = sin((iFrac+jFrac) * 8.0f * PI) + cos(jFrac * 5.5f * PI);
vertData[vertAddr] = ((float)i)*5.0f;
vertData[vertAddr+1] = ((float)j)*5.0f;
vertData[vertAddr+2] = amp*10.0f;
// Color
float rVal = sin(iFrac * 2.0f * PI);
float gVal = cos(iFrac * 8.0f * PI);
float bVal = cos(jFrac * 20.0f * PI);
colorData[vertAddr] = rVal;
colorData[vertAddr+1] = gVal;
colorData[vertAddr+2] = bVal;
// Opacity
float opacity = 0.3f + 0.3f*(cos(iFrac * 1.0f * PI) + sin(jFrac * 7.0f * PI));
opacityData[vertIdx] = opacity;
// Radius
//spacing is 5.0, so make sure not to go over 2.5
float radius = 1.25f + 0.5f*(cos(iFrac * 5.0f * PI) + sin(jFrac * 2.0f * PI));
radiusData[vertIdx] = radius;
// Orientation
int orientAddr = vertIdx*4;
float roll = iFrac*PI*7.3, pitch = jFrac*PI*4.9, yaw = -(jFrac+0.45f)*PI*3.3;
float sinRoll = sin(roll), sinPitch = sin(pitch), sinYaw = sin(yaw);
float cosRoll = cos(roll), cosPitch = cos(pitch), cosYaw = cos(yaw);
orientData[orientAddr] = cosRoll*cosPitch*cosYaw+sinRoll*sinPitch*sinYaw;
orientData[orientAddr+1] = sinRoll*cosPitch*cosYaw-cosRoll*sinPitch*sinYaw;
orientData[orientAddr+2] = cosRoll*sinPitch*cosYaw+sinRoll*cosPitch*sinYaw;
orientData[orientAddr+3] = cosRoll*cosPitch*sinYaw-sinRoll*sinPitch*cosYaw;
}
}
gridData->gridVertex = vertData;
gridData->gridColor = colorData;
gridData->gridOpacity = opacityData;
gridData->gridRadius = radiusData;
gridData->gridOrientation = orientData;
gridData->gridSize[0] = size[0];
gridData->gridSize[1] = size[1];
}
void freeSineWaveGrid(GridData_t* gridData)
{
free(gridData->gridVertex);
free(gridData->gridColor);
free(gridData->gridOpacity);
free(gridData->gridRadius);
free(gridData->gridOrientation);
} | 5,257 | C | 26.385417 | 100 | 0.62355 |
NVIDIA-Omniverse/AnariUsdDevice/examples/anariTutorial_usd_volume.cpp | // Copyright 2021 NVIDIA Corporation
// SPDX-License-Identifier: Apache-2.0
#include <errno.h>
#include <stdint.h>
#include <stdio.h>
#include <array>
#include <random>
// anari
#define ANARI_EXTENSION_UTILITY_IMPL
#include "anari/anari_cpp.hpp"
#include "anari/anari_cpp/ext/std.h"
// stb_image
#include "stb_image_write.h"
using uvec2 = std::array<unsigned int, 2>;
using uvec3 = std::array<unsigned int, 3>;
using ivec3 = std::array<int, 3>;
using vec3 = std::array<float, 3>;
using vec4 = std::array<float, 4>;
using box3 = std::array<vec3, 2>;
void statusFunc(const void *userData,
ANARIDevice device,
ANARIObject source,
ANARIDataType sourceType,
ANARIStatusSeverity severity,
ANARIStatusCode code,
const char *message)
{
(void)userData;
(void)device;
(void)source;
(void)sourceType;
(void)code;
if (severity == ANARI_SEVERITY_FATAL_ERROR) {
fprintf(stderr, "[FATAL] %s\n", message);
} else if (severity == ANARI_SEVERITY_ERROR) {
fprintf(stderr, "[ERROR] %s\n", message);
} else if (severity == ANARI_SEVERITY_WARNING) {
fprintf(stderr, "[WARN ] %s\n", message);
} else if (severity == ANARI_SEVERITY_PERFORMANCE_WARNING) {
fprintf(stderr, "[PERF ] %s\n", message);
} else if (severity == ANARI_SEVERITY_INFO) {
fprintf(stderr, "[INFO ] %s\n", message);
} else if (severity == ANARI_SEVERITY_DEBUG) {
fprintf(stderr, "[DEBUG] %s\n", message);
}
}
struct ParameterInfo
{
const char* m_name;
bool m_param;
const char* m_description;
};
struct GravityVolume
{
GravityVolume(anari::Device d);
~GravityVolume();
std::vector<ParameterInfo> parameters();
anari::World world();
void commit();
private:
anari::Device m_device{nullptr};
anari::World m_world{nullptr};
};
struct Point
{
vec3 center;
float weight;
};
static std::vector<Point> generatePoints(size_t numPoints)
{
// create random number distributions for point center and weight
std::mt19937 gen(0);
std::uniform_real_distribution<float> centerDistribution(-1.f, 1.f);
std::uniform_real_distribution<float> weightDistribution(0.1f, 0.3f);
// populate the points
std::vector<Point> points(numPoints);
for (auto &p : points) {
p.center[0] = centerDistribution(gen);
p.center[1] = centerDistribution(gen);
p.center[2] = centerDistribution(gen);
p.weight = weightDistribution(gen);
}
return points;
}
static std::vector<float> generateVoxels(
const std::vector<Point> &points, ivec3 dims)
{
// get world coordinate in [-1.f, 1.f] from logical coordinates in [0,
// volumeDimension)
auto logicalToWorldCoordinates = [&](int i, int j, int k) {
vec3 result = {-1.f + float(i) / float(dims[0] - 1) * 2.f,
-1.f + float(j) / float(dims[1] - 1) * 2.f,
-1.f + float(k) / float(dims[2] - 1) * 2.f};
return result;
};
// generate voxels
std::vector<float> voxels(size_t(dims[0]) * size_t(dims[1]) * size_t(dims[2]));
for (int k = 0; k < dims[2]; k++) {
for (int j = 0; j < dims[1]; j++) {
for (int i = 0; i < dims[0]; i++) {
// index in array
size_t index = size_t(k) * size_t(dims[2]) * size_t(dims[1])
+ size_t(j) * size_t(dims[0]) + size_t(i);
// compute volume value
float value = 0.f;
for (auto &p : points) {
vec3 pointCoordinate = logicalToWorldCoordinates(i, j, k);
const float distanceSq =
std::pow(pointCoordinate[0] - p.center[0], 2.0f) +
std::pow(pointCoordinate[1] - p.center[1], 2.0f) +
std::pow(pointCoordinate[2] - p.center[2], 2.0f);
// contribution proportional to weighted inverse-square distance
// (i.e. gravity)
value += p.weight / distanceSq;
}
voxels[index] = value;
}
}
}
return voxels;
}
GravityVolume::GravityVolume(anari::Device d)
{
m_device = d;
m_world = anari::newObject<anari::World>(m_device);
}
GravityVolume::~GravityVolume()
{
anari::release(m_device, m_world);
}
std::vector<ParameterInfo> GravityVolume::parameters()
{
return {
{"withGeometry", false, "Include geometry inside the volume?"}
//
};
}
anari::World GravityVolume::world()
{
return m_world;
}
void GravityVolume::commit()
{
anari::Device d = m_device;
const bool withGeometry = false;//getParam<bool>("withGeometry", false);
const int volumeDims = 128;
const size_t numPoints = 10;
const float voxelRange[2] = {0.f, 10.f};
ivec3 volumeDims3 = {volumeDims,volumeDims,volumeDims};
vec3 fieldOrigin = {-1.f, -1.f, -1.f};
vec3 fieldSpacing = {2.f / volumeDims, 2.f / volumeDims, 2.f / volumeDims};
auto points = generatePoints(numPoints);
auto voxels = generateVoxels(points, volumeDims3);
auto field = anari::newObject<anari::SpatialField>(d, "structuredRegular");
anari::setParameter(d, field, "origin", fieldOrigin);
anari::setParameter(d, field, "spacing", fieldSpacing);
anari::setAndReleaseParameter(d,
field,
"data",
anari::newArray3D(d, voxels.data(), volumeDims, volumeDims, volumeDims));
anari::commitParameters(d, field);
auto volume = anari::newObject<anari::Volume>(d, "scivis");
anari::setAndReleaseParameter(d, volume, "value", field);
{
std::vector<vec3> colors;
std::vector<float> opacities;
colors.emplace_back(vec3{0.f, 0.f, 1.f});
colors.emplace_back(vec3{0.f, 1.f, 0.f});
colors.emplace_back(vec3{1.f, 0.f, 0.f});
opacities.emplace_back(0.f);
opacities.emplace_back(0.05f);
opacities.emplace_back(0.1f);
anari::setAndReleaseParameter(
d, volume, "color", anari::newArray1D(d, colors.data(), colors.size()));
anari::setAndReleaseParameter(d,
volume,
"opacity",
anari::newArray1D(d, opacities.data(), opacities.size()));
anariSetParameter(d, volume, "valueRange", ANARI_FLOAT32_BOX1, voxelRange);
}
anari::commitParameters(d, volume);
if (withGeometry) {
std::vector<vec3> positions(numPoints);
std::transform(
points.begin(), points.end(), positions.begin(), [](const Point &p) {
return p.center;
});
ANARIGeometry geom = anari::newObject<anari::Geometry>(d, "sphere");
anari::setAndReleaseParameter(d,
geom,
"vertex.position",
anari::newArray1D(d, positions.data(), positions.size()));
anari::setParameter(d, geom, "radius", 0.05f);
anari::commitParameters(d, geom);
auto mat = anari::newObject<anari::Material>(d, "matte");
anari::commitParameters(d, mat);
auto surface = anari::newObject<anari::Surface>(d);
anari::setAndReleaseParameter(d, surface, "geometry", geom);
anari::setAndReleaseParameter(d, surface, "material", mat);
anari::commitParameters(d, surface);
anari::setAndReleaseParameter(
d, m_world, "surface", anari::newArray1D(d, &surface));
anari::release(d, surface);
} else {
anari::unsetParameter(d, m_world, "surface");
}
anari::setAndReleaseParameter(
d, m_world, "volume", anari::newArray1D(d, &volume));
anari::release(d, volume);
// create and setup light
auto light = anari::newObject<anari::Light>(d, "directional");
anari::commitParameters(d, light);
anari::setAndReleaseParameter(
d, m_world, "light", anari::newArray1D(d, &light));
anari::release(d, light);
anari::commitParameters(d, m_world);
}
int main(int argc, const char **argv)
{
(void)argc;
(void)argv;
stbi_flip_vertically_on_write(1);
// image size
uvec2 imgSize = {1024 /*width*/, 768 /*height*/};
// camera
vec3 cam_pos = {0.f, 0.f, 0.f};
vec3 cam_up = {0.f, 1.f, 0.f};
vec3 cam_view = {0.1f, 0.f, 1.f};
// triangle mesh array
vec3 vertex[] = {{-1.0f, -1.0f, 3.0f},
{-1.0f, 1.0f, 3.0f},
{1.0f, -1.0f, 3.0f},
{0.1f, 0.1f, 0.3f}};
vec4 color[] = {{0.9f, 0.5f, 0.5f, 1.0f},
{0.8f, 0.8f, 0.8f, 1.0f},
{0.8f, 0.8f, 0.8f, 1.0f},
{0.5f, 0.9f, 0.5f, 1.0f}};
uvec3 index[] = {{0, 1, 2}, {1, 2, 3}};
printf("initialize ANARI...");
anari::Library lib = anari::loadLibrary("usd", statusFunc);
anari::Extensions extensions =
anari::extension::getDeviceExtensionStruct(lib, "default");
if (!extensions.ANARI_KHR_GEOMETRY_TRIANGLE)
printf("WARNING: device doesn't support ANARI_KHR_GEOMETRY_TRIANGLE\n");
if (!extensions.ANARI_KHR_CAMERA_PERSPECTIVE)
printf("WARNING: device doesn't support ANARI_KHR_CAMERA_PERSPECTIVE\n");
if (!extensions.ANARI_KHR_LIGHT_DIRECTIONAL)
printf("WARNING: device doesn't support ANARI_KHR_LIGHT_DIRECTIONAL\n");
if (!extensions.ANARI_KHR_MATERIAL_MATTE)
printf("WARNING: device doesn't support ANARI_KHR_MATERIAL_MATTE\n");
ANARIDevice d = anariNewDevice(lib, "default");
printf("done!\n");
printf("setting up camera...");
// create and setup camera
auto camera = anari::newObject<anari::Camera>(d, "perspective");
anari::setParameter(
d, camera, "aspect", (float)imgSize[0] / (float)imgSize[1]);
anari::setParameter(d, camera, "position", cam_pos);
anari::setParameter(d, camera, "direction", cam_view);
anari::setParameter(d, camera, "up", cam_up);
anari::commitParameters(d, camera); // commit objects to indicate setting parameters is done
printf("done!\n");
printf("setting up scene...");
GravityVolume* volumeScene = new GravityVolume(d);
volumeScene->commit();
anari::World world = volumeScene->world();
printf("setting up renderer...");
// create renderer
auto renderer = anari::newObject<anari::Renderer>(d, "default");
// objects can be named for easier identification in debug output etc.
anari::setParameter(d, renderer, "name", "MainRenderer");
printf("done!\n");
// complete setup of renderer
vec4 bgColor = {1.f, 1.f, 1.f, 1.f};
anari::setParameter(d, renderer, "backgroundColor", bgColor); // white
anari::commitParameters(d, renderer);
// create and setup frame
auto frame = anari::newObject<anari::Frame>(d);
anari::setParameter(d, frame, "size", imgSize);
anari::setParameter(d, frame, "channel.color", ANARI_UFIXED8_RGBA_SRGB);
anari::setAndReleaseParameter(d, frame, "renderer", renderer);
anari::setAndReleaseParameter(d, frame, "camera", camera);
anari::setParameter(d, frame, "world", world);
anari::commitParameters(d, frame);
printf("rendering out USD objects via anari::renderFrame()...");
// render one frame
anari::render(d, frame);
anari::wait(d, frame);
printf("done!\n");
printf("\ncleaning up objects...");
// final cleanups
anari::release(d, frame);
delete volumeScene;
anari::release(d, d);
anari::unloadLibrary(lib);
printf("done!\n");
return 0;
}
| 10,686 | C++ | 27.422872 | 94 | 0.644582 |
NVIDIA-Omniverse/AnariUsdDevice/examples/anariTutorial_usd_time.c | // Copyright 2021 NVIDIA Corporation
// SPDX-License-Identifier: Apache-2.0
#include <errno.h>
#include <stdint.h>
#include <stdio.h>
#ifdef _WIN32
#include <malloc.h>
#else
#include <alloca.h>
#endif
#include "anari/anari.h"
// stb_image
#include "stb_image_write.h"
#include "anariTutorial_usd_common.h"
int main(int argc, const char **argv)
{
stbi_flip_vertically_on_write(1);
// image size
int frameSize[2] = { 1024, 768 };
int textureSize[2] = { 256, 256 };
uint8_t* textureData = 0;
int numTexComponents = 3;
textureData = generateTexture(textureSize, numTexComponents);
// camera
float cam_pos[] = {0.f, 0.f, 0.f};
float cam_up[] = {0.f, 1.f, 0.f};
float cam_view[] = {0.1f, 0.f, 1.f};
float transform[16] = {
3.0f, 0.0f, 0.0f, 0.0f,
0.0f, 3.0f, 0.0f, 0.0f,
0.0f, 0.0f, 3.0f, 0.0f,
2.0f, 3.0f, 4.0f, 1.0f };
// triangle mesh data
float vertex[] = {-1.0f,
-1.0f,
3.0f,
-1.0f,
1.0f,
3.0f,
1.0f,
-1.0f,
3.0f,
0.1f,
0.1f,
0.3f};
float color[] = {0.0f,
0.0f,
0.9f,
1.0f,
0.8f,
0.8f,
0.8f,
1.0f,
0.8f,
0.8f,
0.8f,
1.0f,
0.0f,
0.9f,
0.0f,
1.0f};
float texcoord[] = {
0.0f,
0.0f,
1.0f,
0.0f,
1.0f,
1.0f,
0.0f,
1.0f};
float sphereSizes[] = { 0.1f,
2.0f,
0.3f,
0.05f };
int32_t index[] = {0, 1, 2, 1, 2, 3};
float protoVertex[] = {-3.0f,
-1.0f,
-1.0f,
3.0f,
-1.0f,
-1.0f,
-3.0f,
1.0f,
-1.0f,
3.0f,
1.0f,
-1.0f,
-3.0f,
-1.0f,
1.0f,
3.0f,
-1.0f,
1.0f,
-3.0f,
1.0f,
1.0f,
3.0f,
1.0f,
1.0f};
float protoColor[] = {0.0f,
0.0f,
0.9f,
1.0f,
0.8f,
0.8f,
0.8f,
1.0f,
0.8f,
0.8f,
0.8f,
1.0f,
0.0f,
0.9f,
0.0f,
1.0f,
0.0f,
0.0f,
0.9f,
1.0f,
0.8f,
0.8f,
0.8f,
1.0f,
0.8f,
0.8f,
0.8f,
1.0f,
0.0f,
0.9f,
0.0f,
1.0f};
float protoTexcoord[] = {
0.0f,
0.0f,
0.0f,
1.0f,
0.25f,
0.0f,
0.25f,
1.0f,
0.5f,
0.0f,
0.5f,
1.0f,
0.75f,
0.0f,
0.75f,
1.0f};
int32_t protoIndex[] = {0, 1, 2, 2, 1, 3, 2, 3, 4, 4, 3, 5, 4, 5, 6, 6, 5, 7, 6, 7, 0, 0, 7, 1};
float protoTransform[16] = {
0.2f, 0.0f, 0.0f, 0.0f,
0.0f, 0.2f, 0.0f, 0.0f,
0.0f, 0.0f, 0.2f, 0.0f,
0.0f, 0.0f, 0.0f, 1.0f };
float kd[] = { 0.0f, 0.0f, 1.0f };
printf("initialize ANARI...");
ANARILibrary lib = anariLoadLibrary(g_libraryType, statusFunc, NULL);
ANARIDevice dev = anariNewDevice(lib, "usd");
if (!dev) {
printf("\n\nERROR: could not load device '%s'\n", "usd");
return 1;
}
int outputBinary = 0;
int outputOmniverse = 0;
int connLogVerbosity = 0;
anariSetParameter(dev, dev, "usd::connection.logVerbosity", ANARI_INT32, &connLogVerbosity);
if (outputOmniverse)
{
anariSetParameter(dev, dev, "usd::serialize.hostName", ANARI_STRING, "ov-test");
anariSetParameter(dev, dev, "usd::serialize.location", ANARI_STRING, "/Users/test/anari");
}
anariSetParameter(dev, dev, "usd::serialize.outputBinary", ANARI_BOOL, &outputBinary);
// commit device
anariCommitParameters(dev, dev);
printf("done!\n");
printf("setting up camera...");
// create and setup camera
ANARICamera camera = anariNewCamera(dev, "perspective");
float aspect = frameSize[0] / (float)frameSize[1];
anariSetParameter(dev, camera, "aspect", ANARI_FLOAT32, &aspect);
anariSetParameter(dev, camera, "position", ANARI_FLOAT32_VEC3, cam_pos);
anariSetParameter(dev, camera, "direction", ANARI_FLOAT32_VEC3, cam_view);
anariSetParameter(dev, camera, "up", ANARI_FLOAT32_VEC3, cam_up);
anariCommitParameters(dev, camera); // commit each object to indicate mods are done
// Setup texture array
ANARIArray2D texArray = anariNewArray2D(dev, textureData, 0, 0, ANARI_UINT8_VEC3, textureSize[0], textureSize[1]); // Make sure this matches numTexComponents
printf("done!\n");
printf("setting up scene...");
double timeValues[] = { 1, 0, 2, 3, 5, 8, 4, 6, 7, 9, 10 };
double geomTimeValues[] = { 3, 0, 4, 9, 7, 8, 6, 5, 1, 2, 10 };
double matTimeValues[] = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
int numTimeSteps = sizeof(timeValues) / sizeof(double);
int useVertexColors = 0;
int useTexture = 1;
int useUsdGeomPoints = 0;
// CREATE ALL TIMESTEPS:
for (int timeIdx = 0; timeIdx < numTimeSteps; ++timeIdx)
{
int doubleNodes = ((timeIdx % 3) == 1);
anariSetParameter(dev, dev, "usd::time", ANARI_FLOAT64, timeValues + timeIdx);
anariCommitParameters(dev, dev);
ANARIWorld world = anariNewWorld(dev);
// create and setup model and mesh
ANARIGeometry mesh = anariNewGeometry(dev, "triangle");
anariSetParameter(dev, mesh, "name", ANARI_STRING, "tutorialMesh");
float scaledVertex[12];
for (int v = 0; v < 12; ++v)
{
scaledVertex[v] = vertex[v] * (1.0f + timeIdx);
}
ANARIArray1D array = anariNewArray1D(dev, scaledVertex, 0, 0, ANARI_FLOAT32_VEC3, 4);
anariCommitParameters(dev, array);
anariSetParameter(dev, mesh, "vertex.position", ANARI_ARRAY, &array);
anariRelease(dev, array); // we are done using this handle
if (useVertexColors)
{
array = anariNewArray1D(dev, color, 0, 0, ANARI_FLOAT32_VEC4, 4);
anariCommitParameters(dev, array);
anariSetParameter(dev, mesh, "vertex.color", ANARI_ARRAY, &array);
anariRelease(dev, array);
}
array = anariNewArray1D(dev, texcoord, 0, 0, ANARI_FLOAT32_VEC2, 4);
anariCommitParameters(dev, array);
anariSetParameter(dev, mesh, "vertex.attribute0", ANARI_ARRAY, &array);
anariRelease(dev, array);
array = anariNewArray1D(dev, index, 0, 0, ANARI_INT32_VEC3, 2);
anariCommitParameters(dev, array);
anariSetParameter(dev, mesh, "primitive.index", ANARI_ARRAY, &array);
anariRelease(dev, array);
int timevaryTexcoord = 0; // Texcoords are not timeVarying (should now appear in fullscene stage)
anariSetParameter(dev, mesh, "usd::timeVarying.attribute0", ANARI_BOOL, &timevaryTexcoord);
anariSetParameter(dev, mesh, "usd::time", ANARI_FLOAT64, geomTimeValues + timeIdx);
anariCommitParameters(dev, mesh);
ANARISampler sampler = anariNewSampler(dev, "image2D");
anariSetParameter(dev, sampler, "name", ANARI_STRING, "tutorialSampler_0");
//anariSetParameter(dev, sampler, "usd::imageUrl", ANARI_STRING, texFile);
anariSetParameter(dev, sampler, "image", ANARI_ARRAY, &texArray);
anariSetParameter(dev, sampler, "inAttribute", ANARI_STRING, "attribute0");
anariSetParameter(dev, sampler, "wrapMode1", ANARI_STRING, wrapS);
anariSetParameter(dev, sampler, "wrapMode2", ANARI_STRING, wrapT);
anariCommitParameters(dev, sampler);
ANARIMaterial mat = anariNewMaterial(dev, "matte");
anariSetParameter(dev, mat, "name", ANARI_STRING, "tutorialMaterial_0");
float opacity = 1.0;// -timeIdx * 0.1f;
if (useVertexColors)
anariSetParameter(dev, mat, "color", ANARI_STRING, "color");
else if(useTexture)
anariSetParameter(dev, mat, "color", ANARI_SAMPLER, &sampler);
else
anariSetParameter(dev, mat, "color", ANARI_FLOAT32_VEC3, kd);
anariSetParameter(dev, mat, "opacity", ANARI_FLOAT32, &opacity);
anariSetParameter(dev, mat, "usd::time", ANARI_FLOAT64, matTimeValues + timeIdx);
anariCommitParameters(dev, mat);
anariRelease(dev, sampler);
// put the mesh into a model
ANARISurface surface;
surface = anariNewSurface(dev);
anariSetParameter(dev, surface, "name", ANARI_STRING, "tutorialSurface_0");
anariSetParameter(dev, surface, "geometry", ANARI_GEOMETRY, &mesh);
anariSetParameter(dev, surface, "material", ANARI_MATERIAL, &mat);
anariCommitParameters(dev, surface);
anariRelease(dev, mesh);
anariRelease(dev, mat);
// put the surface into a group
ANARIGroup group;
group = anariNewGroup(dev);
anariSetParameter(dev, group, "name", ANARI_STRING, "tutorialGroup_0");
array = anariNewArray1D(dev, &surface, 0, 0, ANARI_SURFACE, 1);
anariCommitParameters(dev, array);
anariSetParameter(dev, group, "surface", ANARI_ARRAY, &array);
anariCommitParameters(dev, group);
anariRelease(dev, surface);
anariRelease(dev, array);
// put the group into an instance (give the group a world transform)
ANARIInstance instance[2];
instance[0] = anariNewInstance(dev, "transform");
anariSetParameter(dev, instance[0], "name", ANARI_STRING, "tutorialInstance_0");
anariSetParameter(dev, instance[0], "transform", ANARI_FLOAT32_MAT4, transform);
anariSetParameter(dev, instance[0], "group", ANARI_GROUP, &group);
anariRelease(dev, group);
// create and setup light for Ambient Occlusion
ANARILight light = anariNewLight(dev, "ambient");
anariSetParameter(dev, light, "name", ANARI_STRING, "tutorialLight");
anariCommitParameters(dev, light);
array = anariNewArray1D(dev, &light, 0, 0, ANARI_LIGHT, 1);
anariCommitParameters(dev, array);
anariSetParameter(dev, world, "light", ANARI_ARRAY, &array);
anariRelease(dev, light);
anariRelease(dev, array);
anariCommitParameters(dev, instance[0]);
if (doubleNodes)
{
//ANARIGeometry protoMesh = anariNewGeometry(dev, "triangle");
//anariSetParameter(dev, protoMesh, "name", ANARI_STRING, "tutorialProtoMesh");
//
//ANARIArray1D array = anariNewArray1D(dev, protoVertex, 0, 0, ANARI_FLOAT32_VEC3, 8);
//anariCommitParameters(dev, array);
//anariSetParameter(dev, protoMesh, "vertex.position", ANARI_ARRAY, &array);
//anariRelease(dev, array); // we are done using this handle
//
//if (useVertexColors)
//{
// array = anariNewArray1D(dev, protoColor, 0, 0, ANARI_FLOAT32_VEC4, 8);
// anariCommitParameters(dev, array);
// anariSetParameter(dev, protoMesh, "vertex.color", ANARI_ARRAY, &array);
// anariRelease(dev, array);
//}
//
//array = anariNewArray1D(dev, protoTexcoord, 0, 0, ANARI_FLOAT32_VEC2, 8);
//anariCommitParameters(dev, array);
//anariSetParameter(dev, protoMesh, "vertex.attribute0", ANARI_ARRAY, &array);
//anariRelease(dev, array);
//
//array = anariNewArray1D(dev, protoIndex, 0, 0, ANARI_INT32_VEC3, 8);
//anariCommitParameters(dev, array);
//anariSetParameter(dev, protoMesh, "primitive.index", ANARI_ARRAY, &array);
//anariRelease(dev, array);
//
//anariCommitParameters(dev, protoMesh);
mesh = anariNewGeometry(dev, "sphere");
anariSetParameter(dev, mesh, "name", ANARI_STRING, "tutorialPoints");
anariSetParameter(dev, mesh, "usd::useUsdGeomPoints", ANARI_BOOL, &useUsdGeomPoints);
//anariSetParameter(dev, mesh, "shapeType", ANARI_STRING, "cylinder");
//anariSetParameter(dev, mesh, "shapeGeometry", ANARI_GEOMETRY, &protoMesh);
//anariSetParameter(dev, mesh, "shapeTransform", ANARI_FLOAT32_MAT4, protoTransform);
//anariRelease(dev, protoMesh);
array = anariNewArray1D(dev, vertex, 0, 0, ANARI_FLOAT32_VEC3, 4);
anariCommitParameters(dev, array);
anariSetParameter(dev, mesh, "vertex.position", ANARI_ARRAY, &array);
anariRelease(dev, array); // we are done using this handle
if (useVertexColors)
{
array = anariNewArray1D(dev, color, 0, 0, ANARI_FLOAT32_VEC4, 4);
anariCommitParameters(dev, array);
anariSetParameter(dev, mesh, "vertex.color", ANARI_ARRAY, &array);
anariRelease(dev, array);
}
array = anariNewArray1D(dev, texcoord, 0, 0, ANARI_FLOAT32_VEC2, 4);
anariCommitParameters(dev, array);
anariSetParameter(dev, mesh, "vertex.attribute0", ANARI_ARRAY, &array);
anariRelease(dev, array);
array = anariNewArray1D(dev, sphereSizes, 0, 0, ANARI_FLOAT32, 4);
anariCommitParameters(dev, array);
anariSetParameter(dev, mesh, "vertex.radius", ANARI_ARRAY, &array);
//anariSetParameter(dev, mesh, "vertex.scale", ANARI_ARRAY, &array);
anariRelease(dev, array);
anariSetParameter(dev, mesh, "usd::time", ANARI_FLOAT64, timeValues + timeIdx);
anariCommitParameters(dev, mesh);
sampler = anariNewSampler(dev, "image2D");
anariSetParameter(dev, sampler, "name", ANARI_STRING, "tutorialSampler_1");
//anariSetParameter(dev, sampler, "usd::imageUrl", ANARI_STRING, texFile);
anariSetParameter(dev, sampler, "image", ANARI_ARRAY, &texArray);
anariSetParameter(dev, sampler, "inAttribute", ANARI_STRING, "attribute0");
anariSetParameter(dev, sampler, "wrapMode1", ANARI_STRING, wrapS);
anariSetParameter(dev, sampler, "wrapMode2", ANARI_STRING, wrapT);
anariCommitParameters(dev, sampler);
mat = anariNewMaterial(dev, "matte");
anariSetParameter(dev, mat, "name", ANARI_STRING, "tutorialMaterial_1");
if (useVertexColors)
anariSetParameter(dev, mat, "color", ANARI_STRING, "color");
else if(useTexture)
anariSetParameter(dev, mat, "color", ANARI_SAMPLER, &sampler);
else
anariSetParameter(dev, mat, "color", ANARI_FLOAT32_VEC3, kd);
anariSetParameter(dev, mat, "usd::time", ANARI_FLOAT64, timeValues + timeIdx);
// Only colors and opacities are timevarying
int timeVaryingMetallic = 1;
int timeVaryingOpacities = 1;
anariSetParameter(dev, mat, "usd::timeVarying.metallic", ANARI_BOOL, &timeVaryingMetallic);
anariSetParameter(dev, mat, "usd::timeVarying.opacity", ANARI_BOOL, &timeVaryingOpacities);
anariCommitParameters(dev, mat);
anariRelease(dev, sampler);
// put the mesh into a model
surface = anariNewSurface(dev);
anariSetParameter(dev, surface, "name", ANARI_STRING, "tutorialSurface_1");
anariSetParameter(dev, surface, "geometry", ANARI_GEOMETRY, &mesh);
anariSetParameter(dev, surface, "material", ANARI_MATERIAL, &mat);
anariCommitParameters(dev, surface);
anariRelease(dev, mesh);
anariRelease(dev, mat);
// put the surface into a group
group = anariNewGroup(dev);
anariSetParameter(dev, group, "name", ANARI_STRING, "tutorialGroup_1");
array = anariNewArray1D(dev, &surface, 0, 0, ANARI_SURFACE, 1);
anariCommitParameters(dev, array);
anariSetParameter(dev, group, "surface", ANARI_ARRAY, &array);
anariCommitParameters(dev, group);
anariRelease(dev, surface);
anariRelease(dev, array);
// put the group into an instance (give the group a world transform)
instance[1] = anariNewInstance(dev, "transform");
anariSetParameter(dev, instance[1], "name", ANARI_STRING, "tutorialInstance_1");
anariSetParameter(dev, instance[1], "transform", ANARI_FLOAT32_MAT4, transform);
anariSetParameter(dev, instance[1], "group", ANARI_GROUP, &group);
anariRelease(dev, group);
anariCommitParameters(dev, instance[1]);
}
// put the instance in the world
anariSetParameter(dev, world, "name", ANARI_STRING, "tutorialWorld");
array = anariNewArray1D(dev, instance, 0, 0, ANARI_INSTANCE, (doubleNodes ? 2 : 1));
anariCommitParameters(dev, array);
anariSetParameter(dev, world, "instance", ANARI_ARRAY, &array);
anariRelease(dev, instance[0]);
if (doubleNodes)
anariRelease(dev, instance[1]);
anariRelease(dev, array);
anariCommitParameters(dev, world);
// create renderer
ANARIRenderer renderer =
anariNewRenderer(dev, "pathtracer"); // choose path tracing renderer
// complete setup of renderer
float bgColor[4] = { 1.f, 1.f, 1.f, 1.f }; // white
anariSetParameter(dev, renderer, "backgroundColor", ANARI_FLOAT32_VEC4, bgColor);
anariCommitParameters(dev, renderer);
// create and setup frame
ANARIFrame frame = anariNewFrame(dev);
ANARIDataType colFormat = ANARI_UFIXED8_RGBA_SRGB;
ANARIDataType depthFormat = ANARI_FLOAT32;
anariSetParameter(dev, frame, "size", ANARI_UINT32_VEC2, frameSize);
anariSetParameter(dev, frame, "channel.color", ANARI_DATA_TYPE, &colFormat);
anariSetParameter(dev, frame, "channel.depth", ANARI_DATA_TYPE, &depthFormat);
anariSetParameter(dev, frame, "renderer", ANARI_RENDERER, &renderer);
anariSetParameter(dev, frame, "camera", ANARI_CAMERA, &camera);
anariSetParameter(dev, frame, "world", ANARI_WORLD, &world);
anariCommitParameters(dev, frame);
printf("rendering frame...");
// render one frame
anariRenderFrame(dev, frame);
anariFrameReady(dev, frame, ANARI_WAIT);
// final cleanups
anariRelease(dev, renderer);
anariRelease(dev, frame);
anariRelease(dev, world);
// USD-SPECIFIC RUNTIME:
// Remove unused prims in usd
// Only useful when objects are possibly removed over the whole timeline
anariSetParameter(dev, dev, "usd::garbageCollect", ANARI_VOID_POINTER, 0);
// Reset generation of unique names for next frame
// Only necessary when relying upon auto-generation of names instead of manual creation, AND not retaining ANARI objects over timesteps
anariSetParameter(dev, dev, "usd::removeUnusedNames", ANARI_VOID_POINTER, 0);
// ~
// Constant color get a bit more red every step
kd[0] = timeIdx / (float)numTimeSteps;
}
// CHANGE THE SCENE: Attach only the instance_1 to the world, so instance_0 gets removed.
for (int timeIdx = 0; timeIdx < numTimeSteps/2; ++timeIdx)
{
anariSetParameter(dev, dev, "usd::time", ANARI_FLOAT64, timeValues + timeIdx);
anariCommitParameters(dev, dev);
ANARIWorld world = anariNewWorld(dev);
ANARIArray1D array;
ANARIInstance instance;
ANARIGeometry mesh;
ANARISampler sampler;
ANARIMaterial mat;
ANARISurface surface;
ANARIGroup group;
{
mesh = anariNewGeometry(dev, "sphere");
anariSetParameter(dev, mesh, "name", ANARI_STRING, "tutorialPoints");
anariSetParameter(dev, mesh, "usd::useUsdGeomPoints", ANARI_BOOL, &useUsdGeomPoints);
ANARIArray1D array = anariNewArray1D(dev, vertex, 0, 0, ANARI_FLOAT32_VEC3, 4);
anariCommitParameters(dev, array);
anariSetParameter(dev, mesh, "vertex.position", ANARI_ARRAY, &array);
anariRelease(dev, array); // we are done using this handle
if (useVertexColors)
{
array = anariNewArray1D(dev, color, 0, 0, ANARI_FLOAT32_VEC4, 4);
anariCommitParameters(dev, array);
anariSetParameter(dev, mesh, "vertex.color", ANARI_ARRAY, &array);
anariRelease(dev, array);
}
array = anariNewArray1D(dev, texcoord, 0, 0, ANARI_FLOAT32_VEC2, 4);
anariCommitParameters(dev, array);
anariSetParameter(dev, mesh, "vertex.attribute0", ANARI_ARRAY, &array);
anariRelease(dev, array);
array = anariNewArray1D(dev, sphereSizes, 0, 0, ANARI_FLOAT32, 4);
anariCommitParameters(dev, array);
anariSetParameter(dev, mesh, "vertex.radius", ANARI_ARRAY, &array);
//anariSetParameter(dev, mesh, "vertex.scale", ANARI_ARRAY, &array);
anariRelease(dev, array);
anariSetParameter(dev, mesh, "usd::time", ANARI_FLOAT64, timeValues + timeIdx*2); // Switch the child timestep for something else
anariCommitParameters(dev, mesh);
sampler = anariNewSampler(dev, "image2D");
anariSetParameter(dev, sampler, "name", ANARI_STRING, "tutorialSampler_1");
//anariSetParameter(dev, sampler, "usd::imageUrl", ANARI_STRING, texFile);
anariSetParameter(dev, sampler, "image", ANARI_ARRAY, &texArray);
anariSetParameter(dev, sampler, "inAttribute", ANARI_STRING, "attribute0");
anariSetParameter(dev, sampler, "wrapMode1", ANARI_STRING, wrapS);
anariSetParameter(dev, sampler, "wrapMode2", ANARI_STRING, wrapT);
anariCommitParameters(dev, sampler);
mat = anariNewMaterial(dev, "matte");
anariSetParameter(dev, mat, "name", ANARI_STRING, "tutorialMaterial_1");
if (useVertexColors)
anariSetParameter(dev, mat, "color", ANARI_STRING, "color");
else
anariSetParameter(dev, mat, "color", ANARI_FLOAT32_VEC3, kd);
anariSetParameter(dev, mat, "usd::time", ANARI_FLOAT64, timeValues + timeIdx*2);
anariCommitParameters(dev, mat);
anariRelease(dev, sampler);
// put the mesh into a model
surface = anariNewSurface(dev);
anariSetParameter(dev, surface, "name", ANARI_STRING, "tutorialSurface_1");
anariSetParameter(dev, surface, "geometry", ANARI_GEOMETRY, &mesh);
anariSetParameter(dev, surface, "material", ANARI_MATERIAL, &mat);
anariCommitParameters(dev, surface);
anariRelease(dev, mesh);
anariRelease(dev, mat);
// put the surface into a group
group = anariNewGroup(dev);
anariSetParameter(dev, group, "name", ANARI_STRING, "tutorialGroup_1");
array = anariNewArray1D(dev, &surface, 0, 0, ANARI_SURFACE, 1);
anariCommitParameters(dev, array);
anariSetParameter(dev, group, "surface", ANARI_ARRAY, &array);
anariCommitParameters(dev, group);
anariRelease(dev, surface);
anariRelease(dev, array);
// put the group into an instance (give the group a world transform)
instance = anariNewInstance(dev, "transform");
anariSetParameter(dev, instance, "name", ANARI_STRING, "tutorialInstance_1");
anariSetParameter(dev, instance, "transform", ANARI_FLOAT32_MAT4, transform);
anariSetParameter(dev, instance, "group", ANARI_GROUP, &group);
anariRelease(dev, group);
anariCommitParameters(dev, instance);
}
// put the instance in the world
anariSetParameter(dev, world, "name", ANARI_STRING, "tutorialWorld");
array = anariNewArray1D(dev, &instance, 0, 0, ANARI_INSTANCE, 1);
anariCommitParameters(dev, array);
anariSetParameter(dev, world, "instance", ANARI_ARRAY, &array);
anariRelease(dev, instance);
anariRelease(dev, array);
anariCommitParameters(dev, world);
// create renderer
ANARIRenderer renderer =
anariNewRenderer(dev, "pathtracer"); // choose path tracing renderer
// complete setup of renderer
float bgColor[4] = { 1.f, 1.f, 1.f, 1.f }; // white
anariSetParameter(dev, renderer, "backgroundColor", ANARI_FLOAT32_VEC4, bgColor);
anariCommitParameters(dev, renderer);
// create and setup frame
ANARIFrame frame = anariNewFrame(dev);
ANARIDataType colFormat = ANARI_UFIXED8_RGBA_SRGB;
ANARIDataType depthFormat = ANARI_FLOAT32;
anariSetParameter(dev, frame, "size", ANARI_UINT32_VEC2, frameSize);
anariSetParameter(dev, frame, "channel.color", ANARI_DATA_TYPE, &colFormat);
anariSetParameter(dev, frame, "channel.depth", ANARI_DATA_TYPE, &depthFormat);
anariSetParameter(dev, frame, "renderer", ANARI_RENDERER, &renderer);
anariSetParameter(dev, frame, "camera", ANARI_CAMERA, &camera);
anariSetParameter(dev, frame, "world", ANARI_WORLD, &world);
anariCommitParameters(dev, frame);
printf("rendering frame...");
// render one frame
anariRenderFrame(dev, frame);
anariFrameReady(dev, frame, ANARI_WAIT);
// final cleanups
anariRelease(dev, renderer);
anariRelease(dev, frame);
anariRelease(dev, world);
// USD-SPECIFIC RUNTIME:
// Remove unused prims in usd
// Only useful when objects are possibly removed over the whole timeline
anariSetParameter(dev, dev, "usd::garbageCollect", ANARI_VOID_POINTER, 0);
// Reset generation of unique names for next frame
// Only necessary when relying upon auto-generation of names instead of manual creation, AND not retaining ANARI objects over timesteps
anariSetParameter(dev, dev, "usd::removeUnusedNames", ANARI_VOID_POINTER, 0);
// ~
}
anariRelease(dev, camera);
anariRelease(dev, texArray);
anariRelease(dev, dev);
freeTexture(textureData);
printf("done!\n");
return 0;
}
| 24,190 | C | 34.315328 | 159 | 0.653989 |
NVIDIA-Omniverse/AnariUsdDevice/superbuild/README.md | # CMake superbuild for USD ANARI Device
This CMake script runs stand alone to optionally build together any of:
- ANARIUsd Device (parent directory)
- ANARI-SDK
- USD + dependencies
The result of building this project is all the contents of the above (if built)
installed to `CMAKE_INSTALL_PREFIX`.
## Build setup
Run CMake (3.16+) on this directory from an empty build directory. This might
look like:
```bash
% mkdir _build
% cd _build
% cmake /path/to/superbuild
```
You can use tools like `ccmake` or `cmake-gui` to see what options you have. The
following variables control which items are to be built, and with which capabilities:
- `BUILD_ANARI_SDK` : build the [ANARI-SDK](https://github.com/KhronosGroup/ANARI-SDK)
- `BUILD_ANARI_USD_DEVICE`: build the root
- `BUILD_USD`: build USD + its dependencies (experimental, `OFF` by default)
- Requires preinstalled boost + tbb in `CMAKE_PREFIX_PATH`
- `USD_DEVICE_USE_OPENVDB`: Add OpenVDB output capability for ANARI volumes to the USD device
- Introduces `USE_USD_OPENVDB_BUILD`: If `ON` (default), OpenVDB is included within the USD installation
- `USD_DEVICE_USE_OMNIVERSE`: Add Omniverse output capability for generated USD output
If `BUILD_USD` or `BUILD_ANARI_SDK` are set to `OFF`, then those dependencies
will need to be found in the host environment. Use `CMAKE_PREFIX_PATH` to
point to your USD + ANARI-SDK (+ OpenVDB + Omniverse) installations respectively. Alternatively,
one can use explicit install dir variables which support `debug/` and `release/` subdirs:
- `ANARI_ROOT_DIR`: for the ANARI-SDK install directory
- `USD_ROOT_DIR`: for the USD install directory
- `OpenVDB_ROOT`: for the OpenVDB install directory (if not `USE_USD_OPENVDB_BUILD`)
- `OMNICLIENT_ROOT_DIR`: for the OmniClient install directory (typically `omni_client_library` from the connect sample deps). Requires:
- `OMNIUSDRESOLVER_ROOT_DIR`: the Omniverse Resolver install directory (typically `omni_usd_resolver` from the connect sample deps).
- `ZLIB_ROOT`: for the ZLIB install directory, required for Linux builds
For ease of use, if you want the USD and Omniverse libraries to be copied into the installation's `bin`
directory, make sure `USD_DEVICE_INSTALL_DEPS` is turned on. Otherwise, all dependency folders have to
be manually included into the path before executing the device binaries.
Lastly, the `BUILD_ANARI_USD_DEVICE` option lets you turn off building the device if you
only want to build the device's dependencies (mostly this is for developers).
## Build
Once you have set up the variables according to your situation, you can invoke the build (Linux) with:
```bash
% cmake --build .
```
or open `_build/anari_usd_superbuild.sln` (Windows) and build/install any configuration from there.
The resulting `install/` directory will contain everything that was built. You
can change the location of this install by setting `CMAKE_INSTALL_PREFIX`.
| 2,931 | Markdown | 44.107692 | 136 | 0.761515 |
NVIDIA-Omniverse/AnariUsdDevice/UsdBridge/UsdBridgeCaches.h | // Copyright 2020 The Khronos Group
// SPDX-License-Identifier: Apache-2.0
#ifndef OmniBridgeCaches_h
#define OmniBridgeCaches_h
#include <string>
#include <map>
#include <vector>
#include <memory>
#include "UsdBridgeData.h"
#include "UsdBridgeUtils_Internal.h"
struct UsdBridgePrimCache;
class UsdBridgeUsdWriter;
class UsdBridgePrimCacheManager;
typedef std::pair<std::string, UsdStageRefPtr> UsdStagePair; //Stage ptr and filename
typedef std::pair<std::pair<bool,bool>, UsdBridgePrimCache*> BoolEntryPair; // Prim exists in stage, prim exists in cache, result cache entry ptr
typedef void (*ResourceCollectFunc)(UsdBridgePrimCache*, UsdBridgeUsdWriter&);
typedef std::function<void(UsdBridgePrimCache*)> AtRemoveFunc;
typedef std::vector<UsdBridgePrimCache*> UsdBridgePrimCacheList;
typedef std::vector<SdfPath> SdfPrimPathList;
struct UsdBridgeResourceKey
{
UsdBridgeResourceKey() = default;
~UsdBridgeResourceKey() = default;
UsdBridgeResourceKey(const UsdBridgeResourceKey& key) = default;
UsdBridgeResourceKey(const char* n, double t)
{
name = n;
#ifdef TIME_BASED_CACHING
timeStep = t;
#endif
}
const char* name;
#ifdef TIME_BASED_CACHING
double timeStep;
#endif
bool operator==(const UsdBridgeResourceKey& rhs) const
{
return ( name ? (rhs.name ? (strEquals(name, rhs.name)
#ifdef TIME_BASED_CACHING
&& timeStep == rhs.timeStep
#endif
) : false ) : !rhs.name);
}
};
struct UsdBridgeRefCache
{
public:
friend class UsdBridgePrimCacheManager;
protected:
void IncRef() { ++RefCount; }
void DecRef() { --RefCount; }
unsigned int RefCount = 0;
};
struct UsdBridgePrimCache : public UsdBridgeRefCache
{
public:
friend class UsdBridgePrimCacheManager;
using ResourceContainer = std::vector<UsdBridgeResourceKey>;
//Constructors
UsdBridgePrimCache(const SdfPath& pp, const SdfPath& nm, ResourceCollectFunc cf);
UsdBridgePrimCache* GetChildCache(const TfToken& nameToken);
bool AddResourceKey(UsdBridgeResourceKey key);
SdfPath PrimPath;
SdfPath Name;
ResourceCollectFunc ResourceCollect;
std::unique_ptr<ResourceContainer> ResourceKeys; // Referenced resources
#ifdef TIME_BASED_CACHING
void SetChildVisibleAtTime(const UsdBridgePrimCache* childCache, double timeCode);
bool SetChildInvisibleAtTime(const UsdBridgePrimCache* childCache, double timeCode); // Returns whether timeCode has been removed AND the visible timeset is empty.
#endif
#ifdef VALUE_CLIP_RETIMING
static constexpr double PrimStageTimeCode = 0.0; // Prim stages are stored in ClipStages under specified time code
const UsdStagePair& GetPrimStagePair() const;
template<typename DataMemberType>
bool TimeVarBitsUpdate(DataMemberType newTimeVarBits);
UsdStagePair ManifestStage; // Holds the manifest
std::unordered_map<double, UsdStagePair> ClipStages; // Holds the stage(s) to the timevarying data
uint32_t LastTimeVaryingBits = 0; // Used to detect changes in timevarying status of parameters
#endif
#ifndef NDEBUG
std::string Debug_Name;
#endif
protected:
void AddChild(UsdBridgePrimCache* child);
void RemoveChild(UsdBridgePrimCache* child);
void RemoveUnreferencedChildTree(AtRemoveFunc atRemove);
std::vector<UsdBridgePrimCache*> Children;
#ifdef TIME_BASED_CACHING
// For each child, hold a vector of timesteps where it's visible (mimicks visibility attribute on the referencing prim)
std::vector<std::vector<double>> ChildVisibleAtTimes;
#endif
};
class UsdBridgePrimCacheManager
{
public:
typedef std::unordered_map<std::string, std::unique_ptr<UsdBridgePrimCache>> PrimCacheContainer;
typedef PrimCacheContainer::iterator PrimCacheIterator;
typedef PrimCacheContainer::const_iterator ConstPrimCacheIterator;
inline UsdBridgePrimCache* ConvertToPrimCache(const UsdBridgeHandle& handle) const
{
#ifndef NDEBUG
auto primCacheIt = FindPrimCache(handle);
assert(ValidIterator(primCacheIt));
#endif
return handle.value;
}
ConstPrimCacheIterator FindPrimCache(const std::string& name) const { return UsdPrimCaches.find(name); }
ConstPrimCacheIterator FindPrimCache(const UsdBridgeHandle& handle) const;
inline bool ValidIterator(ConstPrimCacheIterator it) const { return it != UsdPrimCaches.end(); }
ConstPrimCacheIterator CreatePrimCache(const std::string& name, const std::string& fullPath, ResourceCollectFunc collectFunc = nullptr);
void RemovePrimCache(ConstPrimCacheIterator it, UsdBridgeLogObject& LogObject);
void RemoveUnreferencedPrimCaches(AtRemoveFunc atRemove);
void AddChild(UsdBridgePrimCache* parent, UsdBridgePrimCache* child);
void RemoveChild(UsdBridgePrimCache* parent, UsdBridgePrimCache* child);
void AttachTopLevelPrim(UsdBridgePrimCache* primCache);
void DetachTopLevelPrim(UsdBridgePrimCache* primCache);
protected:
PrimCacheContainer UsdPrimCaches;
};
#ifdef VALUE_CLIP_RETIMING
template<typename DataMemberType>
bool UsdBridgePrimCache::TimeVarBitsUpdate(DataMemberType newTimeVarBits)
{
uint32_t newBits = static_cast<uint32_t>(newTimeVarBits);
bool hasChanged = (LastTimeVaryingBits != newBits);
LastTimeVaryingBits = newBits;
return hasChanged;
}
#endif
#endif | 5,182 | C | 30.035928 | 165 | 0.780973 |
NVIDIA-Omniverse/AnariUsdDevice/UsdBridge/UsdBridgeUsdWriter_Material.cpp | // Copyright 2020 The Khronos Group
// SPDX-License-Identifier: Apache-2.0
#include "UsdBridgeUsdWriter.h"
#include "UsdBridgeUsdWriter_Common.h"
#include "stb_image_write.h"
#include <limits>
_TF_TOKENS_STRUCT_NAME(QualifiedInputTokens)::_TF_TOKENS_STRUCT_NAME(QualifiedInputTokens)()
: roughness(TfToken("inputs:roughness", TfToken::Immortal))
, opacity(TfToken("inputs:opacity", TfToken::Immortal))
, metallic(TfToken("inputs:metallic", TfToken::Immortal))
, ior(TfToken("inputs:ior", TfToken::Immortal))
, diffuseColor(TfToken("inputs:diffuseColor", TfToken::Immortal))
, specularColor(TfToken("inputs:specularColor", TfToken::Immortal))
, emissiveColor(TfToken("inputs:emissiveColor", TfToken::Immortal))
, file(TfToken("inputs:file", TfToken::Immortal))
, WrapS(TfToken("inputs:WrapS", TfToken::Immortal))
, WrapT(TfToken("inputs:WrapT", TfToken::Immortal))
, WrapR(TfToken("inputs:WrapR", TfToken::Immortal))
, varname(TfToken("inputs:varname", TfToken::Immortal))
, reflection_roughness_constant(TfToken("inputs:reflection_roughness_constant", TfToken::Immortal))
, opacity_constant(TfToken("inputs:opacity_constant", TfToken::Immortal))
, metallic_constant(TfToken("inputs:metallic_constant", TfToken::Immortal))
, ior_constant(TfToken("inputs:ior_constant"))
, diffuse_color_constant(TfToken("inputs:diffuse_color_constant", TfToken::Immortal))
, emissive_color(TfToken("inputs:emissive_color", TfToken::Immortal))
, emissive_intensity(TfToken("inputs:emissive_intensity", TfToken::Immortal))
, enable_emission(TfToken("inputs:enable_emission", TfToken::Immortal))
, name(TfToken("inputs:name", TfToken::Immortal))
, tex(TfToken("inputs:tex", TfToken::Immortal))
, wrap_u(TfToken("inputs:wrap_u", TfToken::Immortal))
, wrap_v(TfToken("inputs:wrap_v", TfToken::Immortal))
, wrap_w(TfToken("inputs:wrap_w", TfToken::Immortal))
{}
_TF_TOKENS_STRUCT_NAME(QualifiedInputTokens)::~_TF_TOKENS_STRUCT_NAME(QualifiedInputTokens)() = default;
TfStaticData<_TF_TOKENS_STRUCT_NAME(QualifiedInputTokens)> QualifiedInputTokens;
_TF_TOKENS_STRUCT_NAME(QualifiedOutputTokens)::_TF_TOKENS_STRUCT_NAME(QualifiedOutputTokens)()
: r(TfToken("outputs:r", TfToken::Immortal))
, rg(TfToken("outputs:rg", TfToken::Immortal))
, rgb(TfToken("outputs:rgb", TfToken::Immortal))
, a(TfToken("outputs:a", TfToken::Immortal))
, out(TfToken("outputs:out", TfToken::Immortal))
{}
_TF_TOKENS_STRUCT_NAME(QualifiedOutputTokens)::~_TF_TOKENS_STRUCT_NAME(QualifiedOutputTokens)() = default;
TfStaticData<_TF_TOKENS_STRUCT_NAME(QualifiedOutputTokens)> QualifiedOutputTokens;
namespace
{
struct StbWriteOutput
{
StbWriteOutput() = default;
~StbWriteOutput()
{
delete[] imageData;
}
char* imageData = nullptr;
size_t imageSize = 0;
};
void StbWriteToBuffer(void *context, void *data, int size)
{
if(data)
{
StbWriteOutput* output = reinterpret_cast<StbWriteOutput*>(context);
output->imageData = new char[size];
output->imageSize = size;
memcpy(output->imageData, data, size);
}
}
template<typename CType>
void ConvertSamplerData_Inner(const UsdBridgeSamplerData& samplerData, double normFactor, std::vector<unsigned char>& imageData)
{
int numComponents = samplerData.ImageNumComponents;
uint64_t imageDimX = samplerData.ImageDims[0];
uint64_t imageDimY = samplerData.ImageDims[1];
int64_t yStride = samplerData.ImageStride[1];
const char* samplerDataPtr = reinterpret_cast<const char*>(samplerData.Data);
int64_t baseAddr = 0;
for(uint64_t pY = 0; pY < imageDimY; ++pY, baseAddr += yStride)
{
const CType* lineAddr = reinterpret_cast<const CType*>(samplerDataPtr + baseAddr);
for(uint64_t flatX = 0; flatX < imageDimX*numComponents; ++flatX) //flattened X index
{
uint64_t dstElt = numComponents*pY*imageDimX + flatX;
double result = *(lineAddr+flatX)*normFactor;
result = (result < 0.0) ? 0.0 : ((result > 255.0) ? 255.0 : result);
imageData[dstElt] = static_cast<unsigned char>(result);
}
}
}
void ConvertSamplerDataToImage(const UsdBridgeSamplerData& samplerData, std::vector<unsigned char>& imageData)
{
UsdBridgeType flattenedType = ubutils::UsdBridgeTypeFlatten(samplerData.DataType);
int numComponents = samplerData.ImageNumComponents;
uint64_t imageDimX = samplerData.ImageDims[0];
uint64_t imageDimY = samplerData.ImageDims[1];
bool normalizedFp = (flattenedType == UsdBridgeType::FLOAT) || (flattenedType == UsdBridgeType::DOUBLE);
bool fixedPoint = (flattenedType == UsdBridgeType::USHORT) || (flattenedType == UsdBridgeType::UINT);
if(normalizedFp || fixedPoint)
{
imageData.resize(numComponents*imageDimX*imageDimY);
switch(flattenedType)
{
case UsdBridgeType::FLOAT: ConvertSamplerData_Inner<float>(samplerData, 255.0, imageData); break;
case UsdBridgeType::DOUBLE: ConvertSamplerData_Inner<double>(samplerData, 255.0, imageData); break;
case UsdBridgeType::USHORT: ConvertSamplerData_Inner<unsigned short>(samplerData,
255.0 / static_cast<double>(std::numeric_limits<unsigned short>::max()), imageData); break;
case UsdBridgeType::UINT: ConvertSamplerData_Inner<unsigned int>(samplerData,
255.0 / static_cast<double>(std::numeric_limits<unsigned int>::max()), imageData); break;
default: break;
}
}
}
template<typename DataType>
void CreateShaderInput(UsdShadeShader& shader, const TimeEvaluator<DataType>* timeEval, typename DataType::DataMemberId dataMemberId,
const TfToken& inputToken, const TfToken& qualifiedInputToken, const SdfValueTypeName& valueType)
{
if(!timeEval || timeEval->IsTimeVarying(dataMemberId))
shader.CreateInput(inputToken, valueType);
else
shader.GetPrim().RemoveProperty(qualifiedInputToken);
}
template<bool PreviewSurface>
void CreateMaterialShaderInput(UsdShadeShader& shader, const TimeEvaluator<UsdBridgeMaterialData>* timeEval,
typename UsdBridgeMaterialData::DataMemberId dataMemberId, const SdfValueTypeName& valueType)
{
const TfToken& inputToken = GetMaterialShaderInputToken<PreviewSurface>(dataMemberId);
const TfToken& qualifiedInputToken = GetMaterialShaderInputQualifiedToken<PreviewSurface>(dataMemberId);
CreateShaderInput(shader, timeEval, dataMemberId, inputToken, qualifiedInputToken, valueType);
}
template<typename ValueType, typename DataType>
void SetShaderInput(UsdShadeShader& uniformShadPrim, UsdShadeShader& timeVarShadPrim, const TimeEvaluator<DataType>& timeEval,
const TfToken& inputToken, typename DataType::DataMemberId dataMemberId, ValueType value)
{
using DMI = typename DataType::DataMemberId;
bool timeVaryingUpdate = timeEval.IsTimeVarying(dataMemberId);
UsdShadeInput timeVarInput, uniformInput;
UsdAttribute uniformAttrib, timeVarAttrib;
if(timeVarShadPrim) // Allow for non-existing prims (based on timeVaryingUpdate)
{
timeVarInput = timeVarShadPrim.GetInput(inputToken);
assert(timeVarInput);
timeVarAttrib = timeVarInput.GetAttr();
}
if(uniformShadPrim)
{
uniformInput = uniformShadPrim.GetInput(inputToken);
assert(uniformInput);
uniformAttrib = uniformInput.GetAttr();
}
// Clear the attributes that are not set (based on timeVaryingUpdate)
ClearUsdAttributes(uniformAttrib, timeVarAttrib, timeVaryingUpdate);
// Set the input that requires an update
SET_TIMEVARYING_ATTRIB(timeVaryingUpdate, timeVarInput, uniformInput, value);
}
UsdShadeOutput InitializeMdlGraphNode(UsdShadeShader& graphNode, const TfToken& assetSubIdent, const SdfValueTypeName& returnType,
const char* sourceAssetPath = constring::mdlSupportAssetName)
{
graphNode.CreateImplementationSourceAttr(VtValue(UsdBridgeTokens->sourceAsset));
graphNode.SetSourceAsset(SdfAssetPath(sourceAssetPath), UsdBridgeTokens->mdl);
graphNode.SetSourceAssetSubIdentifier(assetSubIdent, UsdBridgeTokens->mdl);
return graphNode.CreateOutput(UsdBridgeTokens->out, returnType);
}
struct ShadeGraphTypeConversionNodeContext
{
ShadeGraphTypeConversionNodeContext(UsdStageRefPtr sceneStage,
const SdfPath& matPrimPath,
const char* connectionIdentifier)
: SceneStage(sceneStage)
, MatPrimPath(matPrimPath)
, ConnectionIdentifier(connectionIdentifier)
{
}
// sourceOutput is set to the new node's output upon return
UsdShadeShader CreateAndConnectMdlTypeConversionNode(UsdShadeOutput& sourceOutput, const char* primNamePf, const TfToken& assetSubIdent,
const SdfValueTypeName& inType, const SdfValueTypeName& outType, const char* sourceAssetPath = constring::mdlSupportAssetName) const
{
SdfPath nodePrimPath = this->MatPrimPath.AppendPath(SdfPath(std::string(this->ConnectionIdentifier)+primNamePf));
UsdShadeShader conversionNode = UsdShadeShader::Get(this->SceneStage, nodePrimPath);
UsdShadeOutput nodeOut;
if(!conversionNode)
{
conversionNode = UsdShadeShader::Define(this->SceneStage, nodePrimPath);
assert(conversionNode);
nodeOut = InitializeMdlGraphNode(conversionNode, assetSubIdent, outType, sourceAssetPath);
conversionNode.CreateInput(UsdBridgeTokens->a, inType);
}
else
nodeOut = conversionNode.GetOutput(UsdBridgeTokens->out);
conversionNode.GetInput(UsdBridgeTokens->a).ConnectToSource(sourceOutput);
sourceOutput = nodeOut;
return conversionNode;
}
void InsertMdlShaderTypeConversionNodes(const UsdShadeInput& shadeInput, UsdShadeOutput& nodeOutput) const
{
if(shadeInput.GetTypeName() == SdfValueTypeNames->Color3f)
{
// Introduce new nodes until the type matches color3f.
// Otherwise, just connect any random output type to the input.
if(nodeOutput.GetTypeName() == SdfValueTypeNames->Float4)
{
// Changes nodeOutput to the output of the new node
CreateAndConnectMdlTypeConversionNode(nodeOutput, constring::mdlGraphXYZPrimPf,
UsdBridgeTokens->xyz, SdfValueTypeNames->Float4, SdfValueTypeNames->Float3, constring::mdlAuxAssetName);
}
if(nodeOutput.GetTypeName() == SdfValueTypeNames->Float3)
{
CreateAndConnectMdlTypeConversionNode(nodeOutput, constring::mdlGraphColorPrimPf,
UsdBridgeTokens->construct_color, SdfValueTypeNames->Float3, SdfValueTypeNames->Color3f, constring::mdlAuxAssetName);
}
}
if(shadeInput.GetTypeName() == SdfValueTypeNames->Float)
{
const char* componentPrimPf = constring::mdlGraphWPrimPf;
TfToken componentAssetIdent = (nodeOutput.GetTypeName() == SdfValueTypeNames->Float4) ? UsdBridgeTokens->w : UsdBridgeTokens->x;
switch(ChannelSelector)
{
case 0: componentPrimPf = constring::mdlGraphXPrimPf; componentAssetIdent = UsdBridgeTokens->x; break;
case 1: componentPrimPf = constring::mdlGraphYPrimPf; componentAssetIdent = UsdBridgeTokens->y; break;
case 2: componentPrimPf = constring::mdlGraphZPrimPf; componentAssetIdent = UsdBridgeTokens->z; break;
default: break;
}
if(nodeOutput.GetTypeName() == SdfValueTypeNames->Float4)
{
CreateAndConnectMdlTypeConversionNode(nodeOutput, componentPrimPf,
componentAssetIdent, SdfValueTypeNames->Float4, SdfValueTypeNames->Float, constring::mdlAuxAssetName);
}
else if(nodeOutput.GetTypeName() == SdfValueTypeNames->Float3)
{
CreateAndConnectMdlTypeConversionNode(nodeOutput, componentPrimPf,
componentAssetIdent, SdfValueTypeNames->Float3, SdfValueTypeNames->Float, constring::mdlAuxAssetName);
}
}
}
UsdStageRefPtr SceneStage;
const SdfPath& MatPrimPath;
const char* ConnectionIdentifier = nullptr;
// Optional
int ChannelSelector = 0;
};
void InitializePsShaderUniform(UsdShadeShader& shader)
{
shader.CreateIdAttr(VtValue(UsdBridgeTokens->UsdPreviewSurface));
shader.CreateInput(UsdBridgeTokens->useSpecularWorkflow, SdfValueTypeNames->Int).Set(0);
}
void InitializePsShaderTimeVar(UsdShadeShader& shader, const TimeEvaluator<UsdBridgeMaterialData>* timeEval = nullptr)
{
typedef UsdBridgeMaterialData::DataMemberId DMI;
CreateMaterialShaderInput<true>(shader, timeEval, DMI::DIFFUSE, SdfValueTypeNames->Color3f);
CreateMaterialShaderInput<true>(shader, timeEval, DMI::EMISSIVECOLOR, SdfValueTypeNames->Color3f);
CreateMaterialShaderInput<true>(shader, timeEval, DMI::ROUGHNESS, SdfValueTypeNames->Float);
CreateMaterialShaderInput<true>(shader, timeEval, DMI::OPACITY, SdfValueTypeNames->Float);
CreateMaterialShaderInput<true>(shader, timeEval, DMI::METALLIC, SdfValueTypeNames->Float);
CreateMaterialShaderInput<true>(shader, timeEval, DMI::IOR, SdfValueTypeNames->Float);
CreateShaderInput(shader, timeEval, DMI::OPACITY, UsdBridgeTokens->opacityThreshold, QualifiedInputTokens->opacityThreshold, SdfValueTypeNames->Float);
}
void InitializeMdlShaderUniform(UsdShadeShader& shader)
{
typedef UsdBridgeMaterialData::DataMemberId DMI;
shader.CreateImplementationSourceAttr(VtValue(UsdBridgeTokens->sourceAsset));
shader.SetSourceAsset(SdfAssetPath(constring::mdlShaderAssetName), UsdBridgeTokens->mdl);
shader.SetSourceAssetSubIdentifier(UsdBridgeTokens->OmniPBR, UsdBridgeTokens->mdl);
shader.CreateInput(GetMaterialShaderInputToken<false>(DMI::OPACITY), SdfValueTypeNames->Float); // Opacity is handled by the opacitymul node
}
void InitializeMdlShaderTimeVar(UsdShadeShader& shader, const TimeEvaluator<UsdBridgeMaterialData>* timeEval = nullptr)
{
typedef UsdBridgeMaterialData::DataMemberId DMI;
CreateMaterialShaderInput<false>(shader, timeEval, DMI::DIFFUSE, SdfValueTypeNames->Color3f);
CreateMaterialShaderInput<false>(shader, timeEval, DMI::EMISSIVECOLOR, SdfValueTypeNames->Color3f);
CreateMaterialShaderInput<false>(shader, timeEval, DMI::EMISSIVEINTENSITY, SdfValueTypeNames->Float);
CreateMaterialShaderInput<false>(shader, timeEval, DMI::ROUGHNESS, SdfValueTypeNames->Float);
CreateMaterialShaderInput<false>(shader, timeEval, DMI::METALLIC, SdfValueTypeNames->Float);
//CreateMaterialShaderInput<false>(shader, timeEval, DMI::IOR, SdfValueTypeNames->Float); // not supported in OmniPBR.mdl
CreateShaderInput(shader, timeEval, DMI::OPACITY, UsdBridgeTokens->enable_opacity, QualifiedInputTokens->enable_opacity, SdfValueTypeNames->Bool);
CreateShaderInput(shader, timeEval, DMI::OPACITY, UsdBridgeTokens->opacity_threshold, QualifiedInputTokens->opacity_threshold, SdfValueTypeNames->Float);
CreateShaderInput(shader, timeEval, DMI::EMISSIVEINTENSITY, UsdBridgeTokens->enable_emission, QualifiedInputTokens->enable_emission, SdfValueTypeNames->Bool);
}
UsdShadeOutput InitializePsAttributeReaderUniform(UsdShadeShader& attributeReader, const TfToken& readerId, const SdfValueTypeName& returnType)
{
attributeReader.CreateIdAttr(VtValue(readerId));
// Input name and output type are tightly coupled; output type cannot be timevarying, so neither can the name
attributeReader.CreateInput(UsdBridgeTokens->varname, SdfValueTypeNames->Token);
return attributeReader.CreateOutput(UsdBridgeTokens->result, returnType);
}
template<typename DataType>
void InitializePsAttributeReaderTimeVar(UsdShadeShader& attributeReader, typename DataType::DataMemberId dataMemberId, const TimeEvaluator<DataType>* timeEval)
{
//CreateShaderInput(attributeReader, timeEval, dataMemberId, UsdBridgeTokens->varname, QualifiedInputTokens->varname, SdfValueTypeNames->Token);
}
UsdShadeOutput InitializeMdlAttributeReaderUniform(UsdShadeShader& attributeReader, const TfToken& readerId, const SdfValueTypeName& returnType)
{
attributeReader.CreateImplementationSourceAttr(VtValue(UsdBridgeTokens->sourceAsset));
attributeReader.SetSourceAsset(SdfAssetPath(constring::mdlSupportAssetName), UsdBridgeTokens->mdl);
attributeReader.SetSourceAssetSubIdentifier(readerId, UsdBridgeTokens->mdl);
// Input name and output type are tightly coupled; output type cannot be timevarying, so neither can the name
attributeReader.CreateInput(UsdBridgeTokens->name, SdfValueTypeNames->String);
return attributeReader.CreateOutput(UsdBridgeTokens->out, returnType);
}
template<typename DataType>
void InitializeMdlAttributeReaderTimeVar(UsdShadeShader& attributeReader, typename DataType::DataMemberId dataMemberId, const TimeEvaluator<DataType>* timeEval)
{
//CreateShaderInput(attributeReader, timeEval, dataMemberId, UsdBridgeTokens->name, QualifiedInputTokens->name, SdfValueTypeNames->String);
}
void InitializePsSamplerUniform(UsdShadeShader& sampler, const SdfValueTypeName& coordType, const UsdShadeOutput& tcrOutput)
{
sampler.CreateIdAttr(VtValue(UsdBridgeTokens->UsdUVTexture));
sampler.CreateOutput(UsdBridgeTokens->rgb, SdfValueTypeNames->Float3); // Input images with less components are automatically expanded, see usd docs
sampler.CreateOutput(UsdBridgeTokens->a, SdfValueTypeNames->Float);
sampler.CreateInput(UsdBridgeTokens->fallback, SdfValueTypeNames->Float4).Set(GfVec4f(1.0f, 0.0f, 0.0f, 1.0f));
// Bind the texcoord reader's output to the sampler's st input
sampler.CreateInput(UsdBridgeTokens->st, coordType).ConnectToSource(tcrOutput);
}
void InitializePsSamplerTimeVar(UsdShadeShader& sampler, UsdBridgeSamplerData::SamplerType type, const TimeEvaluator<UsdBridgeSamplerData>* timeEval = nullptr)
{
typedef UsdBridgeSamplerData::DataMemberId DMI;
CreateShaderInput(sampler, timeEval, DMI::DATA, UsdBridgeTokens->file, QualifiedInputTokens->file, SdfValueTypeNames->Asset);
CreateShaderInput(sampler, timeEval, DMI::WRAPS, UsdBridgeTokens->WrapS, QualifiedInputTokens->WrapS, SdfValueTypeNames->Token);
if((uint32_t)type >= (uint32_t)UsdBridgeSamplerData::SamplerType::SAMPLER_2D)
CreateShaderInput(sampler, timeEval, DMI::WRAPT, UsdBridgeTokens->WrapT, QualifiedInputTokens->WrapT, SdfValueTypeNames->Token);
if((uint32_t)type >= (uint32_t)UsdBridgeSamplerData::SamplerType::SAMPLER_3D)
CreateShaderInput(sampler, timeEval, DMI::WRAPR, UsdBridgeTokens->WrapR, QualifiedInputTokens->WrapR, SdfValueTypeNames->Token);
}
void InitializeMdlSamplerUniform(UsdShadeShader& sampler, const SdfValueTypeName& coordType, const UsdShadeOutput& tcrOutput)
{
sampler.CreateImplementationSourceAttr(VtValue(UsdBridgeTokens->sourceAsset));
sampler.SetSourceAsset(SdfAssetPath(constring::mdlSupportAssetName), UsdBridgeTokens->mdl);
sampler.SetSourceAssetSubIdentifier(UsdBridgeTokens->lookup_float4, UsdBridgeTokens->mdl);
sampler.CreateOutput(UsdBridgeTokens->out, SdfValueTypeNames->Float4);
// Bind the texcoord reader's output to the sampler's coord input
sampler.CreateInput(UsdBridgeTokens->coord, coordType).ConnectToSource(tcrOutput);
}
void InitializeMdlSamplerTimeVar(UsdShadeShader& sampler, UsdBridgeSamplerData::SamplerType type, const TimeEvaluator<UsdBridgeSamplerData>* timeEval = nullptr)
{
typedef UsdBridgeSamplerData::DataMemberId DMI;
CreateShaderInput(sampler, timeEval, DMI::DATA, UsdBridgeTokens->tex, QualifiedInputTokens->tex, SdfValueTypeNames->Asset);
CreateShaderInput(sampler, timeEval, DMI::WRAPS, UsdBridgeTokens->wrap_u, QualifiedInputTokens->wrap_u, SdfValueTypeNames->Int);
if((uint32_t)type >= (uint32_t)UsdBridgeSamplerData::SamplerType::SAMPLER_2D)
CreateShaderInput(sampler, timeEval, DMI::WRAPT, UsdBridgeTokens->wrap_v, QualifiedInputTokens->wrap_v, SdfValueTypeNames->Int);
if((uint32_t)type >= (uint32_t)UsdBridgeSamplerData::SamplerType::SAMPLER_3D)
CreateShaderInput(sampler, timeEval, DMI::WRAPR, UsdBridgeTokens->wrap_w, QualifiedInputTokens->wrap_w, SdfValueTypeNames->Int);
}
UsdShadeOutput InitializePsShader(UsdStageRefPtr shaderStage, const SdfPath& matPrimPath, bool uniformPrim
, const TimeEvaluator<UsdBridgeMaterialData>* timeEval = nullptr)
{
// Create the shader
SdfPath shadPrimPath = matPrimPath.AppendPath(SdfPath(constring::psShaderPrimPf));
UsdShadeShader shader = GetOrDefinePrim<UsdShadeShader>(shaderStage, shadPrimPath);
assert(shader);
if (uniformPrim)
{
InitializePsShaderUniform(shader);
}
InitializePsShaderTimeVar(shader, timeEval);
if(uniformPrim)
return shader.CreateOutput(UsdBridgeTokens->surface, SdfValueTypeNames->Token);
else
return UsdShadeOutput();
}
UsdShadeOutput InitializeMdlShader(UsdStageRefPtr shaderStage, const SdfPath& matPrimPath, bool uniformPrim
, const TimeEvaluator<UsdBridgeMaterialData>* timeEval = nullptr)
{
typedef UsdBridgeMaterialData::DataMemberId DMI;
// Create the shader
SdfPath shadPrimPath = matPrimPath.AppendPath(SdfPath(constring::mdlShaderPrimPf));
UsdShadeShader shader = GetOrDefinePrim<UsdShadeShader>(shaderStage, shadPrimPath);
assert(shader);
// Create a mul shader node (for connection to opacity)
SdfPath shadPrimPath_opmul = matPrimPath.AppendPath(SdfPath(constring::mdlOpacityMulPrimPf));
UsdShadeShader opacityMul = GetOrDefinePrim<UsdShadeShader>(shaderStage, shadPrimPath_opmul);
assert(opacityMul);
UsdShadeOutput opacityMulOut;
if(uniformPrim)
{
opacityMulOut = InitializeMdlGraphNode(opacityMul, UsdBridgeTokens->mul_float, SdfValueTypeNames->Float);
opacityMul.CreateInput(UsdBridgeTokens->a, SdfValueTypeNames->Float); // Input a is either connected (to sampler/vc opacity) or 1.0, so never timevarying
InitializeMdlShaderUniform(shader);
}
CreateShaderInput(opacityMul, timeEval, DMI::OPACITY, UsdBridgeTokens->b, QualifiedInputTokens->b, SdfValueTypeNames->Float);
InitializeMdlShaderTimeVar(shader, timeEval);
// Connect the opacity mul node to the shader
if(uniformPrim)
{
shader.GetInput(GetMaterialShaderInputToken<false>(DMI::OPACITY)).ConnectToSource(opacityMulOut);
}
if(uniformPrim)
return shader.CreateOutput(UsdBridgeTokens->out, SdfValueTypeNames->Token);
else
return UsdShadeOutput();
}
void BindShaderToMaterial(const UsdShadeMaterial& matPrim, const UsdShadeOutput& shadOut, TfToken* renderContext)
{
// Bind the material to the shader reference subprim.
if(renderContext)
matPrim.CreateSurfaceOutput(*renderContext).ConnectToSource(shadOut);
else
matPrim.CreateSurfaceOutput().ConnectToSource(shadOut);
}
UsdShadeMaterial InitializeUsdMaterial_Impl(UsdStageRefPtr materialStage, const SdfPath& matPrimPath, bool uniformPrim, const UsdBridgeSettings& settings,
const TimeEvaluator<UsdBridgeMaterialData>* timeEval = nullptr)
{
// Create the material
UsdShadeMaterial matPrim = GetOrDefinePrim<UsdShadeMaterial>(materialStage, matPrimPath);
assert(matPrim);
if(settings.EnablePreviewSurfaceShader)
{
// Create a shader
UsdShadeOutput shaderOutput = InitializePsShader(materialStage, matPrimPath, uniformPrim, timeEval);
if(uniformPrim)
BindShaderToMaterial(matPrim, shaderOutput, nullptr);
}
if(settings.EnableMdlShader)
{
// Create an mdl shader
UsdShadeOutput shaderOutput = InitializeMdlShader(materialStage, matPrimPath, uniformPrim, timeEval);
if(uniformPrim)
BindShaderToMaterial(matPrim, shaderOutput, &UsdBridgeTokens->mdl);
}
return matPrim;
}
UsdPrim InitializePsSampler_Impl(UsdStageRefPtr samplerStage, const SdfPath& samplerPrimPath, UsdBridgeSamplerData::SamplerType type, bool uniformPrim,
const TimeEvaluator<UsdBridgeSamplerData>* timeEval = nullptr)
{
typedef UsdBridgeSamplerData::DataMemberId DMI;
UsdShadeShader sampler = GetOrDefinePrim<UsdShadeShader>(samplerStage, samplerPrimPath);
assert(sampler);
if(uniformPrim)
{
SdfPath texCoordReaderPrimPath = samplerPrimPath.AppendPath(SdfPath(constring::texCoordReaderPrimPf));
UsdShadeShader texCoordReader = UsdShadeShader::Define(samplerStage, texCoordReaderPrimPath);
assert(texCoordReader);
// USD does not yet allow for anything but 2D coords, but let's try anyway
TfToken idAttrib;
SdfValueTypeName valueType;
if(type == UsdBridgeSamplerData::SamplerType::SAMPLER_1D)
{
idAttrib = UsdBridgeTokens->PrimVarReader_Float;
valueType = SdfValueTypeNames->Float;
}
else if (type == UsdBridgeSamplerData::SamplerType::SAMPLER_2D)
{
idAttrib = UsdBridgeTokens->PrimVarReader_Float2;
valueType = SdfValueTypeNames->Float2;
}
else
{
idAttrib = UsdBridgeTokens->PrimVarReader_Float3;
valueType = SdfValueTypeNames->Float3;
}
UsdShadeOutput tcrOutput = InitializePsAttributeReaderUniform(texCoordReader, idAttrib, valueType);
InitializePsSamplerUniform(sampler, valueType, tcrOutput);
}
//InitializePsAttributeReaderTimeVar(texCoordReader, DMI::INATTRIBUTE, timeEval); // timevar attribute reader disabled
InitializePsSamplerTimeVar(sampler, type, timeEval);
return sampler.GetPrim();
}
UsdPrim InitializeMdlSampler_Impl(UsdStageRefPtr samplerStage, const SdfPath& samplerPrimPath, UsdBridgeSamplerData::SamplerType type, bool uniformPrim,
const TimeEvaluator<UsdBridgeSamplerData>* timeEval = nullptr)
{
typedef UsdBridgeSamplerData::DataMemberId DMI;
UsdShadeShader sampler = GetOrDefinePrim<UsdShadeShader>(samplerStage, samplerPrimPath);
assert(sampler);
if(uniformPrim)
{
SdfPath texCoordReaderPrimPath = samplerPrimPath.AppendPath(SdfPath(constring::texCoordReaderPrimPf));
UsdShadeShader texCoordReader = UsdShadeShader::Define(samplerStage, texCoordReaderPrimPath);
assert(texCoordReader);
// USD does not yet allow for anything but 2D coords, but let's try anyway
TfToken idAttrib;
SdfValueTypeName valueType;
if(type == UsdBridgeSamplerData::SamplerType::SAMPLER_1D)
{
idAttrib = UsdBridgeTokens->data_lookup_float2; // Currently, there is no 1D lookup
valueType = SdfValueTypeNames->Float2;
}
else if (type == UsdBridgeSamplerData::SamplerType::SAMPLER_2D)
{
idAttrib = UsdBridgeTokens->data_lookup_float2;
valueType = SdfValueTypeNames->Float2;
}
else
{
idAttrib = UsdBridgeTokens->data_lookup_float3;
valueType = SdfValueTypeNames->Float3;
}
UsdShadeOutput tcrOutput = InitializeMdlAttributeReaderUniform(texCoordReader, idAttrib, valueType);
InitializeMdlSamplerUniform(sampler, valueType, tcrOutput);
}
//InitializeMdlAttributeReaderTimeVar(texCoordReader, DMI::INATTRIBUTE, timeEval); // timevar attribute reader disabled
InitializeMdlSamplerTimeVar(sampler, type, timeEval);
if(uniformPrim)
{
sampler.GetInput(UsdBridgeTokens->tex).GetAttr().SetMetadata(UsdBridgeTokens->colorSpace, VtValue("sRGB"));
}
return sampler.GetPrim();
}
void InitializeSampler_Impl(UsdStageRefPtr samplerStage, const SdfPath& samplerPrimPath, UsdBridgeSamplerData::SamplerType type, bool uniformPrim,
const UsdBridgeSettings& settings, const TimeEvaluator<UsdBridgeSamplerData>* timeEval = nullptr)
{
if(settings.EnablePreviewSurfaceShader)
{
SdfPath usdSamplerPrimPath = samplerPrimPath.AppendPath(SdfPath(constring::psSamplerPrimPf));
InitializePsSampler_Impl(samplerStage, usdSamplerPrimPath, type, uniformPrim, timeEval);
}
if(settings.EnableMdlShader)
{
SdfPath usdSamplerPrimPath = samplerPrimPath.AppendPath(SdfPath(constring::mdlSamplerPrimPf));
InitializeMdlSampler_Impl(samplerStage, usdSamplerPrimPath, type, uniformPrim, timeEval);
}
}
template<bool PreviewSurface>
UsdShadeShader InitializeAttributeReader_Impl(UsdStageRefPtr materialStage, const SdfPath& matPrimPath, bool uniformPrim,
UsdBridgeMaterialData::DataMemberId dataMemberId, const TimeEvaluator<UsdBridgeMaterialData>* timeEval)
{
using DMI = UsdBridgeMaterialData::DataMemberId;
if(!uniformPrim) // timevar attribute reader disabled
return UsdShadeShader();
// Create a vertexcolorreader
SdfPath attributeReaderPath = matPrimPath.AppendPath(GetAttributeReaderPathPf<PreviewSurface>(dataMemberId));
UsdShadeShader attributeReader = UsdShadeShader::Get(materialStage, attributeReaderPath);
// Allow for uniform and timevar prims to return already existing prim without triggering re-initialization
// manifest <==> timeEval, and will always take this branch
if(!attributeReader || timeEval)
{
if(!attributeReader) // Currently no need for timevar properties on attribute readers
attributeReader = UsdShadeShader::Define(materialStage, attributeReaderPath);
if(PreviewSurface)
{
if(uniformPrim) // Implies !timeEval, so initialize
{
InitializePsAttributeReaderUniform(attributeReader, GetPsAttributeReaderId(dataMemberId), GetAttributeOutputType(dataMemberId));
}
// Create attribute reader varname, and if timeEval (manifest), can also remove the input
//InitializePsAttributeReaderTimeVar(attributeReader, dataMemberId, timeEval);
}
else
{
if(uniformPrim) // Implies !timeEval, so initialize
{
InitializeMdlAttributeReaderUniform(attributeReader, GetMdlAttributeReaderSubId(dataMemberId), GetAttributeOutputType(dataMemberId));
}
//InitializeMdlAttributeReaderTimeVar(attributeReader, dataMemberId, timeEval);
}
}
return attributeReader;
}
#define INITIALIZE_ATTRIBUTE_READER_MACRO(srcAttrib, dmi) \
if(srcAttrib) InitializeAttributeReader_Impl<PreviewSurface>(materialStage, matPrimPath, false, dmi, timeEval);
template<bool PreviewSurface>
void InitializeAttributeReaderSet(UsdStageRefPtr materialStage, const SdfPath& matPrimPath, const UsdBridgeSettings& settings,
const UsdBridgeMaterialData& matData, const TimeEvaluator<UsdBridgeMaterialData>* timeEval)
{
using DMI = UsdBridgeMaterialData::DataMemberId;
INITIALIZE_ATTRIBUTE_READER_MACRO(matData.Diffuse.SrcAttrib, DMI::DIFFUSE); \
INITIALIZE_ATTRIBUTE_READER_MACRO(matData.Opacity.SrcAttrib, DMI::OPACITY); \
INITIALIZE_ATTRIBUTE_READER_MACRO(matData.Emissive.SrcAttrib, DMI::EMISSIVECOLOR); \
INITIALIZE_ATTRIBUTE_READER_MACRO(matData.EmissiveIntensity.SrcAttrib, DMI::EMISSIVEINTENSITY); \
INITIALIZE_ATTRIBUTE_READER_MACRO(matData.Roughness.SrcAttrib, DMI::ROUGHNESS);
INITIALIZE_ATTRIBUTE_READER_MACRO(matData.Metallic.SrcAttrib, DMI::METALLIC);
INITIALIZE_ATTRIBUTE_READER_MACRO(matData.Ior.SrcAttrib, DMI::IOR);
}
void InitializeAttributeReaders_Impl(UsdStageRefPtr materialStage, const SdfPath& matPrimPath, const UsdBridgeSettings& settings,
const UsdBridgeMaterialData& matData, const TimeEvaluator<UsdBridgeMaterialData>* timeEval)
{
// So far, only used for manifest, so no uniform path required for initialization of attribute readers.
// Instead, uniform and timevar attrib readers are created on demand per-attribute in GetOrCreateAttributeReaders().
if(settings.EnablePreviewSurfaceShader)
{
InitializeAttributeReaderSet<true>(materialStage, matPrimPath, settings, matData, timeEval);
}
if(settings.EnableMdlShader)
{
InitializeAttributeReaderSet<false>(materialStage, matPrimPath, settings, matData, timeEval);
}
}
template<bool PreviewSurface>
void GetOrCreateAttributeReaders(UsdStageRefPtr sceneStage, UsdStageRefPtr timeVarStage, const SdfPath& matPrimPath, UsdBridgeMaterialData::DataMemberId dataMemberId,
UsdShadeShader& uniformReaderPrim)
{
uniformReaderPrim = InitializeAttributeReader_Impl<PreviewSurface>(sceneStage, matPrimPath, true, dataMemberId, nullptr);
//if(timeVarStage && (timeVarStage != sceneStage))
// timeVarReaderPrim = InitializeAttributeReader_Impl<PreviewSurface>(timeVarStage, matPrimPath, false, dataMemberId, nullptr);
}
template<bool PreviewSurface>
void UpdateAttributeReaderName(UsdShadeShader& uniformReaderPrim, const TfToken& nameToken)
{
// Set the correct attribute token for the reader varname
if(PreviewSurface)
{
uniformReaderPrim.GetInput(UsdBridgeTokens->varname).Set(nameToken);
}
else
{
uniformReaderPrim.GetInput(UsdBridgeTokens->name).Set(nameToken.GetString());
}
}
template<bool PreviewSurface>
void UpdateAttributeReaderOutput(UsdShadeShader& uniformReaderPrim, const UsdGeomPrimvarsAPI& boundGeomPrimvars, const TfToken& attribNameToken)
{
const TfToken& outAttribToken = PreviewSurface ? UsdBridgeTokens->result : UsdBridgeTokens->out;
UsdGeomPrimvar geomPrimvar = boundGeomPrimvars.GetPrimvar(attribNameToken);
UsdShadeOutput readerOutput = uniformReaderPrim.GetOutput(outAttribToken);
if(geomPrimvar)
{
const SdfValueTypeName& geomPrimTypeName = geomPrimvar.GetTypeName();
if(geomPrimTypeName != readerOutput.GetTypeName())
{
boundGeomPrimvars.GetPrim().RemoveProperty(PreviewSurface ? QualifiedOutputTokens->result : QualifiedOutputTokens->out);
uniformReaderPrim.CreateOutput(outAttribToken, geomPrimTypeName);
// Also change the asset subidentifier based on the outAttribToken
uniformReaderPrim.SetSourceAssetSubIdentifier(GetMdlAttributeReaderSubId(geomPrimTypeName), UsdBridgeTokens->mdl);
}
}
}
template<bool PreviewSurface>
void UpdateShaderInput_ShadeNode( const UsdShadeShader& uniformShaderIn, const UsdShadeShader& timeVarShaderIn, const TfToken& inputToken,
const UsdShadeShader& shadeNodeOut, const TfToken& outputToken,
const ShadeGraphTypeConversionNodeContext& conversionContext)
{
//Bind the shade node to the input of the uniform shader, so remove any existing values from the timeVar prim
UsdShadeInput timeVarInput = timeVarShaderIn.GetInput(inputToken);
if(timeVarInput)
timeVarInput.GetAttr().Clear();
// Connect shadeNode output to uniformShad input
UsdShadeOutput nodeOutput = shadeNodeOut.GetOutput(outputToken);
assert(nodeOutput);
UsdShadeInput shadeInput = uniformShaderIn.GetInput(inputToken);
if(!PreviewSurface)
{
conversionContext.InsertMdlShaderTypeConversionNodes(shadeInput, nodeOutput);
}
uniformShaderIn.GetInput(inputToken).ConnectToSource(nodeOutput);
}
template<bool PreviewSurface>
void UpdateShaderInputColorOpacity_Constant(UsdStageRefPtr sceneStage, const SdfPath& matPrimPath)
{
if(!PreviewSurface)
{
SdfPath opMulPrimPath = matPrimPath.AppendPath(SdfPath(constring::mdlOpacityMulPrimPf));
UsdShadeShader uniformOpMul = UsdShadeShader::Get(sceneStage, opMulPrimPath);
UsdShadeInput uniformOpMulInput = uniformOpMul.GetInput(UsdBridgeTokens->a);
assert(uniformOpMulInput);
uniformOpMulInput.Set(1.0f);
}
}
template<bool PreviewSurface>
void UpdateShaderInputColorOpacity_AttributeReader(UsdStageRefPtr materialStage,
const UsdShadeShader& outputNode, const ShadeGraphTypeConversionNodeContext& conversionContext)
{
// No PreviewSurface implementation to connect a 4 component attrib reader to a 1 component opacity input.
if(!PreviewSurface)
{
SdfPath opMulPrimPath = conversionContext.MatPrimPath.AppendPath(SdfPath(constring::mdlOpacityMulPrimPf));
UsdShadeShader uniformOpMul = UsdShadeShader::Get(conversionContext.SceneStage, opMulPrimPath);
UsdShadeShader timeVarOpMul = UsdShadeShader::Get(materialStage, opMulPrimPath);
// Input 'a' of the multiply node the target for connecting opacity to; see InitializeMdlShader
TfToken opacityInputToken = UsdBridgeTokens->a;
TfToken opacityOutputToken = UsdBridgeTokens->out;
UpdateShaderInput_ShadeNode<false>(uniformOpMul, timeVarOpMul, opacityInputToken, outputNode, opacityOutputToken, conversionContext);
}
}
template<bool PreviewSurface, typename InputValueType, typename ValueType>
void UpdateShaderInput(UsdBridgeUsdWriter* writer, UsdStageRefPtr sceneStage, UsdStageRefPtr timeVarStage,
UsdShadeShader& uniformShadPrim, UsdShadeShader& timeVarShadPrim, const SdfPath& matPrimPath, const UsdGeomPrimvarsAPI& boundGeomPrimvars,
const TimeEvaluator<UsdBridgeMaterialData>& timeEval, UsdBridgeMaterialData::DataMemberId dataMemberId,
const UsdBridgeMaterialData::MaterialInput<InputValueType>& param, const TfToken& inputToken, const ValueType& inputValue)
{
using DMI = UsdBridgeMaterialData::DataMemberId;
// Handle the case where a geometry attribute reader is connected
if (param.SrcAttrib != nullptr)
{
//bool isTimeVarying = timeEval.IsTimeVarying(dataMemberId);
// Create attribute reader(s) to connect to the material shader input
UsdShadeShader uniformReaderPrim;
GetOrCreateAttributeReaders<PreviewSurface>(sceneStage,
sceneStage, matPrimPath, dataMemberId, uniformReaderPrim);
assert(uniformReaderPrim);
const TfToken& attribNameToken = writer->AttributeNameToken(param.SrcAttrib);
UpdateAttributeReaderName<PreviewSurface>(uniformReaderPrim, writer->AttributeNameToken(param.SrcAttrib));
UpdateAttributeReaderOutput<PreviewSurface>(uniformReaderPrim, boundGeomPrimvars, attribNameToken);
// Connect the reader to the material shader input
ShadeGraphTypeConversionNodeContext conversionContext(
sceneStage, matPrimPath, GetAttributeReaderPathPf<PreviewSurface>(dataMemberId).GetString().c_str());
const TfToken& outputToken = PreviewSurface ? UsdBridgeTokens->result : UsdBridgeTokens->out;
UpdateShaderInput_ShadeNode<PreviewSurface>(uniformShadPrim, timeVarShadPrim, inputToken, uniformReaderPrim, outputToken, conversionContext);
// Diffuse attrib also has to connect to the opacitymul 'a' input. The color primvar (and therefore attrib reader out) is always a float4.
if(dataMemberId == DMI::DIFFUSE)
{
conversionContext.ConnectionIdentifier = PreviewSurface ? "" : constring::mdlDiffuseOpacityPrimPf;
conversionContext.ChannelSelector = 3; // Select the w channel from the float4 input
UpdateShaderInputColorOpacity_AttributeReader<PreviewSurface>(timeVarStage, uniformReaderPrim, conversionContext);
}
}
else if(!param.Sampler)
{
// Handle the case for normal direct values
UsdShadeInput uniformDiffInput = uniformShadPrim.GetInput(inputToken);
if(uniformDiffInput.HasConnectedSource())
uniformDiffInput.DisconnectSource();
// Just treat like regular time-varying inputs
SetShaderInput(uniformShadPrim, timeVarShadPrim, timeEval, inputToken, dataMemberId, inputValue);
// The diffuse input owns the opacitymul's 'a' input.
if(dataMemberId == DMI::DIFFUSE)
UpdateShaderInputColorOpacity_Constant<PreviewSurface>(sceneStage, matPrimPath);
}
}
// Variation for standard material shader input tokens
template<bool PreviewSurface, typename InputValueType, typename ValueType>
void UpdateShaderInput(UsdBridgeUsdWriter* writer, UsdStageRefPtr sceneStage, UsdStageRefPtr timeVarStage,
UsdShadeShader& uniformShadPrim, UsdShadeShader& timeVarShadPrim, const SdfPath& matPrimPath, const UsdGeomPrimvarsAPI& boundGeomPrimvars, const TimeEvaluator<UsdBridgeMaterialData>& timeEval,
UsdBridgeMaterialData::DataMemberId dataMemberId, const UsdBridgeMaterialData::MaterialInput<InputValueType>& param, const ValueType& inputValue)
{
const TfToken& inputToken = GetMaterialShaderInputToken<PreviewSurface>(dataMemberId);
UpdateShaderInput<PreviewSurface>(writer, sceneStage, timeVarStage, uniformShadPrim, timeVarShadPrim, matPrimPath, boundGeomPrimvars, timeEval,
dataMemberId, param, inputToken, inputValue);
}
// Convenience for when param.Value is simply the intended value to be set
template<bool PreviewSurface, typename InputValueType>
void UpdateShaderInput(UsdBridgeUsdWriter* writer, UsdStageRefPtr sceneStage, UsdStageRefPtr timeVarStage,
UsdShadeShader& uniformShadPrim, UsdShadeShader& timeVarShadPrim, const SdfPath& matPrimPath, const UsdGeomPrimvarsAPI& boundGeomPrimvars, const TimeEvaluator<UsdBridgeMaterialData>& timeEval,
UsdBridgeMaterialData::DataMemberId dataMemberId, const UsdBridgeMaterialData::MaterialInput<InputValueType>& param)
{
const TfToken& inputToken = GetMaterialShaderInputToken<PreviewSurface>(dataMemberId);
UpdateShaderInput<PreviewSurface>(writer, sceneStage, timeVarStage, uniformShadPrim, timeVarShadPrim, matPrimPath, boundGeomPrimvars, timeEval,
dataMemberId, param, inputToken, param.Value);
}
template<bool PreviewSurface>
void UpdateShaderInput_Sampler(const UsdShadeShader& uniformShader, const UsdShadeShader& timeVarShader,
const UsdShadeShader& refSampler, const UsdSamplerRefData& samplerRefData, const ShadeGraphTypeConversionNodeContext& conversionContext)
{
using DMI = UsdBridgeMaterialData::DataMemberId;
DMI samplerDMI = samplerRefData.DataMemberId;
const TfToken& inputToken = GetMaterialShaderInputToken<PreviewSurface>(samplerDMI);
const TfToken& outputToken = GetSamplerOutputColorToken<PreviewSurface>(samplerRefData.ImageNumComponents);
UpdateShaderInput_ShadeNode<PreviewSurface>(uniformShader, timeVarShader, inputToken, refSampler, outputToken, conversionContext);
}
template<bool PreviewSurface>
void UpdateShaderInputColorOpacity_Sampler(const UsdShadeShader& uniformShader, const UsdShadeShader& timeVarShader,
const UsdShadeShader& refSampler, ShadeGraphTypeConversionNodeContext& conversionContext)
{
using DMI = UsdBridgeMaterialData::DataMemberId;
TfToken opacityInputToken;
TfToken opacityOutputToken;
if(PreviewSurface)
{
opacityInputToken = GetMaterialShaderInputToken<PreviewSurface>(DMI::OPACITY);
opacityOutputToken = UsdBridgeTokens->a;
}
else
{
// Input 'a' of the multiply node the target for connecting opacity to; see InitializeMdlShader
opacityInputToken = UsdBridgeTokens->a;
opacityOutputToken = UsdBridgeTokens->out;
}
UpdateShaderInput_ShadeNode<PreviewSurface>(uniformShader, timeVarShader, opacityInputToken, refSampler, opacityOutputToken, conversionContext);
}
template<bool PreviewSurface>
void UpdateSamplerInputs(UsdStageRefPtr sceneStage, UsdStageRefPtr timeVarStage, const SdfPath& samplerPrimPath, const UsdBridgeSamplerData& samplerData,
const char* imgFileName, const TfToken& attributeNameToken, const TimeEvaluator<UsdBridgeSamplerData>& timeEval)
{
typedef UsdBridgeSamplerData::DataMemberId DMI;
// Collect the various prims
SdfPath tcReaderPrimPath = samplerPrimPath.AppendPath(SdfPath(constring::texCoordReaderPrimPf));
UsdShadeShader uniformTcReaderPrim = UsdShadeShader::Get(sceneStage, tcReaderPrimPath);
assert(uniformTcReaderPrim);
UsdShadeShader uniformSamplerPrim = UsdShadeShader::Get(sceneStage, samplerPrimPath);
assert(uniformSamplerPrim);
UsdShadeShader timeVarSamplerPrim = UsdShadeShader::Get(timeVarStage, samplerPrimPath);
assert(timeVarSamplerPrim);
SdfAssetPath texFile(imgFileName);
if(PreviewSurface)
{
// Set all the inputs
SetShaderInput(uniformSamplerPrim, timeVarSamplerPrim, timeEval, UsdBridgeTokens->file, DMI::DATA, texFile);
SetShaderInput(uniformSamplerPrim, timeVarSamplerPrim, timeEval, UsdBridgeTokens->WrapS, DMI::WRAPS, TextureWrapToken(samplerData.WrapS));
if((uint32_t)samplerData.Type >= (uint32_t)UsdBridgeSamplerData::SamplerType::SAMPLER_2D)
SetShaderInput(uniformSamplerPrim, timeVarSamplerPrim, timeEval, UsdBridgeTokens->WrapT, DMI::WRAPT, TextureWrapToken(samplerData.WrapT));
if((uint32_t)samplerData.Type >= (uint32_t)UsdBridgeSamplerData::SamplerType::SAMPLER_3D)
SetShaderInput(uniformSamplerPrim, timeVarSamplerPrim, timeEval, UsdBridgeTokens->WrapR, DMI::WRAPR, TextureWrapToken(samplerData.WrapR));
// Check whether the output type is still correct
// (Experimental: assume the output type doesn't change over time, this just gives it a chance to match the image type)
int numComponents = samplerData.ImageNumComponents;
const TfToken& outputToken = GetSamplerOutputColorToken<true>(numComponents);
if(!uniformSamplerPrim.GetOutput(outputToken))
{
// As the previous output type isn't cached, just remove everything:
uniformSamplerPrim.GetPrim().RemoveProperty(QualifiedOutputTokens->r);
uniformSamplerPrim.GetPrim().RemoveProperty(QualifiedOutputTokens->rg);
uniformSamplerPrim.GetPrim().RemoveProperty(QualifiedOutputTokens->rgb);
uniformSamplerPrim.CreateOutput(outputToken, GetSamplerOutputColorType<true>(numComponents));
}
}
else
{
// Set all the inputs
SetShaderInput(uniformSamplerPrim, timeVarSamplerPrim, timeEval, UsdBridgeTokens->tex, DMI::DATA, texFile);
SetShaderInput(uniformSamplerPrim, timeVarSamplerPrim, timeEval, UsdBridgeTokens->wrap_u, DMI::WRAPS, TextureWrapInt(samplerData.WrapS));
if((uint32_t)samplerData.Type >= (uint32_t)UsdBridgeSamplerData::SamplerType::SAMPLER_2D)
SetShaderInput(uniformSamplerPrim, timeVarSamplerPrim, timeEval, UsdBridgeTokens->wrap_v, DMI::WRAPT, TextureWrapInt(samplerData.WrapT));
if((uint32_t)samplerData.Type >= (uint32_t)UsdBridgeSamplerData::SamplerType::SAMPLER_3D)
SetShaderInput(uniformSamplerPrim, timeVarSamplerPrim, timeEval, UsdBridgeTokens->wrap_w, DMI::WRAPR, TextureWrapInt(samplerData.WrapR));
// Check whether the output type is still correct
int numComponents = samplerData.ImageNumComponents;
const TfToken& assetIdent = GetSamplerAssetSubId(numComponents);
const SdfValueTypeName& outputType = GetSamplerOutputColorType<false>(numComponents);
if(uniformSamplerPrim.GetOutput(UsdBridgeTokens->out).GetTypeName() != outputType)
{
uniformSamplerPrim.SetSourceAssetSubIdentifier(assetIdent, UsdBridgeTokens->mdl);
uniformSamplerPrim.GetPrim().RemoveProperty(QualifiedOutputTokens->out);
uniformSamplerPrim.CreateOutput(UsdBridgeTokens->out, outputType);
}
}
UpdateAttributeReaderName<PreviewSurface>(uniformTcReaderPrim, attributeNameToken);
}
void GetMaterialCoreShader(UsdStageRefPtr sceneStage, UsdStageRefPtr materialStage, const SdfPath& shaderPrimPath,
UsdShadeShader& uniformShader, UsdShadeShader& timeVarShader)
{
uniformShader = UsdShadeShader::Get(sceneStage, shaderPrimPath);
assert(uniformShader);
timeVarShader = UsdShadeShader::Get(materialStage, shaderPrimPath);
assert(timeVarShader);
}
template<bool PreviewSurface>
void GetRefSamplerPrim(UsdStageRefPtr sceneStage, const SdfPath& refSamplerPrimPath, UsdShadeShader& refSampler)
{
SdfPath refSamplerPrimPath_Child = refSamplerPrimPath.AppendPath(SdfPath(PreviewSurface ? constring::psSamplerPrimPf : constring::mdlSamplerPrimPf)); // type inherited from sampler prim (in AddRef)
refSampler = UsdShadeShader::Get(sceneStage, refSamplerPrimPath_Child);
assert(refSampler);
}
}
UsdShadeMaterial UsdBridgeUsdWriter::InitializeUsdMaterial(UsdStageRefPtr materialStage, const SdfPath& matPrimPath, bool uniformPrim) const
{
return InitializeUsdMaterial_Impl(materialStage, matPrimPath, uniformPrim, Settings);
}
void UsdBridgeUsdWriter::InitializeUsdSampler(UsdStageRefPtr samplerStage,const SdfPath& samplerPrimPath, UsdBridgeSamplerData::SamplerType type, bool uniformPrim) const
{
InitializeSampler_Impl(samplerStage, samplerPrimPath, type, uniformPrim, Settings);
}
#ifdef USE_INDEX_MATERIALS
namespace
{
UsdShadeOutput InitializeIndexShaderUniform(UsdStageRefPtr volumeStage, UsdShadeShader& indexShader, UsdPrim& colorMapPrim)
{
UsdShadeConnectableAPI colorMapConn(colorMapPrim);
UsdShadeOutput colorMapShadOut = colorMapConn.CreateOutput(UsdBridgeTokens->colormap, SdfValueTypeNames->Token);
colorMapPrim.CreateAttribute(UsdBridgeTokens->domainBoundaryMode , SdfValueTypeNames->Token).Set(UsdBridgeTokens->clampToEdge);
colorMapPrim.CreateAttribute(UsdBridgeTokens->colormapSource , SdfValueTypeNames->Token).Set(UsdBridgeTokens->colormapValues);
indexShader.CreateInput(UsdBridgeTokens->colormap, SdfValueTypeNames->Token).ConnectToSource(colorMapShadOut);
return indexShader.CreateOutput(UsdBridgeTokens->volume, SdfValueTypeNames->Token);
}
void InitializeIndexShaderTimeVar(UsdPrim& colorMapPrim, const TimeEvaluator<UsdBridgeVolumeData>* timeEval = nullptr)
{
typedef UsdBridgeVolumeData::DataMemberId DMI;
// Value range
CREATE_REMOVE_TIMEVARYING_ATTRIB(colorMapPrim, DMI::TFVALUERANGE, UsdBridgeTokens->domain, SdfValueTypeNames->Float2);
// Colors and opacities are grouped into the same attrib
CREATE_REMOVE_TIMEVARYING_ATTRIB(colorMapPrim, (DMI::TFCOLORS | DMI::TFOPACITIES), UsdBridgeTokens->colormapValues, SdfValueTypeNames->Float4Array);
}
}
UsdShadeMaterial UsdBridgeUsdWriter::InitializeIndexVolumeMaterial_Impl(UsdStageRefPtr volumeStage,
const SdfPath& volumePath, bool uniformPrim, const TimeEvaluator<UsdBridgeVolumeData>* timeEval) const
{
SdfPath indexMatPath = volumePath.AppendPath(SdfPath(constring::indexMaterialPf));
SdfPath indexShadPath = indexMatPath.AppendPath(SdfPath(constring::indexShaderPf));
SdfPath colorMapPath = indexMatPath.AppendPath(SdfPath(constring::indexColorMapPf));
UsdShadeMaterial indexMaterial = GetOrDefinePrim<UsdShadeMaterial>(volumeStage, indexMatPath);
assert(indexMaterial);
UsdPrim colorMapPrim = volumeStage->GetPrimAtPath(colorMapPath);
if(!colorMapPrim)
colorMapPrim = volumeStage->DefinePrim(colorMapPath, UsdBridgeTokens->Colormap);
assert(colorMapPrim);
if(uniformPrim)
{
UsdShadeShader indexShader = GetOrDefinePrim<UsdShadeShader>(volumeStage, indexShadPath);
assert(indexShader);
UsdShadeOutput indexShaderOutput = InitializeIndexShaderUniform(volumeStage, indexShader, colorMapPrim);
indexMaterial.CreateVolumeOutput(UsdBridgeTokens->nvindex).ConnectToSource(indexShaderOutput);
}
InitializeIndexShaderTimeVar(colorMapPrim, timeEval);
return indexMaterial;
}
#endif
#ifdef VALUE_CLIP_RETIMING
void UsdBridgeUsdWriter::UpdateUsdMaterialManifest(const UsdBridgePrimCache* cacheEntry, const UsdBridgeMaterialData& matData)
{
TimeEvaluator<UsdBridgeMaterialData> timeEval(matData);
InitializeUsdMaterial_Impl(cacheEntry->ManifestStage.second, cacheEntry->PrimPath, false,
Settings, &timeEval);
InitializeAttributeReaders_Impl(cacheEntry->ManifestStage.second, cacheEntry->PrimPath,
Settings, matData, &timeEval);
if(this->EnableSaving)
cacheEntry->ManifestStage.second->Save();
}
void UsdBridgeUsdWriter::UpdateUsdSamplerManifest(const UsdBridgePrimCache* cacheEntry, const UsdBridgeSamplerData& samplerData)
{
TimeEvaluator<UsdBridgeSamplerData> timeEval(samplerData);
InitializeSampler_Impl(cacheEntry->ManifestStage.second, cacheEntry->PrimPath, samplerData.Type,
false, Settings, &timeEval);
if(this->EnableSaving)
cacheEntry->ManifestStage.second->Save();
}
#endif
void UsdBridgeUsdWriter::ConnectSamplersToMaterial(UsdStageRefPtr materialStage, const SdfPath& matPrimPath, const SdfPrimPathList& refSamplerPrimPaths,
const UsdBridgePrimCacheList& samplerCacheEntries, const UsdSamplerRefData* samplerRefDatas, size_t numSamplers, double worldTimeStep)
{
typedef UsdBridgeMaterialData::DataMemberId DMI;
// Essentially, this is an extension of UpdateShaderInput() for the case of param.Sampler
if(Settings.EnablePreviewSurfaceShader)
{
SdfPath shaderPrimPath = matPrimPath.AppendPath(SdfPath(constring::psShaderPrimPf));
UsdShadeShader uniformShad, timeVarShad;
GetMaterialCoreShader(this->SceneStage, materialStage, shaderPrimPath,
uniformShad, timeVarShad);
for(int i = 0; i < numSamplers; ++i)
{
const char* samplerPrimName = samplerCacheEntries[i]->Name.GetString().c_str();
UsdShadeShader refSampler;
GetRefSamplerPrim<true>(this->SceneStage, refSamplerPrimPaths[i], refSampler);
ShadeGraphTypeConversionNodeContext conversionContext(
this->SceneStage, matPrimPath, samplerPrimName);
UpdateShaderInput_Sampler<true>(uniformShad, timeVarShad, refSampler, samplerRefDatas[i], conversionContext);
bool affectsOpacity = samplerRefDatas[i].DataMemberId == DMI::DIFFUSE && samplerRefDatas[i].ImageNumComponents == 4;
if(affectsOpacity)
UpdateShaderInputColorOpacity_Sampler<true>(uniformShad, timeVarShad, refSampler, conversionContext);
}
}
if(Settings.EnableMdlShader)
{
// Get shader prims
SdfPath shaderPrimPath = matPrimPath.AppendPath(SdfPath(constring::mdlShaderPrimPf));
SdfPath opMulPrimPath = matPrimPath.AppendPath(SdfPath(constring::mdlOpacityMulPrimPf));
UsdShadeShader uniformShad, timeVarShad;
GetMaterialCoreShader(this->SceneStage, materialStage, shaderPrimPath,
uniformShad, timeVarShad);
UsdShadeShader uniformOpMul = UsdShadeShader::Get(this->SceneStage, opMulPrimPath);
UsdShadeShader timeVarOpMul = UsdShadeShader::Get(materialStage, opMulPrimPath);
for(int i = 0; i < numSamplers; ++i)
{
const char* samplerPrimName = samplerCacheEntries[i]->Name.GetString().c_str();
UsdShadeShader refSampler;
GetRefSamplerPrim<false>(this->SceneStage, refSamplerPrimPaths[i], refSampler);
ShadeGraphTypeConversionNodeContext conversionContext(
this->SceneStage, matPrimPath, samplerPrimName);
if(samplerRefDatas[i].DataMemberId != DMI::OPACITY)
{
UpdateShaderInput_Sampler<false>(uniformShad, timeVarShad, refSampler, samplerRefDatas[i], conversionContext);
bool affectsOpacity = samplerRefDatas[i].DataMemberId == DMI::DIFFUSE;
if(affectsOpacity)
{
if(samplerRefDatas[i].ImageNumComponents == 4)
{
conversionContext.ConnectionIdentifier = constring::mdlDiffuseOpacityPrimPf;
conversionContext.ChannelSelector = 3; // Select the w channel from the float4 input
// Connect diffuse sampler to the opacity mul node instead of the main shader; see InitializeMdlShader
UpdateShaderInputColorOpacity_Sampler<false>(uniformOpMul, timeVarOpMul, refSampler, conversionContext);
}
else
UpdateShaderInputColorOpacity_Constant<false>(this->SceneStage, matPrimPath); // Since a sampler was bound, the constant is not set during UpdateShaderInput()
}
}
else
{
// Connect opacity sampler to the 'b' input of opacity mul node, similar to UpdateMdlShader (for attribute readers)
UpdateShaderInput_ShadeNode<false>(uniformOpMul, timeVarOpMul, UsdBridgeTokens->b, refSampler, UsdBridgeTokens->out, conversionContext);
}
}
}
}
void UsdBridgeUsdWriter::UpdateUsdMaterial(UsdStageRefPtr timeVarStage, const SdfPath& matPrimPath, const UsdBridgeMaterialData& matData, const UsdGeomPrimvarsAPI& boundGeomPrimvars, double timeStep)
{
// Update usd shader
if(Settings.EnablePreviewSurfaceShader)
{
this->UpdatePsShader(timeVarStage, matPrimPath, matData, boundGeomPrimvars, timeStep);
}
if(Settings.EnableMdlShader)
{
// Update mdl shader
this->UpdateMdlShader(timeVarStage, matPrimPath, matData, boundGeomPrimvars, timeStep);
}
}
#define UPDATE_USD_SHADER_INPUT_MACRO(...) \
UpdateShaderInput<true>(this, SceneStage, timeVarStage, uniformShadPrim, timeVarShadPrim, matPrimPath, boundGeomPrimvars, timeEval, __VA_ARGS__)
void UsdBridgeUsdWriter::UpdatePsShader(UsdStageRefPtr timeVarStage, const SdfPath& matPrimPath, const UsdBridgeMaterialData& matData, const UsdGeomPrimvarsAPI& boundGeomPrimvars, double timeStep)
{
TimeEvaluator<UsdBridgeMaterialData> timeEval(matData, timeStep);
typedef UsdBridgeMaterialData::DataMemberId DMI;
SdfPath shadPrimPath = matPrimPath.AppendPath(SdfPath(constring::psShaderPrimPf));
UsdShadeShader uniformShadPrim = UsdShadeShader::Get(SceneStage, shadPrimPath);
assert(uniformShadPrim);
UsdShadeShader timeVarShadPrim = UsdShadeShader::Get(timeVarStage, shadPrimPath);
assert(timeVarShadPrim);
GfVec3f difColor(GetValuePtr(matData.Diffuse));
GfVec3f emColor(GetValuePtr(matData.Emissive));
emColor *= matData.EmissiveIntensity.Value; // This multiplication won't translate to vcr/sampler usage
//uniformShadPrim.GetInput(UsdBridgeTokens->useSpecularWorkflow).Set(
// (matData.Metallic.Value > 0.0 || matData.Metallic.SrcAttrib || matData.Metallic.Sampler) ? 0 : 1);
UPDATE_USD_SHADER_INPUT_MACRO(DMI::DIFFUSE, matData.Diffuse, difColor);
UPDATE_USD_SHADER_INPUT_MACRO(DMI::EMISSIVECOLOR, matData.Emissive, emColor);
UPDATE_USD_SHADER_INPUT_MACRO(DMI::ROUGHNESS, matData.Roughness);
UPDATE_USD_SHADER_INPUT_MACRO(DMI::OPACITY, matData.Opacity);
UPDATE_USD_SHADER_INPUT_MACRO(DMI::METALLIC, matData.Metallic);
UPDATE_USD_SHADER_INPUT_MACRO(DMI::IOR, matData.Ior);
// Just a value, not connected to attribreaders or samplers
float opacityCutoffValue = (matData.AlphaMode == UsdBridgeMaterialData::AlphaModes::MASK) ? matData.AlphaCutoff : 0.0f; // don't enable cutoff when not explicitly specified
SetShaderInput(uniformShadPrim, timeVarShadPrim, timeEval, UsdBridgeTokens->opacityThreshold, DMI::OPACITY, opacityCutoffValue);
}
#define UPDATE_MDL_SHADER_INPUT_MACRO(...) \
UpdateShaderInput<false>(this, SceneStage, timeVarStage, uniformShadPrim, timeVarShadPrim, matPrimPath, boundGeomPrimvars, timeEval, __VA_ARGS__)
void UsdBridgeUsdWriter::UpdateMdlShader(UsdStageRefPtr timeVarStage, const SdfPath& matPrimPath, const UsdBridgeMaterialData& matData, const UsdGeomPrimvarsAPI& boundGeomPrimvars, double timeStep)
{
TimeEvaluator<UsdBridgeMaterialData> timeEval(matData, timeStep);
typedef UsdBridgeMaterialData::DataMemberId DMI;
SdfPath shadPrimPath = matPrimPath.AppendPath(SdfPath(constring::mdlShaderPrimPf));
UsdShadeShader uniformShadPrim = UsdShadeShader::Get(SceneStage, shadPrimPath);
assert(uniformShadPrim);
UsdShadeShader timeVarShadPrim = UsdShadeShader::Get(timeVarStage, shadPrimPath);
assert(timeVarShadPrim);
SdfPath opMulPrimPath = matPrimPath.AppendPath(SdfPath(constring::mdlOpacityMulPrimPf));
UsdShadeShader uniformOpMulPrim = UsdShadeShader::Get(SceneStage, opMulPrimPath);
assert(uniformOpMulPrim);
UsdShadeShader timeVarOpMulPrim = UsdShadeShader::Get(timeVarStage, opMulPrimPath);
assert(timeVarOpMulPrim);
GfVec3f difColor(GetValuePtr(matData.Diffuse));
GfVec3f emColor(GetValuePtr(matData.Emissive));
bool enableEmission = (matData.EmissiveIntensity.Value >= 0.0 || matData.EmissiveIntensity.SrcAttrib || matData.EmissiveIntensity.Sampler);
// Only set values on either timevar or uniform prim
UPDATE_MDL_SHADER_INPUT_MACRO(DMI::DIFFUSE, matData.Diffuse, difColor);
UPDATE_MDL_SHADER_INPUT_MACRO(DMI::EMISSIVECOLOR, matData.Emissive, emColor);
UPDATE_MDL_SHADER_INPUT_MACRO(DMI::EMISSIVEINTENSITY, matData.EmissiveIntensity);
UPDATE_MDL_SHADER_INPUT_MACRO(DMI::ROUGHNESS, matData.Roughness);
UPDATE_MDL_SHADER_INPUT_MACRO(DMI::METALLIC, matData.Metallic);
//UPDATE_MDL_SHADER_INPUT_MACRO(DMI::IOR, matData.Ior);
UpdateShaderInput<false>(this, SceneStage, timeVarStage, uniformOpMulPrim, timeVarOpMulPrim, matPrimPath, boundGeomPrimvars,
timeEval, DMI::OPACITY, matData.Opacity, UsdBridgeTokens->b, matData.Opacity.Value); // Connect to the mul shader 'b' input, instead of the opacity input directly
// Just a value, not connected to attribreaders or samplers
float opacityCutoffValue = (matData.AlphaMode == UsdBridgeMaterialData::AlphaModes::MASK) ? matData.AlphaCutoff : 0.0f; // don't enable cutoff when not explicitly specified
bool enableOpacity = matData.AlphaMode != UsdBridgeMaterialData::AlphaModes::NONE;
SetShaderInput(uniformShadPrim, timeVarShadPrim, timeEval, UsdBridgeTokens->opacity_threshold, DMI::OPACITY, opacityCutoffValue);
SetShaderInput(uniformShadPrim, timeVarShadPrim, timeEval, UsdBridgeTokens->enable_opacity, DMI::OPACITY, enableOpacity);
SetShaderInput(uniformShadPrim, timeVarShadPrim, timeEval, UsdBridgeTokens->enable_emission, DMI::EMISSIVEINTENSITY, enableEmission);
#ifdef CUSTOM_PBR_MDL
if (!enableOpacity)
uniformShadPrim.SetSourceAsset(this->MdlOpaqueRelFilePath, UsdBridgeTokens->mdl);
else
uniformShadPrim.SetSourceAsset(this->MdlTranslucentRelFilePath, UsdBridgeTokens->mdl);
#endif
}
void UsdBridgeUsdWriter::UpdateUsdSampler(UsdStageRefPtr timeVarStage, UsdBridgePrimCache* cacheEntry, const UsdBridgeSamplerData& samplerData, double timeStep)
{
TimeEvaluator<UsdBridgeSamplerData> timeEval(samplerData, timeStep);
typedef UsdBridgeSamplerData::DataMemberId DMI;
const SdfPath& samplerPrimPath = cacheEntry->PrimPath;
// Generate an image url
const std::string& defaultName = cacheEntry->Name.GetString();
const std::string& generatedFileName = GetResourceFileName(constring::imgFolder, samplerData.ImageName, defaultName, timeStep, constring::imageExtension);
const char* imgFileName = samplerData.ImageUrl;
bool writeFile = false; // No resource key is stored if no file is written
if(!imgFileName)
{
imgFileName = generatedFileName.c_str();
writeFile = true;
}
const TfToken& attribNameToken = AttributeNameToken(samplerData.InAttribute);
if(Settings.EnablePreviewSurfaceShader)
{
SdfPath usdSamplerPrimPath = samplerPrimPath.AppendPath(SdfPath(constring::psSamplerPrimPf));
UpdateSamplerInputs<true>(SceneStage, timeVarStage, usdSamplerPrimPath, samplerData, imgFileName, attribNameToken, timeEval);
}
if(Settings.EnableMdlShader)
{
SdfPath usdSamplerPrimPath = samplerPrimPath.AppendPath(SdfPath(constring::mdlSamplerPrimPf));
UpdateSamplerInputs<false>(SceneStage, timeVarStage, usdSamplerPrimPath, samplerData, imgFileName, attribNameToken, timeEval);
}
// Update resources
if(writeFile)
{
// Create a resource reference representing the file write
const char* resourceName = samplerData.ImageName ? samplerData.ImageName : defaultName.c_str();
UsdBridgeResourceKey key(resourceName, timeStep);
bool newEntry = cacheEntry->AddResourceKey(key);
bool isSharedResource = samplerData.ImageName;
if(newEntry && isSharedResource)
AddSharedResourceRef(key);
// Upload as image to texFile (in case this hasn't yet been performed)
assert(samplerData.Data);
if(!isSharedResource || !SetSharedResourceModified(key))
{
TempImageData.resize(0);
const void* convertedSamplerData = nullptr;
int64_t convertedSamplerStride = samplerData.ImageStride[1];
int numComponents = samplerData.ImageNumComponents;
UsdBridgeType flattenedType = ubutils::UsdBridgeTypeFlatten(samplerData.DataType);
if( !(flattenedType == UsdBridgeType::UCHAR || flattenedType == UsdBridgeType::UCHAR_SRGB_R))
{
// Convert to 8-bit image data
ConvertSamplerDataToImage(samplerData, TempImageData);
if(TempImageData.size())
{
convertedSamplerData = TempImageData.data();
convertedSamplerStride = samplerData.ImageDims[0]*numComponents;
}
}
else
{
convertedSamplerData = samplerData.Data;
}
if(numComponents <= 4 && convertedSamplerData)
{
StbWriteOutput writeOutput;
stbi_write_png_to_func(StbWriteToBuffer, &writeOutput,
static_cast<int>(samplerData.ImageDims[0]), static_cast<int>(samplerData.ImageDims[1]),
numComponents, convertedSamplerData, convertedSamplerStride);
// Filename, relative from connection working dir
std::string wdRelFilename(SessionDirectory + imgFileName);
Connect->WriteFile(writeOutput.imageData, writeOutput.imageSize, wdRelFilename.c_str(), true);
}
else
{
UsdBridgeLogMacro(this->LogObject, UsdBridgeLogLevel::WARNING, "Image file not written out, format not supported (should be 1-4 component unsigned char/short/int or float/double): " << samplerData.ImageName);
}
}
}
}
namespace
{
template<bool PreviewSurface>
void UpdateAttributeReader_Impl(UsdStageRefPtr sceneStage, UsdStageRefPtr timeVarStage, const SdfPath& matPrimPath,
UsdBridgeMaterialData::DataMemberId dataMemberId, const TfToken& newNameToken, const UsdGeomPrimvarsAPI& boundGeomPrimvars,
const TimeEvaluator<UsdBridgeMaterialData>& timeEval, const UsdBridgeLogObject& logObj)
{
typedef UsdBridgeMaterialData::DataMemberId DMI;
if(PreviewSurface && dataMemberId == DMI::EMISSIVEINTENSITY)
return; // Emissive intensity is not represented as a shader input in the USD preview surface model
// Collect the various prims
SdfPath attributeReaderPath = matPrimPath.AppendPath(GetAttributeReaderPathPf<PreviewSurface>(dataMemberId));
UsdShadeShader uniformAttribReader = UsdShadeShader::Get(sceneStage, attributeReaderPath);
if(!uniformAttribReader)
{
UsdBridgeLogMacro(logObj, UsdBridgeLogLevel::ERR, "In UpdateAttributeReader_Impl(): requesting an attribute reader that hasn't been created during fixup of name token.");
return;
}
UpdateAttributeReaderName<PreviewSurface>(uniformAttribReader, newNameToken);
UpdateAttributeReaderOutput<PreviewSurface>(uniformAttribReader, boundGeomPrimvars, newNameToken);
}
template<bool PreviewSurface>
void UpdateSamplerTcReader(UsdStageRefPtr sceneStage, UsdStageRefPtr timeVarStage, const SdfPath& samplerPrimPath, const TfToken& newNameToken, const TimeEvaluator<UsdBridgeSamplerData>& timeEval)
{
typedef UsdBridgeSamplerData::DataMemberId DMI;
// Collect the various prims
SdfPath tcReaderPrimPath = samplerPrimPath.AppendPath(SdfPath(constring::texCoordReaderPrimPf));
UsdShadeShader uniformTcReaderPrim = UsdShadeShader::Get(sceneStage, tcReaderPrimPath);
assert(uniformTcReaderPrim);
// Set the new Inattribute
UpdateAttributeReaderName<PreviewSurface>(uniformTcReaderPrim, newNameToken);
}
}
void UsdBridgeUsdWriter::UpdateAttributeReader(UsdStageRefPtr timeVarStage, const SdfPath& matPrimPath, MaterialDMI dataMemberId, const char* newName, const UsdGeomPrimvarsAPI& boundGeomPrimvars, double timeStep, MaterialDMI timeVarying)
{
// Time eval with dummy data
UsdBridgeMaterialData materialData;
materialData.TimeVarying = timeVarying;
TimeEvaluator<UsdBridgeMaterialData> timeEval(materialData, timeStep);
const TfToken& newNameToken = AttributeNameToken(newName);
if(Settings.EnablePreviewSurfaceShader)
{
UpdateAttributeReader_Impl<true>(SceneStage, timeVarStage, matPrimPath, dataMemberId, newNameToken, boundGeomPrimvars, timeEval, this->LogObject);
}
if(Settings.EnableMdlShader)
{
UpdateAttributeReader_Impl<false>(SceneStage, timeVarStage, matPrimPath, dataMemberId, newNameToken, boundGeomPrimvars, timeEval, this->LogObject);
}
}
void UsdBridgeUsdWriter::UpdateInAttribute(UsdStageRefPtr timeVarStage, const SdfPath& samplerPrimPath, const char* newName, double timeStep, SamplerDMI timeVarying)
{
// Time eval with dummy data
UsdBridgeSamplerData samplerData;
samplerData.TimeVarying = timeVarying;
TimeEvaluator<UsdBridgeSamplerData> timeEval(samplerData, timeStep);
const TfToken& newNameToken = AttributeNameToken(newName);
if(Settings.EnablePreviewSurfaceShader)
{
SdfPath usdSamplerPrimPath = samplerPrimPath.AppendPath(SdfPath(constring::psSamplerPrimPf));
UpdateSamplerTcReader<true>(SceneStage, timeVarStage, usdSamplerPrimPath, newNameToken, timeEval);
}
if(Settings.EnableMdlShader)
{
SdfPath usdSamplerPrimPath = samplerPrimPath.AppendPath(SdfPath(constring::mdlSamplerPrimPf));
UpdateSamplerTcReader<false>(SceneStage, timeVarStage, usdSamplerPrimPath, newNameToken, timeEval);
}
}
#ifdef USE_INDEX_MATERIALS
void UsdBridgeUsdWriter::UpdateIndexVolumeMaterial(UsdStageRefPtr sceneStage, UsdStageRefPtr timeVarStage, const SdfPath& volumePath, const UsdBridgeVolumeData& volumeData, double timeStep)
{
TimeEvaluator<UsdBridgeVolumeData> timeEval(volumeData, timeStep);
typedef UsdBridgeVolumeData::DataMemberId DMI;
SdfPath indexMatPath = volumePath.AppendPath(SdfPath(constring::indexMaterialPf));
SdfPath colorMapPath = indexMatPath.AppendPath(SdfPath(constring::indexColorMapPf));
// Renormalize the value range based on the volume data type (see CopyToGrid in the volumewriter)
GfVec2f valueRange(GfVec2d(volumeData.TfData.TfValueRange));
// Set the transfer function value array from opacities and colors
assert(volumeData.TfData.TfOpacitiesType == UsdBridgeType::FLOAT);
const float* tfOpacities = static_cast<const float*>(volumeData.TfData.TfOpacities);
// Set domain and colormap values
UsdPrim uniformColorMap = sceneStage->GetPrimAtPath(colorMapPath);
assert(uniformColorMap);
UsdPrim timeVarColorMap = timeVarStage->GetPrimAtPath(colorMapPath);
assert(timeVarColorMap);
UsdAttribute uniformDomainAttr = uniformColorMap.GetAttribute(UsdBridgeTokens->domain);
UsdAttribute timeVarDomainAttr = timeVarColorMap.GetAttribute(UsdBridgeTokens->domain);
UsdAttribute uniformTfValueAttr = uniformColorMap.GetAttribute(UsdBridgeTokens->colormapValues);
UsdAttribute timeVarTfValueAttr = timeVarColorMap.GetAttribute(UsdBridgeTokens->colormapValues);
// Timevarying colormaps/domains are currently not supported by index, so keep this switched off
bool rangeTimeVarying = false;//timeEval.IsTimeVarying(DMI::TFVALUERANGE);
bool valuesTimeVarying = false;//timeEval.IsTimeVarying(DMI::TFCOLORS) || timeEval.IsTimeVarying(DMI::TFOPACITIES);
// Clear timevarying attributes if necessary
ClearUsdAttributes(uniformDomainAttr, timeVarDomainAttr, rangeTimeVarying);
ClearUsdAttributes(uniformTfValueAttr, timeVarTfValueAttr, valuesTimeVarying);
// Set the attributes
UsdAttribute& outAttrib = valuesTimeVarying ? timeVarTfValueAttr : uniformTfValueAttr;
UsdTimeCode outTimeCode = valuesTimeVarying ? timeEval.TimeCode : timeEval.Default();
VtVec4fArray* outArray = AssignColorArrayToPrimvar(LogObject, volumeData.TfData.TfColors, volumeData.TfData.TfNumColors, volumeData.TfData.TfColorsType,
outTimeCode,
outAttrib,
false); // Get the pointer, set the data manually here
for(size_t i = 0; i < outArray->size() && i < volumeData.TfData.TfNumOpacities; ++i)
(*outArray)[i][3] = tfOpacities[i]; // Set the alpha channel
if(outArray)
outAttrib.Set(*outArray, outTimeCode);
SET_TIMEVARYING_ATTRIB(rangeTimeVarying, timeVarDomainAttr, uniformDomainAttr, valueRange);
}
#endif
void ResourceCollectSampler(UsdBridgePrimCache* cache, UsdBridgeUsdWriter& usdWriter)
{
RemoveResourceFiles(cache, usdWriter, constring::imgFolder, constring::imageExtension);
}
| 71,332 | C++ | 46.587058 | 237 | 0.769514 |
NVIDIA-Omniverse/AnariUsdDevice/UsdBridge/UsdBridge.h | // Copyright 2020 The Khronos Group
// SPDX-License-Identifier: Apache-2.0
#ifndef UsdBridge_h
#define UsdBridge_h
#include "UsdBridgeData.h"
struct UsdBridgeInternals;
typedef void* SceneStagePtr; // Placeholder for UsdStage*
class UsdBridge
{
public:
using MaterialDMI = UsdBridgeMaterialData::DataMemberId;
using SamplerDMI = UsdBridgeSamplerData::DataMemberId;
using MaterialInputAttribName = std::pair<MaterialDMI, const char*>;
UsdBridge(const UsdBridgeSettings& settings);
~UsdBridge();
void SetExternalSceneStage(SceneStagePtr sceneStage);
void SetEnableSaving(bool enableSaving);
bool OpenSession(UsdBridgeLogCallback logCallback, void* logUserData);
bool GetSessionValid() const { return SessionValid; }
void CloseSession();
bool CreateWorld(const char* name, UsdWorldHandle& handle);
bool CreateInstance(const char* name, UsdInstanceHandle& handle);
bool CreateGroup(const char* name, UsdGroupHandle& handle);
bool CreateSurface(const char* name, UsdSurfaceHandle& handle);
bool CreateVolume(const char* name, UsdVolumeHandle& handle);
bool CreateGeometry(const char* name, UsdGeometryHandle& handle, const UsdBridgeMeshData& meshData);
bool CreateGeometry(const char* name, UsdGeometryHandle& handle, const UsdBridgeInstancerData& instancerData);
bool CreateGeometry(const char* name, UsdGeometryHandle& handle, const UsdBridgeCurveData& curveData);
bool CreateSpatialField(const char* name, UsdSpatialFieldHandle& handle);
bool CreateMaterial(const char* name, UsdMaterialHandle& handle);
bool CreateSampler(const char* name, UsdSamplerHandle& handle, UsdBridgeSamplerData::SamplerType type);
bool CreateCamera(const char* name, UsdCameraHandle& handle);
void DeleteWorld(UsdWorldHandle handle);
void DeleteInstance(UsdInstanceHandle handle);
void DeleteGroup(UsdGroupHandle handle);
void DeleteSurface(UsdSurfaceHandle handle);
void DeleteVolume(UsdVolumeHandle handle);
void DeleteGeometry(UsdGeometryHandle handle);
void DeleteSpatialField(UsdSpatialFieldHandle handle);
void DeleteMaterial(UsdMaterialHandle handle);
void DeleteSampler(UsdSamplerHandle handle);
void DeleteCamera(UsdCameraHandle handle);
void SetInstanceRefs(UsdWorldHandle world, const UsdInstanceHandle* instances, uint64_t numInstances, bool timeVarying, double timeStep);
void SetGroupRef(UsdInstanceHandle instance, UsdGroupHandle group, bool timeVarying, double timeStep);
void SetSurfaceRefs(UsdWorldHandle world, const UsdSurfaceHandle* surfaces, uint64_t numSurfaces, bool timeVarying, double timeStep);
void SetSurfaceRefs(UsdGroupHandle group, const UsdSurfaceHandle* surfaces, uint64_t numSurfaces, bool timeVarying, double timeStep);
void SetVolumeRefs(UsdWorldHandle world, const UsdVolumeHandle* volumes, uint64_t numVolumes, bool timeVarying, double timeStep);
void SetVolumeRefs(UsdGroupHandle group, const UsdVolumeHandle* volumes, uint64_t numVolumes, bool timeVarying, double timeStep);
void SetGeometryRef(UsdSurfaceHandle surface, UsdGeometryHandle geometry, double timeStep, double geomTimeStep);
void SetGeometryMaterialRef(UsdSurfaceHandle surface, UsdGeometryHandle geometry, UsdMaterialHandle material, double timeStep, double geomTimeStep, double matTimeStep);
void SetSpatialFieldRef(UsdVolumeHandle volume, UsdSpatialFieldHandle field, double timeStep, double fieldTimeStep);
void SetSamplerRefs(UsdMaterialHandle material, const UsdSamplerHandle* samplers, size_t numSamplers, double timeStep, const UsdSamplerRefData* samplerRefData);
void SetPrototypeRefs(UsdGeometryHandle geometry, const UsdGeometryHandle* protoGeometries, size_t numProtoGeometries, double timeStep, double* protoTimeSteps);
void DeleteInstanceRefs(UsdWorldHandle world, bool timeVarying, double timeStep);
void DeleteGroupRef(UsdInstanceHandle instance, bool timeVarying, double timeStep);
void DeleteSurfaceRefs(UsdWorldHandle world, bool timeVarying, double timeStep);
void DeleteSurfaceRefs(UsdGroupHandle group, bool timeVarying, double timeStep);
void DeleteVolumeRefs(UsdWorldHandle world, bool timeVarying, double timeStep);
void DeleteVolumeRefs(UsdGroupHandle group, bool timeVarying, double timeStep);
void DeleteGeometryRef(UsdSurfaceHandle surface, double timeStep);
void DeleteSpatialFieldRef(UsdVolumeHandle volume, double timeStep);
void DeleteMaterialRef(UsdSurfaceHandle surface, double timeStep);
void DeleteSamplerRefs(UsdMaterialHandle material, double timeStep);
void DeletePrototypeRefs(UsdGeometryHandle geometry, double timeStep);
void UpdateBeginEndTime(double timeStep);
void SetInstanceTransform(UsdInstanceHandle instance, const float* transform, bool timeVarying, double timeStep);
void SetGeometryData(UsdGeometryHandle geometry, const UsdBridgeMeshData& meshData, double timeStep);
void SetGeometryData(UsdGeometryHandle geometry, const UsdBridgeInstancerData& instancerData, double timeStep);
void SetGeometryData(UsdGeometryHandle geometry, const UsdBridgeCurveData& curveData, double timeStep);
void SetSpatialFieldData(UsdSpatialFieldHandle field, const UsdBridgeVolumeData& volumeData, double timeStep);
void SetMaterialData(UsdMaterialHandle material, const UsdBridgeMaterialData& matData, double timeStep);
void SetSamplerData(UsdSamplerHandle sampler, const UsdBridgeSamplerData& samplerData, double timeStep);
void SetCameraData(UsdCameraHandle camera, const UsdBridgeCameraData& cameraData, double timeStep);
void SetPrototypeData(UsdGeometryHandle geometry, const UsdBridgeInstancerRefData& instancerRefData); // UsdBridgeInstancerRefData::Shapes used to index into refs from last SetPrototypeRefs (if SHAPE_MESH)
void ChangeMaterialInputAttributes(UsdMaterialHandle material, const MaterialInputAttribName* inputAttribs, size_t numInputAttribs, double timeStep, MaterialDMI timeVarying);
void ChangeInAttribute(UsdSamplerHandle sampler, const char* newName, double timeStep, SamplerDMI timeVarying);
void SaveScene();
void ResetResourceUpdateState(); // Eg. clears all dirty flags on shared resources
void GarbageCollect(); // Deletes all handles without parents (from Set<X>Refs)
const char* GetPrimPath(UsdBridgeHandle* handle);
//
// Static parameter interface
//
static void SetConnectionLogVerbosity(int logVerbosity); // 0 <= logVerbosity <= 4, 0 is quietest
protected:
template<typename GeomDataType>
bool CreateGeometryTemplate(const char* name, UsdGeometryHandle& handle, const GeomDataType& geomData);
template<typename GeomDataType>
void SetGeometryDataTemplate(UsdGeometryHandle geometry, const GeomDataType& geomData, double timeStep);
template<typename ParentHandleType, typename ChildHandleType>
void SetNoClipRefs(ParentHandleType parentHandle, const ChildHandleType* childHandles, uint64_t numChildren,
const char* refPathExt, bool timeVarying, double timeStep, bool instanceable = false);
template<typename ParentHandleType>
void DeleteAllRefs(ParentHandleType parentHandle, const char* refPathExt, bool timeVarying, double timeStep);
void CreateRootPrimAndAttach(UsdBridgePrimCache* cacheEntry, const char* primPathCp, const char* layerId = nullptr);
void RemoveRootPrimAndDetach(UsdBridgePrimCache* cacheEntry, const char* primPathCp);
UsdBridgeInternals* Internals;
bool EnableSaving;
bool SessionValid;
};
#endif
| 7,571 | C | 57.246153 | 209 | 0.799498 |
NVIDIA-Omniverse/AnariUsdDevice/UsdBridge/UsdBridgeDiagnosticMgrDelegate.h | // Copyright 2020 The Khronos Group
// SPDX-License-Identifier: Apache-2.0
#ifndef UsdBridgeDiagnosticMgrDelegate_h
#define UsdBridgeDiagnosticMgrDelegate_h
#include "UsdBridgeData.h"
#include "usd.h"
PXR_NAMESPACE_USING_DIRECTIVE
class UsdBridgeDiagnosticMgrDelegate : public TfDiagnosticMgr::Delegate
{
public:
UsdBridgeDiagnosticMgrDelegate(void* logUserData,
UsdBridgeLogCallback logCallback);
void IssueError(TfError const& err) override;
void IssueFatalError(TfCallContext const& context,
std::string const& msg) override;
void IssueStatus(TfStatus const& status) override;
void IssueWarning(TfWarning const& warning) override;
static void SetOutputEnabled(bool enable){ OutputEnabled = enable; }
protected:
void LogTfMessage(UsdBridgeLogLevel level, TfDiagnosticBase const& diagBase);
void LogMessage(UsdBridgeLogLevel level, const std::string& message);
void* LogUserData;
UsdBridgeLogCallback LogCallback;
static bool OutputEnabled;
};
#endif | 1,026 | C | 24.674999 | 81 | 0.769981 |
NVIDIA-Omniverse/AnariUsdDevice/UsdBridge/usd.h | // Copyright 2020 The Khronos Group
// SPDX-License-Identifier: Apache-2.0
#pragma once
#pragma warning(push)
#pragma warning(disable:4244) // = Conversion from double to float / int to float
#pragma warning(disable:4305) // argument truncation from double to float
#pragma warning(disable:4800) // int to bool
#pragma warning(disable:4996) // call to std::copy with parameters that may be unsafe
#define NOMINMAX // Make sure nobody #defines min or max
// Python must be included first because it monkeys with macros that cause
// TBB to fail to compile in debug mode if TBB is included before Python
#include <boost/python/object.hpp>
#include <pxr/pxr.h>
#include <pxr/base/tf/token.h>
#include <pxr/base/tf/diagnosticMgr.h>
#include <pxr/base/trace/reporter.h>
#include <pxr/base/trace/trace.h>
#include <pxr/base/vt/array.h>
#include <pxr/base/gf/range3f.h>
#include <pxr/base/gf/rotation.h>
#include <pxr/usd/usd/attribute.h>
#include <pxr/usd/usd/notice.h>
#include <pxr/usd/usd/stage.h>
#include <pxr/usd/usd/primRange.h>
#include <pxr/usd/usd/modelAPI.h>
#include <pxr/usd/usd/clipsAPI.h>
#include <pxr/usd/usd/inherits.h>
#include <pxr/usd/usdGeom/mesh.h>
#include <pxr/usd/usdGeom/points.h>
#include <pxr/usd/usdGeom/sphere.h>
#include <pxr/usd/usdGeom/cylinder.h>
#include <pxr/usd/usdGeom/cone.h>
#include <pxr/usd/usdGeom/xform.h>
#include <pxr/usd/usdGeom/pointInstancer.h>
#include <pxr/usd/usdGeom/primvarsAPI.h>
#include <pxr/usd/usdGeom/basisCurves.h>
#include <pxr/usd/usdGeom/camera.h>
#include <pxr/usd/usdGeom/scope.h>
#include <pxr/usd/usdVol/volume.h>
#include <pxr/usd/usdVol/openVDBAsset.h>
#include <pxr/usd/sdf/layer.h>
#include <pxr/usd/sdf/path.h>
#include <pxr/usd/usdShade/material.h>
#include <pxr/usd/usdShade/materialBindingAPI.h>
#include <pxr/usd/kind/registry.h>
#pragma warning(pop)
| 1,825 | C | 36.265305 | 85 | 0.753425 |
NVIDIA-Omniverse/AnariUsdDevice/UsdBridge/UsdBridgeUsdWriter.cpp | // Copyright 2020 The Khronos Group
// SPDX-License-Identifier: Apache-2.0
#include "UsdBridgeUsdWriter.h"
#include "UsdBridgeCaches.h"
#include "UsdBridgeMdlStrings.h"
#include "UsdBridgeUsdWriter_Common.h"
#include "UsdBridgeDiagnosticMgrDelegate.h"
TF_DEFINE_PUBLIC_TOKENS(
UsdBridgeTokens,
ATTRIB_TOKEN_SEQ
USDPREVSURF_TOKEN_SEQ
USDPREVSURF_INPUT_TOKEN_SEQ
MDL_TOKEN_SEQ
MDL_INPUT_TOKEN_SEQ
VOLUME_TOKEN_SEQ
INDEX_TOKEN_SEQ
MISC_TOKEN_SEQ
);
namespace constring
{
const char* const sessionPf = "Session_";
const char* const rootClassName = "/RootClass";
const char* const rootPrimName = "/Root";
const char* const manifestFolder = "manifests/";
const char* const clipFolder = "clips/";
const char* const primStageFolder = "primstages/";
const char* const imgFolder = "images/";
const char* const volFolder = "volumes/";
const char* const texCoordReaderPrimPf = "texcoordreader";
const char* const psShaderPrimPf = "psshader";
const char* const mdlShaderPrimPf = "mdlshader";
const char* const psSamplerPrimPf = "pssampler";
const char* const mdlSamplerPrimPf = "mdlsampler";
const char* const mdlOpacityMulPrimPf = "opacitymul_mdl";
const char* const mdlDiffuseOpacityPrimPf = "diffuseopacity_mdl";
const char* const mdlGraphXYZPrimPf = "_xyz_f";
const char* const mdlGraphColorPrimPf = "_ftocolor";
const char* const mdlGraphXPrimPf = "_x";
const char* const mdlGraphYPrimPf = "_y";
const char* const mdlGraphZPrimPf = "_z";
const char* const mdlGraphWPrimPf = "_w";
const char* const openVDBPrimPf = "ovdbfield";
const char* const protoShapePf = "proto_";
const char* const imageExtension = ".png";
const char* const vdbExtension = ".vdb";
const char* const fullSceneNameBin = "FullScene.usd";
const char* const fullSceneNameAscii = "FullScene.usda";
const char* const mdlShaderAssetName = "OmniPBR.mdl";
const char* const mdlSupportAssetName = "nvidia/support_definitions.mdl";
const char* const mdlAuxAssetName = "nvidia/aux_definitions.mdl";
#ifdef CUSTOM_PBR_MDL
const char* const mdlFolder = "mdls/";
const char* const opaqueMaterialFile = "PBR_Opaque.mdl";
const char* const transparentMaterialFile = "PBR_Transparent.mdl";
#endif
#ifdef USE_INDEX_MATERIALS
const char* const indexMaterialPf = "indexmaterial";
const char* const indexShaderPf = "indexshader";
const char* const indexColorMapPf = "indexcolormap";
#endif
}
#define ATTRIB_TOKENS_ADD(r, data, elem) AttributeTokens.push_back(UsdBridgeTokens->elem);
UsdBridgeUsdWriter::UsdBridgeUsdWriter(const UsdBridgeSettings& settings)
: Settings(settings)
, VolumeWriter(Create_VolumeWriter(), std::mem_fn(&UsdBridgeVolumeWriterI::Release))
{
// Initialize AttributeTokens with common known attribute names
BOOST_PP_SEQ_FOR_EACH(ATTRIB_TOKENS_ADD, ~, ATTRIB_TOKEN_SEQ)
if(Settings.HostName)
ConnectionSettings.HostName = Settings.HostName;
if(Settings.OutputPath)
ConnectionSettings.WorkingDirectory = Settings.OutputPath;
FormatDirName(ConnectionSettings.WorkingDirectory);
}
UsdBridgeUsdWriter::~UsdBridgeUsdWriter()
{
}
void UsdBridgeUsdWriter::SetExternalSceneStage(UsdStageRefPtr sceneStage)
{
this->ExternalSceneStage = sceneStage;
}
void UsdBridgeUsdWriter::SetEnableSaving(bool enableSaving)
{
this->EnableSaving = enableSaving;
}
int UsdBridgeUsdWriter::FindSessionNumber()
{
int sessionNr = Connect->MaxSessionNr();
sessionNr = std::max(0, sessionNr + Settings.CreateNewSession);
return sessionNr;
}
bool UsdBridgeUsdWriter::CreateDirectories()
{
bool valid = true;
valid = Connect->CreateFolder("", true, true);
//Connect->RemoveFolder(SessionDirectory.c_str(), true, true);
bool folderMayExist = !Settings.CreateNewSession;
valid = valid && Connect->CreateFolder(SessionDirectory.c_str(), true, folderMayExist);
#ifdef VALUE_CLIP_RETIMING
valid = valid && Connect->CreateFolder((SessionDirectory + constring::manifestFolder).c_str(), true, folderMayExist);
valid = valid && Connect->CreateFolder((SessionDirectory + constring::primStageFolder).c_str(), true, folderMayExist);
#endif
#ifdef TIME_CLIP_STAGES
valid = valid && Connect->CreateFolder((SessionDirectory + constring::clipFolder).c_str(), true, folderMayExist);
#endif
#ifdef CUSTOM_PBR_MDL
if(Settings.EnableMdlShader)
{
valid = valid && Connect->CreateFolder((SessionDirectory + constring::mdlFolder).c_str(), true, folderMayExist);
}
#endif
valid = valid && Connect->CreateFolder((SessionDirectory + constring::imgFolder).c_str(), true, folderMayExist);
valid = valid && Connect->CreateFolder((SessionDirectory + constring::volFolder).c_str(), true, folderMayExist);
if (!valid)
{
UsdBridgeLogMacro(this->LogObject, UsdBridgeLogLevel::ERR, "Something went wrong in the filesystem creating the required output folders (permissions?).");
}
return valid;
}
#ifdef CUSTOM_PBR_MDL
namespace
{
void WriteMdlFromStrings(const char* string0, const char* string1, const char* fileName, const UsdBridgeConnection* Connect)
{
size_t strLen0 = std::strlen(string0);
size_t strLen1 = std::strlen(string1);
size_t totalStrLen = strLen0 + strLen1;
char* Mdl_Contents = new char[totalStrLen];
std::memcpy(Mdl_Contents, string0, strLen0);
std::memcpy(Mdl_Contents + strLen0, string1, strLen1);
Connect->WriteFile(Mdl_Contents, totalStrLen, fileName, true, false);
delete[] Mdl_Contents;
}
}
bool UsdBridgeUsdWriter::CreateMdlFiles()
{
//Write PBR opacity file contents
{
std::string relMdlPath = constring::mdlFolder + std::string(constring::opaqueMaterialFile);
this->MdlOpaqueRelFilePath = SdfAssetPath(relMdlPath);
std::string mdlFileName = SessionDirectory + relMdlPath;
WriteMdlFromStrings(Mdl_PBRBase_string, Mdl_PBRBase_string_opaque, mdlFileName.c_str(), Connect.get());
}
{
std::string relMdlPath = constring::mdlFolder + std::string(constring::transparentMaterialFile);
this->MdlTranslucentRelFilePath = SdfAssetPath(relMdlPath);
std::string mdlFileName = SessionDirectory + relMdlPath;
WriteMdlFromStrings(Mdl_PBRBase_string, Mdl_PBRBase_string_translucent, mdlFileName.c_str(), Connect.get());
}
return true;
}
#endif
bool UsdBridgeUsdWriter::InitializeSession()
{
if (ConnectionSettings.HostName.empty())
{
if(ConnectionSettings.WorkingDirectory.compare("void") == 0)
Connect = std::make_unique<UsdBridgeVoidConnection>();
else
Connect = std::make_unique<UsdBridgeLocalConnection>();
}
else
Connect = std::make_unique<UsdBridgeRemoteConnection>();
Connect->Initialize(ConnectionSettings, this->LogObject);
SessionNumber = FindSessionNumber();
SessionDirectory = constring::sessionPf + std::to_string(SessionNumber) + "/";
bool valid = true;
valid = CreateDirectories();
valid = valid && VolumeWriter->Initialize(this->LogObject);
#ifdef CUSTOM_PBR_MDL
if(Settings.EnableMdlShader)
{
valid = valid && CreateMdlFiles();
}
#endif
return valid;
}
void UsdBridgeUsdWriter::ResetSession()
{
this->SessionNumber = -1;
this->SceneStage = nullptr;
}
bool UsdBridgeUsdWriter::OpenSceneStage()
{
bool binary = this->Settings.BinaryOutput;
this->SceneFileName = this->SessionDirectory;
this->SceneFileName += (binary ? constring::fullSceneNameBin : constring::fullSceneNameAscii);
#ifdef REPLACE_SCENE_BY_EXTERNAL_STAGE
if (this->ExternalSceneStage)
{
this->SceneStage = this->ExternalSceneStage;
}
#endif
const char* absSceneFile = Connect->GetUrl(this->SceneFileName.c_str());
if (!this->SceneStage && !Settings.CreateNewSession)
this->SceneStage = UsdStage::Open(absSceneFile);
if (!this->SceneStage)
this->SceneStage = UsdStage::CreateNew(absSceneFile);
if (!this->SceneStage)
{
UsdBridgeLogMacro(this->LogObject, UsdBridgeLogLevel::ERR, "Scene UsdStage cannot be created or opened. Maybe a filesystem issue?");
return false;
}
#ifndef REPLACE_SCENE_BY_EXTERNAL_STAGE
else if (this->ExternalSceneStage)
{
// Set the scene stage as a sublayer of the external stage
ExternalSceneStage->GetRootLayer()->InsertSubLayerPath(
this->SceneStage->GetRootLayer()->GetIdentifier());
}
#endif
this->RootClassName = constring::rootClassName;
UsdPrim rootClassPrim = this->SceneStage->CreateClassPrim(SdfPath(this->RootClassName));
assert(rootClassPrim);
this->RootName = constring::rootPrimName;
UsdPrim rootPrim = this->SceneStage->DefinePrim(SdfPath(this->RootName));
assert(rootPrim);
#ifndef REPLACE_SCENE_BY_EXTERNAL_STAGE
if (!this->ExternalSceneStage)
#endif
{
this->SceneStage->SetDefaultPrim(rootPrim);
UsdModelAPI(rootPrim).SetKind(KindTokens->assembly);
}
if(!this->SceneStage->HasAuthoredTimeCodeRange())
{
this->SceneStage->SetStartTimeCode(StartTime);
this->SceneStage->SetEndTimeCode(EndTime);
}
else
{
StartTime = this->SceneStage->GetStartTimeCode();
EndTime = this->SceneStage->GetEndTimeCode();
}
if(this->EnableSaving)
this->SceneStage->Save();
return true;
}
UsdStageRefPtr UsdBridgeUsdWriter::GetSceneStage() const
{
return this->SceneStage;
}
UsdStageRefPtr UsdBridgeUsdWriter::GetTimeVarStage(UsdBridgePrimCache* cache
#ifdef TIME_CLIP_STAGES
, bool useClipStage, const char* clipPf, double timeStep
, std::function<void (UsdStageRefPtr)> initFunc
#endif
) const
{
#ifdef VALUE_CLIP_RETIMING
#ifdef TIME_CLIP_STAGES
if (useClipStage)
{
bool exists;
UsdStageRefPtr clipStage = this->FindOrCreateClipStage(cache, clipPf, timeStep, exists).second;
if(!exists)
initFunc(clipStage);
return clipStage;
}
else
return cache->GetPrimStagePair().second;
#else
return cache->GetPrimStagePair().second;
#endif
#else
return this->SceneStage;
#endif
}
#ifdef VALUE_CLIP_RETIMING
void UsdBridgeUsdWriter::CreateManifestStage(const char* name, const char* primPostfix, UsdBridgePrimCache* cacheEntry)
{
bool binary = this->Settings.BinaryOutput;
cacheEntry->ManifestStage.first = constring::manifestFolder + std::string(name) + primPostfix + (binary ? ".usd" : ".usda");
std::string absoluteFileName = Connect->GetUrl((this->SessionDirectory + cacheEntry->ManifestStage.first).c_str());
UsdBridgeDiagnosticMgrDelegate::SetOutputEnabled(false);
cacheEntry->ManifestStage.second = UsdStage::CreateNew(absoluteFileName);
UsdBridgeDiagnosticMgrDelegate::SetOutputEnabled(true);
if (!cacheEntry->ManifestStage.second)
cacheEntry->ManifestStage.second = UsdStage::Open(absoluteFileName);
assert(cacheEntry->ManifestStage.second);
cacheEntry->ManifestStage.second->DefinePrim(SdfPath(this->RootClassName));
}
void UsdBridgeUsdWriter::RemoveManifestAndClipStages(const UsdBridgePrimCache* cacheEntry)
{
// May be superfluous
if(cacheEntry->ManifestStage.second)
{
cacheEntry->ManifestStage.second->RemovePrim(SdfPath(RootClassName));
// Remove ManifestStage file itself
assert(!cacheEntry->ManifestStage.first.empty());
Connect->RemoveFile((SessionDirectory + cacheEntry->ManifestStage.first).c_str(), true);
}
// remove all clipstage files
for (auto& x : cacheEntry->ClipStages)
{
Connect->RemoveFile((SessionDirectory + x.second.first).c_str(), true);
}
}
const UsdStagePair& UsdBridgeUsdWriter::FindOrCreatePrimStage(UsdBridgePrimCache* cacheEntry, const char* namePostfix) const
{
bool exists;
return FindOrCreatePrimClipStage(cacheEntry, namePostfix, false, UsdBridgePrimCache::PrimStageTimeCode, exists);
}
const UsdStagePair& UsdBridgeUsdWriter::FindOrCreateClipStage(UsdBridgePrimCache* cacheEntry, const char* namePostfix, double timeStep, bool& exists) const
{
return FindOrCreatePrimClipStage(cacheEntry, namePostfix, true, timeStep, exists);
}
const UsdStagePair& UsdBridgeUsdWriter::FindOrCreatePrimClipStage(UsdBridgePrimCache* cacheEntry, const char* namePostfix, bool isClip, double timeStep, bool& exists) const
{
exists = true;
bool binary = this->Settings.BinaryOutput;
auto it = cacheEntry->ClipStages.find(timeStep);
if (it == cacheEntry->ClipStages.end())
{
// Create a new Clipstage
const char* folder = constring::primStageFolder;
std::string fullNamePostfix(namePostfix);
if(isClip)
{
folder = constring::clipFolder;
fullNamePostfix += std::to_string(timeStep);
}
std::string relativeFileName = folder + cacheEntry->Name.GetString() + fullNamePostfix + (binary ? ".usd" : ".usda");
std::string absoluteFileName = Connect->GetUrl((this->SessionDirectory + relativeFileName).c_str());
UsdBridgeDiagnosticMgrDelegate::SetOutputEnabled(false);
UsdStageRefPtr primClipStage = UsdStage::CreateNew(absoluteFileName);
UsdBridgeDiagnosticMgrDelegate::SetOutputEnabled(true);
exists = !primClipStage;
SdfPath rootPrimPath(this->RootClassName);
if (exists)
{
primClipStage = UsdStage::Open(absoluteFileName); //Could happen if written folder is reused
assert(primClipStage->GetPrimAtPath(rootPrimPath));
}
else
primClipStage->DefinePrim(rootPrimPath);
it = cacheEntry->ClipStages.emplace(timeStep, UsdStagePair(std::move(relativeFileName), primClipStage)).first;
}
return it->second;
}
#endif
void UsdBridgeUsdWriter::AddRootPrim(UsdBridgePrimCache* primCache, const char* primPathCp, const char* layerId)
{
SdfPath primPath(this->RootName + "/" + primPathCp);
primPath = primPath.AppendPath(primCache->Name);
UsdPrim sceneGraphPrim = SceneStage->DefinePrim(primPath);
assert(sceneGraphPrim);
UsdReferences primRefs = sceneGraphPrim.GetReferences();
primRefs.ClearReferences();
#ifdef VALUE_CLIP_RETIMING
if(layerId)
{
primRefs.AddReference(layerId, primCache->PrimPath);
}
#endif
// Always add a ref to the internal prim, which is represented by the cache
primRefs.AddInternalReference(primCache->PrimPath);
}
void UsdBridgeUsdWriter::RemoveRootPrim(UsdBridgePrimCache* primCache, const char* primPathCp)
{
SdfPath primPath(this->RootName + "/" + primPathCp);
primPath = primPath.AppendPath(primCache->Name);
this->SceneStage->RemovePrim(primPath);
}
const std::string& UsdBridgeUsdWriter::CreatePrimName(const char * name, const char * category)
{
(this->TempNameStr = this->RootClassName).append("/").append(category).append("/").append(name);
return this->TempNameStr;
}
const std::string& UsdBridgeUsdWriter::GetResourceFileName(const std::string& basePath, double timeStep, const char* fileExtension)
{
this->TempNameStr = basePath;
#ifdef TIME_BASED_CACHING
this->TempNameStr += "_";
this->TempNameStr += std::to_string(timeStep);
#endif
this->TempNameStr += fileExtension;
return this->TempNameStr;
}
const std::string& UsdBridgeUsdWriter::GetResourceFileName(const char* folderName, const std::string& objectName, double timeStep, const char* fileExtension)
{
return GetResourceFileName(folderName + objectName, timeStep, fileExtension);
}
const std::string& UsdBridgeUsdWriter::GetResourceFileName(const char* folderName, const char* optionalObjectName, const std::string& defaultObjectName, double timeStep, const char* fileExtension)
{
return GetResourceFileName(folderName, (optionalObjectName ? std::string(optionalObjectName) : defaultObjectName), timeStep, fileExtension);
}
bool UsdBridgeUsdWriter::CreatePrim(const SdfPath& path)
{
UsdPrim classPrim = SceneStage->GetPrimAtPath(path);
if(!classPrim)
{
classPrim = SceneStage->DefinePrim(path);
assert(classPrim);
return true;
}
return false;
}
void UsdBridgeUsdWriter::DeletePrim(const UsdBridgePrimCache* cacheEntry)
{
if(SceneStage->GetPrimAtPath(cacheEntry->PrimPath))
SceneStage->RemovePrim(cacheEntry->PrimPath);
#ifdef VALUE_CLIP_RETIMING
RemoveManifestAndClipStages(cacheEntry);
#endif
}
#ifdef TIME_BASED_CACHING
void UsdBridgeUsdWriter::InitializePrimVisibility(UsdStageRefPtr stage, const SdfPath& primPath, const UsdTimeCode& timeCode,
UsdBridgePrimCache* parentCache, UsdBridgePrimCache* childCache)
{
UsdGeomImageable imageable = UsdGeomImageable::Get(stage, primPath);
if (imageable)
{
UsdAttribute visAttrib = imageable.GetVisibilityAttr(); // in case MakeVisible fails
if(!visAttrib)
visAttrib = imageable.CreateVisibilityAttr(VtValue(UsdGeomTokens->invisible)); // default is invisible
double startTime = stage->GetStartTimeCode();
double endTime = stage->GetEndTimeCode();
if (startTime < timeCode)
visAttrib.Set(VtValue(UsdGeomTokens->invisible), startTime);//imageable.MakeInvisible(startTime);
if (endTime > timeCode)
visAttrib.Set(VtValue(UsdGeomTokens->invisible), endTime);//imageable.MakeInvisible(endTime);
visAttrib.Set(VtValue(UsdGeomTokens->inherited), timeCode);//imageable.MakeVisible(timeCode);
parentCache->SetChildVisibleAtTime(childCache, timeCode.GetValue());
}
}
void UsdBridgeUsdWriter::SetPrimVisible(UsdStageRefPtr stage, const SdfPath& primPath, const UsdTimeCode& timeCode,
UsdBridgePrimCache* parentCache, UsdBridgePrimCache* childCache)
{
UsdGeomImageable imageable = UsdGeomImageable::Get(stage, primPath);
if (imageable)
{
UsdAttribute visAttrib = imageable.GetVisibilityAttr();
assert(visAttrib);
visAttrib.Set(VtValue(UsdGeomTokens->inherited), timeCode);//imageable.MakeVisible(timeCode);
parentCache->SetChildVisibleAtTime(childCache, timeCode.GetValue());
}
}
void UsdBridgeUsdWriter::PrimRemoveIfInvisibleAnytime(UsdStageRefPtr stage, const UsdPrim& prim, bool timeVarying, const UsdTimeCode& timeCode, AtRemoveRefFunc atRemoveRef,
UsdBridgePrimCache* parentCache, UsdBridgePrimCache* primCache)
{
const SdfPath& primPath = prim.GetPath();
bool removePrim = true; // TimeVarying is not automatically removed
if (timeVarying)
{
if(primCache)
{
// Remove prim only if there are no more visible children AND the timecode has actually been removed
// (so if the timecode wasn't found in the cache, do not remove the prim)
removePrim = parentCache->SetChildInvisibleAtTime(primCache, timeCode.GetValue());
// If prim is still visible at other times, make sure to explicitly set this timeCode as invisible
if(!removePrim)
{
UsdGeomImageable imageable = UsdGeomImageable::Get(stage, primPath);
if (imageable)
{
UsdAttribute visAttrib = imageable.GetVisibilityAttr();
if (visAttrib)
visAttrib.Set(UsdGeomTokens->invisible, timeCode);
}
}
}
else
removePrim = false; // If no cache is available, just don't remove, for possibility of previous timesteps (opposite from when !timeVarying)
}
if (removePrim)
{
// Decrease the ref on the representing cache entry
if(primCache)
atRemoveRef(parentCache, primCache);
// Remove the prim
stage->RemovePrim(primPath);
}
}
void UsdBridgeUsdWriter::ChildrenRemoveIfInvisibleAnytime(UsdStageRefPtr stage, UsdBridgePrimCache* parentCache, const SdfPath& parentPath, bool timeVarying, const UsdTimeCode& timeCode, AtRemoveRefFunc atRemoveRef, const SdfPath& exceptPath)
{
UsdPrim parentPrim = stage->GetPrimAtPath(parentPath);
if (parentPrim)
{
UsdPrimSiblingRange children = parentPrim.GetAllChildren();
for (UsdPrim child : children)
{
UsdBridgePrimCache* childCache = parentCache->GetChildCache(child.GetName());
if (child.GetPath() != exceptPath)
PrimRemoveIfInvisibleAnytime(stage, child, timeVarying, timeCode, atRemoveRef,
parentCache, childCache);
}
}
}
#endif
#ifdef VALUE_CLIP_RETIMING
void UsdBridgeUsdWriter::InitializeClipMetaData(const UsdPrim& clipPrim, UsdBridgePrimCache* childCache, double parentTimeStep, double childTimeStep, bool clipStages, const char* clipPostfix)
{
UsdClipsAPI clipsApi(clipPrim);
clipsApi.SetClipPrimPath(childCache->PrimPath.GetString());
const std::string& manifestPath = childCache->ManifestStage.first;
const std::string* refStagePath;
#ifdef TIME_CLIP_STAGES
if (clipStages)
{
//set interpolatemissingclipvalues?
bool exists;
const UsdStagePair& childStagePair = FindOrCreateClipStage(childCache, clipPostfix, childTimeStep, exists);
//assert(exists); // In case prim creation succeeds but an update is not attempted, no clip stage is generated, so exists will be false
if(!exists)
UsdBridgeLogMacro(this->LogObject, UsdBridgeLogLevel::WARNING, "Child clip stage not found while setting clip metadata, using generated stage instead. Probably the child data has not been properly updated.");
refStagePath = &childStagePair.first;
}
else
#endif
{
refStagePath = &childCache->GetPrimStagePair().first;
}
clipsApi.SetClipManifestAssetPath(SdfAssetPath(manifestPath));
VtArray<SdfAssetPath> assetPaths;
assetPaths.push_back(SdfAssetPath(*refStagePath));
clipsApi.SetClipAssetPaths(assetPaths);
VtVec2dArray clipActives;
clipActives.push_back(GfVec2d(parentTimeStep, 0));
clipsApi.SetClipActive(clipActives);
VtVec2dArray clipTimes;
clipTimes.push_back(GfVec2d(parentTimeStep, childTimeStep));
clipsApi.SetClipTimes(clipTimes);
}
void UsdBridgeUsdWriter::UpdateClipMetaData(const UsdPrim& clipPrim, UsdBridgePrimCache* childCache, double parentTimeStep, double childTimeStep, bool clipStages, const char* clipPostfix)
{
// Add parent-child timestep or update existing relationship
UsdClipsAPI clipsApi(clipPrim);
#ifdef TIME_CLIP_STAGES
if (clipStages)
{
bool exists;
const UsdStagePair& childStagePair = FindOrCreateClipStage(childCache, clipPostfix, childTimeStep, exists);
// At this point, exists should be true, but if clip stage creation failed earlier due to user error,
// exists will be false and we'll just link to the empty new stage created by FindOrCreatePrimClipStage()
const std::string& refStagePath = childStagePair.first;
VtVec2dArray clipActives;
clipsApi.GetClipActive(&clipActives);
VtArray<SdfAssetPath> assetPaths;
clipsApi.GetClipAssetPaths(&assetPaths);
// Find the asset path
SdfAssetPath refStageSdf(refStagePath);
auto assetIt = std::find_if(assetPaths.begin(), assetPaths.end(), [&refStageSdf](const SdfAssetPath& entry) -> bool { return refStageSdf.GetAssetPath() == entry.GetAssetPath(); });
int assetIndex = int(assetIt - assetPaths.begin());
bool newAsset = (assetIndex == assetPaths.size()); // Gives the opportunity to garbage collect unused asset references
{
// Find the parentTimeStep
int timeFindIdx = 0;
for (; timeFindIdx < clipActives.size() && clipActives[timeFindIdx][0] != parentTimeStep; ++timeFindIdx)
{}
bool replaceAsset = false;
// If timestep not found, just add (time, asset ref idx) to actives
if (timeFindIdx == clipActives.size())
clipActives.push_back(GfVec2d(parentTimeStep, assetIndex));
else
{
// Find out whether to update existing active entry with new asset ref idx, or let the entry unchanged and replace the asset itself
double prevAssetIndex = clipActives[timeFindIdx][1];
if (newAsset)
{
//Find prev asset index
int assetIdxFindIdx = 0;
for (; assetIdxFindIdx < clipActives.size() &&
(assetIdxFindIdx == timeFindIdx || clipActives[assetIdxFindIdx][1] != prevAssetIndex);
++assetIdxFindIdx)
{}
// replacement occurs when prevAssetIndex hasn't been found in other entries
replaceAsset = (assetIdxFindIdx == clipActives.size());
}
if(replaceAsset)
assetPaths[int(prevAssetIndex)] = refStageSdf;
else
clipActives[timeFindIdx][1] = assetIndex;
}
// If new asset and not put in place of an old asset, add to assetPaths
if (newAsset && !replaceAsset)
assetPaths.push_back(refStageSdf);
// Send the result through to usd
clipsApi.SetClipAssetPaths(assetPaths);
clipsApi.SetClipActive(clipActives);
}
}
#endif
// Find the parentTimeStep, and change its child (or add the pair if nonexistent)
VtVec2dArray clipTimes;
clipsApi.GetClipTimes(&clipTimes);
{
int findIdx = 0;
for (; findIdx < clipTimes.size(); ++findIdx)
{
if (clipTimes[findIdx][0] == parentTimeStep)
{
clipTimes[findIdx][1] = childTimeStep;
break;
}
}
if (findIdx == clipTimes.size())
clipTimes.push_back(GfVec2d(parentTimeStep, childTimeStep));
clipsApi.SetClipTimes(clipTimes);
}
}
#endif
SdfPath UsdBridgeUsdWriter::AddRef_NoClip(UsdBridgePrimCache* parentCache, UsdBridgePrimCache* childCache, const char* refPathExt,
bool timeVarying, double parentTimeStep, bool instanceable,
const RefModFuncs& refModCallbacks)
{
return AddRef_Impl(parentCache, childCache, refPathExt, timeVarying, false, false, nullptr, parentTimeStep, parentTimeStep, instanceable, refModCallbacks);
}
SdfPath UsdBridgeUsdWriter::AddRef(UsdBridgePrimCache* parentCache, UsdBridgePrimCache* childCache, const char* refPathExt,
bool timeVarying, bool valueClip, bool clipStages, const char* clipPostfix,
double parentTimeStep, double childTimeStep, bool instanceable,
const RefModFuncs& refModCallbacks)
{
// Value clip-enabled references have to be defined on the scenestage, as usd does not re-time recursively.
return AddRef_Impl(parentCache, childCache, refPathExt, timeVarying, valueClip, clipStages, clipPostfix, parentTimeStep, childTimeStep, instanceable, refModCallbacks);
}
SdfPath UsdBridgeUsdWriter::AddRef_Impl(UsdBridgePrimCache* parentCache, UsdBridgePrimCache* childCache, const char* refPathExt,
bool timeVarying, // Timevarying existence (visible or not) of the reference itself
bool valueClip, // Retiming through a value clip
bool clipStages, // Separate stages for separate time slots (can only exist in usd if valueClip enabled)
const char* clipPostfix, double parentTimeStep, double childTimeStep, bool instanceable,
const RefModFuncs& refModCallbacks)
{
UsdTimeCode parentTimeCode(parentTimeStep);
SdfPath childBasePath = parentCache->PrimPath;
if (refPathExt)
childBasePath = parentCache->PrimPath.AppendPath(SdfPath(refPathExt));
SdfPath referencingPrimPath = childBasePath.AppendPath(childCache->Name);
UsdPrim referencingPrim = SceneStage->GetPrimAtPath(referencingPrimPath);
if (!referencingPrim)
{
referencingPrim = SceneStage->DefinePrim(referencingPrimPath);
assert(referencingPrim);
#ifdef VALUE_CLIP_RETIMING
if (valueClip)
InitializeClipMetaData(referencingPrim, childCache, parentTimeStep, childTimeStep, clipStages, clipPostfix);
#endif
{
UsdReferences references = referencingPrim.GetReferences(); //references or inherits?
references.ClearReferences();
references.AddInternalReference(childCache->PrimPath);
//referencingPrim.SetInstanceable(true);
}
refModCallbacks.AtNewRef(parentCache, childCache);
#ifdef TIME_BASED_CACHING
// If time domain of the stage extends beyond timestep in either direction, set visibility false for extremes.
if (timeVarying)
InitializePrimVisibility(SceneStage, referencingPrimPath, parentTimeCode,
parentCache, childCache);
#endif
}
else
{
#ifdef TIME_BASED_CACHING
if (timeVarying)
SetPrimVisible(SceneStage, referencingPrimPath, parentTimeCode,
parentCache, childCache);
#ifdef VALUE_CLIP_RETIMING
// Cliptimes are added as additional info, not actively removed (visibility values remain leading in defining existing relationships over timesteps)
// Also, clip stages at childTimeSteps which are not referenced anymore, are not removed; they could still be referenced from other parents!
if (valueClip)
UpdateClipMetaData(referencingPrim, childCache, parentTimeStep, childTimeStep, clipStages, clipPostfix);
#endif
#endif
}
referencingPrim.SetInstanceable(instanceable);
return referencingPrimPath;
}
void UsdBridgeUsdWriter::RemoveAllRefs(UsdBridgePrimCache* parentCache, const char* refPathExt, bool timeVarying, double timeStep, AtRemoveRefFunc atRemoveRef)
{
SdfPath childBasePath = parentCache->PrimPath;
if (refPathExt)
childBasePath = parentCache->PrimPath.AppendPath(SdfPath(refPathExt));
RemoveAllRefs(SceneStage, parentCache, childBasePath, timeVarying, timeStep, atRemoveRef);
}
void UsdBridgeUsdWriter::RemoveAllRefs(UsdStageRefPtr stage, UsdBridgePrimCache* parentCache, SdfPath childBasePath, bool timeVarying, double timeStep, AtRemoveRefFunc atRemoveRef)
{
#ifdef TIME_BASED_CACHING
UsdTimeCode timeCode(timeStep);
// Make refs just for this timecode invisible and possibly remove,
// but leave refs which are still visible in other timecodes intact.
ChildrenRemoveIfInvisibleAnytime(stage, parentCache, childBasePath, timeVarying, timeCode, atRemoveRef);
#else
UsdPrim parentPrim = stage->GetPrimAtPath(childBasePath);
if(parentPrim)
{
UsdPrimSiblingRange children = parentPrim.GetAllChildren();
for (UsdPrim child : children)
{
UsdBridgePrimCache* childCache = parentCache->GetChildCache(child.GetName());
if(childCache)
{
atRemoveRef(parentCache, childCache); // Decrease reference count in caches
stage->RemovePrim(child.GetPath()); // Remove reference prim
}
}
}
#endif
}
void UsdBridgeUsdWriter::ManageUnusedRefs(UsdBridgePrimCache* parentCache, const UsdBridgePrimCacheList& newChildren, const char* refPathExt, bool timeVarying, double timeStep, AtRemoveRefFunc atRemoveRef)
{
ManageUnusedRefs(SceneStage, parentCache, newChildren, refPathExt, timeVarying, timeStep, atRemoveRef);
}
void UsdBridgeUsdWriter::ManageUnusedRefs(UsdStageRefPtr stage, UsdBridgePrimCache* parentCache, const UsdBridgePrimCacheList& newChildren, const char* refPathExt, bool timeVarying, double timeStep, AtRemoveRefFunc atRemoveRef)
{
UsdTimeCode timeCode(timeStep);
UsdPrim basePrim;
if (refPathExt)
{
SdfPath childBasePath = parentCache->PrimPath.AppendPath(SdfPath(refPathExt));
basePrim = stage->GetPrimAtPath(childBasePath);
}
else
basePrim = stage->GetPrimAtPath(parentCache->PrimPath);
if (basePrim)
{
// For each old (referencing) child prim, find it among the new ones, otherwise
// possibly delete the referencing prim.
UsdPrimSiblingRange children = basePrim.GetAllChildren();
for (UsdPrim oldChild : children)
{
bool found = false;
for (size_t newChildIdx = 0; newChildIdx < newChildren.size() && !found; ++newChildIdx)
{
found = (oldChild.GetName() == newChildren[newChildIdx]->PrimPath.GetNameToken());
}
UsdBridgePrimCache* oldChildCache = parentCache->GetChildCache(oldChild.GetName());
// Not an assert: allow the case where child prims in a stage aren't cached, ie. when the bridge is destroyed and recreated
if (!found)
#ifdef TIME_BASED_CACHING
{
// Remove *referencing* prim if no visible timecode exists anymore
PrimRemoveIfInvisibleAnytime(stage, oldChild, timeVarying, timeCode, atRemoveRef,
parentCache, oldChildCache);
}
#else
{// remove the whole referencing prim
if(oldChildCache)
atRemoveRef(parentCache, oldChildCache);
stage->RemovePrim(oldChild.GetPath());
}
#endif
}
}
}
void UsdBridgeUsdWriter::InitializeUsdTransform(const UsdBridgePrimCache* cacheEntry)
{
SdfPath transformPath = cacheEntry->PrimPath;
UsdGeomXform transform = GetOrDefinePrim<UsdGeomXform>(SceneStage, transformPath);
assert(transform);
}
void UsdBridgeUsdWriter::InitializeUsdCamera(UsdStageRefPtr cameraStage, const SdfPath& cameraPath)
{
UsdGeomCamera cameraPrim = GetOrDefinePrim<UsdGeomCamera>(cameraStage, cameraPath);
assert(cameraPrim);
cameraPrim.CreateProjectionAttr();
cameraPrim.CreateHorizontalApertureAttr();
cameraPrim.CreateVerticalApertureAttr();
cameraPrim.CreateFocalLengthAttr();
cameraPrim.CreateClippingRangeAttr();
}
void UsdBridgeUsdWriter::BindMaterialToGeom(const SdfPath & refGeomPath, const SdfPath & refMatPath)
{
UsdPrim refGeomPrim = this->SceneStage->GetPrimAtPath(refGeomPath);
assert(refGeomPrim);
// Bind the material to the mesh (use paths existing fully within the surface class definition, not the inherited geometry/material)
UsdShadeMaterial refMatPrim = UsdShadeMaterial::Get(this->SceneStage, refMatPath);
assert(refMatPrim);
UsdShadeMaterialBindingAPI(refGeomPrim).Bind(refMatPrim);
}
void UsdBridgeUsdWriter::UnbindMaterialFromGeom(const SdfPath & refGeomPath)
{
UsdPrim refGeomPrim = this->SceneStage->GetPrimAtPath(refGeomPath);
assert(refGeomPrim);
UsdShadeMaterialBindingAPI(refGeomPrim).UnbindDirectBinding();
}
void UsdBridgeUsdWriter::UpdateUsdTransform(const SdfPath& transPrimPath, const float* transform, bool timeVarying, double timeStep)
{
TimeEvaluator<bool> timeEval(timeVarying, timeStep);
// Note: USD employs left-multiplication (vector in row-space)
GfMatrix4d transMat; // Transforms can only be double, see UsdGeomXform::AddTransformOp (UsdGeomXformable)
transMat.SetRow(0, GfVec4d(GfVec4f(&transform[0])));
transMat.SetRow(1, GfVec4d(GfVec4f(&transform[4])));
transMat.SetRow(2, GfVec4d(GfVec4f(&transform[8])));
transMat.SetRow(3, GfVec4d(GfVec4f(&transform[12])));
//Note that instance transform nodes have already been created.
UsdGeomXform tfPrim = UsdGeomXform::Get(this->SceneStage, transPrimPath);
assert(tfPrim);
tfPrim.ClearXformOpOrder();
UsdGeomXformOp xformOp = tfPrim.AddTransformOp();
ClearAndSetUsdAttribute(xformOp.GetAttr(), transMat, timeEval.Eval(), !timeEval.TimeVarying);
}
void UsdBridgeUsdWriter::UpdateUsdCamera(UsdStageRefPtr timeVarStage, const SdfPath& cameraPrimPath,
const UsdBridgeCameraData& cameraData, double timeStep, bool timeVarHasChanged)
{
const TimeEvaluator<UsdBridgeCameraData> timeEval(cameraData, timeStep);
typedef UsdBridgeCameraData::DataMemberId DMI;
UsdGeomCamera cameraPrim = UsdGeomCamera::Get(timeVarStage, cameraPrimPath);
assert(cameraPrim);
// Set the view matrix
GfVec3d eyePoint(cameraData.Position.Data);
GfVec3d fwdDir(cameraData.Direction.Data);
GfVec3d upDir(cameraData.Up.Data);
GfVec3d lookAtPoint = eyePoint+fwdDir;
GfMatrix4d viewMatrix;
viewMatrix.SetLookAt(eyePoint, lookAtPoint, upDir);
cameraPrim.ClearXformOpOrder();
UsdGeomXformOp xformOp = cameraPrim.AddTransformOp();
ClearAndSetUsdAttribute(xformOp.GetAttr(), viewMatrix, timeEval.Eval(DMI::VIEW),
timeVarHasChanged && !timeEval.IsTimeVarying(DMI::VIEW));
// Helper function for the projection matrix
GfCamera gfCam;
gfCam.SetPerspectiveFromAspectRatioAndFieldOfView(cameraData.Aspect, cameraData.Fovy, GfCamera::FOVVertical);
// Update all attributes affected by SetPerspectiveFromAspectRatioAndFieldOfView (see implementation)
UsdTimeCode projectTime = timeEval.Eval(DMI::PROJECTION);
bool clearProjAttrib = timeVarHasChanged && !timeEval.IsTimeVarying(DMI::PROJECTION);
ClearAndSetUsdAttribute(cameraPrim.GetProjectionAttr(),
gfCam.GetProjection() == GfCamera::Perspective ?
UsdGeomTokens->perspective : UsdGeomTokens->orthographic,
projectTime, clearProjAttrib);
ClearAndSetUsdAttribute(cameraPrim.GetHorizontalApertureAttr(), gfCam.GetHorizontalAperture(), projectTime, clearProjAttrib);
ClearAndSetUsdAttribute(cameraPrim.GetVerticalApertureAttr(), gfCam.GetVerticalAperture(), projectTime, clearProjAttrib);
ClearAndSetUsdAttribute(cameraPrim.GetFocalLengthAttr(), gfCam.GetFocalLength(), projectTime, clearProjAttrib);
ClearAndSetUsdAttribute(cameraPrim.GetClippingRangeAttr(), GfVec2f(cameraData.Near, cameraData.Far), projectTime, clearProjAttrib);
}
void UsdBridgeUsdWriter::UpdateBeginEndTime(double timeStep)
{
if (timeStep < StartTime)
{
StartTime = timeStep;
SceneStage->SetStartTimeCode(timeStep);
}
if (timeStep > EndTime)
{
EndTime = timeStep;
SceneStage->SetEndTimeCode(timeStep);
}
}
TfToken& UsdBridgeUsdWriter::AttributeNameToken(const char* attribName)
{
int i = 0;
for(; i < AttributeTokens.size(); ++i)
{
if(AttributeTokens[i] == attribName) // Overloaded == operator on TfToken
break;
}
if(i == AttributeTokens.size())
AttributeTokens.emplace_back(TfToken(attribName));
return AttributeTokens[i];
}
void UsdBridgeUsdWriter::AddSharedResourceRef(const UsdBridgeResourceKey& key)
{
bool found = false;
for(auto& entry : SharedResourceCache)
{
if(entry.first == key)
{
++entry.second.first;
found = true;
}
}
if(!found)
SharedResourceCache.push_back(SharedResourceKV(key, SharedResourceValue(1, false)));
}
bool UsdBridgeUsdWriter::RemoveSharedResourceRef(const UsdBridgeResourceKey& key)
{
bool removed = false;
SharedResourceContainer::iterator it = SharedResourceCache.begin();
while(it != SharedResourceCache.end())
{
if(it->first == key)
--it->second.first;
if(it->second.first == 0)
{
it = SharedResourceCache.erase(it);
removed = true;
}
else
++it;
}
return removed;
}
bool UsdBridgeUsdWriter::SetSharedResourceModified(const UsdBridgeResourceKey& key)
{
bool modified = false;
for(auto& entry : SharedResourceCache)
{
if(entry.first == key)
{
modified = entry.second.second;
entry.second.second = true;
}
}
return modified;
}
void UsdBridgeUsdWriter::ResetSharedResourceModified()
{
for(auto& entry : SharedResourceCache)
{
entry.second.second = false;
}
}
void RemoveResourceFiles(UsdBridgePrimCache* cache, UsdBridgeUsdWriter& usdWriter,
const char* resourceFolder, const char* fileExtension)
{
// Directly from usd is inaccurate, as timesteps may have been cleared without file removal
//// Assuming prim without clip stages.
//const UsdStageRefPtr volumeStage = usdWriter.GetTimeVarStage(cache);
//const UsdStageRefPtr volumeStage = usdWriter.GetTimeVarStage(cache);
//const SdfPath& volPrimPath = cache->PrimPath;
//
//UsdVolVolume volume = UsdVolVolume::Get(volumeStage, volPrimPath);
//assert(volume);
//
//SdfPath ovdbFieldPath = volPrimPath.AppendPath(SdfPath(constring::openVDBPrimPf));
//UsdVolOpenVDBAsset ovdbField = UsdVolOpenVDBAsset::Get(volumeStage, ovdbFieldPath);
//
//UsdAttribute fileAttr = ovdbField.GetFilePathAttr();
//
//std::vector<double> fileTimes;
//fileAttr.GetTimeSamples(&fileTimes);
assert(cache->ResourceKeys);
UsdBridgePrimCache::ResourceContainer& keys = *(cache->ResourceKeys);
std::string basePath = usdWriter.SessionDirectory; basePath.append(resourceFolder);
for (const UsdBridgeResourceKey& key : keys)
{
bool removeFile = true;
if(key.name)
removeFile = usdWriter.RemoveSharedResourceRef(key);
if(removeFile)
{
double timeStep =
#ifdef TIME_BASED_CACHING
key.timeStep;
#else
0.0;
#endif
const std::string& resFileName = usdWriter.GetResourceFileName(basePath.c_str(), key.name, timeStep, fileExtension);
usdWriter.Connect->RemoveFile(resFileName.c_str(), true);
}
}
keys.resize(0);
} | 39,261 | C++ | 33.806738 | 242 | 0.744912 |
NVIDIA-Omniverse/AnariUsdDevice/UsdBridge/UsdBridgeUsdWriter.h | // Copyright 2020 The Khronos Group
// SPDX-License-Identifier: Apache-2.0
#ifndef UsdBridgeUsdWriter_h
#define UsdBridgeUsdWriter_h
#include "usd.h"
PXR_NAMESPACE_USING_DIRECTIVE
#include "UsdBridgeData.h"
#include "UsdBridgeCaches.h"
#include "UsdBridgeVolumeWriter.h"
#include "UsdBridgeConnection.h"
#include "UsdBridgeTimeEvaluator.h"
#include <memory>
#include <functional>
//Includes detailed usd translation interface of Usd Bridge
class UsdBridgeUsdWriter
{
public:
using MaterialDMI = UsdBridgeMaterialData::DataMemberId;
using SamplerDMI = UsdBridgeSamplerData::DataMemberId;
using AtNewRefFunc = std::function<void(UsdBridgePrimCache* parentCache, UsdBridgePrimCache* childCache)>;
using AtRemoveRefFunc = std::function<void(UsdBridgePrimCache* parentCache, UsdBridgePrimCache* childCache)>;
struct RefModFuncs
{
AtNewRefFunc AtNewRef;
AtRemoveRefFunc AtRemoveRef;
};
UsdBridgeUsdWriter(const UsdBridgeSettings& settings);
~UsdBridgeUsdWriter();
void SetExternalSceneStage(UsdStageRefPtr sceneStage);
void SetEnableSaving(bool enableSaving);
int FindSessionNumber();
bool CreateDirectories();
#ifdef CUSTOM_PBR_MDL
bool CreateMdlFiles();
#endif
bool InitializeSession();
void ResetSession();
bool OpenSceneStage();
UsdStageRefPtr GetSceneStage() const;
UsdStageRefPtr GetTimeVarStage(UsdBridgePrimCache* cache
#ifdef TIME_CLIP_STAGES
, bool useClipStage = false, const char* clipPf = nullptr, double timeStep = 0.0
, std::function<void (UsdStageRefPtr)> initFunc = [](UsdStageRefPtr){}
#endif
) const;
#ifdef VALUE_CLIP_RETIMING
void CreateManifestStage(const char* name, const char* primPostfix, UsdBridgePrimCache* cacheEntry);
void RemoveManifestAndClipStages(const UsdBridgePrimCache* cacheEntry);
const UsdStagePair& FindOrCreatePrimStage(UsdBridgePrimCache* cacheEntry, const char* namePostfix) const;
const UsdStagePair& FindOrCreateClipStage(UsdBridgePrimCache* cacheEntry, const char* namePostfix, double timeStep, bool& exists) const;
const UsdStagePair& FindOrCreatePrimClipStage(UsdBridgePrimCache* cacheEntry, const char* namePostfix, bool isClip, double timeStep, bool& exists) const;
#endif
void AddRootPrim(UsdBridgePrimCache* primCache, const char* primPathCp, const char* layerId = nullptr);
void RemoveRootPrim(UsdBridgePrimCache* primCache, const char* primPathCp);
const std::string& CreatePrimName(const char* name, const char* category);
const std::string& GetResourceFileName(const std::string& basePath, double timeStep, const char* fileExtension);
const std::string& GetResourceFileName(const char* folderName, const std::string& objectName, double timeStep, const char* fileExtension);
const std::string& GetResourceFileName(const char* folderName, const char* optionalObjectName, const std::string& defaultObjectName, double timeStep, const char* fileExtension);
bool CreatePrim(const SdfPath& path);
void DeletePrim(const UsdBridgePrimCache* cacheEntry);
#ifdef TIME_BASED_CACHING
void InitializePrimVisibility(UsdStageRefPtr stage, const SdfPath& primPath, const UsdTimeCode& timeCode,
UsdBridgePrimCache* parentCache, UsdBridgePrimCache* childCache);
void SetPrimVisible(UsdStageRefPtr stage, const SdfPath& primPath, const UsdTimeCode& timeCode,
UsdBridgePrimCache* parentCache, UsdBridgePrimCache* childCache);
void PrimRemoveIfInvisibleAnytime(UsdStageRefPtr stage, const UsdPrim& prim, bool timeVarying, const UsdTimeCode& timeCode, AtRemoveRefFunc atRemoveRef,
UsdBridgePrimCache* parentCache, UsdBridgePrimCache* primCache);
void ChildrenRemoveIfInvisibleAnytime(UsdStageRefPtr stage, UsdBridgePrimCache* parentCache, const SdfPath& parentPath, bool timeVarying, const UsdTimeCode& timeCode, AtRemoveRefFunc atRemoveRef, const SdfPath& exceptPath = SdfPath());
#endif
#ifdef VALUE_CLIP_RETIMING
void InitializeClipMetaData(const UsdPrim& clipPrim, UsdBridgePrimCache* childCache, double parentTimeStep, double childTimeStep, bool clipStages, const char* clipPostfix);
void UpdateClipMetaData(const UsdPrim& clipPrim, UsdBridgePrimCache* childCache, double parentTimeStep, double childTimeStep, bool clipStages, const char* clipPostfix);
#endif
SdfPath AddRef_NoClip(UsdBridgePrimCache* parentCache, UsdBridgePrimCache* childCache, const char* refPathExt,
bool timeVarying, double parentTimeStep, bool instanceable,
const RefModFuncs& refModCallbacks);
SdfPath AddRef(UsdBridgePrimCache* parentCache, UsdBridgePrimCache* childCache, const char* refPathExt,
bool timeVarying, bool valueClip, bool clipStages, const char* clipPostFix,
double parentTimeStep, double childTimeStep, bool instanceable,
const RefModFuncs& refModCallbacks);
// Timevarying means that the existence of a reference between prim A and B can differ over time, valueClip denotes the addition of clip metadata for re-timing,
// and clipStages will carve up the referenced clip asset files into one for each timestep (stages are created as necessary). clipPostFix is irrelevant if !clipStages.
// Returns the path to the parent's subprim which represents/holds the reference to the child's main class prim.
SdfPath AddRef_Impl(UsdBridgePrimCache* parentCache, UsdBridgePrimCache* childCache, const char* refPathExt,
bool timeVarying, bool valueClip, bool clipStages, const char* clipPostFix,
double parentTimeStep, double childTimeStep, bool instanceable,
const RefModFuncs& refModCallbacks);
void RemoveAllRefs(UsdBridgePrimCache* parentCache, const char* refPathExt, bool timeVarying, double timeStep, AtRemoveRefFunc atRemoveRef);
void RemoveAllRefs(UsdStageRefPtr stage, UsdBridgePrimCache* parentCache, SdfPath childBasePath, bool timeVarying, double timeStep, AtRemoveRefFunc atRemoveRef);
void ManageUnusedRefs(UsdBridgePrimCache* parentCache, const UsdBridgePrimCacheList& newChildren, const char* refPathExt, bool timeVarying, double timeStep, AtRemoveRefFunc atRemoveRef);
void ManageUnusedRefs(UsdStageRefPtr stage, UsdBridgePrimCache* parentCache, const UsdBridgePrimCacheList& newChildren, const char* refPathExt, bool timeVarying, double timeStep, AtRemoveRefFunc atRemoveRef);
void InitializeUsdTransform(const UsdBridgePrimCache* cacheEntry);
UsdPrim InitializeUsdGeometry(UsdStageRefPtr geometryStage, const SdfPath& geomPath, const UsdBridgeMeshData& meshData, bool uniformPrim);
UsdPrim InitializeUsdGeometry(UsdStageRefPtr geometryStage, const SdfPath& geomPath, const UsdBridgeInstancerData& instancerData, bool uniformPrim);
UsdPrim InitializeUsdGeometry(UsdStageRefPtr geometryStage, const SdfPath& geomPath, const UsdBridgeCurveData& curveData, bool uniformPrim);
UsdPrim InitializeUsdVolume(UsdStageRefPtr volumeStage, const SdfPath& volumePath, bool uniformPrim) const;
UsdShadeMaterial InitializeUsdMaterial(UsdStageRefPtr materialStage, const SdfPath& matPrimPath, bool uniformPrim) const;
void InitializeUsdSampler(UsdStageRefPtr samplerStage,const SdfPath& samplerPrimPath, UsdBridgeSamplerData::SamplerType type, bool uniformPrim) const;
void InitializeUsdCamera(UsdStageRefPtr cameraStage, const SdfPath& geomPath);
UsdShadeShader GetOrCreateAttributeReader() const;
#ifdef USE_INDEX_MATERIALS
UsdShadeMaterial InitializeIndexVolumeMaterial_Impl(UsdStageRefPtr volumeStage,
const SdfPath& volumePath, bool uniformPrim, const UsdBridgeTimeEvaluator<UsdBridgeVolumeData>* timeEval = nullptr) const;
#endif
#ifdef VALUE_CLIP_RETIMING
void UpdateUsdGeometryManifest(const UsdBridgePrimCache* cacheEntry, const UsdBridgeMeshData& meshData);
void UpdateUsdGeometryManifest(const UsdBridgePrimCache* cacheEntry, const UsdBridgeInstancerData& instancerData);
void UpdateUsdGeometryManifest(const UsdBridgePrimCache* cacheEntry, const UsdBridgeCurveData& curveData);
void UpdateUsdVolumeManifest(const UsdBridgePrimCache* cacheEntry, const UsdBridgeVolumeData& volumeData);
void UpdateUsdMaterialManifest(const UsdBridgePrimCache* cacheEntry, const UsdBridgeMaterialData& matData);
void UpdateUsdSamplerManifest(const UsdBridgePrimCache* cacheEntry, const UsdBridgeSamplerData& samplerData);
#endif
void BindMaterialToGeom(const SdfPath& refGeomPath, const SdfPath& refMatPath);
void ConnectSamplersToMaterial(UsdStageRefPtr materialStage, const SdfPath& matPrimPath, const SdfPrimPathList& refSamplerPrimPaths,
const UsdBridgePrimCacheList& samplerCacheEntries, const UsdSamplerRefData* samplerRefDatas, size_t numSamplers, double worldTimeStep); // Disconnect happens automatically at parameter overwrite
void UnbindMaterialFromGeom(const SdfPath & refGeomPath);
void UpdateUsdTransform(const SdfPath& transPrimPath, const float* transform, bool timeVarying, double timeStep);
void UpdateUsdGeometry(const UsdStagePtr& timeVarStage, const SdfPath& meshPath, const UsdBridgeMeshData& geomData, double timeStep);
void UpdateUsdGeometry(const UsdStagePtr& timeVarStage, const SdfPath& instancerPath, const UsdBridgeInstancerData& geomData, double timeStep);
void UpdateUsdGeometry(const UsdStagePtr& timeVarStage, const SdfPath& curvePath, const UsdBridgeCurveData& geomData, double timeStep);
void UpdateUsdMaterial(UsdStageRefPtr timeVarStage, const SdfPath& matPrimPath, const UsdBridgeMaterialData& matData, const UsdGeomPrimvarsAPI& boundGeomPrimvars, double timeStep);
void UpdatePsShader(UsdStageRefPtr timeVarStage, const SdfPath& matPrimPath, const UsdBridgeMaterialData& matData, const UsdGeomPrimvarsAPI& boundGeomPrimvars, double timeStep);
void UpdateMdlShader(UsdStageRefPtr timeVarStage, const SdfPath& matPrimPath, const UsdBridgeMaterialData& matData, const UsdGeomPrimvarsAPI& boundGeomPrimvars, double timeStep);
void UpdateUsdVolume(UsdStageRefPtr timeVarStage, UsdBridgePrimCache* cacheEntry, const UsdBridgeVolumeData& volumeData, double timeStep);
void UpdateUsdSampler(UsdStageRefPtr timeVarStage, UsdBridgePrimCache* cacheEntry, const UsdBridgeSamplerData& samplerData, double timeStep);
void UpdateUsdCamera(UsdStageRefPtr timeVarStage, const SdfPath& cameraPrimPath,
const UsdBridgeCameraData& cameraData, double timeStep, bool timeVarHasChanged);
void UpdateUsdInstancerPrototypes(const SdfPath& instancerPath, const UsdBridgeInstancerRefData& geomRefData, const SdfPrimPathList& refProtoGeomPrimPaths, const char* protoShapePathRp);
void UpdateAttributeReader(UsdStageRefPtr timeVarStage, const SdfPath& matPrimPath, MaterialDMI dataMemberId, const char* newName, const UsdGeomPrimvarsAPI& boundGeomPrimvars, double timeStep, MaterialDMI timeVarying);
void UpdateInAttribute(UsdStageRefPtr timeVarStage, const SdfPath& samplerPrimPath, const char* newName, double timeStep, SamplerDMI timeVarying);
void UpdateBeginEndTime(double timeStep);
#ifdef USE_INDEX_MATERIALS
void UpdateIndexVolumeMaterial(UsdStageRefPtr sceneStage, UsdStageRefPtr timeVarStage, const SdfPath& volumePath, const UsdBridgeVolumeData& volumeData, double timeStep);
#endif
void ResetSharedResourceModified();
TfToken& AttributeNameToken(const char* attribName);
friend void ResourceCollectVolume(UsdBridgePrimCache* cache, UsdBridgeUsdWriter& usdWriter);
friend void ResourceCollectSampler(UsdBridgePrimCache* cache, UsdBridgeUsdWriter& usdWriter);
friend void RemoveResourceFiles(UsdBridgePrimCache* cache, UsdBridgeUsdWriter& usdWriter,
const char* resourceFolder, const char* extension);
// Settings
UsdBridgeSettings Settings;
UsdBridgeConnectionSettings ConnectionSettings;
UsdBridgeLogObject LogObject;
protected:
// Connect
std::unique_ptr<UsdBridgeConnection> Connect = nullptr;
// Volume writer
std::shared_ptr<UsdBridgeVolumeWriterI> VolumeWriter; // shared - requires custom deleter
// Shared resource cache (ie. resources shared between UsdBridgePrimCache entries)
// Maps keys to a refcount and modified flag
using SharedResourceValue = std::pair<int, bool>;
using SharedResourceKV = std::pair<UsdBridgeResourceKey, SharedResourceValue>;
using SharedResourceContainer = std::vector<SharedResourceKV>;
SharedResourceContainer SharedResourceCache;
void AddSharedResourceRef(const UsdBridgeResourceKey& key);
bool RemoveSharedResourceRef(const UsdBridgeResourceKey& key);
// Sets modified flag and returns whether the shared resource has been modified since ResetSharedResourceModified()
bool SetSharedResourceModified(const UsdBridgeResourceKey& key);
// Token cache for attribute names
std::vector<TfToken> AttributeTokens;
// Session specific info
int SessionNumber = -1;
UsdStageRefPtr SceneStage;
UsdStageRefPtr ExternalSceneStage;
bool EnableSaving = true;
std::string SceneFileName;
std::string SessionDirectory;
std::string RootName;
std::string RootClassName;
#ifdef CUSTOM_PBR_MDL
SdfAssetPath MdlOpaqueRelFilePath; // relative from Scene Folder
SdfAssetPath MdlTranslucentRelFilePath; // relative from Scene Folder
#endif
double StartTime = 0.0;
double EndTime = 0.0;
std::string TempNameStr;
std::vector<unsigned char> TempImageData;
};
void RemoveResourceFiles(UsdBridgePrimCache* cache, UsdBridgeUsdWriter& usdWriter,
const char* resourceFolder, const char* fileExtension);
void ResourceCollectVolume(UsdBridgePrimCache* cache, UsdBridgeUsdWriter& usdWriter);
void ResourceCollectSampler(UsdBridgePrimCache* cache, UsdBridgeUsdWriter& usdWriter);
#endif | 13,391 | C | 59.597285 | 237 | 0.821074 |
NVIDIA-Omniverse/AnariUsdDevice/UsdBridge/UsdBridgeUsdWriter_Volume.cpp | // Copyright 2020 The Khronos Group
// SPDX-License-Identifier: Apache-2.0
#include "UsdBridgeUsdWriter.h"
#include "UsdBridgeUsdWriter_Common.h"
namespace
{
void InitializeUsdVolumeTimeVar(UsdVolVolume& volume, const TimeEvaluator<UsdBridgeVolumeData>* timeEval = nullptr)
{
typedef UsdBridgeVolumeData::DataMemberId DMI;
}
void InitializeUsdVolumeAssetTimeVar(UsdVolOpenVDBAsset& volAsset, const TimeEvaluator<UsdBridgeVolumeData>* timeEval = nullptr)
{
typedef UsdBridgeVolumeData::DataMemberId DMI;
UsdVolOpenVDBAsset& attribCreatePrim = volAsset;
UsdPrim attribRemovePrim = volAsset.GetPrim();
CREATE_REMOVE_TIMEVARYING_ATTRIB_QUALIFIED(DMI::DATA, CreateFilePathAttr, UsdBridgeTokens->filePath);
}
UsdPrim InitializeUsdVolume_Impl(UsdStageRefPtr volumeStage, const SdfPath & volumePath, bool uniformPrim,
TimeEvaluator<UsdBridgeVolumeData>* timeEval = nullptr)
{
UsdVolVolume volume = GetOrDefinePrim<UsdVolVolume>(volumeStage, volumePath);
SdfPath ovdbFieldPath = volumePath.AppendPath(SdfPath(constring::openVDBPrimPf));
UsdVolOpenVDBAsset volAsset = GetOrDefinePrim<UsdVolOpenVDBAsset>(volumeStage, ovdbFieldPath);
if (uniformPrim)
{
volume.CreateFieldRelationship(UsdBridgeTokens->density, ovdbFieldPath);
volAsset.CreateFieldNameAttr(VtValue(UsdBridgeTokens->density));
}
InitializeUsdVolumeTimeVar(volume, timeEval);
InitializeUsdVolumeAssetTimeVar(volAsset, timeEval);
return volume.GetPrim();
}
void UpdateUsdVolumeAttributes(UsdVolVolume& uniformVolume, UsdVolVolume& timeVarVolume, UsdVolOpenVDBAsset& uniformField, UsdVolOpenVDBAsset& timeVarField,
const UsdBridgeVolumeData& volumeData, double timeStep, const std::string& relVolPath)
{
TimeEvaluator<UsdBridgeVolumeData> timeEval(volumeData, timeStep);
typedef UsdBridgeVolumeData::DataMemberId DMI;
SdfAssetPath volAsset(relVolPath);
// Set extents in usd
float minX = volumeData.Origin[0];
float minY = volumeData.Origin[1];
float minZ = volumeData.Origin[2];
float maxX = ((float)volumeData.NumElements[0] * volumeData.CellDimensions[0]) + minX;
float maxY = ((float)volumeData.NumElements[1] * volumeData.CellDimensions[1]) + minY;
float maxZ = ((float)volumeData.NumElements[2] * volumeData.CellDimensions[2]) + minZ;
VtVec3fArray extentArray(2);
extentArray[0].Set(minX, minY, minZ);
extentArray[1].Set(maxX, maxY, maxZ);
UsdAttribute uniformFileAttr = uniformField.GetFilePathAttr();
UsdAttribute timeVarFileAttr = timeVarField.GetFilePathAttr();
UsdAttribute uniformExtentAttr = uniformVolume.GetExtentAttr();
UsdAttribute timeVarExtentAttr = timeVarVolume.GetExtentAttr();
bool dataTimeVarying = timeEval.IsTimeVarying(DMI::DATA);
// Clear timevarying attributes if necessary
ClearUsdAttributes(uniformFileAttr, timeVarFileAttr, dataTimeVarying);
ClearUsdAttributes(uniformExtentAttr, timeVarExtentAttr, dataTimeVarying);
// Set the attributes
SET_TIMEVARYING_ATTRIB(dataTimeVarying, timeVarFileAttr, uniformFileAttr, volAsset);
SET_TIMEVARYING_ATTRIB(dataTimeVarying, timeVarExtentAttr, uniformExtentAttr, extentArray);
}
}
UsdPrim UsdBridgeUsdWriter::InitializeUsdVolume(UsdStageRefPtr volumeStage, const SdfPath & volumePath, bool uniformPrim) const
{
UsdPrim volumePrim = InitializeUsdVolume_Impl(volumeStage, volumePath, uniformPrim);
#ifdef USE_INDEX_MATERIALS
UsdShadeMaterial matPrim = InitializeIndexVolumeMaterial_Impl(volumeStage, volumePath, uniformPrim);
UsdShadeMaterialBindingAPI(volumePrim).Bind(matPrim);
#endif
return volumePrim;
}
#ifdef VALUE_CLIP_RETIMING
void UsdBridgeUsdWriter::UpdateUsdVolumeManifest(const UsdBridgePrimCache* cacheEntry, const UsdBridgeVolumeData& volumeData)
{
const SdfPath & volumePath = cacheEntry->PrimPath;
UsdStageRefPtr volumeStage = cacheEntry->ManifestStage.second;
TimeEvaluator<UsdBridgeVolumeData> timeEval(volumeData);
InitializeUsdVolume_Impl(volumeStage, volumePath,
false, &timeEval);
#ifdef USE_INDEX_MATERIALS
InitializeIndexVolumeMaterial_Impl(volumeStage, volumePath, false, &timeEval);
#endif
if(this->EnableSaving)
cacheEntry->ManifestStage.second->Save();
}
#endif
void UsdBridgeUsdWriter::UpdateUsdVolume(UsdStageRefPtr timeVarStage, UsdBridgePrimCache* cacheEntry, const UsdBridgeVolumeData& volumeData, double timeStep)
{
const SdfPath& volPrimPath = cacheEntry->PrimPath;
// Get the volume and ovdb field prims
UsdVolVolume uniformVolume = UsdVolVolume::Get(SceneStage, volPrimPath);
assert(uniformVolume);
UsdVolVolume timeVarVolume = UsdVolVolume::Get(timeVarStage, volPrimPath);
assert(timeVarVolume);
SdfPath ovdbFieldPath = volPrimPath.AppendPath(SdfPath(constring::openVDBPrimPf));
UsdVolOpenVDBAsset uniformField = UsdVolOpenVDBAsset::Get(SceneStage, ovdbFieldPath);
assert(uniformField);
UsdVolOpenVDBAsset timeVarField = UsdVolOpenVDBAsset::Get(timeVarStage, ovdbFieldPath);
assert(timeVarField);
// Set the file path reference in usd
const std::string& relVolPath = GetResourceFileName(constring::volFolder, cacheEntry->Name.GetString(), timeStep, constring::vdbExtension);
UpdateUsdVolumeAttributes(uniformVolume, timeVarVolume, uniformField, timeVarField, volumeData, timeStep, relVolPath);
#ifdef USE_INDEX_MATERIALS
UpdateIndexVolumeMaterial(SceneStage, timeVarStage, volPrimPath, volumeData, timeStep);
#endif
// Output stream path (relative from connection working dir)
std::string wdRelVolPath(SessionDirectory + relVolPath);
// Write VDB data to stream
VolumeWriter->ToVDB(volumeData);
// Flush stream out to storage
const char* volumeStreamData; size_t volumeStreamDataSize;
VolumeWriter->GetSerializedVolumeData(volumeStreamData, volumeStreamDataSize);
Connect->WriteFile(volumeStreamData, volumeStreamDataSize, wdRelVolPath.c_str(), true);
// Record file write for timestep
cacheEntry->AddResourceKey(UsdBridgeResourceKey(nullptr, timeStep));
}
void ResourceCollectVolume(UsdBridgePrimCache* cache, UsdBridgeUsdWriter& usdWriter)
{
RemoveResourceFiles(cache, usdWriter, constring::volFolder, constring::vdbExtension);
} | 6,214 | C++ | 38.335443 | 158 | 0.78822 |
NVIDIA-Omniverse/AnariUsdDevice/UsdBridge/UsdBridgeTimeEvaluator.cpp | // Copyright 2020 The Khronos Group
// SPDX-License-Identifier: Apache-2.0
#include "UsdBridgeTimeEvaluator.h"
#include "usd.h"
PXR_NAMESPACE_USING_DIRECTIVE
const UsdTimeCode UsdBridgeTimeEvaluator<bool>::DefaultTime = UsdTimeCode::Default(); | 245 | C++ | 29.749996 | 85 | 0.795918 |
NVIDIA-Omniverse/AnariUsdDevice/UsdBridge/UsdBridgeUsdWriter_Geometry.cpp | // Copyright 2020 The Khronos Group
// SPDX-License-Identifier: Apache-2.0
#include "UsdBridgeUsdWriter.h"
#include "UsdBridgeUsdWriter_Common.h"
namespace
{
template<typename UsdGeomType>
UsdAttribute UsdGeomGetPointsAttribute(UsdGeomType& usdGeom) { return UsdAttribute(); }
template<>
UsdAttribute UsdGeomGetPointsAttribute(UsdGeomMesh& usdGeom) { return usdGeom.GetPointsAttr(); }
template<>
UsdAttribute UsdGeomGetPointsAttribute(UsdGeomPoints& usdGeom) { return usdGeom.GetPointsAttr(); }
template<>
UsdAttribute UsdGeomGetPointsAttribute(UsdGeomBasisCurves& usdGeom) { return usdGeom.GetPointsAttr(); }
template<>
UsdAttribute UsdGeomGetPointsAttribute(UsdGeomPointInstancer& usdGeom) { return usdGeom.GetPositionsAttr(); }
template<typename GeomDataType>
void CreateUsdGeomColorPrimvars(UsdGeomPrimvarsAPI& primvarApi, const GeomDataType& geomData, const UsdBridgeSettings& settings, const TimeEvaluator<GeomDataType>* timeEval = nullptr)
{
using DMI = typename GeomDataType::DataMemberId;
bool timeVarChecked = true;
if(timeEval)
{
timeVarChecked = timeEval->IsTimeVarying(DMI::COLORS);
}
if (timeVarChecked)
{
primvarApi.CreatePrimvar(UsdBridgeTokens->color, SdfValueTypeNames->Float4Array);
}
else
{
primvarApi.RemovePrimvar(UsdBridgeTokens->color);
}
}
template<typename GeomDataType>
void CreateUsdGeomTexturePrimvars(UsdGeomPrimvarsAPI& primvarApi, const GeomDataType& geomData, const UsdBridgeSettings& settings, const TimeEvaluator<GeomDataType>* timeEval = nullptr)
{
using DMI = typename GeomDataType::DataMemberId;
bool timeVarChecked = true;
if(timeEval)
{
timeVarChecked = timeEval->IsTimeVarying(DMI::ATTRIBUTE0);
}
if (timeVarChecked)
primvarApi.CreatePrimvar(UsdBridgeTokens->st, SdfValueTypeNames->TexCoord2fArray);
else if (timeEval)
primvarApi.RemovePrimvar(UsdBridgeTokens->st);
}
template<typename GeomDataType>
void CreateUsdGeomAttributePrimvar(UsdBridgeUsdWriter* writer, UsdGeomPrimvarsAPI& primvarApi, const GeomDataType& geomData, uint32_t attribIndex, const TimeEvaluator<GeomDataType>* timeEval = nullptr)
{
using DMI = typename GeomDataType::DataMemberId;
const UsdBridgeAttribute& attrib = geomData.Attributes[attribIndex];
if(attrib.DataType != UsdBridgeType::UNDEFINED)
{
bool timeVarChecked = true;
if(timeEval)
{
DMI attributeId = DMI::ATTRIBUTE0 + attribIndex;
timeVarChecked = timeEval->IsTimeVarying(attributeId);
}
TfToken attribToken = attrib.Name ? writer->AttributeNameToken(attrib.Name) : AttribIndexToToken(attribIndex);
if(timeVarChecked)
{
SdfValueTypeName primvarType = GetPrimvarArrayType(attrib.DataType);
if(primvarType == SdfValueTypeNames->BoolArray)
{
UsdBridgeLogMacro(writer->LogObject, UsdBridgeLogLevel::WARNING, "UsdGeom Attribute<" << attribIndex << "> primvar does not support source data type: " << attrib.DataType);
}
// Allow for attrib primvar types to change
UsdGeomPrimvar primvar = primvarApi.GetPrimvar(attribToken);
if(primvar && primvar.GetTypeName() != primvarType)
{
primvarApi.RemovePrimvar(attribToken);
}
primvarApi.CreatePrimvar(attribToken, primvarType);
}
else if(timeEval)
{
primvarApi.RemovePrimvar(attribToken);
}
}
}
template<typename GeomDataType>
void CreateUsdGeomAttributePrimvars(UsdBridgeUsdWriter* writer, UsdGeomPrimvarsAPI& primvarApi, const GeomDataType& geomData, const TimeEvaluator<GeomDataType>* timeEval = nullptr)
{
for(uint32_t attribIndex = 0; attribIndex < geomData.NumAttributes; ++attribIndex)
{
CreateUsdGeomAttributePrimvar(writer, primvarApi, geomData, attribIndex, timeEval);
}
}
void InitializeUsdGeometryTimeVar(UsdBridgeUsdWriter* writer, UsdGeomMesh& meshGeom, const UsdBridgeMeshData& meshData, const UsdBridgeSettings& settings,
const TimeEvaluator<UsdBridgeMeshData>* timeEval = nullptr)
{
typedef UsdBridgeMeshData::DataMemberId DMI;
UsdGeomPrimvarsAPI primvarApi(meshGeom);
UsdGeomMesh& attribCreatePrim = meshGeom;
UsdPrim attribRemovePrim = meshGeom.GetPrim();
CREATE_REMOVE_TIMEVARYING_ATTRIB_QUALIFIED(DMI::POINTS, CreatePointsAttr, UsdBridgeTokens->points);
CREATE_REMOVE_TIMEVARYING_ATTRIB_QUALIFIED(DMI::POINTS, CreateExtentAttr, UsdBridgeTokens->extent);
CREATE_REMOVE_TIMEVARYING_ATTRIB_QUALIFIED(DMI::INDICES, CreateFaceVertexIndicesAttr, UsdBridgeTokens->faceVertexCounts);
CREATE_REMOVE_TIMEVARYING_ATTRIB_QUALIFIED(DMI::INDICES, CreateFaceVertexCountsAttr, UsdBridgeTokens->faceVertexIndices);
CREATE_REMOVE_TIMEVARYING_ATTRIB_QUALIFIED(DMI::NORMALS, CreateNormalsAttr, UsdBridgeTokens->normals);
CreateUsdGeomColorPrimvars(primvarApi, meshData, settings, timeEval);
if(settings.EnableStTexCoords)
CreateUsdGeomTexturePrimvars(primvarApi, meshData, settings, timeEval);
CreateUsdGeomAttributePrimvars(writer, primvarApi, meshData, timeEval);
}
void InitializeUsdGeometryTimeVar(UsdBridgeUsdWriter* writer, UsdGeomPoints& pointsGeom, const UsdBridgeInstancerData& instancerData, const UsdBridgeSettings& settings,
const TimeEvaluator<UsdBridgeInstancerData>* timeEval = nullptr)
{
typedef UsdBridgeInstancerData::DataMemberId DMI;
UsdGeomPrimvarsAPI primvarApi(pointsGeom);
UsdGeomPoints& attribCreatePrim = pointsGeom;
UsdPrim attribRemovePrim = pointsGeom.GetPrim();
CREATE_REMOVE_TIMEVARYING_ATTRIB_QUALIFIED(DMI::POINTS, CreatePointsAttr, UsdBridgeTokens->points);
CREATE_REMOVE_TIMEVARYING_ATTRIB_QUALIFIED(DMI::POINTS, CreateExtentAttr, UsdBridgeTokens->extent);
CREATE_REMOVE_TIMEVARYING_ATTRIB_QUALIFIED(DMI::INSTANCEIDS, CreateIdsAttr, UsdBridgeTokens->ids);
CREATE_REMOVE_TIMEVARYING_ATTRIB_QUALIFIED(DMI::ORIENTATIONS, CreateNormalsAttr, UsdBridgeTokens->normals);
CREATE_REMOVE_TIMEVARYING_ATTRIB_QUALIFIED(DMI::SCALES, CreateWidthsAttr, UsdBridgeTokens->widths);
CreateUsdGeomColorPrimvars(primvarApi, instancerData, settings, timeEval);
if(settings.EnableStTexCoords)
CreateUsdGeomTexturePrimvars(primvarApi, instancerData, settings, timeEval);
CreateUsdGeomAttributePrimvars(writer, primvarApi, instancerData, timeEval);
}
void InitializeUsdGeometryTimeVar(UsdBridgeUsdWriter* writer, UsdGeomPointInstancer& pointsGeom, const UsdBridgeInstancerData& instancerData, const UsdBridgeSettings& settings,
const TimeEvaluator<UsdBridgeInstancerData>* timeEval = nullptr)
{
typedef UsdBridgeInstancerData::DataMemberId DMI;
UsdGeomPrimvarsAPI primvarApi(pointsGeom);
UsdGeomPointInstancer& attribCreatePrim = pointsGeom;
UsdPrim attribRemovePrim = pointsGeom.GetPrim();
CREATE_REMOVE_TIMEVARYING_ATTRIB_QUALIFIED(DMI::POINTS, CreatePositionsAttr, UsdBridgeTokens->positions);
CREATE_REMOVE_TIMEVARYING_ATTRIB_QUALIFIED(DMI::POINTS, CreateExtentAttr, UsdBridgeTokens->extent);
CREATE_REMOVE_TIMEVARYING_ATTRIB_QUALIFIED(DMI::SHAPEINDICES, CreateProtoIndicesAttr, UsdBridgeTokens->protoIndices);
CREATE_REMOVE_TIMEVARYING_ATTRIB_QUALIFIED(DMI::INSTANCEIDS, CreateIdsAttr, UsdBridgeTokens->ids);
CREATE_REMOVE_TIMEVARYING_ATTRIB_QUALIFIED(DMI::ORIENTATIONS, CreateOrientationsAttr, UsdBridgeTokens->orientations);
CREATE_REMOVE_TIMEVARYING_ATTRIB_QUALIFIED(DMI::SCALES, CreateScalesAttr, UsdBridgeTokens->scales);
CreateUsdGeomColorPrimvars(primvarApi, instancerData, settings, timeEval);
if(settings.EnableStTexCoords)
CreateUsdGeomTexturePrimvars(primvarApi, instancerData, settings, timeEval);
CreateUsdGeomAttributePrimvars(writer, primvarApi, instancerData, timeEval);
//CREATE_REMOVE_TIMEVARYING_ATTRIB_QUALIFIED(DMI::LINEARVELOCITIES, CreateVelocitiesAttr, UsdBridgeTokens->velocities);
//CREATE_REMOVE_TIMEVARYING_ATTRIB_QUALIFIED(DMI::ANGULARVELOCITIES, CreateAngularVelocitiesAttr, UsdBridgeTokens->angularVelocities);
CREATE_REMOVE_TIMEVARYING_ATTRIB_QUALIFIED(DMI::INVISIBLEIDS, CreateInvisibleIdsAttr, UsdBridgeTokens->invisibleIds);
}
void InitializeUsdGeometryTimeVar(UsdBridgeUsdWriter* writer, UsdGeomBasisCurves& curveGeom, const UsdBridgeCurveData& curveData, const UsdBridgeSettings& settings,
const TimeEvaluator<UsdBridgeCurveData>* timeEval = nullptr)
{
typedef UsdBridgeCurveData::DataMemberId DMI;
UsdGeomPrimvarsAPI primvarApi(curveGeom);
UsdGeomBasisCurves& attribCreatePrim = curveGeom;
UsdPrim attribRemovePrim = curveGeom.GetPrim();
CREATE_REMOVE_TIMEVARYING_ATTRIB_QUALIFIED(DMI::POINTS, CreatePointsAttr, UsdBridgeTokens->positions);
CREATE_REMOVE_TIMEVARYING_ATTRIB_QUALIFIED(DMI::POINTS, CreateExtentAttr, UsdBridgeTokens->extent);
CREATE_REMOVE_TIMEVARYING_ATTRIB_QUALIFIED(DMI::CURVELENGTHS, CreateCurveVertexCountsAttr, UsdBridgeTokens->curveVertexCounts);
CREATE_REMOVE_TIMEVARYING_ATTRIB_QUALIFIED(DMI::NORMALS, CreateNormalsAttr, UsdBridgeTokens->normals);
CREATE_REMOVE_TIMEVARYING_ATTRIB_QUALIFIED(DMI::SCALES, CreateWidthsAttr, UsdBridgeTokens->widths);
CreateUsdGeomColorPrimvars(primvarApi, curveData, settings, timeEval);
if(settings.EnableStTexCoords)
CreateUsdGeomTexturePrimvars(primvarApi, curveData, settings, timeEval);
CreateUsdGeomAttributePrimvars(writer, primvarApi, curveData, timeEval);
}
UsdPrim InitializeUsdGeometry_Impl(UsdBridgeUsdWriter* writer, UsdStageRefPtr geometryStage, const SdfPath& geomPath, const UsdBridgeMeshData& meshData, bool uniformPrim,
const UsdBridgeSettings& settings,
TimeEvaluator<UsdBridgeMeshData>* timeEval = nullptr)
{
UsdGeomMesh geomMesh = GetOrDefinePrim<UsdGeomMesh>(geometryStage, geomPath);
InitializeUsdGeometryTimeVar(writer, geomMesh, meshData, settings, timeEval);
if (uniformPrim)
{
geomMesh.CreateDoubleSidedAttr(VtValue(true));
geomMesh.CreateSubdivisionSchemeAttr().Set(UsdGeomTokens->none);
}
return geomMesh.GetPrim();
}
UsdPrim InitializeUsdGeometry_Impl(UsdBridgeUsdWriter* writer, UsdStageRefPtr geometryStage, const SdfPath& geomPath, const UsdBridgeInstancerData& instancerData, bool uniformPrim,
const UsdBridgeSettings& settings,
TimeEvaluator<UsdBridgeInstancerData>* timeEval = nullptr)
{
if (instancerData.UseUsdGeomPoints)
{
UsdGeomPoints geomPoints = GetOrDefinePrim<UsdGeomPoints>(geometryStage, geomPath);
InitializeUsdGeometryTimeVar(writer, geomPoints, instancerData, settings, timeEval);
if (uniformPrim)
{
geomPoints.CreateDoubleSidedAttr(VtValue(true));
}
return geomPoints.GetPrim();
}
else
{
UsdGeomPointInstancer geomPoints = GetOrDefinePrim<UsdGeomPointInstancer>(geometryStage, geomPath);
InitializeUsdGeometryTimeVar(writer, geomPoints, instancerData, settings, timeEval);
return geomPoints.GetPrim();
}
}
UsdPrim InitializeUsdGeometry_Impl(UsdBridgeUsdWriter* writer, UsdStageRefPtr geometryStage, const SdfPath& geomPath, const UsdBridgeCurveData& curveData, bool uniformPrim,
const UsdBridgeSettings& settings,
TimeEvaluator<UsdBridgeCurveData>* timeEval = nullptr)
{
UsdGeomBasisCurves geomCurves = GetOrDefinePrim<UsdGeomBasisCurves>(geometryStage, geomPath);
InitializeUsdGeometryTimeVar(writer, geomCurves, curveData, settings, timeEval);
if (uniformPrim)
{
geomCurves.CreateDoubleSidedAttr(VtValue(true));
geomCurves.GetTypeAttr().Set(UsdGeomTokens->linear);
}
return geomCurves.GetPrim();
}
template<typename UsdGeomType, typename GeomDataType>
void UpdateUsdGeomPoints(const UsdBridgeLogObject& logObj, UsdGeomType& timeVarGeom, UsdGeomType& uniformGeom, const GeomDataType& geomData, uint64_t numPrims,
UsdBridgeUpdateEvaluator<const GeomDataType>& updateEval, TimeEvaluator<GeomDataType>& timeEval)
{
using DMI = typename GeomDataType::DataMemberId;
bool performsUpdate = updateEval.PerformsUpdate(DMI::POINTS);
bool timeVaryingUpdate = timeEval.IsTimeVarying(DMI::POINTS);
ClearUsdAttributes(UsdGeomGetPointsAttribute(uniformGeom), UsdGeomGetPointsAttribute(timeVarGeom), timeVaryingUpdate);
ClearUsdAttributes(uniformGeom.GetExtentAttr(), timeVarGeom.GetExtentAttr(), timeVaryingUpdate);
if (performsUpdate)
{
if (!geomData.Points)
{
UsdBridgeLogMacro(logObj, UsdBridgeLogLevel::ERR, "GeomData requires points.");
}
else
{
UsdGeomType* outGeom = timeVaryingUpdate ? &timeVarGeom : &uniformGeom;
UsdTimeCode timeCode = timeEval.Eval(DMI::POINTS);
// Points
UsdAttribute pointsAttr = UsdGeomGetPointsAttribute(*outGeom);
const void* arrayData = geomData.Points;
size_t arrayNumElements = geomData.NumPoints;
UsdAttribute arrayPrimvar = pointsAttr;
VtVec3fArray& usdVerts = GetStaticTempArray<VtVec3fArray>();
bool setPrimvar = true;
switch (geomData.PointsType)
{
case UsdBridgeType::FLOAT3: {ASSIGN_PRIMVAR_CUSTOM_ARRAY_MACRO(VtVec3fArray, usdVerts); break; }
case UsdBridgeType::DOUBLE3: {ASSIGN_PRIMVAR_CONVERT_CUSTOM_ARRAY_MACRO(VtVec3fArray, GfVec3d, usdVerts); break; }
default: { UsdBridgeLogMacro(logObj, UsdBridgeLogLevel::ERR, "UsdGeom PointsAttr should be FLOAT3 or DOUBLE3."); break; }
}
// Usd requires extent.
GfRange3f extent;
for (const auto& pt : usdVerts) {
extent.UnionWith(pt);
}
VtVec3fArray extentArray(2);
extentArray[0] = extent.GetMin();
extentArray[1] = extent.GetMax();
outGeom->GetExtentAttr().Set(extentArray, timeCode);
}
}
}
template<typename UsdGeomType, typename GeomDataType>
void UpdateUsdGeomIndices(const UsdBridgeLogObject& logObj, UsdGeomType& timeVarGeom, UsdGeomType& uniformGeom, const GeomDataType& geomData, uint64_t numPrims,
UsdBridgeUpdateEvaluator<const GeomDataType>& updateEval, TimeEvaluator<GeomDataType>& timeEval)
{
using DMI = typename GeomDataType::DataMemberId;
bool performsUpdate = updateEval.PerformsUpdate(DMI::INDICES);
bool timeVaryingUpdate = timeEval.IsTimeVarying(DMI::INDICES);
ClearUsdAttributes(uniformGeom.GetFaceVertexIndicesAttr(), timeVarGeom.GetFaceVertexIndicesAttr(), timeVaryingUpdate);
ClearUsdAttributes(uniformGeom.GetFaceVertexCountsAttr(), timeVarGeom.GetFaceVertexCountsAttr(), timeVaryingUpdate);
if (performsUpdate)
{
UsdGeomType* outGeom = timeVaryingUpdate ? &timeVarGeom : &uniformGeom;
UsdTimeCode timeCode = timeEval.Eval(DMI::INDICES);
uint64_t numIndices = geomData.NumIndices;
VtArray<int>& usdVertexCounts = GetStaticTempArray<VtIntArray>();
usdVertexCounts.resize(numPrims);
int vertexCount = numIndices / numPrims;
for (uint64_t i = 0; i < numPrims; ++i)
usdVertexCounts[i] = vertexCount;//geomData.FaceVertCounts[i];
// Face Vertex counts
UsdAttribute faceVertCountsAttr = outGeom->GetFaceVertexCountsAttr();
faceVertCountsAttr.Set(usdVertexCounts, timeCode);
if (!geomData.Indices)
{
VtIntArray& tempIndices = GetStaticTempArray<VtIntArray>();
tempIndices.resize(numIndices);
for (uint64_t i = 0; i < numIndices; ++i)
tempIndices[i] = (int)i;
UsdAttribute arrayPrimvar = outGeom->GetFaceVertexIndicesAttr();
arrayPrimvar.Set(tempIndices, timeCode);
}
else
{
// Face indices
const void* arrayData = geomData.Indices;
size_t arrayNumElements = numIndices;
UsdAttribute arrayPrimvar = outGeom->GetFaceVertexIndicesAttr();
bool setPrimvar = true;
switch (geomData.IndicesType)
{
case UsdBridgeType::ULONG: {ASSIGN_PRIMVAR_CONVERT_MACRO(VtIntArray, uint64_t); break; }
case UsdBridgeType::LONG: {ASSIGN_PRIMVAR_CONVERT_MACRO(VtIntArray, int64_t); break; }
case UsdBridgeType::INT: {ASSIGN_PRIMVAR_MACRO(VtIntArray); break; }
case UsdBridgeType::UINT: {ASSIGN_PRIMVAR_MACRO(VtIntArray); break; }
default: { UsdBridgeLogMacro(logObj, UsdBridgeLogLevel::ERR, "UsdGeom FaceVertexIndicesAttr should be (U)LONG or (U)INT."); break; }
}
}
}
}
template<typename UsdGeomType, typename GeomDataType>
void UpdateUsdGeomNormals(const UsdBridgeLogObject& logObj, UsdGeomType& timeVarGeom, UsdGeomType& uniformGeom, const GeomDataType& geomData, uint64_t numPrims,
UsdBridgeUpdateEvaluator<const GeomDataType>& updateEval, TimeEvaluator<GeomDataType>& timeEval)
{
using DMI = typename GeomDataType::DataMemberId;
bool performsUpdate = updateEval.PerformsUpdate(DMI::NORMALS);
bool timeVaryingUpdate = timeEval.IsTimeVarying(DMI::NORMALS);
ClearUsdAttributes(uniformGeom.GetNormalsAttr(), timeVarGeom.GetNormalsAttr(), timeVaryingUpdate);
if (performsUpdate)
{
UsdGeomType* outGeom = timeVaryingUpdate ? &timeVarGeom : &uniformGeom;
UsdTimeCode timeCode = timeEval.Eval(DMI::NORMALS);
UsdAttribute normalsAttr = outGeom->GetNormalsAttr();
if (geomData.Normals != nullptr)
{
const void* arrayData = geomData.Normals;
size_t arrayNumElements = geomData.PerPrimNormals ? numPrims : geomData.NumPoints;
UsdAttribute arrayPrimvar = normalsAttr;
bool setPrimvar = true;
switch (geomData.NormalsType)
{
case UsdBridgeType::FLOAT3: {ASSIGN_PRIMVAR_MACRO(VtVec3fArray); break; }
case UsdBridgeType::DOUBLE3: {ASSIGN_PRIMVAR_CONVERT_MACRO(VtVec3fArray, GfVec3d); break; }
default: { UsdBridgeLogMacro(logObj, UsdBridgeLogLevel::ERR, "UsdGeom NormalsAttr should be FLOAT3 or DOUBLE3."); break; }
}
// Per face or per-vertex interpolation. This will break timesteps that have been written before.
TfToken normalInterpolation = geomData.PerPrimNormals ? UsdGeomTokens->uniform : UsdGeomTokens->vertex;
uniformGeom.SetNormalsInterpolation(normalInterpolation);
}
else
{
normalsAttr.Set(SdfValueBlock(), timeCode);
}
}
}
template<typename GeomDataType>
void UpdateUsdGeomTexCoords(UsdBridgeUsdWriter* writer, UsdGeomPrimvarsAPI& timeVarPrimvars, UsdGeomPrimvarsAPI& uniformPrimvars, const GeomDataType& geomData, uint64_t numPrims,
UsdBridgeUpdateEvaluator<const GeomDataType>& updateEval, TimeEvaluator<GeomDataType>& timeEval)
{
using DMI = typename GeomDataType::DataMemberId;
bool performsUpdate = updateEval.PerformsUpdate(DMI::ATTRIBUTE0);
bool timeVaryingUpdate = timeEval.IsTimeVarying(DMI::ATTRIBUTE0);
UsdGeomPrimvar uniformPrimvar = uniformPrimvars.GetPrimvar(UsdBridgeTokens->st);
UsdGeomPrimvar timeVarPrimvar = timeVarPrimvars.GetPrimvar(UsdBridgeTokens->st);
ClearUsdAttributes(uniformPrimvar.GetAttr(), timeVarPrimvar.GetAttr(), timeVaryingUpdate);
if (performsUpdate)
{
UsdTimeCode timeCode = timeEval.Eval(DMI::ATTRIBUTE0);
UsdAttribute texcoordPrimvar = timeVaryingUpdate ? timeVarPrimvar : uniformPrimvar;
assert(texcoordPrimvar);
const UsdBridgeAttribute& texCoordAttrib = geomData.Attributes[0];
if (texCoordAttrib.Data != nullptr)
{
const void* arrayData = texCoordAttrib.Data;
size_t arrayNumElements = texCoordAttrib.PerPrimData ? numPrims : geomData.NumPoints;
UsdAttribute arrayPrimvar = texcoordPrimvar;
bool setPrimvar = true;
switch (texCoordAttrib.DataType)
{
case UsdBridgeType::FLOAT2: { ASSIGN_PRIMVAR_MACRO(VtVec2fArray); break; }
case UsdBridgeType::DOUBLE2: { ASSIGN_PRIMVAR_CONVERT_MACRO(VtVec2fArray, GfVec2d); break; }
default: { UsdBridgeLogMacro(writer->LogObject, UsdBridgeLogLevel::ERR, "UsdGeom st primvar should be FLOAT2 or DOUBLE2."); break; }
}
// Per face or per-vertex interpolation. This will break timesteps that have been written before.
TfToken texcoordInterpolation = texCoordAttrib.PerPrimData ? UsdGeomTokens->uniform : UsdGeomTokens->vertex;
uniformPrimvar.SetInterpolation(texcoordInterpolation);
}
else
{
texcoordPrimvar.Set(SdfValueBlock(), timeCode);
}
}
}
template<typename GeomDataType>
void UpdateUsdGeomAttribute(UsdBridgeUsdWriter* writer, UsdGeomPrimvarsAPI& timeVarPrimvars, UsdGeomPrimvarsAPI& uniformPrimvars, const GeomDataType& geomData, uint64_t numPrims,
UsdBridgeUpdateEvaluator<const GeomDataType>& updateEval, TimeEvaluator<GeomDataType>& timeEval, uint32_t attribIndex)
{
assert(attribIndex < geomData.NumAttributes);
const UsdBridgeAttribute& bridgeAttrib = geomData.Attributes[attribIndex];
TfToken attribToken = bridgeAttrib.Name ? writer->AttributeNameToken(bridgeAttrib.Name) : AttribIndexToToken(attribIndex);
UsdGeomPrimvar uniformPrimvar = uniformPrimvars.GetPrimvar(attribToken);
// The uniform primvar has to exist, otherwise any timevarying data will be ignored as well
if(!uniformPrimvar || uniformPrimvar.GetTypeName() != GetPrimvarArrayType(bridgeAttrib.DataType))
{
CreateUsdGeomAttributePrimvar(writer, uniformPrimvars, geomData, attribIndex); // No timeEval, to force attribute primvar creation on the uniform api
}
UsdGeomPrimvar timeVarPrimvar = timeVarPrimvars.GetPrimvar(attribToken);
if(!timeVarPrimvar || timeVarPrimvar.GetTypeName() != GetPrimvarArrayType(bridgeAttrib.DataType)) // even though new clipstages initialize the correct primvar type/name, it may still be wrong for existing ones (or primstages if so configured)
{
CreateUsdGeomAttributePrimvar(writer, timeVarPrimvars, geomData, attribIndex, &timeEval);
}
using DMI = typename GeomDataType::DataMemberId;
DMI attributeId = DMI::ATTRIBUTE0 + attribIndex;
bool performsUpdate = updateEval.PerformsUpdate(attributeId);
bool timeVaryingUpdate = timeEval.IsTimeVarying(attributeId);
ClearUsdAttributes(uniformPrimvar.GetAttr(), timeVarPrimvar.GetAttr(), timeVaryingUpdate);
if (performsUpdate)
{
UsdTimeCode timeCode = timeEval.Eval(attributeId);
UsdAttribute attributePrimvar = timeVaryingUpdate ? timeVarPrimvar : uniformPrimvar;
if(!attributePrimvar)
{
UsdBridgeLogMacro(writer->LogObject, UsdBridgeLogLevel::ERR, "UsdGeom Attribute<Index> primvar not found, was the attribute at requested index valid during initialization of the prim? Index is " << attribIndex);
}
else
{
if (bridgeAttrib.Data != nullptr)
{
const void* arrayData = bridgeAttrib.Data;
size_t arrayNumElements = bridgeAttrib.PerPrimData ? numPrims : geomData.NumPoints;
UsdAttribute arrayPrimvar = attributePrimvar;
AssignAttribArrayToPrimvar(writer->LogObject, arrayData, bridgeAttrib.DataType, arrayNumElements, arrayPrimvar, timeCode);
// Per face or per-vertex interpolation. This will break timesteps that have been written before.
TfToken attribInterpolation = bridgeAttrib.PerPrimData ? UsdGeomTokens->uniform : UsdGeomTokens->vertex;
uniformPrimvar.SetInterpolation(attribInterpolation);
}
else
{
attributePrimvar.Set(SdfValueBlock(), timeCode);
}
}
}
}
template<typename GeomDataType>
void UpdateUsdGeomAttributes(UsdBridgeUsdWriter* writer, UsdGeomPrimvarsAPI& timeVarPrimvars, UsdGeomPrimvarsAPI& uniformPrimvars, const GeomDataType& geomData, uint64_t numPrims,
UsdBridgeUpdateEvaluator<const GeomDataType>& updateEval, TimeEvaluator<GeomDataType>& timeEval)
{
uint32_t startIdx = 0;
for(uint32_t attribIndex = startIdx; attribIndex < geomData.NumAttributes; ++attribIndex)
{
const UsdBridgeAttribute& attrib = geomData.Attributes[attribIndex];
if(attrib.DataType != UsdBridgeType::UNDEFINED)
UpdateUsdGeomAttribute(writer, timeVarPrimvars, uniformPrimvars, geomData, numPrims, updateEval, timeEval, attribIndex);
}
}
template<typename GeomDataType>
void UpdateUsdGeomColors(UsdBridgeUsdWriter* writer, UsdGeomPrimvarsAPI& timeVarPrimvars, UsdGeomPrimvarsAPI& uniformPrimvars, const GeomDataType& geomData, uint64_t numPrims,
UsdBridgeUpdateEvaluator<const GeomDataType>& updateEval, TimeEvaluator<GeomDataType>& timeEval)
{
using DMI = typename GeomDataType::DataMemberId;
bool performsUpdate = updateEval.PerformsUpdate(DMI::COLORS);
bool timeVaryingUpdate = timeEval.IsTimeVarying(DMI::COLORS);
UsdGeomPrimvar uniformDispPrimvar = uniformPrimvars.GetPrimvar(UsdBridgeTokens->color);
UsdGeomPrimvar timeVarDispPrimvar = timeVarPrimvars.GetPrimvar(UsdBridgeTokens->color);
ClearUsdAttributes(uniformDispPrimvar.GetAttr(), timeVarDispPrimvar.GetAttr(), timeVaryingUpdate);
if (performsUpdate)
{
UsdTimeCode timeCode = timeEval.Eval(DMI::COLORS);
UsdGeomPrimvar colorPrimvar = timeVaryingUpdate ? timeVarDispPrimvar : uniformDispPrimvar;
if (geomData.Colors != nullptr)
{
size_t arrayNumElements = geomData.PerPrimColors ? numPrims : geomData.NumPoints;
assert(colorPrimvar);
AssignColorArrayToPrimvar(writer->LogObject, geomData.Colors, arrayNumElements, geomData.ColorsType, timeEval.Eval(DMI::COLORS), colorPrimvar.GetAttr());
// Per face or per-vertex interpolation. This will break timesteps that have been written before.
TfToken colorInterpolation = geomData.PerPrimColors ? UsdGeomTokens->uniform : UsdGeomTokens->vertex;
uniformDispPrimvar.SetInterpolation(colorInterpolation);
}
else
{
colorPrimvar.GetAttr().Set(SdfValueBlock(), timeCode);
}
}
}
template<typename UsdGeomType, typename GeomDataType>
void UpdateUsdGeomInstanceIds(const UsdBridgeLogObject& logObj, UsdGeomType& timeVarGeom, UsdGeomType& uniformGeom, const GeomDataType& geomData, uint64_t numPrims,
UsdBridgeUpdateEvaluator<const GeomDataType>& updateEval, TimeEvaluator<GeomDataType>& timeEval)
{
using DMI = typename GeomDataType::DataMemberId;
bool performsUpdate = updateEval.PerformsUpdate(DMI::INSTANCEIDS);
bool timeVaryingUpdate = timeEval.IsTimeVarying(DMI::INSTANCEIDS);
ClearUsdAttributes(uniformGeom.GetIdsAttr(), timeVarGeom.GetIdsAttr(), timeVaryingUpdate);
if (performsUpdate)
{
UsdGeomType* outGeom = timeVaryingUpdate ? &timeVarGeom : &uniformGeom;
UsdTimeCode timeCode = timeEval.Eval(DMI::INSTANCEIDS);
UsdAttribute idsAttr = outGeom->GetIdsAttr();
if (geomData.InstanceIds)
{
const void* arrayData = geomData.InstanceIds;
size_t arrayNumElements = geomData.NumPoints;
UsdAttribute arrayPrimvar = idsAttr;
bool setPrimvar = true;
switch (geomData.InstanceIdsType)
{
case UsdBridgeType::UINT: {ASSIGN_PRIMVAR_CONVERT_MACRO(VtInt64Array, unsigned int); break; }
case UsdBridgeType::INT: {ASSIGN_PRIMVAR_CONVERT_MACRO(VtInt64Array, int); break; }
case UsdBridgeType::LONG: {ASSIGN_PRIMVAR_MACRO(VtInt64Array); break; }
case UsdBridgeType::ULONG: {ASSIGN_PRIMVAR_MACRO(VtInt64Array); break; }
default: { UsdBridgeLogMacro(logObj, UsdBridgeLogLevel::ERR, "UsdGeom IdsAttribute should be (U)LONG or (U)INT."); break; }
}
}
else
{
idsAttr.Set(SdfValueBlock(), timeCode);
}
}
}
template<typename UsdGeomType, typename GeomDataType>
void UpdateUsdGeomWidths(const UsdBridgeLogObject& logObj, UsdGeomType& timeVarGeom, UsdGeomType& uniformGeom, const GeomDataType& geomData, uint64_t numPrims,
UsdBridgeUpdateEvaluator<const GeomDataType>& updateEval, TimeEvaluator<GeomDataType>& timeEval)
{
using DMI = typename GeomDataType::DataMemberId;
bool performsUpdate = updateEval.PerformsUpdate(DMI::SCALES);
bool timeVaryingUpdate = timeEval.IsTimeVarying(DMI::SCALES);
ClearUsdAttributes(uniformGeom.GetWidthsAttr(), timeVarGeom.GetWidthsAttr(), timeVaryingUpdate);
if (performsUpdate)
{
UsdGeomType& outGeom = timeVaryingUpdate ? timeVarGeom : uniformGeom;
UsdTimeCode timeCode = timeEval.Eval(DMI::SCALES);
UsdAttribute widthsAttribute = outGeom.GetWidthsAttr();
assert(widthsAttribute);
if (geomData.Scales)
{
const void* arrayData = geomData.Scales;
size_t arrayNumElements = geomData.NumPoints;
UsdAttribute arrayPrimvar = widthsAttribute;
bool setPrimvar = false;
auto doubleFn = [](VtFloatArray& usdArray) { for(auto& x : usdArray) { x *= 2.0f; } };
switch (geomData.ScalesType)
{
case UsdBridgeType::FLOAT: {ASSIGN_PRIMVAR_MACRO(VtFloatArray); doubleFn(usdArray); arrayPrimvar.Set(usdArray, timeCode); break; }
case UsdBridgeType::DOUBLE: {ASSIGN_PRIMVAR_CONVERT_MACRO(VtFloatArray, double); doubleFn(usdArray); arrayPrimvar.Set(usdArray, timeCode); break; }
default: { UsdBridgeLogMacro(logObj, UsdBridgeLogLevel::ERR, "UsdGeom WidthsAttribute should be FLOAT or DOUBLE."); break; }
}
}
else
{
// Remember that widths define a diameter, so a default width (1.0) corresponds to a scale of 0.5.
if(geomData.getUniformScale() != 0.5f)
{
VtFloatArray& usdWidths = GetStaticTempArray<VtFloatArray>();
usdWidths.resize(geomData.NumPoints);
for(auto& x : usdWidths) x = geomData.getUniformScale() * 2.0f;
widthsAttribute.Set(usdWidths, timeCode);
}
else
{
widthsAttribute.Set(SdfValueBlock(), timeCode);
}
}
}
}
template<typename UsdGeomType, typename GeomDataType>
void UpdateUsdGeomScales(const UsdBridgeLogObject& logObj, UsdGeomType& timeVarGeom, UsdGeomType& uniformGeom, const GeomDataType& geomData, uint64_t numPrims,
UsdBridgeUpdateEvaluator<const GeomDataType>& updateEval, TimeEvaluator<GeomDataType>& timeEval)
{
using DMI = typename GeomDataType::DataMemberId;
bool performsUpdate = updateEval.PerformsUpdate(DMI::SCALES);
bool timeVaryingUpdate = timeEval.IsTimeVarying(DMI::SCALES);
ClearUsdAttributes(uniformGeom.GetScalesAttr(), timeVarGeom.GetScalesAttr(), timeVaryingUpdate);
if (performsUpdate)
{
UsdGeomType& outGeom = timeVaryingUpdate ? timeVarGeom : uniformGeom;
UsdTimeCode timeCode = timeEval.Eval(DMI::SCALES);
UsdAttribute scalesAttribute = outGeom.GetScalesAttr();
assert(scalesAttribute);
if (geomData.Scales)
{
const void* arrayData = geomData.Scales;
size_t arrayNumElements = geomData.NumPoints;
UsdAttribute arrayPrimvar = scalesAttribute;
bool setPrimvar = true;
switch (geomData.ScalesType)
{
case UsdBridgeType::FLOAT: {ASSIGN_PRIMVAR_MACRO_1EXPAND3(VtVec3fArray, float); break;}
case UsdBridgeType::DOUBLE: {ASSIGN_PRIMVAR_MACRO_1EXPAND3(VtVec3fArray, double); break;}
case UsdBridgeType::FLOAT3: {ASSIGN_PRIMVAR_MACRO(VtVec3fArray); break; }
case UsdBridgeType::DOUBLE3: {ASSIGN_PRIMVAR_CONVERT_MACRO(VtVec3fArray, GfVec3d); break; }
default: { UsdBridgeLogMacro(logObj, UsdBridgeLogLevel::ERR, "UsdGeom ScalesAttribute should be FLOAT(3) or DOUBLE(3)."); break; }
}
}
else
{
if(!usdbridgenumerics::isIdentity(geomData.Scale))
{
GfVec3f defaultScale(geomData.Scale.Data);
VtVec3fArray& usdScales = GetStaticTempArray<VtVec3fArray>();
usdScales.resize(geomData.NumPoints);
for(auto& x : usdScales) x = defaultScale;
scalesAttribute.Set(usdScales, timeCode);
}
else
{
scalesAttribute.Set(SdfValueBlock(), timeCode);
}
}
}
}
template<typename UsdGeomType, typename GeomDataType>
void UpdateUsdGeomOrientNormals(const UsdBridgeLogObject& logObj, UsdGeomType& timeVarGeom, UsdGeomType& uniformGeom, const GeomDataType& geomData, uint64_t numPrims,
UsdBridgeUpdateEvaluator<const GeomDataType>& updateEval, TimeEvaluator<GeomDataType>& timeEval)
{
using DMI = typename GeomDataType::DataMemberId;
bool performsUpdate = updateEval.PerformsUpdate(DMI::ORIENTATIONS);
bool timeVaryingUpdate = timeEval.IsTimeVarying(DMI::ORIENTATIONS);
ClearUsdAttributes(uniformGeom.GetNormalsAttr(), timeVarGeom.GetNormalsAttr(), timeVaryingUpdate);
if (performsUpdate)
{
UsdGeomType& outGeom = timeVaryingUpdate ? timeVarGeom : uniformGeom;
UsdTimeCode timeCode = timeEval.Eval(DMI::ORIENTATIONS);
UsdAttribute normalsAttribute = outGeom.GetNormalsAttr();
assert(normalsAttribute);
if (geomData.Orientations)
{
const void* arrayData = geomData.Orientations;
size_t arrayNumElements = geomData.NumPoints;
UsdAttribute arrayPrimvar = normalsAttribute;
bool setPrimvar = true;
switch (geomData.OrientationsType)
{
case UsdBridgeType::FLOAT3: {ASSIGN_PRIMVAR_MACRO(VtVec3fArray); break; }
case UsdBridgeType::DOUBLE3: {ASSIGN_PRIMVAR_CONVERT_MACRO(VtVec3fArray, GfVec3d); break; }
default: { UsdBridgeLogMacro(logObj, UsdBridgeLogLevel::ERR, "UsdGeom NormalsAttribute (orientations) should be FLOAT3 or DOUBLE3."); break; }
}
}
else
{
//GfVec3f defaultNormal(1, 0, 0);
//VtVec3fArray& usdNormals = GetStaticTempArray<VtVec3fArray>();
//usdNormals.resize(geomData.NumPoints);
//for(auto& x : usdNormals) x = defaultNormal;
//normalsAttribute.Set(usdNormals, timeCode);
normalsAttribute.Set(SdfValueBlock(), timeCode);
}
}
}
template<typename UsdGeomType, typename GeomDataType>
void UpdateUsdGeomOrientations(const UsdBridgeLogObject& logObj, UsdGeomType& timeVarGeom, UsdGeomType& uniformGeom, const GeomDataType& geomData, uint64_t numPrims,
UsdBridgeUpdateEvaluator<const GeomDataType>& updateEval, TimeEvaluator<GeomDataType>& timeEval)
{
using DMI = typename GeomDataType::DataMemberId;
bool performsUpdate = updateEval.PerformsUpdate(DMI::ORIENTATIONS);
bool timeVaryingUpdate = timeEval.IsTimeVarying(DMI::ORIENTATIONS);
ClearUsdAttributes(uniformGeom.GetOrientationsAttr(), timeVarGeom.GetOrientationsAttr(), timeVaryingUpdate);
if (performsUpdate)
{
UsdGeomType& outGeom = timeVaryingUpdate ? timeVarGeom : uniformGeom;
UsdTimeCode timeCode = timeEval.Eval(DMI::ORIENTATIONS);
// Orientations
UsdAttribute orientationsAttribute = outGeom.GetOrientationsAttr();
assert(orientationsAttribute);
VtQuathArray& usdOrients = GetStaticTempArray<VtQuathArray>();
if (geomData.Orientations)
{
usdOrients.resize(geomData.NumPoints);
switch (geomData.OrientationsType)
{
case UsdBridgeType::FLOAT3: { ConvertNormalsToQuaternions<float>(usdOrients, geomData.Orientations, geomData.NumPoints); break; }
case UsdBridgeType::DOUBLE3: { ConvertNormalsToQuaternions<double>(usdOrients, geomData.Orientations, geomData.NumPoints); break; }
case UsdBridgeType::FLOAT4:
{
for (uint64_t i = 0; i < geomData.NumPoints; ++i)
{
const float* orients = reinterpret_cast<const float*>(geomData.Orientations);
usdOrients[i] = GfQuath(orients[i * 4], orients[i * 4 + 1], orients[i * 4 + 2], orients[i * 4 + 3]);
}
orientationsAttribute.Set(usdOrients, timeCode);
break;
}
default: { UsdBridgeLogMacro(logObj, UsdBridgeLogLevel::ERR, "UsdGeom OrientationsAttribute should be FLOAT3, DOUBLE3 or FLOAT4."); break; }
}
orientationsAttribute.Set(usdOrients, timeCode);
}
else
{
if(!usdbridgenumerics::isIdentity(geomData.Orientation))
{
GfQuath defaultOrient(geomData.Orientation.Data[0], geomData.Orientation.Data[1], geomData.Orientation.Data[2], geomData.Orientation.Data[3]);
usdOrients.resize(geomData.NumPoints);
for(auto& x : usdOrients) x = defaultOrient;
orientationsAttribute.Set(usdOrients, timeCode);
}
else
{
orientationsAttribute.Set(SdfValueBlock(), timeCode);
}
}
}
}
template<typename UsdGeomType, typename GeomDataType>
void UpdateUsdGeomProtoIndices(const UsdBridgeLogObject& logObj, UsdGeomType& timeVarGeom, UsdGeomType& uniformGeom, const GeomDataType& geomData, uint64_t numPrims,
UsdBridgeUpdateEvaluator<const GeomDataType>& updateEval, TimeEvaluator<GeomDataType>& timeEval)
{
using DMI = typename GeomDataType::DataMemberId;
bool performsUpdate = updateEval.PerformsUpdate(DMI::SHAPEINDICES);
bool timeVaryingUpdate = timeEval.IsTimeVarying(DMI::SHAPEINDICES);
if (performsUpdate)
{
UsdTimeCode timeCode = timeEval.Eval(DMI::SHAPEINDICES);
UsdGeomType* outGeom = timeCode.IsDefault() ? &uniformGeom : &timeVarGeom;
UsdAttribute protoIndexAttr = outGeom->GetProtoIndicesAttr();
assert(protoIndexAttr);
//Shape indices
if(geomData.ShapeIndices)
{
const void* arrayData = geomData.ShapeIndices;
size_t arrayNumElements = geomData.NumPoints;
UsdAttribute arrayPrimvar = protoIndexAttr;
bool setPrimvar = true;
switch (geomData.OrientationsType)
{
case UsdBridgeType::INT: {ASSIGN_PRIMVAR_MACRO(VtIntArray); break; }
default: { UsdBridgeLogMacro(logObj, UsdBridgeLogLevel::ERR, "UsdGeom ProtoIndicesAttr (ShapeIndices) should be INT."); break; }
}
}
else
{
VtIntArray& protoIndices = GetStaticTempArray<VtIntArray>();
protoIndices.resize(geomData.NumPoints);
for(auto& x : protoIndices) x = 0;
protoIndexAttr.Set(protoIndices, timeCode);
}
}
}
template<typename UsdGeomType, typename GeomDataType>
void UpdateUsdGeomLinearVelocities(const UsdBridgeLogObject& logObj, UsdGeomType& timeVarGeom, UsdGeomType& uniformGeom, const GeomDataType& geomData, uint64_t numPrims,
UsdBridgeUpdateEvaluator<const GeomDataType>& updateEval, TimeEvaluator<GeomDataType>& timeEval)
{
using DMI = typename GeomDataType::DataMemberId;
bool performsUpdate = updateEval.PerformsUpdate(DMI::LINEARVELOCITIES);
bool timeVaryingUpdate = timeEval.IsTimeVarying(DMI::LINEARVELOCITIES);
ClearUsdAttributes(uniformGeom.GetVelocitiesAttr(), timeVarGeom.GetVelocitiesAttr(), timeVaryingUpdate);
if (performsUpdate)
{
UsdGeomType& outGeom = timeVaryingUpdate ? timeVarGeom : uniformGeom;
UsdTimeCode timeCode = timeEval.Eval(DMI::LINEARVELOCITIES);
// Linear velocities
UsdAttribute linearVelocitiesAttribute = outGeom.GetVelocitiesAttr();
assert(linearVelocitiesAttribute);
if (geomData.LinearVelocities)
{
GfVec3f* linVels = (GfVec3f*)geomData.LinearVelocities;
VtVec3fArray& usdVelocities = GetStaticTempArray<VtVec3fArray>();
usdVelocities.assign(linVels, linVels + geomData.NumPoints);
linearVelocitiesAttribute.Set(usdVelocities, timeCode);
}
else
{
linearVelocitiesAttribute.Set(SdfValueBlock(), timeCode);
}
}
}
template<typename UsdGeomType, typename GeomDataType>
void UpdateUsdGeomAngularVelocities(const UsdBridgeLogObject& logObj, UsdGeomType& timeVarGeom, UsdGeomType& uniformGeom, const GeomDataType& geomData, uint64_t numPrims,
UsdBridgeUpdateEvaluator<const GeomDataType>& updateEval, TimeEvaluator<GeomDataType>& timeEval)
{
using DMI = typename GeomDataType::DataMemberId;
bool performsUpdate = updateEval.PerformsUpdate(DMI::ANGULARVELOCITIES);
bool timeVaryingUpdate = timeEval.IsTimeVarying(DMI::ANGULARVELOCITIES);
ClearUsdAttributes(uniformGeom.GetAngularVelocitiesAttr(), timeVarGeom.GetAngularVelocitiesAttr(), timeVaryingUpdate);
if (performsUpdate)
{
UsdGeomType& outGeom = timeVaryingUpdate ? timeVarGeom : uniformGeom;
UsdTimeCode timeCode = timeEval.Eval(DMI::ANGULARVELOCITIES);
// Angular velocities
UsdAttribute angularVelocitiesAttribute = outGeom.GetAngularVelocitiesAttr();
assert(angularVelocitiesAttribute);
if (geomData.AngularVelocities)
{
GfVec3f* angVels = (GfVec3f*)geomData.AngularVelocities;
VtVec3fArray& usdAngularVelocities = GetStaticTempArray<VtVec3fArray>();
usdAngularVelocities.assign(angVels, angVels + geomData.NumPoints);
angularVelocitiesAttribute.Set(usdAngularVelocities, timeCode);
}
else
{
angularVelocitiesAttribute.Set(SdfValueBlock(), timeCode);
}
}
}
template<typename UsdGeomType, typename GeomDataType>
void UpdateUsdGeomInvisibleIds(const UsdBridgeLogObject& logObj, UsdGeomType& timeVarGeom, UsdGeomType& uniformGeom, const GeomDataType& geomData, uint64_t numPrims,
UsdBridgeUpdateEvaluator<const GeomDataType>& updateEval, TimeEvaluator<GeomDataType>& timeEval)
{
using DMI = typename GeomDataType::DataMemberId;
bool performsUpdate = updateEval.PerformsUpdate(DMI::INVISIBLEIDS);
bool timeVaryingUpdate = timeEval.IsTimeVarying(DMI::INVISIBLEIDS);
ClearUsdAttributes(uniformGeom.GetInvisibleIdsAttr(), timeVarGeom.GetInvisibleIdsAttr(), timeVaryingUpdate);
if (performsUpdate)
{
UsdGeomType& outGeom = timeVaryingUpdate ? timeVarGeom : uniformGeom;
UsdTimeCode timeCode = timeEval.Eval(DMI::INVISIBLEIDS);
// Invisible ids
UsdAttribute invisIdsAttr = outGeom.GetInvisibleIdsAttr();
assert(invisIdsAttr);
uint64_t numInvisibleIds = geomData.NumInvisibleIds;
if (numInvisibleIds)
{
const void* arrayData = geomData.InvisibleIds;
size_t arrayNumElements = numInvisibleIds;
UsdAttribute arrayPrimvar = invisIdsAttr;
bool setPrimvar = true;
switch (geomData.InvisibleIdsType)
{
case UsdBridgeType::UINT: {ASSIGN_PRIMVAR_CONVERT_MACRO(VtInt64Array, unsigned int); break; }
case UsdBridgeType::INT: {ASSIGN_PRIMVAR_CONVERT_MACRO(VtInt64Array, int); break; }
case UsdBridgeType::LONG: {ASSIGN_PRIMVAR_MACRO(VtInt64Array); break; }
case UsdBridgeType::ULONG: {ASSIGN_PRIMVAR_MACRO(VtInt64Array); break; }
default: { UsdBridgeLogMacro(logObj, UsdBridgeLogLevel::ERR, "UsdGeom GetInvisibleIdsAttr should be (U)LONG or (U)INT."); break; }
}
}
else
{
invisIdsAttr.Set(SdfValueBlock(), timeCode);
}
}
}
static void UpdateUsdGeomCurveLengths(const UsdBridgeLogObject& logObj, UsdGeomBasisCurves& timeVarGeom, UsdGeomBasisCurves& uniformGeom, const UsdBridgeCurveData& geomData, uint64_t numPrims,
UsdBridgeUpdateEvaluator<const UsdBridgeCurveData>& updateEval, TimeEvaluator<UsdBridgeCurveData>& timeEval)
{
using DMI = typename UsdBridgeCurveData::DataMemberId;
// Fill geom prim and geometry layer with data.
bool performsUpdate = updateEval.PerformsUpdate(DMI::CURVELENGTHS);
bool timeVaryingUpdate = timeEval.IsTimeVarying(DMI::CURVELENGTHS);
ClearUsdAttributes(uniformGeom.GetCurveVertexCountsAttr(), timeVarGeom.GetCurveVertexCountsAttr(), timeVaryingUpdate);
if (performsUpdate)
{
UsdGeomBasisCurves& outGeom = timeVaryingUpdate ? timeVarGeom : uniformGeom;
UsdTimeCode timeCode = timeEval.Eval(DMI::POINTS);
UsdAttribute vertCountAttr = outGeom.GetCurveVertexCountsAttr();
assert(vertCountAttr);
const void* arrayData = geomData.CurveLengths;
size_t arrayNumElements = geomData.NumCurveLengths;
UsdAttribute arrayPrimvar = vertCountAttr;
bool setPrimvar = true;
{ ASSIGN_PRIMVAR_MACRO(VtIntArray); }
}
}
void UpdateUsdGeomPrototypes(const UsdBridgeLogObject& logObj, const UsdStagePtr& sceneStage, UsdGeomPointInstancer& uniformGeom,
const UsdBridgeInstancerRefData& geomRefData, const SdfPrimPathList& protoGeomPaths,
const char* protoShapePathRp)
{
using DMI = typename UsdBridgeInstancerData::DataMemberId;
SdfPath protoBasePath = uniformGeom.GetPath().AppendPath(SdfPath(protoShapePathRp));
sceneStage->RemovePrim(protoBasePath);
UsdRelationship protoRel = uniformGeom.GetPrototypesRel();
for(int shapeIdx = 0; shapeIdx < geomRefData.NumShapes; ++shapeIdx)
{
SdfPath shapePath;
if(geomRefData.Shapes[shapeIdx] != UsdBridgeInstancerRefData::SHAPE_MESH)
{
std::string protoName = constring::protoShapePf + std::to_string(shapeIdx);
shapePath = protoBasePath.AppendPath(SdfPath(protoName.c_str()));
}
else
{
int protoGeomIdx = static_cast<int>(geomRefData.Shapes[shapeIdx]); // The mesh shape value is an index into protoGeomPaths
assert(protoGeomIdx < protoGeomPaths.size());
shapePath = protoGeomPaths[protoGeomIdx];
}
UsdGeomXformable geomXformable;
switch (geomRefData.Shapes[shapeIdx])
{
case UsdBridgeInstancerRefData::SHAPE_SPHERE:
{
geomXformable = UsdGeomSphere::Define(sceneStage, shapePath);
break;
}
case UsdBridgeInstancerRefData::SHAPE_CYLINDER:
{
geomXformable = UsdGeomCylinder::Define(sceneStage, shapePath);
break;
}
case UsdBridgeInstancerRefData::SHAPE_CONE:
{
geomXformable = UsdGeomCone::Define(sceneStage, shapePath);
break;
}
default:
{
geomXformable = UsdGeomXformable::Get(sceneStage, shapePath);
break;
}
}
// Add a transform
geomXformable.ClearXformOpOrder();
if(!usdbridgenumerics::isIdentity(geomRefData.ShapeTransform))
{
const float* transform = geomRefData.ShapeTransform.Data;
GfMatrix4d transMat;
transMat.SetRow(0, GfVec4d(GfVec4f(&transform[0])));
transMat.SetRow(1, GfVec4d(GfVec4f(&transform[4])));
transMat.SetRow(2, GfVec4d(GfVec4f(&transform[8])));
transMat.SetRow(3, GfVec4d(GfVec4f(&transform[12])));
geomXformable.AddTransformOp().Set(transMat);
}
protoRel.AddTarget(shapePath);
}
}
}
UsdPrim UsdBridgeUsdWriter::InitializeUsdGeometry(UsdStageRefPtr geometryStage, const SdfPath& geomPath, const UsdBridgeMeshData& meshData, bool uniformPrim)
{
return InitializeUsdGeometry_Impl(this, geometryStage, geomPath, meshData, uniformPrim, Settings);
}
UsdPrim UsdBridgeUsdWriter::InitializeUsdGeometry(UsdStageRefPtr geometryStage, const SdfPath& geomPath, const UsdBridgeInstancerData& instancerData, bool uniformPrim)
{
return InitializeUsdGeometry_Impl(this, geometryStage, geomPath, instancerData, uniformPrim, Settings);
}
UsdPrim UsdBridgeUsdWriter::InitializeUsdGeometry(UsdStageRefPtr geometryStage, const SdfPath& geomPath, const UsdBridgeCurveData& curveData, bool uniformPrim)
{
return InitializeUsdGeometry_Impl(this, geometryStage, geomPath, curveData, uniformPrim, Settings);
}
#ifdef VALUE_CLIP_RETIMING
void UsdBridgeUsdWriter::UpdateUsdGeometryManifest(const UsdBridgePrimCache* cacheEntry, const UsdBridgeMeshData& meshData)
{
TimeEvaluator<UsdBridgeMeshData> timeEval(meshData);
InitializeUsdGeometry_Impl(this, cacheEntry->ManifestStage.second, cacheEntry->PrimPath, meshData, false,
Settings, &timeEval);
if(this->EnableSaving)
cacheEntry->ManifestStage.second->Save();
}
void UsdBridgeUsdWriter::UpdateUsdGeometryManifest(const UsdBridgePrimCache* cacheEntry, const UsdBridgeInstancerData& instancerData)
{
TimeEvaluator<UsdBridgeInstancerData> timeEval(instancerData);
InitializeUsdGeometry_Impl(this, cacheEntry->ManifestStage.second, cacheEntry->PrimPath, instancerData, false,
Settings, &timeEval);
if(this->EnableSaving)
cacheEntry->ManifestStage.second->Save();
}
void UsdBridgeUsdWriter::UpdateUsdGeometryManifest(const UsdBridgePrimCache* cacheEntry, const UsdBridgeCurveData& curveData)
{
TimeEvaluator<UsdBridgeCurveData> timeEval(curveData);
InitializeUsdGeometry_Impl(this, cacheEntry->ManifestStage.second, cacheEntry->PrimPath, curveData, false,
Settings, &timeEval);
if(this->EnableSaving)
cacheEntry->ManifestStage.second->Save();
}
#endif
#define UPDATE_USDGEOM_ARRAYS(FuncDef) \
FuncDef(this->LogObject, timeVarGeom, uniformGeom, geomData, numPrims, updateEval, timeEval)
#define UPDATE_USDGEOM_PRIMVAR_ARRAYS(FuncDef) \
FuncDef(this, timeVarPrimvars, uniformPrimvars, geomData, numPrims, updateEval, timeEval)
void UsdBridgeUsdWriter::UpdateUsdGeometry(const UsdStagePtr& timeVarStage, const SdfPath& meshPath, const UsdBridgeMeshData& geomData, double timeStep)
{
// To avoid data duplication when using of clip stages, we need to potentially use the scenestage prim for time-uniform data.
UsdGeomMesh uniformGeom = UsdGeomMesh::Get(this->SceneStage, meshPath);
assert(uniformGeom);
UsdGeomPrimvarsAPI uniformPrimvars(uniformGeom);
UsdGeomMesh timeVarGeom = UsdGeomMesh::Get(timeVarStage, meshPath);
assert(timeVarGeom);
UsdGeomPrimvarsAPI timeVarPrimvars(timeVarGeom);
// Update the mesh
UsdBridgeUpdateEvaluator<const UsdBridgeMeshData> updateEval(geomData);
TimeEvaluator<UsdBridgeMeshData> timeEval(geomData, timeStep);
assert((geomData.NumIndices % geomData.FaceVertexCount) == 0);
uint64_t numPrims = int(geomData.NumIndices) / geomData.FaceVertexCount;
UPDATE_USDGEOM_ARRAYS(UpdateUsdGeomPoints);
UPDATE_USDGEOM_ARRAYS(UpdateUsdGeomNormals);
if( Settings.EnableStTexCoords && UsdGeomDataHasTexCoords(geomData) )
{ UPDATE_USDGEOM_PRIMVAR_ARRAYS(UpdateUsdGeomTexCoords); }
UPDATE_USDGEOM_PRIMVAR_ARRAYS(UpdateUsdGeomAttributes);
UPDATE_USDGEOM_PRIMVAR_ARRAYS(UpdateUsdGeomColors);
UPDATE_USDGEOM_ARRAYS(UpdateUsdGeomIndices);
}
void UsdBridgeUsdWriter::UpdateUsdGeometry(const UsdStagePtr& timeVarStage, const SdfPath& instancerPath, const UsdBridgeInstancerData& geomData, double timeStep)
{
UsdBridgeUpdateEvaluator<const UsdBridgeInstancerData> updateEval(geomData);
TimeEvaluator<UsdBridgeInstancerData> timeEval(geomData, timeStep);
bool useGeomPoints = geomData.UseUsdGeomPoints;
uint64_t numPrims = geomData.NumPoints;
if (useGeomPoints)
{
UsdGeomPoints uniformGeom = UsdGeomPoints::Get(this->SceneStage, instancerPath);
assert(uniformGeom);
UsdGeomPrimvarsAPI uniformPrimvars(uniformGeom);
UsdGeomPoints timeVarGeom = UsdGeomPoints::Get(timeVarStage, instancerPath);
assert(timeVarGeom);
UsdGeomPrimvarsAPI timeVarPrimvars(timeVarGeom);
UPDATE_USDGEOM_ARRAYS(UpdateUsdGeomPoints);
UPDATE_USDGEOM_ARRAYS(UpdateUsdGeomInstanceIds);
UPDATE_USDGEOM_ARRAYS(UpdateUsdGeomWidths);
UPDATE_USDGEOM_ARRAYS(UpdateUsdGeomOrientNormals);
if( Settings.EnableStTexCoords && UsdGeomDataHasTexCoords(geomData) )
{ UPDATE_USDGEOM_PRIMVAR_ARRAYS(UpdateUsdGeomTexCoords); }
UPDATE_USDGEOM_PRIMVAR_ARRAYS(UpdateUsdGeomAttributes);
UPDATE_USDGEOM_PRIMVAR_ARRAYS(UpdateUsdGeomColors);
}
else
{
UsdGeomPointInstancer uniformGeom = UsdGeomPointInstancer::Get(this->SceneStage, instancerPath);
assert(uniformGeom);
UsdGeomPrimvarsAPI uniformPrimvars(uniformGeom);
UsdGeomPointInstancer timeVarGeom = UsdGeomPointInstancer::Get(timeVarStage, instancerPath);
assert(timeVarGeom);
UsdGeomPrimvarsAPI timeVarPrimvars(timeVarGeom);
UPDATE_USDGEOM_ARRAYS(UpdateUsdGeomPoints);
UPDATE_USDGEOM_ARRAYS(UpdateUsdGeomInstanceIds);
UPDATE_USDGEOM_ARRAYS(UpdateUsdGeomScales);
UPDATE_USDGEOM_ARRAYS(UpdateUsdGeomOrientations);
if( Settings.EnableStTexCoords && UsdGeomDataHasTexCoords(geomData) )
{ UPDATE_USDGEOM_PRIMVAR_ARRAYS(UpdateUsdGeomTexCoords); }
UPDATE_USDGEOM_PRIMVAR_ARRAYS(UpdateUsdGeomAttributes);
UPDATE_USDGEOM_PRIMVAR_ARRAYS(UpdateUsdGeomColors);
UPDATE_USDGEOM_ARRAYS(UpdateUsdGeomProtoIndices);
//UPDATE_USDGEOM_ARRAYS(UpdateUsdGeomLinearVelocities);
//UPDATE_USDGEOM_ARRAYS(UpdateUsdGeomAngularVelocities);
UPDATE_USDGEOM_ARRAYS(UpdateUsdGeomInvisibleIds);
}
}
void UsdBridgeUsdWriter::UpdateUsdGeometry(const UsdStagePtr& timeVarStage, const SdfPath& curvePath, const UsdBridgeCurveData& geomData, double timeStep)
{
// To avoid data duplication when using of clip stages, we need to potentially use the scenestage prim for time-uniform data.
UsdGeomBasisCurves uniformGeom = UsdGeomBasisCurves::Get(this->SceneStage, curvePath);
assert(uniformGeom);
UsdGeomPrimvarsAPI uniformPrimvars(uniformGeom);
UsdGeomBasisCurves timeVarGeom = UsdGeomBasisCurves::Get(timeVarStage, curvePath);
assert(timeVarGeom);
UsdGeomPrimvarsAPI timeVarPrimvars(timeVarGeom);
// Update the curve
UsdBridgeUpdateEvaluator<const UsdBridgeCurveData> updateEval(geomData);
TimeEvaluator<UsdBridgeCurveData> timeEval(geomData, timeStep);
uint64_t numPrims = geomData.NumCurveLengths;
UPDATE_USDGEOM_ARRAYS(UpdateUsdGeomPoints);
UPDATE_USDGEOM_ARRAYS(UpdateUsdGeomNormals);
if( Settings.EnableStTexCoords && UsdGeomDataHasTexCoords(geomData) )
{ UPDATE_USDGEOM_PRIMVAR_ARRAYS(UpdateUsdGeomTexCoords); }
UPDATE_USDGEOM_PRIMVAR_ARRAYS(UpdateUsdGeomAttributes);
UPDATE_USDGEOM_PRIMVAR_ARRAYS(UpdateUsdGeomColors);
UPDATE_USDGEOM_ARRAYS(UpdateUsdGeomWidths);
UPDATE_USDGEOM_ARRAYS(UpdateUsdGeomCurveLengths);
}
void UsdBridgeUsdWriter::UpdateUsdInstancerPrototypes(const SdfPath& instancerPath, const UsdBridgeInstancerRefData& geomRefData,
const SdfPrimPathList& refProtoGeomPrimPaths, const char* protoShapePathRp)
{
UsdGeomPointInstancer uniformGeom = UsdGeomPointInstancer::Get(this->SceneStage, instancerPath);
if(!uniformGeom)
{
UsdBridgeLogMacro(this->LogObject, UsdBridgeLogLevel::WARNING, "Attempt to perform update of prototypes on a prim that is not a UsdGeomPointInstancer.");
return;
}
// Very basic rel update, without any timevarying aspects
UpdateUsdGeomPrototypes(this->LogObject, this->SceneStage, uniformGeom, geomRefData, refProtoGeomPrimPaths, protoShapePathRp);
} | 54,355 | C++ | 42.835484 | 246 | 0.739582 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.