file_path
stringlengths
21
207
content
stringlengths
5
1.02M
size
int64
5
1.02M
lang
stringclasses
9 values
avg_line_length
float64
1.33
100
max_line_length
int64
4
993
alphanum_fraction
float64
0.27
0.93
NVIDIA-Omniverse/OpenUSD-Code-Samples/source/transforms/get-world-transforms/py_omni_usd.py
# SPDX-FileCopyrightText: Copyright (c) 2023 NVIDIA CORPORATION & AFFILIATES. All rights reserved. # SPDX-License-Identifier: Apache-2.0 import omni.usd from pxr import Usd, Gf import typing def get_world_transform_xform(prim: Usd.Prim) -> typing.Tuple[Gf.Vec3d, Gf.Rotation, Gf.Vec3d]: """ Get the local transformation of a prim using omni.usd.get_world_transform_matrix(). See https://docs.omniverse.nvidia.com/kit/docs/omni.usd/latest/omni.usd/omni.usd.get_world_transform_matrix.html Args: prim: The prim to calculate the world transformation. Returns: A tuple of: - Translation vector. - Rotation quaternion, i.e. 3d vector plus angle. - Scale vector. """ world_transform: Gf.Matrix4d = omni.usd.get_world_transform_matrix(prim) translation: Gf.Vec3d = world_transform.ExtractTranslation() rotation: Gf.Rotation = world_transform.ExtractRotation() scale: Gf.Vec3d = Gf.Vec3d(*(v.GetLength() for v in world_transform.ExtractRotationMatrix())) return translation, rotation, scale ############# # Full Usage ############# import omni.kit.commands # Create an Xform with a Cube Prim as it's Child omni.kit.commands.execute('CreatePrimWithDefaultXform', prim_type='Xform', attributes={}, select_new_prim=True) omni.kit.commands.execute('TransformMultiPrimsSRTCpp', count=1, paths=['/World/Xform'], new_translations=[100, 0, 0], new_rotation_eulers=[0, 50 ,0], new_rotation_orders=[0, 1, 2], new_scales=[5, 5, 5], old_translations=[0.0, 0.0, 0.0], old_rotation_eulers=[0.0, 0.0, 0.0], old_rotation_orders=[0, 1, 2], old_scales=[1.0, 1.0, 1.0], usd_context_name='', time_code=0.0) omni.kit.commands.execute('CreateMeshPrimWithDefaultXform', prim_type='Cube', prim_path='/World/Xform/Cube', select_new_prim=True, prepend_default_prim=False) omni.kit.commands.execute('TransformMultiPrimsSRTCpp', count=1, paths=['/World/Xform/Cube'], new_translations=[4, 0, 0], new_rotation_eulers=[100, 0 ,0], new_rotation_orders=[0, 1, 2], new_scales=[2, 2, 2], old_translations=[0.0, 0.0, 0.0], old_rotation_eulers=[0.0, 0.0, 0.0], old_rotation_orders=[0, 1, 2], old_scales=[1.0, 1.0, 1.0], usd_context_name='', time_code=0.0) stage = omni.usd.get_context().get_stage() cube_prim = stage.GetPrimAtPath("/World/Xform/Cube") transform = get_world_transform_xform(cube_prim)
2,383
Python
31.216216
116
0.689467
NVIDIA-Omniverse/OpenUSD-Code-Samples/source/transforms/get-world-transforms/py_usd.md
``` {literalinclude} py_usd.py :language: py ``` Alternatively, if you need to compute the world transform for multiple prims on a stage, [UsdGeom.XformCache](https://openusd.org/release/api/class_usd_geom_xform_cache.html) is more efficient. ``` {literalinclude} py_usd_var1.py :language: py ```
298
Markdown
32.222219
193
0.741611
NVIDIA-Omniverse/OpenUSD-Code-Samples/source/transforms/get-world-transforms/usda.md
This is an example USDA result from creating a Xform with a Cube as a child. ``` {literalinclude} usda.usda :language: usd ```
127
Markdown
30.999992
76
0.732283
NVIDIA-Omniverse/OpenUSD-Code-Samples/source/transforms/get-world-transforms/config.toml
[core] title = "Get the World Space Transforms for a Prim" [metadata] description = "Universal Scene Description (OpenUSD) code samples showing how to get the world space transforms for a prim." keywords = ["OpenUSD", "USD", "Python", "snippet", "code sample", "omni.usd", "world space", "world", "transforms", "omni.usd","get_world_transform_matrix", "ComputeLocalToWorldTransform"]
384
TOML
63.166656
188
0.734375
NVIDIA-Omniverse/OpenUSD-Code-Samples/source/transforms/get-world-transforms/py_omni_usd.md
``` {literalinclude} py_omni_usd.py :language: py ```
53
Markdown
16.999994
35
0.660377
NVIDIA-Omniverse/OpenUSD-Code-Samples/source/transforms/get-world-transforms/py_usd_var1.py
# SPDX-FileCopyrightText: Copyright (c) 2023 NVIDIA CORPORATION & AFFILIATES. All rights reserved. # SPDX-License-Identifier: Apache-2.0 import typing from pxr import Usd, UsdGeom, Gf def get_world_transform_cache(cache: UsdGeom.XformCache, prim: Usd.Prim) -> typing.Tuple[Gf.Vec3d, Gf.Rotation, Gf.Vec3d]: """ Get the local transformation of a prim using UsdGeom.XformCache. See: https://openusd.org/release/api/class_usd_geom_xform_cache.html Args: cache: A cache, created for example as `UsdGeom.XformCache()` prim: The prim to calculate the world transformation. Returns: A tuple of: - Translation vector. - Rotation quaternion, i.e. 3d vector plus angle. - Scale vector. """ world_transform: Gf.Matrix4d = cache.GetLocalToWorldTransform(prim) translation: Gf.Vec3d = world_transform.ExtractTranslation() rotation: Gf.Rotation = world_transform.ExtractRotation() scale: Gf.Vec3d = Gf.Vec3d(*(v.GetLength() for v in world_transform.ExtractRotationMatrix())) return translation, rotation, scale ############# # Full Usage ############# from pxr import Sdf # Create an in-memory Stage with /World Xform prim as the default prim stage: Usd.Stage = Usd.Stage.CreateInMemory() default_prim: Usd.Prim = UsdGeom.Xform.Define(stage, Sdf.Path("/World")).GetPrim() stage.SetDefaultPrim(default_prim) xform: Usd.Prim = UsdGeom.Xform.Define(stage, default_prim.GetPath().AppendPath("Xform")) xform.AddTranslateOp().Set(value=(100,10,0)) xform.AddRotateXYZOp().Set(value=(0,50,0)) xform.AddScaleOp().Set(value=(5,5,5)) cube = UsdGeom.Cube.Define(stage, xform.GetPath().AppendPath("Cube")) cube.AddTranslateOp().Set(value=(4,0,0)) cube.AddRotateXYZOp().Set(value=(100,0,0)) cube.AddScaleOp().Set(value=(2,2,2)) time = Usd.TimeCode.Default() # The time at which we compute the bounding box cache = UsdGeom.XformCache(time) transform = get_world_transform_cache(cache, cube.GetPrim()) usda = stage.GetRootLayer().ExportToString() print(usda)
2,030
Python
37.320754
122
0.714778
NVIDIA-Omniverse/OpenUSD-Code-Samples/source/transforms/compute-prim-bounding-box/py_usd.py
# SPDX-FileCopyrightText: Copyright (c) 2023 NVIDIA CORPORATION & AFFILIATES. All rights reserved. # SPDX-License-Identifier: Apache-2.0 from pxr import Usd, UsdGeom, Gf def compute_bbox(prim: Usd.Prim) -> Gf.Range3d: """ Compute Bounding Box using ComputeWorldBound at UsdGeom.Imageable See https://openusd.org/release/api/class_usd_geom_imageable.html Args: prim: A prim to compute the bounding box. Returns: A range (i.e. bounding box), see more at: https://openusd.org/release/api/class_gf_range3d.html """ imageable = UsdGeom.Imageable(prim) time = Usd.TimeCode.Default() # The time at which we compute the bounding box bound = imageable.ComputeWorldBound(time, UsdGeom.Tokens.default_) bound_range = bound.ComputeAlignedBox() return bound_range
815
Python
37.857141
103
0.715337
NVIDIA-Omniverse/OpenUSD-Code-Samples/source/transforms/compute-prim-bounding-box/py_omni_usd.py
import typing import carb import omni.usd def compute_path_bbox(prim_path: str) -> typing.Tuple[carb.Double3, carb.Double3]: """ Compute Bounding Box using omni.usd.UsdContext.compute_path_world_bounding_box See https://docs.omniverse.nvidia.com/kit/docs/omni.usd/latest/omni.usd/omni.usd.UsdContext.html#omni.usd.UsdContext.compute_path_world_bounding_box Args: prim_path: A prim path to compute the bounding box. Returns: A range (i.e. bounding box) as a minimum point and maximum point. """ return omni.usd.get_context().compute_path_world_bounding_box(prim_path)
614
Python
37.437498
152
0.723127
NVIDIA-Omniverse/OpenUSD-Code-Samples/source/transforms/compute-prim-bounding-box/py_usd.md
``` {literalinclude} py_usd.py :language: py ``` Alternatively, if you need to compute the bounding box for multiple prims on a stage, [UsdGeom.BBoxCache](https://openusd.org/release/api/class_usd_geom_b_box_cache.html) is more efficient. ``` {literalinclude} py_usd_var1.py :language: py ```
294
Markdown
31.777774
189
0.734694
NVIDIA-Omniverse/OpenUSD-Code-Samples/source/transforms/compute-prim-bounding-box/config.toml
[core] title = "Compute the Bounding Box for a Prim" [metadata] description = "Universal Scene Description (OpenUSD) code samples showing how to compute the bounding box for a prim." keywords = ["OpenUSD", "USD", "Python", "snippet", "code sample", "bounding box", "prim", "omni.usd", "bbox", "ComputeWorldBound", "ComputeAlignedBox"]
335
TOML
54.999991
151
0.722388
NVIDIA-Omniverse/OpenUSD-Code-Samples/source/transforms/compute-prim-bounding-box/py_omni_usd.md
``` {literalinclude} py_omni_usd.py :language: py ```
53
Markdown
16.999994
35
0.660377
NVIDIA-Omniverse/OpenUSD-Code-Samples/source/transforms/compute-prim-bounding-box/py_usd_var1.py
# SPDX-FileCopyrightText: Copyright (c) 2023 NVIDIA CORPORATION & AFFILIATES. All rights reserved. # SPDX-License-Identifier: Apache-2.0 from pxr import Usd, UsdGeom, Gf def compute_bbox_with_cache(cache: UsdGeom.BBoxCache, prim: Usd.Prim) -> Gf.Range3d: """ Compute Bounding Box using ComputeWorldBound at UsdGeom.BBoxCache. More efficient if used multiple times. See https://openusd.org/release/api/class_usd_geom_b_box_cache.html Args: cache: A cached, i.e. `UsdGeom.BBoxCache(Usd.TimeCode.Default(), ['default', 'render'])` prim: A prim to compute the bounding box. Returns: A range (i.e. bounding box), see more at: https://openusd.org/release/api/class_gf_range3d.html """ bound = cache.ComputeWorldBound(prim) bound_range = bound.ComputeAlignedBox() return bound_range
846
Python
37.499998
109
0.702128
NVIDIA-Omniverse/OpenUSD-Code-Samples/source/hierarchy-traversal/find-prim-by-name/py_usd.py
# SPDX-FileCopyrightText: Copyright (c) 2023 NVIDIA CORPORATION & AFFILIATES. All rights reserved. # SPDX-License-Identifier: Apache-2.0 from typing import List from pxr import Usd def find_prims_by_name(stage: Usd.Stage, prim_name: str) -> List[Usd.Prim]: found_prims = [x for x in stage.Traverse() if x.GetName() == prim_name] return found_prims ############## # Full Usage ############## from pxr import UsdGeom, Sdf # Create an in-memory Stage with /World Xform prim as the default prim stage: Usd.Stage = Usd.Stage.CreateInMemory() default_prim = UsdGeom.Xform.Define(stage, Sdf.Path("/World")) stage.SetDefaultPrim(default_prim.GetPrim()) # Create some shape prims UsdGeom.Xform.Define(stage, "/World/Group") UsdGeom.Cone.Define(stage, "/World/Foo") UsdGeom.Cube.Define(stage, "/World/Group/Foo") UsdGeom.Sphere.Define(stage, "/World/Group/Bar") # find the prims with the name "Foo" prims: List[Usd.Prim] = find_prims_by_name(stage, "Foo") # Print the prims to check the found prims by name. print(prims) # Check the number of prims found and whether the found data is correct. assert len(prims) == 2 assert isinstance(prims[0], Usd.Prim) assert prims[0].GetName() == "Foo"
1,198
Python
29.743589
98
0.716194
NVIDIA-Omniverse/OpenUSD-Code-Samples/source/hierarchy-traversal/find-prim-by-name/py_usd.md
``` {literalinclude} py_usd.py :language: py ``` ```{warning} This will be slow for stages with many prims, as stage traversal is currently single-threaded. Learn more about [scene complexity](https://openusd.org/release/maxperf.html#what-makes-a-usd-scene-heavy-expensive). ```
286
Markdown
22.916665
212
0.730769
NVIDIA-Omniverse/OpenUSD-Code-Samples/source/hierarchy-traversal/find-prim-by-name/config.toml
[core] title = "Find a Prim by Name" [metadata] description = "Universal Scene Description (OpenUSD) code samples for finding a Prim by its name on a Stage." keywords = ["OpenUSD", "USD", "Python", "snippet", "code sample", "prim", "name", "Traverse"]
252
TOML
41.16666
109
0.694444
NVIDIA-Omniverse/OpenUSD-Code-Samples/source/hierarchy-traversal/find-prim-by-name/header.md
If you want to find all of the prims of a certain type, you can [Traverse](https://openusd.org/release/api/class_usd_stage.html#adba675b55f41cc1b305bed414fc4f178) the stage and use [Usd.Prim.GetName()](https://openusd.org/release/api/class_usd_object.html#ae57e12beedf10c423e11c5b889343f6d) to compare the name of every prim on the stage with the name you are looking for. ```{note} There could be more than one prim with the same name on a stage. ```
454
Markdown
63.999991
372
0.777533
NVIDIA-Omniverse/OpenUSD-Code-Samples/source/hierarchy-traversal/get-prim-child/py_usd.py
# SPDX-FileCopyrightText: Copyright (c) 2023 NVIDIA CORPORATION & AFFILIATES. All rights reserved. # SPDX-License-Identifier: Apache-2.0 from pxr import Usd def get_child_prim(parent_prim, child_name) -> Usd.Prim: child_prim: Usd.Prim = parent_prim.GetChild(child_name) return child_prim ############# # Full Usage ############# from pxr import Sdf, UsdGeom # Create an in-memory Stage with /World Xform prim as the default prim stage: Usd.Stage = Usd.Stage.CreateInMemory() default_prim: Usd.Prim = UsdGeom.Xform.Define(stage, Sdf.Path("/World")).GetPrim() stage.SetDefaultPrim(default_prim) # Create a Cube prim cube: Usd.Prim = UsdGeom.Cube.Define(stage, default_prim.GetPath().AppendPath("Box")) # Get the child prim of the default prim with the name "Box" child_prim = get_child_prim(default_prim, "Box") # Print the full Stage usda = stage.GetRootLayer().ExportToString() print(usda) # Print the path of the child prim you were looking for. print(child_prim.GetPath()) # Verify the child and parent relationship assert child_prim.GetParent() == default_prim assert child_prim.GetPath() == cube.GetPath()
1,128
Python
31.257142
98
0.728723
NVIDIA-Omniverse/OpenUSD-Code-Samples/source/hierarchy-traversal/get-prim-child/py_usd.md
If you know the name of the child prim, you can use `Usd.Prim.GetChild()`. This returns an invalid prim if the child doesn't exist. You can [check if the returned prim exists](../prims/check-prim-exists). ``` {literalinclude} py_usd.py :language: py ``` Another option is to iterate through all of the prim's children to operate on all the children or query them to find the child you are looking for. ``` {literalinclude} py_usd_var1.py :language: py ```
457
Markdown
44.799996
204
0.737418
NVIDIA-Omniverse/OpenUSD-Code-Samples/source/hierarchy-traversal/get-prim-child/usda.md
This is an example USDA result to show that the Cube prim is the Child Prim of World. ``` {literalinclude} usda.usda :language: usd ```
136
Markdown
33.249992
85
0.735294
NVIDIA-Omniverse/OpenUSD-Code-Samples/source/hierarchy-traversal/get-prim-child/config.toml
[core] title = "Get the Child of a Prim" [metadata] description = "Universal Scene Description (OpenUSD) code samples for getting the child of a Prim." keywords = ["OpenUSD", "USD", "Python", "snippet", "code sample", "prim", "child", "children"]
247
TOML
40.333327
99
0.696356
NVIDIA-Omniverse/OpenUSD-Code-Samples/source/hierarchy-traversal/get-prim-child/py_usd_var1.py
# SPDX-FileCopyrightText: Copyright (c) 2023 NVIDIA CORPORATION & AFFILIATES. All rights reserved. # SPDX-License-Identifier: Apache-2.0 from pxr import Usd, UsdGeom def get_first_child_mesh(parent_prim: Usd.Prim) -> Usd.Prim: # Iterates only active, loaded, defined, non-abstract children for child_prim in parent_prim.GetChildren(): if child_prim.IsA(UsdGeom.Mesh): return child_prim def print_all_children_names(parent_prim: Usd.Prim): # Iterates over all children for child_prim in parent_prim.GetAllChildren(): print(child_prim.GetName())
590
Python
38.399997
98
0.716949
NVIDIA-Omniverse/OpenUSD-Code-Samples/source/hierarchy-traversal/find-prims-by-type/py_usd.py
# SPDX-FileCopyrightText: Copyright (c) 2023 NVIDIA CORPORATION & AFFILIATES. All rights reserved. # SPDX-License-Identifier: Apache-2.0 from typing import List, Type from pxr import Usd, UsdGeom def find_prims_by_type(stage: Usd.Stage, prim_type: Type[Usd.Typed]) -> List[Usd.Prim]: found_prims = [x for x in stage.Traverse() if x.IsA(prim_type)] return found_prims ############## # Full Usage ############## from pxr import UsdGeom, Sdf # Create an in-memory Stage with /World Xform prim as the default prim stage: Usd.Stage = Usd.Stage.CreateInMemory() default_prim = UsdGeom.Xform.Define(stage, Sdf.Path("/World")) stage.SetDefaultPrim(default_prim.GetPrim()) # Create some shape prims UsdGeom.Xform.Define(stage, "/World/Group") UsdGeom.Mesh.Define(stage, "/World/Foo") UsdGeom.Mesh.Define(stage, "/World/Group/Bar") UsdGeom.Sphere.Define(stage, "/World/Group/Baz") # find the prims with of type UsdGeom.Mesh prims: List[Usd.Prim] = find_prims_by_type(stage, UsdGeom.Mesh) # Print the mesh prims you found print(prims) # Check the number of prims found and whether the found data is correct. assert len(prims) == 2 prim: Usd.Prim for prim in prims: assert isinstance(prim, Usd.Prim) assert prim.GetTypeName() == "Mesh"
1,250
Python
29.512194
98
0.7208
NVIDIA-Omniverse/OpenUSD-Code-Samples/source/hierarchy-traversal/find-prims-by-type/py_usd.md
``` {literalinclude} py_usd.py :language: py ``` ```{warning} This will be slow for stages with many prims, as stage traversal is currently single-threaded. Learn more about [scene complexity](https://openusd.org/release/maxperf.html#what-makes-a-usd-scene-heavy-expensive). ```
279
Markdown
38.999994
212
0.749104
NVIDIA-Omniverse/OpenUSD-Code-Samples/source/hierarchy-traversal/find-prims-by-type/config.toml
[core] title = "Find All the Prims of a Given Type" [metadata] description = "Universal Scene Description (OpenUSD) code samples for finding all the Prims on a Stage of a certain type." keywords = ["OpenUSD", "USD", "Python", "code sample", "snippet", "code sample", "prim", "IsA", "Traverse"]
294
TOML
48.166659
122
0.704082
NVIDIA-Omniverse/OpenUSD-Code-Samples/sphinx/usd_header.rst
======================================================== Universal Scene Description (OpenUSD) Code Samples ======================================================== This is an index of code samples or snippets for Universal Scene Description (OpenUSD). The code samples are indexed by topics and each code sample is titled by the task that it is used for. Where applicable, we include code samples using Kit OpenUSD wrappers for developing within Omniverse apart from the original USD API. New USD developers will find this useful for finding the appropriate API used to accomplish a task and using the `OpenUSD Python API reference <https://docs.omniverse.nvidia.com/kit/docs/pxr-usd-api>`__ or `OpenUSD C++ API reference <https://openusd.org/release/api/index.html>`_ to learn more about the API. Experienced developers can use this index for quick code lookups. **Want to contribute to the USD Code Samples?** All the code samples are open-source with a permissive license. You can contribute new code samples for new tasks or improve existing code samples. Visit the `OpenUSD Code Samples GitHub Repository <https://github.com/NVIDIA-Omniverse/OpenUSD-Code-Samples>`__ to learn more and contribute. .. button-link:: https://github.com/NVIDIA-Omniverse/OpenUSD-Code-Samples :color: secondary :align: center :outline: Contribute
1,357
reStructuredText
74.44444
699
0.714075
NVIDIA-Omniverse/OpenUSD-Code-Samples/sphinx/index.rst
.. toctree:: :caption: USD Code Samples :maxdepth: 4 usd
66
reStructuredText
12.399998
29
0.606061
NVIDIA-Omniverse/OpenUSD-Code-Samples/sphinx/conf.py
# SPDX-FileCopyrightText: Copyright (c) 2023 NVIDIA CORPORATION & AFFILIATES. All rights reserved. # SPDX-License-Identifier: Apache-2.0 # Configuration file for the Sphinx documentation builder. # # This file only contains a selection of the most common options. For a full # list see the documentation: # https://www.sphinx-doc.org/en/master/usage/configuration.html # -- Path setup -------------------------------------------------------------- # If extensions (or modules to document with autodoc) are in another directory, # add these directories to sys.path here. If the directory is relative to the # documentation root, use os.path.abspath to make it absolute, like shown here. # # import os # import sys # sys.path.insert(0, os.path.abspath('.')) # -- Project information ----------------------------------------------------- project = 'USD Code Samples' copyright = '2023, NVIDIA' author = 'NVIDIA' # -- General configuration --------------------------------------------------- # Add any Sphinx extension module names here, as strings. They can be # extensions coming with Sphinx (named 'sphinx.ext.*') or your custom # ones. extensions = [ "myst_parser", "sphinx_design", "sphinx_rtd_theme" ] # Add any paths that contain templates here, relative to this directory. templates_path = ['_templates'] # List of patterns, relative to source directory, that match files and # directories to ignore when looking for source files. # This pattern also affects html_static_path and html_extra_path. exclude_patterns = ['_build', 'Thumbs.db', '.DS_Store'] # -- Options for HTML output ------------------------------------------------- # The theme to use for HTML and HTML Help pages. See the documentation for # a list of builtin themes. # html_theme = 'sphinx_rtd_theme' html_theme_options = { 'collapse_navigation': True, 'navigation_depth': -1 } # Add any paths that contain custom static files (such as style sheets) here, # relative to this directory. They are copied after the builtin static files, # so a file named "default.css" will overwrite the builtin "default.css". html_static_path = ['_static']
2,147
Python
33.095238
98
0.658593
NVIDIA-Omniverse/kit-workshop-siggraph2022/README.md
# Extension Project Template This project was automatically generated. - `app` - It is a folder link to the location of your *Omniverse Kit* based app. - `exts` - It is a folder where you can add new extensions. It was automatically added to extension search path. (Extension Manager -> Gear Icon -> Extension Search Path). Open this folder using Visual Studio Code. It will suggest you to install few extensions that will make python experience better. Look for "omni.workshop.siggraph" extension in extension manager and enable it. Try applying changes to any python files, it will hot-reload and you can observe results immediately. Alternatively, you can launch your app from console with this folder added to search path and your extension enabled, e.g.: ``` > app\omni.code.bat --ext-folder exts --enable company.hello.world ``` # App Link Setup 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" ``` # Sharing Your Extensions 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-workshop-siggraph2022.git?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
2,070
Markdown
38.075471
258
0.761353
NVIDIA-Omniverse/kit-workshop-siggraph2022/LICENSE.md
Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 1. Definitions. "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and (b) You must cause any modified files to carry prominent notices stating that You changed the files; and (c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and (d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. END OF TERMS AND CONDITIONS APPENDIX: How to apply the Apache License to your work. To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "[]" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives. Copyright [yyyy] [name of copyright owner] 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.
11,357
Markdown
55.227722
77
0.73206
NVIDIA-Omniverse/kit-workshop-siggraph2022/tools/scripts/link_app.py
import os import argparse import sys import json import packmanapi import urllib3 def find_omniverse_apps(): http = urllib3.PoolManager() try: r = http.request("GET", "http://127.0.0.1:33480/components") except Exception as e: print(f"Failed retrieving apps from an Omniverse Launcher, maybe it is not installed?\nError: {e}") sys.exit(1) apps = {} for x in json.loads(r.data.decode("utf-8")): latest = x.get("installedVersions", {}).get("latest", "") if latest: for s in x.get("settings", []): if s.get("version", "") == latest: root = s.get("launch", {}).get("root", "") apps[x["slug"]] = (x["name"], root) break return apps def create_link(src, dst): print(f"Creating a link '{src}' -> '{dst}'") packmanapi.link(src, dst) APP_PRIORITIES = ["code", "create", "view"] if __name__ == "__main__": parser = argparse.ArgumentParser(description="Create folder link to Kit App installed from Omniverse Launcher") parser.add_argument( "--path", help="Path to Kit App installed from Omniverse Launcher, e.g.: 'C:/Users/bob/AppData/Local/ov/pkg/create-2021.3.4'", required=False, ) parser.add_argument( "--app", help="Name of Kit App installed from Omniverse Launcher, e.g.: 'code', 'create'", required=False ) args = parser.parse_args() path = args.path if not path: print("Path is not specified, looking for Omniverse Apps...") apps = find_omniverse_apps() if len(apps) == 0: print( "Can't find any Omniverse Apps. Use Omniverse Launcher to install one. 'Code' is the recommended app for developers." ) sys.exit(0) print("\nFound following Omniverse Apps:") for i, slug in enumerate(apps): name, root = apps[slug] print(f"{i}: {name} ({slug}) at: '{root}'") if args.app: selected_app = args.app.lower() if selected_app not in apps: choices = ", ".join(apps.keys()) print(f"Passed app: '{selected_app}' is not found. Specify one of the following found Apps: {choices}") sys.exit(0) else: selected_app = next((x for x in APP_PRIORITIES if x in apps), None) if not selected_app: selected_app = next(iter(apps)) print(f"\nSelected app: {selected_app}") _, path = apps[selected_app] if not os.path.exists(path): print(f"Provided path doesn't exist: {path}") else: SCRIPT_ROOT = os.path.dirname(os.path.realpath(__file__)) create_link(f"{SCRIPT_ROOT}/../../app", path) print("Success!")
2,813
Python
32.5
133
0.562389
NVIDIA-Omniverse/kit-workshop-siggraph2022/tools/packman/config.packman.xml
<config remotes="cloudfront"> <remote2 name="cloudfront"> <transport actions="download" protocol="https" packageLocation="d4i3qtqj3r0z5.cloudfront.net/${name}@${version}" /> </remote2> </config>
211
XML
34.333328
123
0.691943
NVIDIA-Omniverse/kit-workshop-siggraph2022/tools/packman/bootstrap/install_package.py
# Copyright 2019 NVIDIA CORPORATION # 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 logging import zipfile import tempfile import sys import shutil __author__ = "hfannar" logging.basicConfig(level=logging.WARNING, format="%(message)s") logger = logging.getLogger("install_package") class TemporaryDirectory: def __init__(self): self.path = None def __enter__(self): self.path = tempfile.mkdtemp() return self.path def __exit__(self, type, value, traceback): # Remove temporary data created shutil.rmtree(self.path) def install_package(package_src_path, package_dst_path): with zipfile.ZipFile( package_src_path, allowZip64=True ) as zip_file, TemporaryDirectory() as temp_dir: zip_file.extractall(temp_dir) # Recursively copy (temp_dir will be automatically cleaned up on exit) try: # Recursive copy is needed because both package name and version folder could be missing in # target directory: shutil.copytree(temp_dir, package_dst_path) except OSError as exc: logger.warning( "Directory %s already present, packaged installation aborted" % package_dst_path ) else: logger.info("Package successfully installed to %s" % package_dst_path) install_package(sys.argv[1], sys.argv[2])
1,888
Python
31.568965
103
0.68697
NVIDIA-Omniverse/kit-workshop-siggraph2022/exts/omni.example.ui_scene.light_man_siggraph/config/extension.toml
[package] version = "1.1.1" authors = ["NVIDIA"] title = "Omni.UI Scene Sample For Manipulating Select Light" description = "This example show an 3D manipulator for a selected light" readme = "docs/README.md" repository = "https://gitlab-master.nvidia.com/omniverse/kit-extensions/kit-scene" category = "Documentation" keywords = ["ui", "example", "scene", "docs", "documentation", "light"] changelog = "docs/CHANGELOG.md" preview_image = "data/preview.png" icon = "data/icon.png" [dependencies] "omni.ui.scene" = { } "omni.usd" = { } "omni.kit.viewport.utility" = { } "omni.kit.commands" = { } [[python.module]] name = "omni.example.ui_scene.light_man_siggraph" [[test]] args = [ "--/renderer/enabled=pxr", "--/renderer/active=pxr", "--/app/viewport/forceHideFps=true", "--/app/window/dpiScaleOverride=1.0", "--/app/window/scaleToMonitor=false", "--no-window" ] dependencies = [ "omni.hydra.pxr", "omni.kit.test_helpers_gfx", "omni.kit.viewport.utility", "omni.kit.window.viewport" ]
1,031
TOML
26.157894
82
0.667313
NVIDIA-Omniverse/kit-workshop-siggraph2022/exts/omni.example.ui_scene.light_man_siggraph/omni/example/ui_scene/light_man_siggraph/extension.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__ = ["LightManipulatorExtension"] import carb import omni.ext from omni.kit.viewport.utility import get_active_viewport_window from .viewport_scene import ViewportScene class LightManipulatorExtension(omni.ext.IExt): def __init__(self): self._viewport_scene = None def on_startup(self, ext_id): # Get the active (which at startup is the default Viewport) viewport_window = get_active_viewport_window() # Issue an error if there is no Viewport if not viewport_window: carb.log_error(f"No Viewport Window to add {ext_id} scene to") return # Build out the scene self._viewport_scene = ViewportScene(viewport_window, ext_id) def on_shutdown(self): if self._viewport_scene: self._viewport_scene.destroy() self._viewport_scene = None
1,294
Python
33.078946
76
0.705564
NVIDIA-Omniverse/kit-workshop-siggraph2022/exts/omni.example.ui_scene.light_man_siggraph/omni/example/ui_scene/light_man_siggraph/viewport_scene.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__ = ["ViewportScene"] from omni.ui import scene as sc from .light_model import LightModel from .light_manipulator import LightManipulator class ViewportScene: """The light Manipulator, placed into a Viewport""" def __init__(self, viewport_window, ext_id: str): self._scene_view = None self._viewport_window = viewport_window # Create a unique frame for our SceneView with self._viewport_window.get_frame(ext_id): # Create a default SceneView (it has a default camera-model) self._scene_view = sc.SceneView() # Add the manipulator into the SceneView's scene with self._scene_view.scene: LightManipulator(model=LightModel()) # Register the SceneView with the Viewport to get projection and view updates self._viewport_window.viewport_api.add_scene_view(self._scene_view) def __del__(self): self.destroy() def destroy(self): if self._scene_view: # Empty the SceneView of any elements it may have self._scene_view.scene.clear() # Be a good citizen, and un-register the SceneView from Viewport updates if self._viewport_window: self._viewport_window.viewport_api.remove_scene_view(self._scene_view) # Remove our references to these objects self._viewport_window = None self._scene_view = None
1,871
Python
37.999999
89
0.676109
NVIDIA-Omniverse/kit-workshop-siggraph2022/exts/omni.example.ui_scene.light_man_siggraph/omni/example/ui_scene/light_man_siggraph/__init__.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. # from .extension import * from .light_manipulator import LightManipulator from .light_model import LightModel
537
Python
43.83333
76
0.81378
NVIDIA-Omniverse/kit-workshop-siggraph2022/exts/omni.example.ui_scene.light_man_siggraph/omni/example/ui_scene/light_man_siggraph/light_model.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__ = ["LightModel"] import carb from omni.ui import scene as sc import omni.usd from pxr import Usd, UsdGeom, UsdLux, Tf, Gf def _flatten_matrix(matrix: Gf.Matrix4d): m0, m1, m2, m3 = matrix[0], matrix[1], matrix[2], matrix[3] return [ m0[0], m0[1], m0[2], m0[3], m1[0], m1[1], m1[2], m1[3], m2[0], m2[1], m2[2], m2[3], m3[0], m3[1], m3[2], m3[3], ] class LightModel(sc.AbstractManipulatorModel): """ User part. The model tracks the attributes of the selected light. """ class MatrixItem(sc.AbstractManipulatorItem): """ The Model Item represents the tranformation. It doesn't contain anything because we take the tranformation directly from USD when requesting. """ identity = [1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1] def __init__(self): super().__init__() self.value = self.identity.copy() class FloatItem(sc.AbstractManipulatorItem): """The Model Item contains a single float value about some attibute""" def __init__(self, value=0.0): super().__init__() self.value = value class StringItem(sc.AbstractManipulatorItem): """The Model Item contains a single string value about some attibute""" def __init__(self, value=""): super().__init__() self.value = value def __init__(self): super().__init__() self.prim_path = LightModel.StringItem() self.transform = LightModel.MatrixItem() self.intensity = LightModel.FloatItem() self.width = LightModel.FloatItem() self.height = LightModel.FloatItem() # Save the UsdContext name (we currently only work with single Context) self._usd_context_name = "" # Current selection self._light = None self._stage_listener = None # Track selection change self._events = self._usd_context.get_stage_event_stream() self._stage_event_sub = self._events.create_subscription_to_pop( self._on_stage_event, name="Light Manipulator Selection Change" ) def __del__(self): self._invalidate_object() @property def _usd_context(self) -> Usd.Stage: # Get the UsdContext we are attached to return omni.usd.get_context(self._usd_context_name) @property def _current_path(self): return self.prim_path.value @property def _time(self): return Usd.TimeCode.Default() def _notice_changed(self, notice, stage): """Called by Tf.Notice. When USD data changes, we update the ui""" light_path = self.prim_path.value if not light_path: return changed_items = set() for p in notice.GetChangedInfoOnlyPaths(): prim_path = p.GetPrimPath().pathString if prim_path != light_path: # Update on any parent transformation changes too if light_path.startswith(prim_path): if UsdGeom.Xformable.IsTransformationAffectedByAttrNamed(p.name): changed_items.add(self.transform) continue if UsdGeom.Xformable.IsTransformationAffectedByAttrNamed(p.name): changed_items.add(self.transform) elif self.width and p.name == "width": changed_items.add(self.width) elif self.height and p.name == "height": changed_items.add(self.height) elif self.intensity and p.name == "intensity": changed_items.add(self.intensity) for item in changed_items: self._item_changed(item) def get_as_floats(self, item): """get the item value directly from USD""" if item == self.transform: return self._get_transform(self._time) if item == self.intensity: return self._get_intensity(self._time) if item == self.width: return self._get_width(self._time) if item == self.height: return self._get_height(self._time) if item: # Get the value directly from the item return item.value return None def set_floats_commands(self, item, value): """set the item value to USD using commands, this is useful because it supports undo/redo""" if not self._current_path: return if not value or not item: return # we get the previous value from the model instead of USD if item == self.height: prev_value = self.height.value if prev_value == value: return height_attr = self._light.GetHeightAttr() omni.kit.commands.execute('ChangeProperty', prop_path=height_attr.GetPath(), value=value, prev=prev_value) elif item == self.width: prev_value = self.width.value if prev_value == value: return width_attr = self._light.GetWidthAttr() omni.kit.commands.execute('ChangeProperty', prop_path=width_attr.GetPath(), value=value, prev=prev_value) elif item == self.intensity: prev_value = self.intensity.value if prev_value == value: return intensity_attr = self._light.GetIntensityAttr() omni.kit.commands.execute('ChangeProperty', prop_path=intensity_attr.GetPath(), value=value, prev=prev_value) # This makes the manipulator updated self._item_changed(item) def set_item_value(self, item, value): """ This is used to set the model value instead of the usd. This is used to record previous value for omni.kit.commands """ item.value = value def set_floats(self, item, value): """set the item value directly to USD. This is useful when we want to update the usd but not record it in commands""" if not self._current_path: return if not value or not item: return pre_value = self.get_as_floats(item) # no need to update if the updated value is the same if pre_value == value: return if item == self.height: self._set_height(self._time, value) elif item == self.width: self._set_width(self._time, value) elif item == self.intensity: self._set_intensity(self._time, value) def _on_stage_event(self, event): """Called by stage_event_stream""" if event.type == int(omni.usd.StageEventType.SELECTION_CHANGED): self._on_kit_selection_changed() def _invalidate_object(self, settings): # Revoke the Tf.Notice listener, we don't need to update anything if self._stage_listener: self._stage_listener.Revoke() self._stage_listener = None # Reset original Viewport gizmo line width settings.set("/persistent/app/viewport/gizmo/lineWidth", 0) # Clear any cached UsdLux.Light object self._light = None # Set the prim_path to empty self.prim_path.value = "" self._item_changed(self.prim_path) def _on_kit_selection_changed(self): # selection change, reset it for now self._light = None # Turn off any native selected light drawing settings = carb.settings.get_settings() settings.set("/persistent/app/viewport/gizmo/lineWidth", 0) usd_context = self._usd_context if not usd_context: return self._invalidate_object(settings) stage = usd_context.get_stage() if not stage: return self._invalidate_object(settings) prim_paths = usd_context.get_selection().get_selected_prim_paths() if usd_context else None if not prim_paths: return self._invalidate_object(settings) prim = stage.GetPrimAtPath(prim_paths[0]) if prim and prim.IsA(UsdLux.RectLight): self._light = UsdLux.RectLight(prim) if not self._light: return self._invalidate_object(settings) selected_path = self._light.GetPrim().GetPath().pathString if selected_path != self.prim_path.value: self.prim_path.value = selected_path self._item_changed(self.prim_path) # Add a Tf.Notice listener to update the light attributes if not self._stage_listener: self._stage_listener = Tf.Notice.Register(Usd.Notice.ObjectsChanged, self._notice_changed, stage) def _get_transform(self, time: Usd.TimeCode): """Returns world transform of currently selected object""" if not self._light: return LightModel.MatrixItem.identity.copy() # Compute matrix from world-transform in USD world_xform = self._light.ComputeLocalToWorldTransform(time) # Flatten Gf.Matrix4d to list return _flatten_matrix(world_xform) def _get_intensity(self, time: Usd.TimeCode): """Returns intensity of currently selected light""" if not self._light: return 0.0 # Get intensity directly from USD return self._light.GetIntensityAttr().Get(time) def _set_intensity(self, time: Usd.TimeCode, value): """set intensity of currently selected light""" if not self._light: return # set height dirctly to USD self._light.GetIntensityAttr().Set(value, time=time) def _get_width(self, time: Usd.TimeCode): """Returns width of currently selected light""" if not self._light: return 0.0 # Get radius directly from USD return self._light.GetWidthAttr().Get(time) def _set_width(self, time: Usd.TimeCode, value): """set width of currently selected light""" if not self._light: return # set height dirctly to USD self._light.GetWidthAttr().Set(value, time=time) def _get_height(self, time: Usd.TimeCode): """Returns height of currently selected light""" if not self._light: return 0.0 # Get height directly from USD return self._light.GetHeightAttr().Get(time) def _set_height(self, time: Usd.TimeCode, value): """set height of currently selected light""" if not self._light: return # set height dirctly to USD self._light.GetHeightAttr().Set(value, time=time)
11,040
Python
33.07716
125
0.600272
NVIDIA-Omniverse/kit-workshop-siggraph2022/exts/omni.example.ui_scene.light_man_siggraph/omni/example/ui_scene/light_man_siggraph/light_manipulator.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__ = ["LightManipulator"] from omni.ui import scene as sc from omni.ui import color as cl import omni.kit import omni.kit.commands INTENSITY_SCALE = 500.0 ARROW_WIDTH = 0.015 ARROW_HEIGHT = 0.1 ARROW_P = [ [ARROW_WIDTH, ARROW_WIDTH, 0], [-ARROW_WIDTH, ARROW_WIDTH, 0], [0, 0, ARROW_HEIGHT], # [ARROW_WIDTH, -ARROW_WIDTH, 0], [-ARROW_WIDTH, -ARROW_WIDTH, 0], [0, 0, ARROW_HEIGHT], # [ARROW_WIDTH, ARROW_WIDTH, 0], [ARROW_WIDTH, -ARROW_WIDTH, 0], [0, 0, ARROW_HEIGHT], # [-ARROW_WIDTH, ARROW_WIDTH, 0], [-ARROW_WIDTH, -ARROW_WIDTH, 0], [0, 0, ARROW_HEIGHT], # [ARROW_WIDTH, ARROW_WIDTH, 0], [-ARROW_WIDTH, ARROW_WIDTH, 0], [-ARROW_WIDTH, -ARROW_WIDTH, 0], [ARROW_WIDTH, -ARROW_WIDTH, 0], ] ARROW_VC = [3, 3, 3, 3, 4] ARROW_VI = [i for i in range(sum(ARROW_VC))] class _ViewportLegacyDisableSelection: """Disables selection in the Viewport Legacy""" def __init__(self): self._focused_windows = None focused_windows = [] try: # For some reason is_focused may return False, when a Window is definitely in fact is the focused window! # And there's no good solution to this when mutliple Viewport-1 instances are open; so we just have to # operate on all Viewports for a given usd_context. import omni.kit.viewport_legacy as vp vpi = vp.acquire_viewport_interface() for instance in vpi.get_instance_list(): window = vpi.get_viewport_window(instance) if not window: continue focused_windows.append(window) if focused_windows: self._focused_windows = focused_windows for window in self._focused_windows: # Disable the selection_rect, but enable_picking for snapping window.disable_selection_rect(True) except Exception: pass class _DragGesture(sc.DragGesture): """"Gesture to disable rectangle selection in the viewport legacy""" def __init__(self, manipulator, orientation, flag): super().__init__() self._manipulator = manipulator # record this _previous_ray_point to get the mouse moved vector self._previous_ray_point = None # this defines the orientation of the move, 0 means x, 1 means y, 2 means z. It's a list so that we can move a selection self.orientations = orientation # global flag to indicate if the manipulator changes all the width, height and intensity, rectangle manipulator # in the example self.is_global = len(self.orientations) > 1 # this defines the negative or positive of the move. E.g. when we move the positive x line to the right, it # enlarges the width, and when we move the negative line to the left, it also enlarges the width # 1 means positive and -1 means negative. It's a list so that we can reflect list orientation self.flag = flag def on_began(self): # When the user drags the slider, we don't want to see the selection # rect. In Viewport Next, it works well automatically because the # selection rect is a manipulator with its gesture, and we add the # slider manipulator to the same SceneView. # In Viewport Legacy, the selection rect is not a manipulator. Thus it's # not disabled automatically, and we need to disable it with the code. self.__disable_selection = _ViewportLegacyDisableSelection() # initialize the self._previous_ray_point self._previous_ray_point = self.gesture_payload.ray_closest_point # record the previous value for the model self.model = self._manipulator.model if 0 in self.orientations: self.width_item = self.model.width self._manipulator.model.set_item_value(self.width_item, self.model.get_as_floats(self.width_item)) if 1 in self.orientations: self.height_item = self.model.height self._manipulator.model.set_item_value(self.height_item, self.model.get_as_floats(self.height_item)) if 2 in self.orientations or self.is_global: self.intensity_item = self.model.intensity self._manipulator.model.set_item_value(self.intensity_item, self.model.get_as_floats(self.intensity_item)) def on_changed(self): object_ray_point = self.gesture_payload.ray_closest_point # calculate the ray moved vector moved = [a - b for a, b in zip(object_ray_point, self._previous_ray_point)] # transfer moved from world to object space, [0] to make it a normal, not point moved = self._manipulator._x_xform.transform_space(sc.Space.WORLD, sc.Space.OBJECT, moved + [0]) # 2.0 because `_shape_xform.transform` is a scale matrix and it means # the width of the rectangle is twice the scale matrix. moved_x = moved[0] * 2.0 * self.flag[0] moved_y = moved[1] * 2.0 * (self.flag[1] if self.is_global else self.flag[0]) moved_z = moved[2] * self.flag[0] # update the self._previous_ray_point self._previous_ray_point = object_ray_point # since self._shape_xform.transform = [x, 0, 0, 0, 0, y, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1] # when we want to update the manipulator, we are actually updating self._manipulator._shape_xform.transform[0] # for width and self._manipulator._shape_xform.transform[5] for height and # self._manipulator._shape_xform.transform[10] for intensity width = self._manipulator._shape_xform.transform[0] height = self._manipulator._shape_xform.transform[5] intensity = self._manipulator._shape_xform.transform[10] self.width_new = width + moved_x self.height_new = height + moved_y # update the USD as well as update the ui if 0 in self.orientations: # update the data in the model self.model.set_floats(self.width_item, self.width_new) self._manipulator._shape_xform.transform[0] = self.width_new if 1 in self.orientations: # update the data in the model self.model.set_floats(self.height_item, self.height_new) self._manipulator._shape_xform.transform[5] = self.height_new if 2 in self.orientations: self._manipulator._shape_xform.transform[10] += moved_z self.intensity_new = self._manipulator._shape_xform.transform[10] * INTENSITY_SCALE self.model.set_floats(self.intensity_item, self.intensity_new) if self.is_global: # need to update the intensity in a different way intensity_new = intensity * width * height / (self.width_new * self.height_new) self._manipulator._shape_xform.transform[10] = intensity_new self.intensity_new = intensity_new * INTENSITY_SCALE self.model.set_floats(self.intensity_item, self.intensity_new) def on_ended(self): # This re-enables the selection in the Viewport Legacy self.__disable_selection = None if self.is_global: # start group command omni.kit.undo.begin_group() if 0 in self.orientations: self.model.set_floats_commands(self.width_item, self.width_new) if 1 in self.orientations: self.model.set_floats_commands(self.height_item, self.height_new) if 2 in self.orientations or self.is_global: self.model.set_floats_commands(self.intensity_item, self.intensity_new) if self.is_global: # end group command omni.kit.undo.end_group() class LightManipulator(sc.Manipulator): def __init__(self, **kwargs): super().__init__(**kwargs) self._shape_xform = None def __del__(self): self.model = None def _build_shape(self): if not self.model: return if self.model.width and self.model.height and self.model.intensity: x = self.model.get_as_floats(self.model.width) y = self.model.get_as_floats(self.model.height) # this INTENSITY_SCALE is too make the transform a reasonable length with large intensity number z = self.model.get_as_floats(self.model.intensity) / INTENSITY_SCALE self._shape_xform.transform = [x, 0, 0, 0, 0, y, 0, 0, 0, 0, z, 0, 0, 0, 0, 1] def on_build(self): """Called when the model is changed and rebuilds the whole slider""" model = self.model if not model: return # if we don't have selection then just return prim_path_item = model.prim_path prim_path = prim_path_item.value if prim_path_item else None if not prim_path: return # Style settings, as kwargs thickness = 1 hover_thickness = 3 color = cl.yellow shape_style = {"thickness": thickness, "color": color} def set_thickness(sender, shapes, thickness): for shape in shapes: shape.thickness = thickness self.__root_xf = sc.Transform(model.get_as_floats(model.transform)) with self.__root_xf: self._x_xform = sc.Transform() with self._x_xform: self._shape_xform = sc.Transform() # Build the shape's transform self._build_shape() with self._shape_xform: # Build the shape geomtery as unit-sized h = 0.5 z = -1.0 # the rectangle shape1 = sc.Line((-h, h, 0), (h, h, 0), **shape_style) shape2 = sc.Line((-h, -h, 0), (h, -h, 0), **shape_style) shape3 = sc.Line((h, h, 0), (h, -h, 0), **shape_style) shape4 = sc.Line((-h, h, 0), (-h, -h, 0), **shape_style) # add gesture to the lines of the rectangle to update width or height of the light vertical_hover_gesture = sc.HoverGesture( on_began_fn=lambda sender: set_thickness(sender, [shape1, shape2], hover_thickness), on_ended_fn=lambda sender: set_thickness(sender, [shape1, shape2], thickness), ) shape1.gestures = [_DragGesture(self, [1], [1]), vertical_hover_gesture] shape2.gestures = [_DragGesture(self, [1], [-1]), vertical_hover_gesture] horizontal_hover_gesture = sc.HoverGesture( on_began_fn=lambda sender: set_thickness(sender, [shape3, shape4], hover_thickness), on_ended_fn=lambda sender: set_thickness(sender, [shape3, shape4], thickness), ) shape3.gestures = [_DragGesture(self, [0], [1]), horizontal_hover_gesture] shape4.gestures = [_DragGesture(self, [0], [-1]), horizontal_hover_gesture] # create z-axis to indicate the intensity z1 = sc.Line((h, h, 0), (h, h, z), **shape_style) z2 = sc.Line((-h, -h, 0), (-h, -h, z), **shape_style) z3 = sc.Line((h, -h, 0), (h, -h, z), **shape_style) z4 = sc.Line((-h, h, 0), (-h, h, z), **shape_style) def make_arrow(translate): vert_count = len(ARROW_VI) with sc.Transform( transform=sc.Matrix44.get_translation_matrix(translate[0], translate[1], translate[2]) * sc.Matrix44.get_rotation_matrix(0, -180, 0, True) ): return sc.PolygonMesh(ARROW_P, [color] * vert_count, ARROW_VC, ARROW_VI, visible=False) # arrows on the z-axis arrow_1 = make_arrow((h, h, z)) arrow_2 = make_arrow((-h, -h, z)) arrow_3 = make_arrow((h, -h, z)) arrow_4 = make_arrow((-h, h, z)) # the line underneath the arrow which is where the gesture applies z1_arrow = sc.Line((h, h, z), (h, h, z - ARROW_HEIGHT), **shape_style) z2_arrow = sc.Line((-h, -h, z), (-h, -h, z - ARROW_HEIGHT), **shape_style) z3_arrow = sc.Line((h, -h, z), (h, -h, z - ARROW_HEIGHT), **shape_style) z4_arrow = sc.Line((-h, h, z), (-h, h, z - ARROW_HEIGHT), **shape_style) def set_visible(sender, shapes, thickness, arrows, visible): set_thickness(sender, shapes, thickness) for arrow in arrows: arrow.visible = visible thickness_group = [z1, z1_arrow, z2, z2_arrow, z3, z3_arrow, z4, z4_arrow] visible_group = [arrow_1, arrow_2, arrow_3, arrow_4] visible_arrow_gesture = sc.HoverGesture( on_began_fn=lambda sender: set_visible(sender, thickness_group, hover_thickness, visible_group, True), on_ended_fn=lambda sender: set_visible(sender, thickness_group, thickness, visible_group, False), ) gestures = [_DragGesture(self, [2], [-1]), visible_arrow_gesture] z1_arrow.gestures = gestures z2_arrow.gestures = gestures z3_arrow.gestures = gestures z4_arrow.gestures = gestures # create 4 rectangles at the corner, and add gesture to update width, height and intensity at the same time s = 0.03 def make_corner_rect(translate): with sc.Transform(transform=sc.Matrix44.get_translation_matrix(translate[0], translate[1], translate[2])): return sc.Rectangle(s, s, color=0x0) r1 = make_corner_rect((h - 0.5 * s, -h + 0.5 * s, 0)) r2 = make_corner_rect((h - 0.5 * s, h - 0.5 * s, 0)) r3 = make_corner_rect((-h + 0.5 * s, h - 0.5 * s, 0)) r4 = make_corner_rect((-h + 0.5 * s, -h + 0.5 * s, 0)) def set_color_and_visible(sender, shapes, thickness, arrows, visible, rects, color): set_visible(sender, shapes, thickness, arrows, visible) for rect in rects: rect.color = color highlight_group = [shape1, shape2, shape3, shape4] + thickness_group color_group = [r1, r2, r3, r4] hight_all_gesture = sc.HoverGesture( on_began_fn=lambda sender: set_color_and_visible(sender, highlight_group, hover_thickness, visible_group, True, color_group, color), on_ended_fn=lambda sender: set_color_and_visible(sender, highlight_group, thickness, visible_group, False, color_group, 0x0), ) r1.gestures = [_DragGesture(self, [0, 1], [1, -1]), hight_all_gesture] r2.gestures = [_DragGesture(self, [0, 1], [1, 1]), hight_all_gesture] r3.gestures = [_DragGesture(self, [0, 1], [-1, 1]), hight_all_gesture] r4.gestures = [_DragGesture(self, [0, 1], [-1, -1]), hight_all_gesture] def on_model_updated(self, item): # Regenerate the mesh if not self.model: return if item == self.model.transform: # If transform changed, update the root transform self.__root_xf.transform = self.model.get_as_floats(item) elif item == self.model.prim_path: # If prim_path or width or height or intensity changed, redraw everything self.invalidate() elif item == self.model.width or item == self.model.height or item == self.model.intensity: # Interpret None as changing multiple light shape settings self._build_shape()
16,572
Python
48.471642
156
0.57573
NVIDIA-Omniverse/kit-workshop-siggraph2022/exts/omni.example.ui_scene.light_man_siggraph/omni/example/ui_scene/light_man_siggraph/tests/test_manipulator.py
## Copyright (c) 2021, 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. ## from omni.ui.tests.test_base import OmniUiTest from pathlib import Path import carb import omni.kit import omni.kit.app import omni.kit.test from omni.example.ui_scene.light_manipulator import LightManipulator, LightModel import omni.usd from omni.ui import scene as sc from pxr import UsdLux, UsdGeom from omni.kit.viewport.utility import next_viewport_frame_async from omni.kit.viewport.utility.tests import setup_vieport_test_window CURRENT_PATH = Path(carb.tokens.get_tokens_interface().resolve("${omni.example.ui_scene.light_manipulator}/data")) OUTPUTS_DIR = Path(omni.kit.test.get_test_output_path()) class TestLightManipulator(OmniUiTest): # Before running each test async def setUp(self): await super().setUp() self._golden_img_dir = CURRENT_PATH.absolute().resolve().joinpath("tests") # After running each test async def tearDown(self): self._golden_img_dir = None await super().tearDown() async def setup_viewport(self, resolution_x: int = 800, resolution_y: int = 600): await self.create_test_area(resolution_x, resolution_y) return await setup_vieport_test_window(resolution_x, resolution_y) async def test_manipulator_transform(self): viewport_window = await self.setup_viewport() viewport = viewport_window.viewport_api await omni.usd.get_context().new_stage_async() stage = omni.usd.get_context().get_stage() # Wait until the Viewport has delivered some frames await next_viewport_frame_async(viewport, 2) with viewport_window.get_frame(0): # Create a default SceneView (it has a default camera-model) scene_view = sc.SceneView() # Add the manipulator into the SceneView's scene with scene_view.scene: LightManipulator(model=LightModel()) omni.kit.commands.execute( "CreatePrim", prim_path="/RectLight", prim_type="RectLight", select_new_prim=True, attributes={}, ) rect_light = UsdLux.RectLight(stage.GetPrimAtPath("/RectLight")) # change light attribute rect_light.GetHeightAttr().Set(100) rect_light.GetWidthAttr().Set(200) rect_light.GetIntensityAttr().Set(10000) # rotate the light to have a better angle rect_light_x = UsdGeom.Xformable(rect_light) rect_light_x.ClearXformOpOrder() rect_light_x.AddRotateXOp().Set(30) rect_light_x.AddRotateYOp().Set(45) for _ in range(10): await omni.kit.app.get_app().next_update_async() await self.finalize_test(golden_img_dir=self._golden_img_dir)
3,133
Python
37.219512
114
0.684966
NVIDIA-Omniverse/kit-workshop-siggraph2022/exts/omni.example.ui_scene.light_man_siggraph/omni/example/ui_scene/light_man_siggraph/tests/__init__.py
from .test_manipulator import TestLightManipulator
50
Python
49.99995
50
0.9
NVIDIA-Omniverse/kit-workshop-siggraph2022/exts/omni.example.ui_scene.light_man_siggraph/docs/CHANGELOG.md
# Changelog omni.example.ui_scene.light_manipulator ## [1.1.1] - 2022-6-21 ### Added - Documentation ## [1.1.0] - 2022-6-06 ### Changed - Removed other lights except RectLight - Added gesture to the RectLight so that users can drag the manipulator to change the width, height and intensity - The drag gesture can be just on the width (x-axis line) or height (y-axis line) or intensity (z-axis line) or all of them when drag the corner rectangles - Added test for the extension ## [1.0.0] - 2022-5-26 ### Added - The initial version
536
Markdown
25.849999
118
0.720149
NVIDIA-Omniverse/kit-workshop-siggraph2022/exts/omni.example.ui_scene.light_man_siggraph/docs/README.md
# Light Manipulator (omni.example.ui_scene.light_manipulator) ## Overview We provide an End-to-End example of a light manipulator extension, which adds manipulators to RectLight. There are 6 types of lights in Omniverse, shown in the image below. Here is the link of how to add a light: https://www.youtube.com/watch?v=c7qyI8pZvF4. In this example, we only create manipulators to RectLight. ![](../data/lights.png) It contains the LightModel which stores the light attribute values. Focused on "width", "height" and "intensity" in this example. It also plays the role of communication with the USD data, reading and writing updated attributes from and to USD. LightManipulator defines 4 types of manipulators which separately control the light's width, height, intensity and all of the three. ## [Tutorial](../tutorial/tutorial.md) Follow this [step-by-step guide](../tutorial/tutorial.md) to learn how this extension was created. ## Manipulator The manipulator contains a rectangle and 4 lines perpendicular to the rectangle face. The manipulator is generated in a unit size, and the update of the look is through the parent transform of the manipulator. - When you hover over the rectangle's width or height of the manipulator, you will see the line representation of the width or height highlighted and you can drag and move the manipulator. When you drag and move the height or width of the rectangle of the manipulator, you will see the width or height attributes of the RectLight in the property window are updated. ![](../data/width_s.png) ![](../data/height_s.png) - When you hover over on the tip of any line perpendicular to the rectangle face, you will see the 4 lines will be highlighted and the arrow on the tip will reveal. When you drag and move the arrow, you will see the intensity attribute of the RectLight is updated. ![](../data/intensity_s.png) - When you hover over to the corner of the rectangle (slightly inside the rectangle), you will see the entire manipulator is highlighted, and there will be 4 small rectangles revealed at the corner of the rectangle. When you drag and move the small rectangle, you will see all of the width, height and intensity attributes of the RectLight are updated. ![](../data/preview_s.png) - When you change the attributes (Width, height and intensity) of the RectLight in the property window, you will see the manipulator appearance updates. ![](../data/attribute_s.png) ## Gesture The example defined a customized `_DragGesture` for the manipulator. This is how the gesture is implemented: - `on_began`: the start attributes data is restored into the model, so that we have a record of previous values later for running `omni.kit.commands`. - `on_changed`: update the attributes into the model, and the model will directly write the value to the USD without keeping it since we want to see the real-time updating of attribute value in the property window - `on_ended`: update the attributes into the model, and the model will call `omni.kit.commands` to change the property since we want to support the undo/redo for the dragging. The previous value from `on_began` is used here. ## Model The model contains the following named items: - width - the width attribute of the RectLight - height - the height attribute of the RectLight - intensity - the intensity attribute of the RectLight - prim_path - the USD prim path of the RectLight. - transform - the transform of the RectLight. The model is the bridge between the manipulator and the attributes data. The manipulator subscribes to the model change to update the look. All the attributes values are directly coming from USD data. We use `Tf.Notice` to watch the rectLight and update the model. The model itself doesn't keep and doesn't duplicate the USD data, except the previous value when a gesture starts. - When the model's `width`, `height` or `intensity` changes, the manipulator's parent transform is updated. - The model's `prim_path` is subscribed to `omni.usd.StageEventType.SELECTION_CHANGED`, so when the selection of RectLight is changed, the entire manipulator is redrawn. - When the model's `transform` is changed, the root transform of the manipulator is updated. For width, height and intensity, the model demonstrates two strategies working with the data. It keeps the attribute data during the manipulating, so that the manipulator has the only one truth of data from the model. When the manipulator requests the attributes from the model, the model computes the position using USD API and returns it to the manipulator. ## Overlaying with the viewport We use `sc.Manipulator` to draw the manipulator in 3D view. To show it in the viewport, we overlay `sc.SceneView` with our `sc.Manipulator` on top of the viewport window. ```python from omni.kit.viewport.utility import get_active_viewport_window viewport_window = get_active_viewport_window() # Create a unique frame for our SceneView with viewport_window.get_frame(ext_id): # Create a default SceneView (it has a default camera-model) self._scene_view = sc.SceneView() # Add the manipulator into the SceneView's scene with self._scene_view.scene: LightManipulator(model=LightModel()) ``` To synchronize the projection and view matrices, `omni.kit.viewport.utility` has the method `add_scene_view`, which replaces the camera model, and the manipulator visually looks like it's in the main viewport. ```python # Register the SceneView with the Viewport to get projection and view updates viewport_window.viewport_api.add_scene_view(self._scene_view) ```
5,614
Markdown
64.290697
366
0.773245
NVIDIA-Omniverse/kit-workshop-siggraph2022/exts/omni.example.ui_scene.light_man_siggraph/docs/index.rst
omni.example.ui_scene.light_manipulator ######################################## Example of Python only extension .. toctree:: :maxdepth: 1 README CHANGELOG
170
reStructuredText
13.249999
40
0.547059
NVIDIA-Omniverse/kit-workshop-siggraph2022/exts/omni.example.custom_ui/Workshop/Siggraph2022_Scatter_Workshop.md
![](https://github.com/NVIDIA-Omniverse/kit-workshop-siggraph2022/blob/main/exts/omni.example.ui_scatter_tool/Workshop/images/logo.png?raw=true) # NVIDIA OMNIVERSE # Build Beautiful, Custom UI for 3D Tools on NVIDIA Omniverse​ Become a master in UI with a hands-on deep dive into NVIDIA Omniverse Kit’s powerful omni.ui suite of tools and frameworks. In this session, you’ll build your own custom UI for workflows in Omniverse with Python script. # Learning Objectives - Enable Extension - Build with omni.ui - Create Columns and Rows - Create a button <video width="560" height="315" controls> <source src="https://d36m44n9vdbmda.cloudfront.net/assets/x-ov-05-v1/BuildUIIntro.mp4" type="video/mp4"> </video> # Omni.ui_Window Scatter ## Section I <video width="560" height="315" controls> <source src="https://d36m44n9vdbmda.cloudfront.net/assets/x-ov-05-v1/BuildUISection1.mp4" type="video/mp4"> </video> ### Step 1: Open the Workshop Stage #### <b>Step 1.1: Download the Stage from the Link Provided</b> [Stage Link](https://dli-lms.s3.amazonaws.com/assets/x-ov-05-v1/Stage.zip) #### <b> Step 1.2: Unzip Stage Using Extract All... This creates an unzipped file folder called `Stage`. #### <b> Step 1.3: Open Stage in Omniverse Navigate inside Omniverse Code's `Content tab` to the stage file's location on your system. (i.e. C:/Users/yourName/Downloads/Stage) **Double Click** `Stage.usd` in the center window pane of the `Content tab` at the bottom of the Omniverse Code Console and it will appear in the viewport. ### Step 2: Install the Scatter Tool Extension #### <b>Step 2.1: Open the Extensions Tab</b> Click on `Extensions` Manager Tab #### <b>Step 2.2: Filter by Commnuity / Third Party Extensions</b> Select `Community / Third Party` tab <br> ![](https://github.com/NVIDIA-Omniverse/kit-workshop-siggraph2022/blob/workshop_3/exts/omni.example.ui_scatter_tool/Workshop/images/extensionCommunity.PNG?raw=true) <br> #### <b>Step 2.3: Search for Scatter Tool</b> Search for `Scatter Tool` and click on `Omni.UI Window Scatter` ![](https://github.com/NVIDIA-Omniverse/kit-workshop-siggraph2022/blob/workshop_3/exts/omni.example.ui_scatter_tool/Workshop/images/windowScatter.png?raw=true) <br> #### <b>Step 2.4: Install/Enable the Extension</b> Click on the extension and then click `Install` in the right console. Once installed, enable the extension. <span>&#10071;</span> You may get a warning that this extension is not verified. It is safe to install this extension. <br> `Scatter Window` will appear on the screen when the extension is enabled. ![](https://github.com/NVIDIA-Omniverse/kit-workshop-siggraph2022/blob/workshop_3/exts/omni.example.ui_scatter_tool/Workshop/images/ScatterWindow.png?raw=true) <br> #### <b>Step 2.5: Does it work? Set the Source</b> In the `Viewport` select a prim in the `Stage Hierarchy` and then set the Source of the prim in the Scatter Window by clicking the "S" in Source of `Scatter Window` . A `prim` is short for primitive. The prim is the fundamental unit in Omniverse. Anything imported or created in a `USD`, Universal Scene Description, scene. This includes camera, sounds, lights, meshes, etc. ![](https://github.com/NVIDIA-Omniverse/kit-workshop-siggraph2022/blob/workshop_3/exts/omni.example.ui_scatter_tool/Workshop/images/scatterSource.png?raw=true) <br> #### <b>Step 2.6: Scatter the Prim</b> Scatter 20 objects on the `X-axis` with a distance of 30. Leave Y and Z at default and then click `Scatter Prim A` at the bottom of the `Scatter Window`. Here is an example of what your scene may look like: ![](https://github.com/NVIDIA-Omniverse/kit-workshop-siggraph2022/blob/workshop_3/exts/omni.example.ui_scatter_tool/Workshop/images/scatterPrim.png?raw=true) ><span>&#10067;</span>Did you notice? >- Prim scatters at World Origin `[0,0,0]`. How do you think this can be fixed? >- You can set multiple prim's in the Source but you cannot scatter multiple prim's individually, which we will fix in Section II! <br> #### <b>Step 3: Enable Physics</b> Find the `Play` button and enable physics, watch what happens! Don't forget to hit the `Stop` button after the physics have played. <details> <summary>Click here to see where the play button is located</summary> ![](https://github.com/NVIDIA-Omniverse/kit-workshop-siggraph2022/blob/workshop_3/exts/omni.example.ui_scatter_tool/Workshop/images/playButton.png?raw=true) </details> <br> ### <b>Step 4: Undo Scatter</b> Find the `Scatter01` folder in `Stage` and left-click on the folder then right-click to delete or hit the `delete` button on your keyboard. `Stage` is the panel that allows you to see all the assets in your current `USD`, or Universal Scene Description. It lists the prims in heirarchical order. ><span>&#10071;</span> Warning <span>&#10071;</span> If you `ctrl+z` you will undo the last 3 scatters. ![](https://github.com/NVIDIA-Omniverse/kit-workshop-siggraph2022/blob/workshop_3/exts/omni.example.ui_scatter_tool/Workshop/images/deletescatter.gif?raw=true) <br> >#### <span>&#129504;</span><b>Challenge Step 5: Brainstorm Use Cases</b> ><i>All Challenges in this workshop are optional</i> > >Think of 3 ways this tool could be used. Brain storm with your peers and think of how it can be used for your industry! <br> >### <span>&#9940;</span> Stop here and wait to move on to Section II <br> ## Section II <video width="560" height="315" controls> <source src="https://d36m44n9vdbmda.cloudfront.net/assets/x-ov-05-v1/BuildUIIntroSection2.mp4" type="video/mp4"> </video> <video width="560" height="315" controls> <source src="https://d36m44n9vdbmda.cloudfront.net/assets/x-ov-05-v1/buildUISection2.mp4" type="video/mp4"> </video> ### Step 6: Add another Source to the UI #### <b>Step 6.1: Open Visual Studio</b> Go to the `Extensions` tab and click the `Scatter Window` extension to open the extension overview to the right. Click the `VS Code` icon next to the folder icon: ![](https://github.com/NVIDIA-Omniverse/kit-workshop-siggraph2022/blob/workshop_3/exts/omni.example.ui_scatter_tool/Workshop/images/VScode.png?raw=true) <br> #### <b>Step 6.2: Locate Window Script</b> Locate the files you need for this session at: `exts -> omni\example\ui_scatter_tool` You are working in `window.py` <br> ![](https://github.com/NVIDIA-Omniverse/kit-workshop-siggraph2022/blob/workshop_3/exts/omni.example.ui_scatter_tool/Workshop/images/vsCodeStruct.gif?raw=true) <br> #### <b>Step 6.3: Locate Models</b> Locate the sets of `Models` at the top of the `ScatterWindow` class. This is where prim A is defined for both the source and the scatter properties. ![](https://github.com/NVIDIA-Omniverse/kit-workshop-siggraph2022/blob/workshop_3/exts/omni.example.ui_scatter_tool/Workshop/images/models.png?raw=true) <br> #### <b>Step 6.4: Add Prim Model B to Models</b> Below `self._scatter_prim_model_a` in the sets of `Models`, add the source and scatter for our new prim, `prim model b`, as so: ```python self._source_prim_model_b = ui.SimpleStringModel() self._scatter_prim_model_b = ui.SimpleStringModel() ``` ><span>&#10071;</span> Check that you have tabbed correctly. Your new `Models` section should look like this: ![](https://github.com/NVIDIA-Omniverse/kit-workshop-siggraph2022/blob/workshop_3/exts/omni.example.ui_scatter_tool/Workshop/images/primModelB.png?raw=true) <br> #### <b>Step 6.5: Locate Defaults</b> Locate the sets of `Defaults` below the sets of `Models`. This is the default name for the scatter that will be nested in `Stage`. ![](https://github.com/NVIDIA-Omniverse/kit-workshop-siggraph2022/blob/workshop_3/exts/omni.example.ui_scatter_tool/Workshop/images/defaults.png?raw=true) <br> #### <b>Step 6.6: Add Default for Prim Model B </b> Below the property for `self._scatter_prim_model_a._as_string`, set the same for `prim model b` but instead, define the path in the stage as `/World/Scatter02`. This will default where the scatter for prim b will be nested in `Stage`. ```python self._scatter_prim_model_b.as_string = "/World/Scatter02" ``` Now your `Defaults` section should look like this: ![](https://github.com/NVIDIA-Omniverse/kit-workshop-siggraph2022/blob/workshop_3/exts/omni.example.ui_scatter_tool/Workshop/images/defaultPrimB.png?raw=true) <br> #### <b>Step 6.7: Locate _build_source function</b> Locate `_build_source` function in the same script. ![](https://github.com/NVIDIA-Omniverse/kit-workshop-siggraph2022/blob/workshop_3/exts/omni.example.ui_scatter_tool/Workshop/images/buildSource.png?raw=true) This function creates the UI for the `Source` of `Scatter Window` where you set the selected prim by clicking the "S". <br> #### <b>Step 6.8: Add Source UI for Prim B</b> Add this new `ui.HStack` to the bottom of this function, underneath the existing `ui.HStack` for Prim A. ```python with ui.HStack(): ui.Label("Prim B", name="attribute_name", width=self.label_width) ui.StringField(model=self._source_prim_model_b) # Button that puts the selection to the string field ui.Button( " S ", width=0, height=0, style={"margin": 0}, clicked_fn=lambda:self._on_get_selection(self._source_prim_model_b), tooltip="Get From Selection", ) ``` So that your updated function looks like this: ![](https://github.com/NVIDIA-Omniverse/kit-workshop-siggraph2022/blob/workshop_3/exts/omni.example.ui_scatter_tool/Workshop/images/newHstack.png?raw=true) <br> Save your `window.py` script and check that your Scatter Window UI updated. ## <span>&#127881;</span> CONGRATULATIONS! <span>&#127881;</span> You have created your first piece of UI in Omniverse! ![](https://github.com/NVIDIA-Omniverse/kit-workshop-siggraph2022/blob/workshop_3/exts/omni.example.ui_scatter_tool/Workshop/images/sourceUiPrimB.png?raw=true) <br> ><span>&#10067;</span> If your UI did not update or your `Scatter Window` disappeared, check the console for errors. The `Console` tab can be found here: > >![](https://github.com/NVIDIA-Omniverse/kit-workshop-siggraph2022/blob/workshop_3/exts/omni.example.ui_scatter_tool/Workshop/images/console.png?raw=true) <br> ><span>&#10071;</span> A common error may be that your code is not aligned properly. Check that the indents match the snippets in step 6.8. <br> #### <b>Step 6.9: Locate _build_scatter Function</b> Locate the function `_build_scatter` in `window.py`. This function creates the UI for the Scatter group below `Source` in `Scatter Window`. ![](https://github.com/NVIDIA-Omniverse/kit-workshop-siggraph2022/blob/workshop_3/exts/omni.example.ui_scatter_tool/Workshop/images/buildScattercode.png?raw=true) <br> #### <b>Step 6.10: Add Scatter UI for Prim B</b> Create this new `ui.HStack`, for `Prim B Path` below the row for `Prim A Path` as follows: ```python with ui.HStack(): ui.Label("Prim B Path", name="attribute_name", width=self.label_width) ui.StringField(model=self._scatter_prim_model_b) ``` So now your `_build_scatter` looks like this: ![](https://github.com/NVIDIA-Omniverse/kit-workshop-siggraph2022/blob/workshop_3/exts/omni.example.ui_scatter_tool/Workshop/images/newBuildScatter.png?raw=true) <br> Save your `window.py` script and check that your UI has updated in Omniverse. ## <span>&#127775;</span> AMAZING! <span>&#127775;</span> You've done it again and successfully created UI! ![](https://github.com/NVIDIA-Omniverse/kit-workshop-siggraph2022/blob/workshop_3/exts/omni.example.ui_scatter_tool/Workshop/images/PathUiPrimB.png?raw=true) <br> #### <b>Step 6.11: Locate _build_fn Function</b> Locate the function `_build_fn` in `window.py` This function builds the entire UI in the `Scatter Window` and also calls the function for when the `Scatter Prim` button is clicked. ![](https://github.com/NVIDIA-Omniverse/kit-workshop-siggraph2022/blob/workshop_3/exts/omni.example.ui_scatter_tool/Workshop/images/buildFN.png?raw=true) <br> #### <b>Step 6.12: Add a scatter button for Prim B</b> Create this new button underneath the `Go Button` for `Prim A`. ```python # The Go button ui.Button("Scatter Prim B", clicked_fn=lambda:self._on_scatter(self._source_prim_model_b, self._scatter_prim_model_b)) ``` So your `_build_fn` should look like this: ![](https://github.com/NVIDIA-Omniverse/kit-workshop-siggraph2022/blob/workshop_3/exts/omni.example.ui_scatter_tool/Workshop/images/newGo.png?raw=true) <br> Save `window.py` and check that your UI has been updated in Omniverse. ## <span>&#10024;</span> WOW! <span>&#10024;</span> You've created a new button, great job! ![](https://github.com/NVIDIA-Omniverse/kit-workshop-siggraph2022/blob/workshop_3/exts/omni.example.ui_scatter_tool/Workshop/images/ButtonUi.png?raw=true) <br> ### Step 7: Set and Scatter Prim A and Prim B #### <b>Step 7.1: Set the Source of Prim A and Prim B</b> Set the Source for Prim A and Prim B, just as you did in Step 2.5 ![](./images/setPrimA.png) <br> Make sure that you have set Prim B as a different Prim than Prim A. For example, set Prim A as Twist Marble and set Prim B as Gummy Bear. ![](https://github.com/NVIDIA-Omniverse/kit-workshop-siggraph2022/blob/workshop_3/exts/omni.example.ui_scatter_tool/Workshop/images/setPrimB.png?raw=true) <br> #### <b>Step 7.2: Set Parameters for X, Y, Z Axis</b> Set X axis object count to 5 with a distance of 25. Set Y axis object count to 4 with a distance of 25. Set Z axis object count to 4 with distance of 25. ![](https://github.com/NVIDIA-Omniverse/kit-workshop-siggraph2022/blob/workshop_3/exts/omni.example.ui_scatter_tool/Workshop/images/objectCount.png?raw=true) <br> #### <b>Step 7.3: Scatter Prim A</b> Click Scatter Prim A button. You should see a quad of Prim A appear on the screen and a folder in `Stage` labeled `Scatter01`. Select the prims in `Scatter 01` by selecting the first prim in the folder and then <b>shift+click</b> the last prim in the folder then move the quad of Prims over the serving bowl in the viewport. ![](https://github.com/NVIDIA-Omniverse/kit-workshop-siggraph2022/blob/workshop_3/exts/omni.example.ui_scatter_tool/Workshop/images/scatterA.gif?raw=true) <br> #### <b>Step 7.4: Scatter Prim B</b> Click Scatter Prim B button. You should see a quad of Pim B appear on the screen and a folder in `Stage` labeled `Scatter 02`. Leave these prims where they originated. ![](https://github.com/NVIDIA-Omniverse/kit-workshop-siggraph2022/blob/workshop_3/exts/omni.example.ui_scatter_tool/Workshop/images/scatterB.png?raw=true) <br> #### <b>Step 7.5: Press the Play Button</b> Press `Play` and watch the Prims fall into the bowl and jar! Press `Stop` when you are done. ![](https://github.com/NVIDIA-Omniverse/kit-workshop-siggraph2022/blob/workshop_3/exts/omni.example.ui_scatter_tool/Workshop/images/playScatter.gif?raw=true) <br> >#### <span>&#129504;</span><b>Challenge Step 8: Set Scale Parameters in the UI</b> ><i>All Challenges in this workshop are optional</i> > >The function to scale the prim on scatter already exists in the code, can you create the UI for it? > ><b>Hint:</b> It will be built in `_build_scatter`. > >[You can search the omni.ui documentation here.](https://docs.omniverse.nvidia.com/py/kit/source/extensions/omni.ui/docs/index.html#omni.ui.StringField) > ><details> ><summary> Click here for the answer </summary> > >### Challenge Step 8.1: Build UI for Scale ><i>All Challenges in this workshop are optional</i> > >Locate `_build_scatter` in `window.py` as we did in step 6.9. > >Add this new row for Scale at the bottom of the function: > >```python > with ui.HStack(): > ui.Label("Scale", name="attribute_name", width=self.label_width) > for field in zip(["X:", "Y:", "Z:"], self._scale_models): > ui.Label(field[0], width=0, style={"margin": 3.0}) > ui.FloatField(model=field[1], height=0, style={"margin": 3.0}) >``` > >So now your `_build_scatter` function should look like this: > >![](https://github.com/NVIDIA-Omniverse/kit-workshop-siggraph2022/blob/workshop_3/exts/omni.example.ui_scatter_tool/Workshop/images/scaleChallengeScatter.png?raw=true) > >Save `window.py` and check that the UI has updated in Omniverse. > >This is what your new UI should look like: > >![](https://github.com/NVIDIA-Omniverse/kit-workshop-siggraph2022/blob/workshop_3/exts/omni.example.ui_scatter_tool/Workshop/images/scaleUi.png?raw=true) > >Check that it is working by setting new parameters for scale and object count then click `Scatter Prim A`. > ></details> <br> >### <span>&#9940;</span> Stop here and wait to move on to Section III <br> ## Section III <video width="560" height="315" controls> <source src="https://d36m44n9vdbmda.cloudfront.net/assets/x-ov-05-v1/buildUISection3.mp4" type="video/mp4"> </video> ### Step 9: Make your scene #### <b>Step 9.1: Play with the Parameters</b> Scatter your prims using various object and distance parameters along the X, Y, and Z axis. #### <b>Step 9.2: Randomize your Parameters</b> Scatter your prims again changing the `Random` parameters along the different axis. What does Random do? The `Random` parameter in `Scatter Tool` is a scalar factor that multiples against a random number and is then added to the uniform distribution for each object. For example: If the `Distance` parameter is set to 20, each other be would distanced at 0, 20, 40, etc. If you add a `Random` parameter of 15 then it turns into 0 = (15 * random_number_gen), 20 + (15 * random_number_gen), etc. >:bulb:Press play when you are finished > >![](https://github.com/NVIDIA-Omniverse/kit-workshop-siggraph2022/blob/workshop_3/exts/omni.example.ui_scatter_tool/Workshop/images/playButton.png?raw=true) >#### <span>&#129504;</span><b>Challenge Step 10: How many marbles can you get in the jars and bowls?</b> > ><i>All Challenges in this workshop are optional</i> > >How can you use the scatter tool to drop as many marbles into the jars and bowls? > ><details> ><summary>Click here for a suggestion</summary> > >Similar to Step 7.2, scatter a Prim in a smaller distance and higher object count to create a large stack of prims then move over a jar or bowl before pressing play. Then watch them all fall! > >![](https://github.com/NVIDIA-Omniverse/kit-workshop-siggraph2022/blob/workshop_3/exts/omni.example.ui_scatter_tool/Workshop/images/scatterMarblesChallenge.gif?raw=true) > ></details> <br> ## Congratulations! You have completed this workshop! We hope you have enjoyed learning and playing in Omniverse! [Join us on Discord to extend the conversation!](https://discord.com/invite/nvidiaomniverse)
19,036
Markdown
35.12334
235
0.718061
NVIDIA-Omniverse/kit-workshop-siggraph2022/exts/omni.example.custom_ui/Workshop/CN_UI_Workshop.md
![](https://github.com/NVIDIA-Omniverse/kit-workshop-siggraph2022/blob/main/exts/omni.example.ui_scatter_tool/Workshop/images/logo.png?raw=true) # NVIDIA OMNIVERSE # 通过 NVIDIA Omniverse 为 3D 工具构建漂亮的自定义 UI 界面 亲自试用 NVIDIA Omniverse 套件中的 Omni.ui 工具及框架套件,深入了解其强大功能,从而成为用户界面大师。在本培训中,您将使用 Python 脚本在 Omniverse 中为工作流构建自定义用户界面。 # 学习目标 - 启用扩展程序 - 使用 omni.ui 构建用户界面 - 创建列和行 - 创建按钮 <video width="560" height="315" controls> <source src="https://dli-lms.s3.amazonaws.com/assets/x-ov-05-v1-zh/BuildUIIntro_CN_v1.mp4" type="video/mp4"> </video> # Omni.ui_Window Scatter ## 第 I 部分 <video width="560" height="315" controls> <source src="https://dli-lms.s3.amazonaws.com/assets/x-ov-05-v1-zh/BuildUISection1_CN_v1.mp4" type="video/mp4"> </video> ### <b>第 1 步:打开 Workshop Stage</b> #### <b>第 1.1 步:从下面提供的链接下载 Stage</b> [Stage的下载链接](https://dli-lms.s3.amazonaws.com/assets/x-ov-05-v1/Stage.zip) #### <b>第 1.2 步:使用 “Extract All...”(提取所有文件...)解压 Stage</b> 此操作会创建一个名为 `Stage` 的解压文件夹。 #### <b>第 1.3 步:在 Omniverse 中打开 Stage</b> 在 Omniverse Code 的 `Content`(内容)选项卡中,找到系统中存放 Stage 文件的位置。 (即 C:/Users/yourName/Downloads/Stage) 在 Omniverse Code 控制台底部的 `Content` (内容)选项卡中,**双击**中间窗格中的 `Stage.usd`,即可在视图区中打开该 Stage。 ### <b> 第 2 步:安装 Scatter 工具扩展功能</b> #### <b>第 2.1 步:打开`Extensions`(扩展功能)选项卡</b> 单击 `Extensions`(扩展功能)管理器选项卡 #### <b>第 2.2 步:对来自社区或第三方的扩展功能进行筛选</b> 选择 `Community/Third Party`(社区/第三方)选项卡 <br> ![](https://github.com/NVIDIA-Omniverse/kit-workshop-siggraph2022/blob/workshop_3/exts/omni.example.ui_scatter_tool/Workshop/images/extensionCommunity.PNG?raw=true) <br> #### <b>第 2.3 步:搜索 Scatter 工具</b> 搜索 `Scatter Tool`(散布工具),然后单击 `Omni.UI Window Scatter` ![](https://github.com/NVIDIA-Omniverse/kit-workshop-siggraph2022/blob/workshop_3/exts/omni.example.ui_scatter_tool/Workshop/images/windowScatter.png?raw=true) <br> #### <b>第 2.4 步:安装/启用扩展功能</b> 单击选中的扩展功能,然后在右侧控制台中单击 `Install`(安装)。安装后,启用该扩展功能。 <span>&#10071;</span>您可能会收到一个警告,指明此扩展功能未经验证。安装此扩展功能是安全的。 <br> 启用此扩展功能后,屏幕上会显示 `Scatter Window`(散布窗口)。 ![](https://github.com/NVIDIA-Omniverse/kit-workshop-siggraph2022/blob/workshop_3/exts/omni.example.ui_scatter_tool/Workshop/images/ScatterWindow.png?raw=true) <br> #### <b>第 2.5 步:看到窗口了吗? 设置来源</b> 在 `Viewport`(视图区)部分的 `Stage Hierarchy`(Stage 层次结构)中选择一个 prim (基元),然后按此方式在`Scatter Window`(散布窗口)中设置基元的来源:在 `Scatter Window`(散布窗口)中,单击`Source`(资源)下的`S`按钮。 `Prim`(基元)是 primitive 的简写,它是 Omniverse 中的基本单元。在 `USD` 中导入或创建的任何对象都是一个基元(prim),例如照相机、声音、光线、网格等等。 ![](https://github.com/NVIDIA-Omniverse/kit-workshop-siggraph2022/blob/workshop_3/exts/omni.example.ui_scatter_tool/Workshop/images/scatterSource.png?raw=true) <br> #### <b>第 2.6 步:对基元执行散布操作</b> 在 X 轴上,以 30 为间距值散布 20 个对象。 在 Y 轴和 Z 轴上保留默认设置,然后单击 `Scatter Window`(散布窗口)底部的 `Scatter Prim A`(散布基元 A)。 此时,您的 Stage 应该与下面的示例相似: ![](https://github.com/NVIDIA-Omniverse/kit-workshop-siggraph2022/blob/workshop_3/exts/omni.example.ui_scatter_tool/Workshop/images/scatterPrim.png?raw=true) ><span>&#10067;</span>您注意到了吗? >- 基元散布操作将在 Stage 的原点 `[0,0,0]` 执行。您有什么方法可以解决这个问题? >- 您可以在 `Source`(来源)部分设置多个基元,但是无法对多个基元单独执行散布操作。我们将在第 II 部分解决这个问题。 <br> ### <b>第 3 步:启用物理效果</b> 找到 `Play`(播放)按钮并启用物理效果,看看会发生什么!物理效果播放完毕后,请记得单击 `Stop`(停止)按钮。 <details> <summary>单击此处,查看 Play(播放)按钮所在的位置。</summary> ![](https://github.com/NVIDIA-Omniverse/kit-workshop-siggraph2022/blob/workshop_3/exts/omni.example.ui_scatter_tool/Workshop/images/playButton.png?raw=true) </details> <br> ### <b>第 4 步:撤消散布操作</b> 在 `Stage` 中找到 `Scatter01` 文件夹并用左键单击该文件夹,然后单击鼠标右键选择“Delete”(删除)或按下键盘上的 `delete` 键。 `Stage`是一个面板,在上面您可以看到当前 `USD` (Universal Scene Description) 中的所有素材。它会按层次顺序列出所有的基元。 ><span>&#10071;</span> 警告 <span>&#10071;</span> 如果使用 `ctrl+z` 组合键,则会撤消最后 3 项散布操作。 ![](https://github.com/NVIDIA-Omniverse/kit-workshop-siggraph2022/blob/workshop_3/exts/omni.example.ui_scatter_tool/Workshop/images/deletescatter.gif?raw=true) <br> >### <span>&#129504;</span><b>第 5 步(自我挑战):尽情想象用例</b> ><i>本培训中的所有自我挑战都是可选的。</i> > >思考此工具的 3 种使用方式。与同事进行头脑风暴,并思考如何将此工具应用于您所从事的行业! <br> >### <span>&#9940;</span> 建议在此处暂停,思考一下,再继续学习第 II 部分 <br> ## 第 II 部分 <video width="560" height="315" controls> <source src="https://dli-lms.s3.amazonaws.com/assets/x-ov-05-v1-zh/BuildUIIntroSection2_CN_v1.mp4" type="video/mp4"> </video> <video width="560" height="315" controls> <source src="https://dli-lms.s3.amazonaws.com/assets/x-ov-05-v1-zh/BuildUISection2_CN_v1.mp4" type="video/mp4"> </video> ### <b> 第 6 步:向用户界面添加其他来源</b> #### <b>第 6.1 步:打开 Visual Studio</b> 转至 `Extensions`(扩展功能)选项卡,然后单击 `Scatter Window`(散布窗口)扩展功能,以在右侧打开扩展功能的概览。单击文件夹图标旁边的 `VS Code` 图标: ![](https://github.com/NVIDIA-Omniverse/kit-workshop-siggraph2022/blob/workshop_3/exts/omni.example.ui_scatter_tool/Workshop/images/VScode.png?raw=true) <br> #### <b>第 6.2 步:找到窗口脚本</b> 在以下位置找到本培训需要使用的文件: `exts -> omni\example\ui_scatter_tool` 我们将使用 `window.py` <br> ![](https://github.com/NVIDIA-Omniverse/kit-workshop-siggraph2022/blob/workshop_3/exts/omni.example.ui_scatter_tool/Workshop/images/vsCodeStruct.gif?raw=true) <br> #### <b>第 6.3 步:找到模型</b> 在 `ScatterWindow` 类的顶部,找到 `Models`(模型)代码集。 此代码集定义了基元 A 的来源和散布属性。 ![](https://github.com/NVIDIA-Omniverse/kit-workshop-siggraph2022/blob/workshop_3/exts/omni.example.ui_scatter_tool/Workshop/images/models.png?raw=true) <br> #### <b>第 6.4 步:在模型代码集中添加基元模型 B</b> 在 `Models`(模型)代码集的 `self._scatter_prim_model_a` 下方,添加新基元 `prim model b` 的来源和散布属性,具体如下: ```python self._source_prim_model_b = ui.SimpleStringModel() self._scatter_prim_model_b = ui.SimpleStringModel() ``` ><span>&#10071;</span> 确保代码正确对齐。编辑后的 `Models` 部分将与以下示例类似: ![](https://github.com/NVIDIA-Omniverse/kit-workshop-siggraph2022/blob/workshop_3/exts/omni.example.ui_scatter_tool/Workshop/images/primModelB.png?raw=true) <br> #### <b>第 6.5 步:找到默认设置</b> 在 `Models`(模型)代码集下面,找到 `Defaults`(默认设置)代码集。 这是将要在 `Stage`中执行的散布操作的默认名称。 ![](https://github.com/NVIDIA-Omniverse/kit-workshop-siggraph2022/blob/workshop_3/exts/omni.example.ui_scatter_tool/Workshop/images/defaults.png?raw=true) <br> #### <b>第 6.6 步:为基元模型 B 添加默认设置</b> 在 `self._scatter_prim_model_a._as_string` 属性下方,为 `prim model b` 设置相同的属性,但是将其在场景中的路径定义为 `/World/Scatter02`。这将决定在 `Stage`中对基元 B 执行散布操作的默认位置。 ```python self._scatter_prim_model_b.as_string = "/World/Scatter02" ``` 此时,您的 `Defaults`(默认设置)部分应该与下面的示例相似: ![](https://github.com/NVIDIA-Omniverse/kit-workshop-siggraph2022/blob/workshop_3/exts/omni.example.ui_scatter_tool/Workshop/images/defaultPrimB.png?raw=true) <br> #### <b>第 6.7 步:找到 _build_source 函数</b> 在同一脚本中,找到 `_build_source` 函数。 ![](https://github.com/NVIDIA-Omniverse/kit-workshop-siggraph2022/blob/workshop_3/exts/omni.example.ui_scatter_tool/Workshop/images/buildSource.png?raw=true) 此函数用于为 `Scatter Window`(散布窗口)中`Source`(来源)选项(即单击“S”按钮设置所选基元的功能)创建用户界面。 <br> #### <b>第 6.8 步:为基元 B 添加来源用户界面</b> 在这个函数的底部,将下面的新 `ui.HStack` 添加到原有的基元 A 的 `ui.HStack` 下方。 ```python with ui.HStack(): ui.Label("Prim B", name="attribute_name", width=self.label_width) ui.StringField(model=self._source_prim_model_b) # Button that puts the selection to the string field ui.Button( " S ", width=0, height=0, style={"margin": 0}, clicked_fn=lambda:self._on_get_selection(self._source_prim_model_b), tooltip="Get From Selection", ) ``` 此时,更新后的函数应该与下面的示例相似: ![](https://github.com/NVIDIA-Omniverse/kit-workshop-siggraph2022/blob/workshop_3/exts/omni.example.ui_scatter_tool/Workshop/images/newHstack.png?raw=true) <br> 保存更改后的 `window.py` 脚本,然后查看`Scatter Window`(散布窗口)的用户界面是否相应更新。 ## <span>&#127881;</span> 恭喜! <span>&#127881;</span> 您在 Omniverse 中创建了自己的第一个用户界面组件! ![](https://github.com/NVIDIA-Omniverse/kit-workshop-siggraph2022/blob/workshop_3/exts/omni.example.ui_scatter_tool/Workshop/images/sourceUiPrimB.png?raw=true) <br> ><span>&#10067;</span> 如果用户界面没有更新或者 `Scatter Window`(散布窗口)消失了,请在控制台中检查代码是否有误。`Console`(控制台)选项卡位于此处: > >![](https://github.com/NVIDIA-Omniverse/kit-workshop-siggraph2022/blob/workshop_3/exts/omni.example.ui_scatter_tool/Workshop/images/console.png?raw=true) <br> ><span>&#10071;</span> 造成这些问题的一个常见错误是代码没有正确对齐。请检查代码缩进格式是否与第 6.8 步中的屏幕截图完全相同。 <br> #### <b>第 6.9 步:找到 _build_scatter 函数</b> 在 `window.py` 中,找到 `_build_scatter` 函数。 此函数用于为 `Scatter Window`(散布窗口)中 `Source`(资源)下的散布组创建用户界面。 ![](https://github.com/NVIDIA-Omniverse/kit-workshop-siggraph2022/blob/workshop_3/exts/omni.example.ui_scatter_tool/Workshop/images/buildScattercode.png?raw=true) <br> #### <b>第 6.10 步:为基元 B 添加散布工具用户界面</b> 使用如下代码,在 `Prim A Path` 行的下面,为 `Prim B Path` 创建新的 `ui.HStack`: ```python with ui.HStack(): ui.Label("Prim B Path", name="attribute_name", width=self.label_width) ui.StringField(model=self._scatter_prim_model_b) ``` 此时,您的 `_build_scatter` 应该与下面的示例相似: ![](https://github.com/NVIDIA-Omniverse/kit-workshop-siggraph2022/blob/workshop_3/exts/omni.example.ui_scatter_tool/Workshop/images/newBuildScatter.png?raw=true) <br> 保存更改后的 `window.py` 脚本,然后查看 Omniverse 中的用户界面是否相应更新。 ## <span>&#127775;</span> 太棒了! <span>&#127775;</span> 您又一次成功创建了用户界面! ![](https://github.com/NVIDIA-Omniverse/kit-workshop-siggraph2022/blob/workshop_3/exts/omni.example.ui_scatter_tool/Workshop/images/PathUiPrimB.png?raw=true) <br> #### <b>第 6.11 步:找到 _build_fn 函数</b> 在 `window.py`中,找到函数 `_build_fn`。 此函数用于构建整个 `Scatter Window`(散布窗口)的用户界面,它还会调用单击 `Scatter Prim`(散布基元)按钮时触发的函数。 ![](https://github.com/NVIDIA-Omniverse/kit-workshop-siggraph2022/blob/workshop_3/exts/omni.example.ui_scatter_tool/Workshop/images/buildFN.png?raw=true) <br> #### <b>第 6.12 步:为基元 B 添加散布按钮</b> 在 `Prim A`(基元 A)的 `Go`(执行)按钮下面,创建这个新按钮。 ```python # “Go”(执行)按钮 ui.Button("Scatter Prim B", clicked_fn=lambda:self._on_scatter(self._source_prim_model_b, self._scatter_prim_model_b)) ``` 此时,您的 `_build_fn` 应该与下面的示例相似: ![](https://github.com/NVIDIA-Omniverse/kit-workshop-siggraph2022/blob/workshop_3/exts/omni.example.ui_scatter_tool/Workshop/images/newGo.png?raw=true) <br> 保存 `window.py`,然后查看 Omniverse 中的用户界面是否相应更新。 ## <span>&#10024;</span> 太赞了! <span>&#10024;</span> 您创建了一个新按钮,做的好! ![](https://github.com/NVIDIA-Omniverse/kit-workshop-siggraph2022/blob/workshop_3/exts/omni.example.ui_scatter_tool/Workshop/images/ButtonUi.png?raw=true) <br> ### <b> 第 7 步:设置基元 A 和基元 B 并执行散布操作</b> #### <b>第 7.1 步:设置基元 A 和基元 B 的来源</b> 按照第 2.5 步的操作,为基元 A 和基元 B 设置来源。 ![](./images/setPrimA.png) <br> 在设置基元 B 时,务必使用与基元 A 不同的基元。 例如,将基元 A 设置为 “TwistMarble”,将基元 B 设置为 “GummyBear”。 ![](https://github.com/NVIDIA-Omniverse/kit-workshop-siggraph2022/blob/workshop_3/exts/omni.example.ui_scatter_tool/Workshop/images/setPrimB.png?raw=true) <br> #### <b>第 7.2 步:为 X 轴、Y 轴和 Z 轴设置参数</b> 将 X 轴的 “Object Count”(对象数量)和 “Distance”(距离)分别设置为 5 和 25。 将 Y 轴的 “Object Count”(对象数量)和 “Distance”(距离)分别设置为 4 和 25。 将 Z 轴的 “Object Count”(对象数量)和 “Distance”(距离)分别设置为 4 和 25。 ![](https://github.com/NVIDIA-Omniverse/kit-workshop-siggraph2022/blob/workshop_3/exts/omni.example.ui_scatter_tool/Workshop/images/objectCount.png?raw=true) <br> #### <b>第 7.3 步:对基元 A 执行散布操作</b> 单击 `Scatter Prim A`(散布基元 A)按钮。 屏幕上将会显示一个由基元 A 组成的正方形,而且 `Stage` 里会出现一个名为 `Scatter01` 的文件夹。 选择该文件夹中的第一个基元,再<b>按住 Shift 键单击</b>该文件夹中的最后一个基元,以选择 `Scatter 01` 中的所有基元。然后在视图中,将基元方阵移动到大碗的上方。 ![](https://github.com/NVIDIA-Omniverse/kit-workshop-siggraph2022/blob/workshop_3/exts/omni.example.ui_scatter_tool/Workshop/images/scatterA.gif?raw=true) <br> #### <b>第 7.4 步:对基元 A 执行散布操作</b> 单击`Scatter Prim B`(散布基元 B)按钮。 屏幕上将会显示一个由基元 B 组成的正方形,而且 `Stage` 中会出现一个名为 `Scatter 02` 的文件夹。 将这些基元留在原位。 ![](https://github.com/NVIDIA-Omniverse/kit-workshop-siggraph2022/blob/workshop_3/exts/omni.example.ui_scatter_tool/Workshop/images/scatterB.png?raw=true) <br> #### <b>第 7.5 步:按下 `Play`(播放)按钮</b> 按下 `Play`(播放)按钮,观看基元掉入碗和瓶中! 完成后,按下 `Stop`(停止)按钮。 ![](https://github.com/NVIDIA-Omniverse/kit-workshop-siggraph2022/blob/workshop_3/exts/omni.example.ui_scatter_tool/Workshop/images/playScatter.gif?raw=true) <br> >### <span>&#129504;</span><b>第 8 步(自我挑战):在用户界面中设置范围参数</b> ><i>本培训中的所有自我挑战都是可选的。</i> > >代码中已经包含了用于确定基元散布范围的函数,您能为它创建相应的用户界面吗? > ><b>提示:</b>请在 `_build_scatter` 中进行构建。 > >[您可以在此处搜索 omni.ui 文档。](https://docs.omniverse.nvidia.com/py/kit/source/extensions/omni.ui/docs/index.html#omni.ui.StringField) > ><details> ><summary> 单击此处获取答案 </summary> > >### 第 8.1 步(自我挑战):为范围功能构建用户界面 ><i>本培训中的所有自我挑战都是可选的</i> > >按照第 6.9 步的操作,在 `window.py` 中找到 `_build_scatter`。 > >将下面几行用于范围功能的代码添加到函数底部: > >```python > with ui.HStack(): > ui.Label("Scale", name="attribute_name", width=self.label_width) > for field in zip(["X:", "Y:", "Z:"], self._scale_models): > ui.Label(field[0], width=0, style={"margin": 3.0}) > ui.FloatField(model=field[1], height=0, style={"margin": 3.0}) >``` > >此时,您的 `_build_scatter` 函数应该与下面的示例相似: > >![](https://github.com/NVIDIA-Omniverse/kit-workshop-siggraph2022/blob/workshop_3/exts/omni.example.ui_scatter_tool/Workshop/images/scaleChallengeScatter.png?raw=true) > >保存 `window.py`,然后查看 Omniverse 中的用户界面是否相应更新。 > >新用户界面应如下图所示: > >![](https://github.com/NVIDIA-Omniverse/kit-workshop-siggraph2022/blob/workshop_3/exts/omni.example.ui_scatter_tool/Workshop/images/scaleUi.png?raw=true) > >设置新的范围和对象数量参数,然后单击 `Scatter Prim A`(散布基元 A),看看是否有效。 > ></details> <br> >### <span>&#9940;</span> 建议在此处暂停,思考一下,再继续学习第 III 部分 <br> ## 第 III 部分 <video width="560" height="315" controls> <source src="https://dli-lms.s3.amazonaws.com/assets/x-ov-05-v1-zh/BuildUISection3_CN_v1.mp4" type="video/mp4"> </video> ### <b> 第 9 步:制作您自己的场景</b> #### <b>第 9.1 步:尝试不同的参数</b> 使用多组不同的 X 轴、Y 轴和 Z 轴对象数量和距离参数,对基元执行散布操作。 #### <b>第 9.2 步:使用随机参数</b> 更改各个轴的 `Random`(随机)参数值,然后再次对基元执行散布操作。 `Random`(随机)参数有什么作用? 在`Scatter Tool`(散布工具)中,`Random`(随机)参数是一个标量因子,系统会用它乘以一个随机值,并将计算结果添加到每个对象的均匀分布值上。 例如:如果 `Distance`(距离)参数设置为 20,每个对象将被分配 0、20、40...(以此类推)的距离值。如果添加一个 15 左右的`Random`(随机)参数 ,则各个对象的距离值会变为 0 + (15 * random_number_gen)、20 + (15 * random_number_gen) 等等。 >&#128161; 完成设置后,按下`Play`(播放)按钮 > >![](https://github.com/NVIDIA-Omniverse/kit-workshop-siggraph2022/blob/workshop_3/exts/omni.example.ui_scatter_tool/Workshop/images/playButton.png?raw=true) >### <span>&#129504;</span><b>第 10 步(自我挑战):瓶和碗里会有多少块大理石?</b> > ><i>本培训中的所有自我挑战都是可选的。</i> > >您如何使用缩放工具,让尽可能多的大理石掉落到瓶和碗里? > ><details> ><summary>单击此处查看建议</summary> > >与第 7.2 步类似,在对基元执行散布操作时,只需使用较小的`Distance`(距离)值,并设置较大的`Object Count`(对象数量)值来创建大量基元,然后将其移动到瓶或碗的上方,再按下`Play`(播放)键,观看基元落下即可! > >![](https://github.com/NVIDIA-Omniverse/kit-workshop-siggraph2022/blob/workshop_3/exts/omni.example.ui_scatter_tool/Workshop/images/scatterMarblesChallenge.gif?raw=true) > ></details> <br> ## 恭喜! 您已完成本培训!希望您在学习和使用 Omniverse 的过程中找到乐趣! [欢迎在 Discord 上加入我们,进行更深入的交流!](https://discord.com/invite/nvidiaomniverse)
15,066
Markdown
27.482042
170
0.696668
NVIDIA-Omniverse/kit-workshop-siggraph2022/exts/omni.example.custom_ui/config/extension.toml
[package] title = "omni.ui Window Scatter" description = "The full end to end example of the window" version = "1.0.1" category = "Scatter" authors = ["Victor Yudin"] repository = "https://gitlab-master.nvidia.com/omniverse/kit-extensions/kit-windows" keywords = ["example", "window", "ui"] changelog = "docs/CHANGELOG.md" icon = "data/icon.png" preview_image = "data/preview.png" [dependencies] "omni.ui" = {} "omni.usd" = {} "omni.kit.menu.utils" = {} [[python.module]] name = "omni.example.custom_ui" [[test]] args = [ "--/app/window/dpiScaleOverride=1.0", "--/app/window/scaleToMonitor=false", "--no-window" ] dependencies = [ "omni.kit.renderer.core", "omni.kit.renderer.capture", ]
711
TOML
21.967741
84
0.666667
NVIDIA-Omniverse/kit-workshop-siggraph2022/exts/omni.example.custom_ui/omni/example/custom_ui/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__ = ["scatter_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.scatter_window_hovered = cl("#2b2e2e") cl.scatter_window_text = cl("#9e9e9e") fl.scatter_window_attr_hspacing = 10 fl.scatter_window_attr_spacing = 1 fl.scatter_window_group_spacing = 2 # The main style dict scatter_window_style = { "Label::attribute_name": { "color": cl.scatter_window_text, "margin_height": fl.scatter_window_attr_spacing, "margin_width": fl.scatter_window_attr_hspacing, }, "CollapsableFrame::group": {"margin_height": fl.scatter_window_group_spacing}, "CollapsableFrame::group:hovered": {"secondary_color": cl.scatter_window_hovered}, }
1,408
Python
35.128204
89
0.740767
NVIDIA-Omniverse/kit-workshop-siggraph2022/exts/omni.example.custom_ui/omni/example/custom_ui/commands.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__ = ["ScatterCreatePointInstancerCommand"] from pxr import Gf from pxr import Sdf from pxr import Usd from pxr import UsdGeom from typing import List from typing import Optional from typing import Tuple import omni.kit.commands import omni.usd.commands class ScatterCreatePointInstancerCommand(omni.kit.commands.Command, omni.usd.commands.stage_helper.UsdStageHelper): """ Create PointInstancer undoable **Command**. ### Arguments: `path_to: str` The path for the new prims `transforms: List` Pairs containing transform matrices and ids to apply to new objects `prim_names: List[str]` Prims to duplicate """ def __init__( self, path_to: str, transforms: List[Tuple[Gf.Matrix4d, int]], prim_names: List[str], stage: Optional[Usd.Stage] = None, context_name: Optional[str] = None, ): omni.usd.commands.stage_helper.UsdStageHelper.__init__(self, stage, context_name) self._path_to = path_to # We have it like [(tr, id), (tr, id), ...] # It will be transformaed to [[tr, tr, ...], [id, id, ...]] unzipped = list(zip(*transforms)) self._positions = [m.ExtractTranslation() for m in unzipped[0]] self._proto_indices = unzipped[1] self._prim_names = prim_names.copy() def do(self): stage = self._get_stage() # Set up PointInstancer instancer = UsdGeom.PointInstancer.Define(stage, Sdf.Path(self._path_to)) attr = instancer.CreatePrototypesRel() for name in self._prim_names: attr.AddTarget(Sdf.Path(name)) instancer.CreatePositionsAttr().Set(self._positions) instancer.CreateProtoIndicesAttr().Set(self._proto_indices) def undo(self): delete_cmd = omni.usd.commands.DeletePrimsCommand([self._path_to]) delete_cmd.do()
2,346
Python
32.056338
115
0.663257
NVIDIA-Omniverse/kit-workshop-siggraph2022/exts/omni.example.custom_ui/omni/example/custom_ui/extension.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__ = ["ScatterWindowExtension"] from .window import ScatterWindow from functools import partial import asyncio import omni.ext import omni.kit.ui import omni.ui as ui class ScatterWindowExtension(omni.ext.IExt): """The entry point for Scatter Window""" WINDOW_NAME = "Scatter Window" MENU_PATH = f"Window/{WINDOW_NAME}" def on_startup(self): # The ability to show up the window if the system requires it. We use it # in QuickLayout. ui.Workspace.set_show_window_fn(ScatterWindowExtension.WINDOW_NAME, partial(self.show_window, None)) # Put the new menu editor_menu = omni.kit.ui.get_editor_menu() if editor_menu: self._menu = editor_menu.add_item( ScatterWindowExtension.MENU_PATH, self.show_window, toggle=True, value=True ) # Show the window. It will call `self.show_window` ui.Workspace.show_window(ScatterWindowExtension.WINDOW_NAME) def on_shutdown(self): self._menu = None if self._window: self._window.destroy() self._window = None # Deregister the function that shows the window from omni.ui ui.Workspace.set_show_window_fn(ScatterWindowExtension.WINDOW_NAME, None) def _set_menu(self, value): """Set the menu to create this window on and off""" editor_menu = omni.kit.ui.get_editor_menu() if editor_menu: editor_menu.set_value(ScatterWindowExtension.MENU_PATH, value) async def _destroy_window_async(self): # wait one frame, this is due to the one frame defer # in Window::_moveToMainOSWindow() await omni.kit.app.get_app().next_update_async() if self._window: self._window.destroy() self._window = None def _visiblity_changed_fn(self, visible): # Called when the user pressed "X" self._set_menu(visible) if not visible: # Destroy the window, since we are creating new window # in show_window asyncio.ensure_future(self._destroy_window_async()) def show_window(self, menu, value): if value: self._window = ScatterWindow(ScatterWindowExtension.WINDOW_NAME, width=300, height=500) self._window.set_visibility_changed_fn(self._visiblity_changed_fn) elif self._window: self._window.visible = False
2,849
Python
36.012987
108
0.662338
NVIDIA-Omniverse/kit-workshop-siggraph2022/exts/omni.example.custom_ui/omni/example/custom_ui/scatter.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__ = ["scatter"] from typing import List, Optional import random from pxr import Gf def scatter( count: List[int], distance: List[float], randomization: List[float], id_count: int = 1, seed: Optional[int] = None ): """ Returns generator with pairs containing transform matrices and ids to arrange multiple objects. ### Arguments: `count: List[int]` Number of matrices to generage per axis `distance: List[float]` The distance between objects per axis `randomization: List[float]` Random distance per axis `id_count: int` Count of differrent id `seed: int` If seed is omitted or None, the current system time is used. If seed is an int, it is used directly. """ # Initialize the random number generator. random.seed(seed) for i in range(count[0]): x = (i - 0.5 * (count[0] - 1)) * distance[0] for j in range(count[1]): y = (j - 0.5 * (count[1] - 1)) * distance[1] for k in range(count[2]): z = (k - 0.5 * (count[2] - 1)) * distance[2] # Create a matrix with position randomization result = Gf.Matrix4d(1) result.SetTranslate( Gf.Vec3d( x + random.random() * randomization[0], y + random.random() * randomization[1], z + random.random() * randomization[2], ) ) id = int(random.random() * id_count) yield (result, id)
2,076
Python
30
118
0.577553
NVIDIA-Omniverse/kit-workshop-siggraph2022/exts/omni.example.custom_ui/omni/example/custom_ui/__init__.py
# Copyright (c) 2018-2020, 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__ = ["ScatterCreatePointInstancerCommand", "ScatterWindowExtension", "ScatterWindow"] from .commands import ScatterCreatePointInstancerCommand from .extension import ScatterWindowExtension from .window import ScatterWindow
663
Python
46.428568
91
0.820513
NVIDIA-Omniverse/kit-workshop-siggraph2022/exts/omni.example.custom_ui/omni/example/custom_ui/combo_box_model.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__ = ["ComboBoxModel"] from typing import Optional import omni.ui as ui class ListItem(ui.AbstractItem): """Single item of the model""" def __init__(self, text): super().__init__() self.name_model = ui.SimpleStringModel(text) def __repr__(self): return f'"{self.name_model.as_string}"' @property def as_string(self): """Return the string of the name model""" return self.name_model.as_string class ComboBoxModel(ui.AbstractItemModel): """ Represents the model for lists. It's very easy to initialize it with any string list: string_list = ["Hello", "World"] model = ComboBoxModel(*string_list) ui.ComboBox(model) """ def __init__(self, *args, default=0): super().__init__() self._children = [ListItem(t) for t in args] self._default = ui.SimpleIntModel() self._default.as_int = default # Update the combo box when default is changed self._default.add_value_changed_fn(lambda _: self._item_changed(None)) def get_item_children(self, item): """Returns all the children when the widget asks it.""" if item is not None: # Since we are doing a flat list, we return the children of root only. # If it's not root we return. return [] return self._children def get_item_value_model_count(self, item): """The number of columns""" return 1 def get_item_value_model(self, item: Optional[ListItem], column_id): """ Return value model. It's the object that tracks the specific value. In our case we use ui.SimpleStringModel. """ if item is None: return self._default return item.name_model def get_current_item(self) -> ListItem: """Returns the currently selected item in ComboBox""" return self._children[self._default.as_int]
2,391
Python
30.893333
82
0.637808
NVIDIA-Omniverse/kit-workshop-siggraph2022/exts/omni.example.custom_ui/omni/example/custom_ui/utils.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__ = ["get_selection", "duplicate_prims"] from typing import List import omni.usd import omni.kit.commands from pxr import Sdf from pxr import Gf def get_selection() -> List[str]: """Get the list of currently selected prims""" return omni.usd.get_context().get_selection().get_selected_prim_paths() def duplicate_prims(transforms: List = [], prim_names: List[str] = [], target_path: str = "", mode: str = "Copy", scale: List[float] = [1,1,1]): """ Returns generator with pairs containing transform matrices and ids to arrange multiple objects. ### Arguments: `transforms: List` Pairs containing transform matrices and ids to apply to new objects `prim_names: List[str]` Prims to duplicate `target_path: str` The parent for the new prims `mode: str` "Reference": Create a reference of the given prim path "Copy": Create a copy of the given prim path "PointInstancer": Create a PointInstancer """ if mode == "PointInstancer": omni.kit.commands.execute( "ScatterCreatePointInstancer", path_to=target_path, transforms=transforms, prim_names=prim_names, ) return usd_context = omni.usd.get_context() # Call commands in a single undo group. So the user will undo everything # with a single press of ctrl-z with omni.kit.undo.group(): # Create a group omni.kit.commands.execute("CreatePrim", prim_path=target_path, prim_type="Scope") for i, matrix in enumerate(transforms): id = matrix[1] matrix = matrix[0] path_from = Sdf.Path(prim_names[id]) path_to = Sdf.Path(target_path).AppendChild(f"{path_from.name}{i}") # Create a new prim if mode == "Copy": omni.kit.commands.execute("CopyPrims", paths_from=[path_from.pathString], paths_to=[path_to.pathString]) elif mode == "Reference": omni.kit.commands.execute( "CreateReference", usd_context=usd_context, prim_path=path_from, path_to=path_to, asset_path="" ) else: continue stage = usd_context.get_stage() prim = stage.GetPrimAtPath(path_to) trans_matrix = matrix[3] new_transform = Gf.Vec3d(trans_matrix[0], trans_matrix[1], trans_matrix[2]) omni.kit.commands.execute("TransformPrimSRT", path=path_to, new_translation=new_transform, new_scale=scale)
3,044
Python
34.823529
144
0.625493
NVIDIA-Omniverse/kit-workshop-siggraph2022/exts/omni.example.custom_ui/omni/example/custom_ui/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__ = ["ScatterWindow"] import omni.ui as ui from .style import scatter_window_style from .utils import get_selection from .combo_box_model import ComboBoxModel from .scatter import scatter from .utils import duplicate_prims LABEL_WIDTH = 120 SPACING = 4 class ScatterWindow(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) # Models self._source_prim_model_a = ui.SimpleStringModel() self._scatter_prim_model_a = ui.SimpleStringModel() ## Step 6.4: Add Prim Model B Here ## self._scatter_type_model = ComboBoxModel("Reference", "Copy", "PointInstancer") self._scatter_seed_model = ui.SimpleIntModel() self._scatter_count_models = [ui.SimpleIntModel(), ui.SimpleIntModel(), ui.SimpleIntModel()] self._scatter_distance_models = [ui.SimpleFloatModel(), ui.SimpleFloatModel(), ui.SimpleFloatModel()] self._scatter_random_models = [ui.SimpleFloatModel(), ui.SimpleFloatModel(), ui.SimpleFloatModel()] self._scale_models = [ui.SimpleFloatModel(), ui.SimpleFloatModel(), ui.SimpleFloatModel()] # Defaults self._scatter_prim_model_a.as_string = "/World/Scatter01" ## Step 6.6: Add Prim Model B Here ## self._scatter_count_models[0].as_int = 50 self._scatter_count_models[1].as_int = 1 self._scatter_count_models[2].as_int = 1 self._scatter_distance_models[0].as_float = 10 self._scatter_distance_models[1].as_float = 10 self._scatter_distance_models[2].as_float = 10 self._scale_models[0].as_float = 1 self._scale_models[1].as_float = 1 self._scale_models[2].as_float = 1 # Apply the style to all the widgets of this window self.frame.style = scatter_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 _on_get_selection(self, model): """Called when the user presses the "Get From Selection" button""" model.as_string = ", ".join(get_selection()) def _on_scatter(self, source_model, scatter_model): """Called when the user presses the "Scatter Prim" button""" prim_names = [i.strip() for i in source_model.as_string.split(",")] if not prim_names: prim_names = get_selection() if not prim_names: return transforms = scatter( count=[m.as_int for m in self._scatter_count_models], distance=[m.as_float for m in self._scatter_distance_models], randomization=[m.as_float for m in self._scatter_random_models], id_count=len(prim_names), seed=self._scatter_seed_model.as_int, ) duplicate_prims( transforms=transforms, prim_names=prim_names, target_path=scatter_model.as_string, mode=self._scatter_type_model.get_current_item().as_string, scale=[self._scale_models[0].as_float, self._scale_models[1].as_float, self._scale_models[2].as_float] ) def _build_source(self): """Build the widgets of the "Source" group""" with ui.CollapsableFrame("Source", name="group"): with ui.VStack(height=0, spacing=SPACING): with ui.HStack(): ui.Label("Prim A", name="attribute_name", width=self.label_width) ui.StringField(model=self._source_prim_model_a) # Button that puts the selection to the string field ui.Button( " S ", width=0, height=0, style={"margin": 0}, clicked_fn=lambda:self._on_get_selection(self._source_prim_model_a), tooltip="Get From Selection", ) ## Step 6.8: Add New HStack Below ## def _build_scatter(self): """Build the widgets of the "Scatter" group""" with ui.CollapsableFrame("Scatter", name="group"): with ui.VStack(height=0, spacing=SPACING): with ui.HStack(): ui.Label("Prim A Path", name="attribute_name", width=self.label_width) ui.StringField(model=self._scatter_prim_model_a) ## Step 6.10: Add new ui.HStack Below ## with ui.HStack(): ui.Label("Prim Type", name="attribute_name", width=self.label_width) ui.ComboBox(self._scatter_type_model) with ui.HStack(): ui.Label("Seed", name="attribute_name", width=self.label_width) ui.IntDrag(model=self._scatter_seed_model, min=0, max=10000) def _build_axis(self, axis_id, axis_name): """Build the widgets of the "X" or "Y" or "Z" group""" with ui.CollapsableFrame(axis_name, name="group"): with ui.VStack(height=0, spacing=SPACING): with ui.HStack(): ui.Label("Object Count", name="attribute_name", width=self.label_width) ui.IntDrag(model=self._scatter_count_models[axis_id], min=1, max=100) with ui.HStack(): ui.Label("Distance", name="attribute_name", width=self.label_width) ui.FloatDrag(self._scatter_distance_models[axis_id], min=0, max=10000) with ui.HStack(): ui.Label("Random", name="attribute_name", width=self.label_width) ui.FloatDrag(self._scatter_random_models[axis_id], min=0, max=10000) 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_source() self._build_scatter() self._build_axis(0, "X Axis") self._build_axis(1, "Y Axis") self._build_axis(2, "Z Axis") # The Go button ui.Button("Scatter Prim A", clicked_fn=lambda:self._on_scatter(self._source_prim_model_a, self._scatter_prim_model_a)) ## Step 6.12: Add Go Button Below ##
7,416
Python
43.148809
134
0.572816
NVIDIA-Omniverse/kit-workshop-siggraph2022/exts/omni.example.custom_ui/omni/example/custom_ui/tests/__init__.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. # from .test_window import TestWindow
463
Python
50.55555
76
0.812095
NVIDIA-Omniverse/kit-workshop-siggraph2022/exts/omni.example.custom_ui/omni/example/custom_ui/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_scatter_tool import ScatterWindow 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 = ScatterWindow("Test") await omni.kit.app.get_app().next_update_async() await self.docked_test_window( window=window, width=300, height=550, ) # 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,344
Python
34.394736
115
0.706101
NVIDIA-Omniverse/kit-workshop-siggraph2022/exts/omni.example.custom_ui/docs/CHANGELOG.md
# Changelog ## [1.0.0] - 2022-06-27 ### Added - Initial window
64
Markdown
9.833332
23
0.59375
NVIDIA-Omniverse/kit-workshop-siggraph2022/exts/omni.example.custom_ui/docs/README.md
# Scatter Tool (omni.example.ui_scatter_tool) ![](https://github.com/NVIDIA-Omniverse/kit-extension-sample-scatter/raw/main/exts/omni.example.ui_scatter_tool/data/preview.png) ​ ## Overview This Extension creates a new UI and function to `Scatter` a selected primitive along the X, Y, and Z Axis. The user can set parameters for Objecct Count, Distance, and Randomization. ​ ## [Tutorial](../Tutorial/Scatter_Tool_Guide.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. In the tutorial you will learn how to build off exisitng modules using `Omniverse Ui Framework` and create `Scatter Properties`. Additionally, the tutorial has a `Final Scripts` folder to use as a reference as you go along. ​[Get started with the tutorial.](../Tutorial/Scatter_Tool_Guide.md) ## Usage Once the extension is enabled in the `Extension Manager` the `Scatter Window` will appear. You may dock this window or keep it floating in the console. Select your primitive in the hierarchy that you want to scatter and then click the `S` button next to the `Source > Prim` pathway to set the selected primitive. Then, set your `Scatter Properties` and click the `Scatter` button.
1,259
Markdown
65.315786
380
0.77363
NVIDIA-Omniverse/kit-workshop-siggraph2022/exts/omni.example.custom_ui/docs/index.rst
omni.example.ui_scatter_tool ######################################## Scatter of Python only extension .. toctree:: :maxdepth: 1 README CHANGELOG
159
reStructuredText
12.333332
40
0.522013
NVIDIA-Omniverse/kit-workshop-siggraph2022/exts/omni.example.scene_auth_scatter/config/extension.toml
[package] title = "Scatter Tool SIGGRAPH 2022 Scene Authoring" description = "The full end to end example of the window" version = "1.0.1" category = "Scatter" authors = ["Victor Yudin"] repository = "https://gitlab-master.nvidia.com/omniverse/kit-extensions/kit-windows" keywords = ["example", "window", "ui"] changelog = "docs/CHANGELOG.md" icon = "data/icon.png" preview_image = "data/preview.png" [dependencies] "omni.ui" = {} "omni.usd" = {} "omni.kit.menu.utils" = {} [[python.module]] name = "omni.example.ui_scatter_tool" [[test]] args = [ "--/app/window/dpiScaleOverride=1.0", "--/app/window/scaleToMonitor=false", "--no-window" ] dependencies = [ "omni.kit.renderer.core", "omni.kit.renderer.capture", ]
737
TOML
22.806451
84
0.674355
NVIDIA-Omniverse/kit-workshop-siggraph2022/exts/omni.example.scene_auth_scatter/omni/example/ui_scatter_tool/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__ = ["scatter_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.scatter_window_hovered = cl("#2b2e2e") cl.scatter_window_text = cl("#9e9e9e") fl.scatter_window_attr_hspacing = 10 fl.scatter_window_attr_spacing = 1 fl.scatter_window_group_spacing = 2 # The main style dict scatter_window_style = { "Label::attribute_name": { "color": cl.scatter_window_text, "margin_height": fl.scatter_window_attr_spacing, "margin_width": fl.scatter_window_attr_hspacing, }, "CollapsableFrame::group": {"margin_height": fl.scatter_window_group_spacing}, "CollapsableFrame::group:hovered": {"secondary_color": cl.scatter_window_hovered}, }
1,408
Python
35.128204
89
0.740767
NVIDIA-Omniverse/kit-workshop-siggraph2022/exts/omni.example.scene_auth_scatter/omni/example/ui_scatter_tool/commands.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__ = ["ScatterCreatePointInstancerCommand"] from pxr import Gf from pxr import Sdf from pxr import Usd from pxr import UsdGeom from typing import List from typing import Optional from typing import Tuple import omni.kit.commands import omni.usd.commands class ScatterCreatePointInstancerCommand(omni.kit.commands.Command, omni.usd.commands.stage_helper.UsdStageHelper): """ Create PointInstancer undoable **Command**. ### Arguments: `path_to: str` The path for the new prims `transforms: List` Pairs containing transform matrices and ids to apply to new objects `prim_names: List[str]` Prims to duplicate """ def __init__( self, path_to: str, transforms: List[Tuple[Gf.Matrix4d, int]], prim_names: List[str], stage: Optional[Usd.Stage] = None, context_name: Optional[str] = None, ): omni.usd.commands.stage_helper.UsdStageHelper.__init__(self, stage, context_name) self._path_to = path_to # We have it like [(tr, id), (tr, id), ...] # It will be transformaed to [[tr, tr, ...], [id, id, ...]] unzipped = list(zip(*transforms)) self._positions = [m.ExtractTranslation() for m in unzipped[0]] self._proto_indices = unzipped[1] self._prim_names = prim_names.copy() def do(self): stage = self._get_stage() # Set up PointInstancer instancer = UsdGeom.PointInstancer.Define(stage, Sdf.Path(self._path_to)) attr = instancer.CreatePrototypesRel() for name in self._prim_names: attr.AddTarget(Sdf.Path(name)) instancer.CreatePositionsAttr().Set(self._positions) instancer.CreateProtoIndicesAttr().Set(self._proto_indices) def undo(self): delete_cmd = omni.usd.commands.DeletePrimsCommand([self._path_to]) delete_cmd.do()
2,346
Python
32.056338
115
0.663257
NVIDIA-Omniverse/kit-workshop-siggraph2022/exts/omni.example.scene_auth_scatter/omni/example/ui_scatter_tool/extension.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__ = ["ScatterWindowExtension"] from .window import ScatterWindow from functools import partial import asyncio import omni.ext import omni.kit.ui import omni.ui as ui class ScatterWindowExtension(omni.ext.IExt): """The entry point for Scatter Window""" WINDOW_NAME = "Scatter Window" MENU_PATH = f"Window/{WINDOW_NAME}" def on_startup(self): # The ability to show up the window if the system requires it. We use it # in QuickLayout. ui.Workspace.set_show_window_fn(ScatterWindowExtension.WINDOW_NAME, partial(self.show_window, None)) # Put the new menu editor_menu = omni.kit.ui.get_editor_menu() if editor_menu: self._menu = editor_menu.add_item( ScatterWindowExtension.MENU_PATH, self.show_window, toggle=True, value=True ) # Show the window. It will call `self.show_window` ui.Workspace.show_window(ScatterWindowExtension.WINDOW_NAME) def on_shutdown(self): self._menu = None if self._window: self._window.destroy() self._window = None # Deregister the function that shows the window from omni.ui ui.Workspace.set_show_window_fn(ScatterWindowExtension.WINDOW_NAME, None) def _set_menu(self, value): """Set the menu to create this window on and off""" editor_menu = omni.kit.ui.get_editor_menu() if editor_menu: editor_menu.set_value(ScatterWindowExtension.MENU_PATH, value) async def _destroy_window_async(self): # wait one frame, this is due to the one frame defer # in Window::_moveToMainOSWindow() await omni.kit.app.get_app().next_update_async() if self._window: self._window.destroy() self._window = None def _visiblity_changed_fn(self, visible): # Called when the user pressed "X" self._set_menu(visible) if not visible: # Destroy the window, since we are creating new window # in show_window asyncio.ensure_future(self._destroy_window_async()) def show_window(self, menu, value): if value: self._window = ScatterWindow(ScatterWindowExtension.WINDOW_NAME, width=300, height=500) self._window.set_visibility_changed_fn(self._visiblity_changed_fn) elif self._window: self._window.visible = False
2,849
Python
36.012987
108
0.662338
NVIDIA-Omniverse/kit-workshop-siggraph2022/exts/omni.example.scene_auth_scatter/omni/example/ui_scatter_tool/scatter.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__ = ["scatter"] from typing import List, Optional import random from pxr import Gf def scatter( count: List[int], distance: List[float], randomization: List[float], id_count: int = 1, seed: Optional[int] = None ): """ Returns generator with pairs containing transform matrices and ids to arrange multiple objects. ### Arguments: `count: List[int]` Number of matrices to generage per axis `distance: List[float]` The distance between objects per axis `randomization: List[float]` Random distance per axis `id_count: int` Count of differrent id `seed: int` If seed is omitted or None, the current system time is used. If seed is an int, it is used directly. """ # Initialize the random number generator. random.seed(seed) for i in range(count[0]): x = (i - 0.5 * (count[0] - 1)) * distance[0] for j in range(count[1]): y = (j - 0.5 * (count[1] - 1)) * distance[1] for k in range(count[2]): z = (k - 0.5 * (count[2] - 1)) * distance[2] # Create a matrix with position randomization result = Gf.Matrix4d(1) result.SetTranslate( Gf.Vec3d( x, y, z, ) ) id = int(random.random() * id_count) yield (result, id)
1,981
Python
26.915493
80
0.565876
NVIDIA-Omniverse/kit-workshop-siggraph2022/exts/omni.example.scene_auth_scatter/omni/example/ui_scatter_tool/__init__.py
# Copyright (c) 2018-2020, 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__ = ["ScatterCreatePointInstancerCommand", "ScatterWindowExtension", "ScatterWindow"] from .commands import ScatterCreatePointInstancerCommand from .extension import ScatterWindowExtension from .window import ScatterWindow
663
Python
46.428568
91
0.820513
NVIDIA-Omniverse/kit-workshop-siggraph2022/exts/omni.example.scene_auth_scatter/omni/example/ui_scatter_tool/combo_box_model.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__ = ["ComboBoxModel"] from typing import Optional import omni.ui as ui class ListItem(ui.AbstractItem): """Single item of the model""" def __init__(self, text): super().__init__() self.name_model = ui.SimpleStringModel(text) def __repr__(self): return f'"{self.name_model.as_string}"' @property def as_string(self): """Return the string of the name model""" return self.name_model.as_string class ComboBoxModel(ui.AbstractItemModel): """ Represents the model for lists. It's very easy to initialize it with any string list: string_list = ["Hello", "World"] model = ComboBoxModel(*string_list) ui.ComboBox(model) """ def __init__(self, *args, default=0): super().__init__() self._children = [ListItem(t) for t in args] self._default = ui.SimpleIntModel() self._default.as_int = default # Update the combo box when default is changed self._default.add_value_changed_fn(lambda _: self._item_changed(None)) def get_item_children(self, item): """Returns all the children when the widget asks it.""" if item is not None: # Since we are doing a flat list, we return the children of root only. # If it's not root we return. return [] return self._children def get_item_value_model_count(self, item): """The number of columns""" return 1 def get_item_value_model(self, item: Optional[ListItem], column_id): """ Return value model. It's the object that tracks the specific value. In our case we use ui.SimpleStringModel. """ if item is None: return self._default return item.name_model def get_current_item(self) -> ListItem: """Returns the currently selected item in ComboBox""" return self._children[self._default.as_int]
2,391
Python
30.893333
82
0.637808
NVIDIA-Omniverse/kit-workshop-siggraph2022/exts/omni.example.scene_auth_scatter/omni/example/ui_scatter_tool/utils.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__ = ["get_selection", "duplicate_prims"] from typing import List import omni.usd import omni.kit.commands from pxr import Sdf from pxr import UsdShade from pxr import Gf def get_material_prim(prim): if prim is None: return None if prim.GetPrimTypeInfo().GetTypeName() == "Material": return prim children = prim.GetAllChildren() for child in children: if child.GetPrimTypeInfo().GetTypeName() == "Material": return child elif child.GetChildren(): return get_material_prim(child) def get_selection() -> List[str]: """Get the list of currently selected prims""" return omni.usd.get_context().get_selection().get_selected_prim_paths() def duplicate_prims(transforms: List = [], prim_names: List[str] = [], target_path: str = "", mode: str = "Copy"): """ Returns generator with pairs containing transform matrices and ids to arrange multiple objects. ### Arguments: `transforms: List` Pairs containing transform matrices and ids to apply to new objects `prim_names: List[str]` Prims to duplicate `target_path: str` The parent for the new prims `mode: str` "Reference": Create a reference of the given prim path "Copy": Create a copy of the given prim path "PointInstancer": Create a PointInstancer """ if mode == "PointInstancer": omni.kit.commands.execute( "ScatterCreatePointInstancer", path_to=target_path, transforms=transforms, prim_names=prim_names, ) return usd_context = omni.usd.get_context() # Call commands in a single undo group. So the user will undo everything # with a single press of ctrl-z with omni.kit.undo.group(): # Create a group omni.kit.commands.execute("CreatePrim", prim_path=target_path, prim_type="Scope") for i, matrix in enumerate(transforms): id = matrix[1] matrix = matrix[0] path_from = Sdf.Path(prim_names[id]) path_to = Sdf.Path(target_path).AppendChild(f"{path_from.name}{i}") # Create a new prim if mode == "Copy": omni.kit.commands.execute("CopyPrims", paths_from=[path_from.pathString], paths_to=[path_to.pathString]) elif mode == "Reference": omni.kit.commands.execute( "CreateReference", usd_context=usd_context, prim_path=path_from, path_to=path_to, asset_path="" ) else: continue stage = usd_context.get_stage() prim = stage.GetPrimAtPath(path_to) trans_matrix = matrix[3] new_transform = Gf.Vec3d(trans_matrix[0], trans_matrix[1], trans_matrix[2]) omni.kit.commands.execute("TransformPrimSRT", path=path_to, new_translation=new_transform)
3,437
Python
30.833333
120
0.620017
NVIDIA-Omniverse/kit-workshop-siggraph2022/exts/omni.example.scene_auth_scatter/omni/example/ui_scatter_tool/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__ = ["ScatterWindow"] import omni.ui as ui from .style import scatter_window_style from .utils import get_selection from .combo_box_model import ComboBoxModel from .scatter import scatter from .utils import duplicate_prims LABEL_WIDTH = 120 SPACING = 4 class ScatterWindow(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) # Models self._source_prim_model = ui.SimpleStringModel() self._scatter_prim_model = ui.SimpleStringModel() self._scatter_type_model = ComboBoxModel("Reference", "Copy", "PointInstancer") self._scatter_seed_model = ui.SimpleIntModel() self._scatter_count_models = [ui.SimpleIntModel(), ui.SimpleIntModel(), ui.SimpleIntModel()] self._scatter_distance_models = [ui.SimpleFloatModel(), ui.SimpleFloatModel(), ui.SimpleFloatModel()] self._scatter_random_models = [ui.SimpleFloatModel(), ui.SimpleFloatModel(), ui.SimpleFloatModel()] self._scale_models = [ui.SimpleFloatModel(), ui.SimpleFloatModel(), ui.SimpleFloatModel()] # Defaults self._scatter_prim_model.as_string = "/World/Scatter01" self._scatter_count_models[0].as_int = 15 self._scatter_count_models[1].as_int = 1 self._scatter_count_models[2].as_int = 1 self._scatter_distance_models[0].as_float = 10 self._scatter_distance_models[1].as_float = 10 self._scatter_distance_models[2].as_float = 10 self._scale_models[0].as_float = 1 self._scale_models[1].as_float = 1 self._scale_models[2].as_float = 1 # Apply the style to all the widgets of this window self.frame.style = scatter_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 _on_get_selection(self): """Called when tthe user presses the "Get From Selection" button""" self._source_prim_model.as_string = ", ".join(get_selection()) def _on_scatter(self): """Called when the user presses the "Scatter" button""" prim_names = [i.strip() for i in self._source_prim_model.as_string.split(",")] if not prim_names: prim_names = get_selection() if not prim_names: # TODO: "Can't clone" message pass transforms = scatter( count=[m.as_int for m in self._scatter_count_models], distance=[m.as_float for m in self._scatter_distance_models], randomization=[m.as_float for m in self._scatter_random_models], id_count=len(prim_names), seed=self._scatter_seed_model.as_int, ) duplicate_prims( transforms=transforms, prim_names=prim_names, target_path=self._scatter_prim_model.as_string, mode=self._scatter_type_model.get_current_item().as_string ) def _build_source(self): """Build the widgets of the "Source" group""" with ui.CollapsableFrame("Source", name="group"): with ui.VStack(height=0, spacing=SPACING): with ui.HStack(): ui.Label("Prim", name="attribute_name", width=self.label_width) ui.StringField(model=self._source_prim_model) # Button that puts the selection to the string field ui.Button( " S ", width=0, height=0, style={"margin": 0}, clicked_fn=self._on_get_selection, tooltip="Get From Selection", ) def _build_scatter(self): """Build the widgets of the "Scatter" group""" with ui.CollapsableFrame("Scatter", name="group"): with ui.VStack(height=0, spacing=SPACING): with ui.HStack(): ui.Label("Prim Path", name="attribute_name", width=self.label_width) ui.StringField(model=self._scatter_prim_model) with ui.HStack(): ui.Label("Prim Type", name="attribute_name", width=self.label_width) ui.ComboBox(self._scatter_type_model) with ui.HStack(): ui.Label("Seed", name="attribute_name", width=self.label_width) ui.IntDrag(model=self._scatter_seed_model, min=0, max=10000) with ui.HStack(): ui.Label("Scale", name="attribute_name", width=self.label_width) for field in zip(["X:", "Y:", "Z:"], self._scale_models): ui.Label(field[0], width=0, style={"margin": 3.0}) ui.FloatField(model=field[1], height=0, style={"margin": 3.0}) def _build_axis(self, axis_id, axis_name): """Build the widgets of the "X" or "Y" or "Z" group""" with ui.CollapsableFrame(axis_name, name="group"): with ui.VStack(height=0, spacing=SPACING): with ui.HStack(): ui.Label("Object Count", name="attribute_name", width=self.label_width) ui.IntDrag(model=self._scatter_count_models[axis_id], min=1, max=100) with ui.HStack(): ui.Label("Distance", name="attribute_name", width=self.label_width) ui.FloatDrag(self._scatter_distance_models[axis_id], min=0, max=10000) with ui.HStack(): ui.Label("Random", name="attribute_name", width=self.label_width) ui.FloatDrag(self._scatter_random_models[axis_id], min=0, max=10000) 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_source() self._build_scatter() self._build_axis(0, "X Axis") self._build_axis(1, "Y Axis") self._build_axis(2, "Z Axis") # The Go button ui.Button("Scatter", clicked_fn=self._on_scatter)
7,160
Python
39.92
109
0.580168
NVIDIA-Omniverse/kit-workshop-siggraph2022/exts/omni.example.scene_auth_scatter/omni/example/ui_scatter_tool/tests/__init__.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. # from .test_window import TestWindow
463
Python
50.55555
76
0.812095
NVIDIA-Omniverse/kit-workshop-siggraph2022/exts/omni.example.scene_auth_scatter/omni/example/ui_scatter_tool/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_scatter_tool import ScatterWindow 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 = ScatterWindow("Test") await omni.kit.app.get_app().next_update_async() await self.docked_test_window( window=window, width=300, height=550, ) # 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,344
Python
34.394736
115
0.706101
NVIDIA-Omniverse/kit-workshop-siggraph2022/exts/omni.example.scene_auth_scatter/docs/CHANGELOG.md
# Changelog ## [1.0.0] - 2022-06-27 ### Added - Initial window
64
Markdown
9.833332
23
0.59375
NVIDIA-Omniverse/kit-workshop-siggraph2022/exts/omni.example.scene_auth_scatter/docs/README.md
# Scatter Tool (omni.example.ui_scatter_tool) ![](https://github.com/NVIDIA-Omniverse/kit-extension-sample-scatter/raw/main/exts/omni.example.ui_scatter_tool/data/preview.png) ​ ## Overview This Extension creates a new UI and function to `Scatter` a selected primitive along the X, Y, and Z Axis. The user can set parameters for Objecct Count, Distance, and Randomization. ## Usage Once the extension is enabled in the `Extension Manager` the `Scatter Window` will appear. You may dock this window or keep it floating in the console. Select your primitive in the hierarchy that you want to scatter and then click the `S` button next to the `Source > Prim` pathway to set the selected primitive. Then, set your `Scatter Properties` and click the `Scatter` button.
767
Markdown
68.818176
380
0.773142
NVIDIA-Omniverse/kit-workshop-siggraph2022/exts/omni.example.scene_auth_scatter/docs/index.rst
omni.example.ui_scatter_tool ######################################## Scatter of Python only extension .. toctree:: :maxdepth: 1 README CHANGELOG
159
reStructuredText
12.333332
40
0.522013
NVIDIA-Omniverse/kit-workshop-siggraph2022/exts/omni.example.scene_auth_scatter/workshop/Siggraph2022_Scatter_Workshop_1.md
![](https://github.com/NVIDIA-Omniverse/kit-workshop-siggraph2022/blob/workshop_1/exts/omni.example.scene_auth_scatter/workshop/images/logo.png?raw=true) # NVIDIA OMNIVERSE # Easily Develop Advanced 3D Layout Tools on NVIDIA Omniverse See how to easily create your own custom scene layout tool with the modular Omniverse platform with a few lines of Python script. In this workshop, you'll build your own custom scene layout in Omniverse using Python. # Learning Objectives - How to Enable an extension - Utilize Command Executions - Create a feature to Scatter from a Prim's origin <video width="560" height="315" controls> <source src="https://dli-lms.s3.amazonaws.com/assets/x-ov-02-v1/3DLayoutToolsIntro.mp4" type="video/mp4"> </video> # Section I <video width="560" height="315" controls> <source src="https://dli-lms.s3.amazonaws.com/assets/x-ov-02-v1/3DLayoutToolsSection1.mp4" type="video/mp4"> </video> # Open Stage and Get Extension from Community / Third Party ## Step 1: Open the Workshop Stage ### <b>Step 1.1: Download the Stage from the Link Provided</b> [Stage Link](https://dli-lms.s3.amazonaws.com/assets/x-ov-02-v1/Stage.zip) ### <b> Step 1.2: Unzip Stage Using Extract All... This creates an unzipped file folder called `Stage`. ### <b> Step 1.3: Open Stage in Omniverse Navigate inside Omniverse Code's `Content tab` to the stage file's location on your system. (i.e. C:/Users/yourName/Downloads/Stage) **Double Click** `Stage.usd` in the center window pane of the `Content tab` at the bottom of the Omniverse Code Console and it will appear in the viewport. ## Step 2: Adding the Extension We will be getting an extension from the *Community / Third Party Section* of the *Extension Manager*. There are also other extensions developed by NVIDIA in the *NVIDIA Section*. ### Step 2.1: Open Extension Manager **Click** on the *Extension Tab*. ### Step 2.2: Filter by Community / Third Party Extensions **Select** *Community / Third Party* tab. ![](https://github.com/NVIDIA-Omniverse/kit-workshop-siggraph2022/blob/workshop_1/exts/omni.example.scene_auth_scatter/workshop/images/filtercommunity.png?raw=true) *Community / Third Party* section is where you can find other developer's extensions from the Community. ### Step 2.3: Search for Scatter **Search** for "scatter" and **Click** on the extension with the subtitle *omni.example.scene_auth_scatter*. > **Note:** There are two different scatter tools. Please double check that the one installed has the subtitle: *omni.example.scene_auth_scatter*. ![](https://github.com/NVIDIA-Omniverse/kit-workshop-siggraph2022/blob/workshop_1/exts/omni.example.scene_auth_scatter/workshop/images/communitysearch.png?raw=true) ### Step 2.4: Install/Enable the Extension **Click** on the *Install button* to download the extension. If the extension is already downloaded **Click** on the toggle next to *Disable*. ![](https://github.com/NVIDIA-Omniverse/kit-workshop-siggraph2022/blob/workshop_1/exts/omni.example.scene_auth_scatter/workshop/images/installext.png?raw=true) ## Step 3: Using the Extension With the extension enabled, try the following steps. ### Step 3.1: Select a Prim Select a Prim in the *Stage* > **Note:** Prim is short for “primitive”, the prim is the fundamental unit in Omniverse. Anything imported or created in a USD scene is a prim. This includes, cameras, sounds, lights, meshes, and more. Primitives are technically containers of metadata, properties, and other prims. Read more about USD prims in the official documentation. We recommend using any of these Prims: ![](https://github.com/NVIDIA-Omniverse/kit-workshop-siggraph2022/blob/workshop_1/exts/omni.example.scene_auth_scatter/workshop/images/primstoselect.png?raw=true) #### Step 3.2: Set Prim Path to Scatter Window With the selected Prim, **click** the *S button* in the *Scatter Window*. ![](https://github.com/NVIDIA-Omniverse/kit-workshop-siggraph2022/blob/workshop_1/exts/omni.example.scene_auth_scatter/workshop/images/clickS.png?raw=true) #### Step 3.3: Scatter Selected Prim At the bottom of the *Scatter Window*, **click** the *Scatter button* ![](https://github.com/NVIDIA-Omniverse/kit-workshop-siggraph2022/blob/workshop_1/exts/omni.example.scene_auth_scatter/workshop/images/scatterbutton.png?raw=true) ### Step 3.4: Undo Scatter Find the `Scatter01` folder in `Stage` and left-click on the folder then right-click to delete or hit the `delete` button on your keyboard. `Stage` is the panel that allows you to see all the assets in your current `USD`, or Universal Scene Description. It lists the prims in heirarchical order. ![](https://github.com/NVIDIA-Omniverse/kit-workshop-siggraph2022/blob/workshop_3/exts/omni.example.ui_scatter_tool/Workshop/images/deletescatter.gif?raw=true) ## Challenge Step 4: What else can you do with the Scatter Extension These are *optional* challenges. ### Challenge 4.1: Use Cases Come up with 5 use cases on how you would expand this extension. ### Challenge 4.2: Scatter Multiple Prims at Once Try to scatter more than one marble at once. <details> <summary>Hint</summary> #### Challenge Step 4.2.1: Scatter Multiple Prims at Once In the *Stage*, **hold** *Ctrl key* and **select** multiple Prims. ![](https://github.com/NVIDIA-Omniverse/kit-workshop-siggraph2022/blob/workshop_1/exts/omni.example.scene_auth_scatter/workshop/images/multiprim.png?raw=true) #### Challenge Step 4.2.2: Scatter Multiple Prims at Once **Repeat** steps `3.2` and `2.3`. </details> # Section II <video width="560" height="315" controls> <source src="https://dli-lms.s3.amazonaws.com/assets/x-ov-02-v1/3DLayoutToolsSection2Intro.mp4" type="video/mp4"> </video> <video width="560" height="315" controls> <source src="https://dli-lms.s3.amazonaws.com/assets/x-ov-02-v1/3DLayoutToolsWorkshop2.mp4" type="video/mp4"> </video> # Scatter Relative to Source Prim ## Step 5: Change the Scatter functionality to Handle any Given Origin To use any origin we will be modifying the scatter functionality to recieve a position. The current scatter tool sets scatter at world origin (0,0,0). This is inconvient when there are prims far away from origin. ### Step 5.1: Open the Extension in Visual Studio Code From the *Scatter Extension*, **Click** the Visual Studio Icon. ![](https://github.com/NVIDIA-Omniverse/kit-workshop-siggraph2022/blob/workshop_1/exts/omni.example.scene_auth_scatter/workshop/images/open_vs.png?raw=true) A new instance of *Visual Studio Code* will open up. ![](https://github.com/NVIDIA-Omniverse/kit-workshop-siggraph2022/blob/workshop_1/exts/omni.example.scene_auth_scatter/workshop/images/vs_code.png?raw=true) ### Step 5.2: Open `scatter.py` **Locate** and **Open** `scatter.py` from `exts/omni.example.scene_auth_scatter > omni/example/ui_scatter_tool > scatter.py` ![](https://github.com/NVIDIA-Omniverse/kit-workshop-siggraph2022/blob/workshop_1/exts/omni.example.scene_auth_scatter/workshop/images/scatterpy.png?raw=true) ### Step 5.3: Add New Origin Parameter to `scatter()` **Add** `source_prim_location: List[float] = (0,0,0)` as a parameter for `scatter()` ``` python def scatter( count: List[int], distance: List[float], randomization: List[float], id_count: int = 1, seed: Optional[int] = None, source_prim_location: List[float] = (0,0,0) ): ``` `source_prim_location` will contain x, y, and z coordinates of the prim we selected to scatter. ### Step 5.4: Locate `result.SetTranslate` **Locate** near the bottom of `scatter.py` the code snippet below. ``` python result.SetTranslate( Gf.Vec3d( x, y, z, ) ) ``` `Vec3d` creates a 3 dimensional vector. Each prim's position is generated via the code above. ### Step 5.5: Calculate the New Origin During `Vec3d` creation, **add** each coordinate value stored in `source_prim_location` to the generated coordinate. i.e. `x` would turn into `source_prim_location[0] + x`. ``` python result.SetTranslate( Gf.Vec3d( source_prim_location[0] + x, source_prim_location[1] + y, source_prim_location[2] + z, ) ) ``` `scatter()` should look as follows: ``` python def scatter( count: List[int], distance: List[float], randomization: List[float], id_count: int = 1, seed: Optional[int] = None, source_prim_location: List[float] = (0,0,0) ): """ Returns generator with pairs containing transform matrices and ids to arrange multiple objects. ### Arguments: `count: List[int]` Number of matrices to generage per axis `distance: List[float]` The distance between objects per axis `randomization: List[float]` Random distance per axis `id_count: int` Count of differrent id `seed: int` If seed is omitted or None, the current system time is used. If seed is an int, it is used directly. """ # Initialize the random number generator. random.seed(seed) for i in range(count[0]): x = (i - 0.5 * (count[0] - 1)) * distance[0] for j in range(count[1]): y = (j - 0.5 * (count[1] - 1)) * distance[1] for k in range(count[2]): z = (k - 0.5 * (count[2] - 1)) * distance[2] # Create a matrix result = Gf.Matrix4d(1) result.SetTranslate( Gf.Vec3d( source_prim_location[0] + x, source_prim_location[1] + y, source_prim_location[2] + z, ) ) id = int(random.random() * id_count) yield (result, id) ``` ### Step 5.6: Save `scatter.py` and Open `window.py` **Save** `scatter.py` and **Open** `window.py` from `ext/omni.example.scene_auth_scatter > omni/example/ui_scatter_tool > window.py`. ![](https://github.com/NVIDIA-Omniverse/kit-workshop-siggraph2022/blob/workshop_1/exts/omni.example.scene_auth_scatter/workshop/images/windowpy.png?raw=true) ### Step 5.7: Add Gf module Underneath the imports and above `LABEL_WIDTH`, **add** the line `from pxr import Gf` ``` python import omni.ui as ui from .style import scatter_window_style from .utils import get_selection from .combo_box_model import ComboBoxModel from .scatter import scatter from .utils import duplicate_prims from pxr import Gf LABEL_WIDTH = 120 SPACING = 4 ``` ### Step 5.8: Locate `transforms` **Locate** where `transforms` is declared inside of `_on_scatter()` ``` python transforms = scatter( count=[m.as_int for m in self._scatter_count_models], distance=[m.as_float for m in self._scatter_distance_models], randomization=[m.as_float for m in self._scatter_random_models], id_count=len(prim_names), seed=self._scatter_seed_model.as_int ) ``` ### Step 5.9 Hard Code Origin Position **Add** `source_prim_location=Gf.Vec3d((0,0,-500))`after `seed=self._scatter_seed_model.as_int`. >**Note:** Don't forget to add a comma after `seed=self._scatter_seed_model.as_int`. ``` python transforms = scatter( count=[m.as_int for m in self._scatter_count_models], distance=[m.as_float for m in self._scatter_distance_models], randomization=[m.as_float for m in self._scatter_random_models], id_count=len(prim_names), seed=self._scatter_seed_model.as_int, source_prim_location=Gf.Vec3d((0,0,-500)) ) ``` `Gf.Vec3d((0,0,-500))` creates a 3 coordinate vector where x = 0, y = 0 and z = -500. Since Y represents up and down in the scene, X and Z are like a floor. By setting Z to -500 we are setting the scatter location -500 units along the Z axis. ### Step 5.10: Select a Marble in the *Stage* **Save** `window.py` and go back to *Omniverse Code*. Go to *Stage* and **expand** Marbles, then **select** any marble. ![](https://github.com/NVIDIA-Omniverse/kit-workshop-siggraph2022/blob/workshop_1/exts/omni.example.scene_auth_scatter/workshop/images/marbleselect.png?raw=true) ### Step 5.11: Set the Selected Marble's Path to the Scatter Extension With a marble selected, **click** on the *S button* in the *Scatter Window*. ![](https://github.com/NVIDIA-Omniverse/kit-workshop-siggraph2022/blob/workshop_1/exts/omni.example.scene_auth_scatter/workshop/images/clickS.png?raw=true) ### Step 5.12: Scatter the Marbles **Scroll** to the bottom of the extension and **click** the *Scatter button*. > **Note**: If you do not see the *Scatter button* **scroll down** in the *extension window* or **expand** the *extension window* using the right corner. ![](https://github.com/NVIDIA-Omniverse/kit-workshop-siggraph2022/blob/workshop_1/exts/omni.example.scene_auth_scatter/workshop/images/scatterbutton.png?raw=true) Notice how the marbles scattered to the right of the stage. This is -500 units on the Z axis. Try and change some of the values in the Y and/or X axis as well to see where the marbles will scatter next. ![](https://github.com/NVIDIA-Omniverse/kit-workshop-siggraph2022/blob/workshop_1/exts/omni.example.scene_auth_scatter/workshop/images/sidescatter.png?raw=true) ## Step 6: Get the Location of the Source Prim We will be changing the origin where the Prims get scattered. Firstly, we will be grabbing the location of the source prim. ### Step 6.1: Open `window.py` **Open** `window.py` from `ext/omni.example.scene_auth_scatter > omni/example/ui_scatter_tool > window.py` ![](https://github.com/NVIDIA-Omniverse/kit-workshop-siggraph2022/blob/workshop_1/exts/omni.example.scene_auth_scatter/workshop/images/windowpy.png?raw=true) ### Step 6.2: Add `omni.usd` module Under `import omni.ui as ui`, **add** the line `import omni.usd` ``` python # Import omni.usd module import omni.usd ``` You should then have the following at the top of your file: ``` python import omni.ui as ui import omni.usd from .style import scatter_window_style from .utils import get_selection from .combo_box_model import ComboBoxModel from .scatter import scatter from .utils import duplicate_prims from pxr import Gf ``` The `omni.usd` module is one of the core Kit APIs, and provides access to USD (Universal Scene Description) and USD-related application services. ### Step 6.3: Locate `_on_scatter()` **Scroll Down** to find `_on_scatter()`, and **add** a new line before the variable declaration of `transforms`. ![](https://github.com/NVIDIA-Omniverse/kit-workshop-siggraph2022/blob/workshop_1/exts/omni.example.scene_auth_scatter/workshop/images/newline.png?raw=true) `_on_scatter()` is called when the user presses the *Scatter* button in the extension window. ### Step 6.4: Get USD Context On the new line, **declare** `usd_context`. Make sure the line is tabbed in and parallel with the line `if not prim_names:`. ``` python usd_context = omni.usd.get_context() ``` Your code should look like the following: ``` python def _on_scatter(self): """Called when the user presses the "Scatter" button""" prim_names = [i.strip() for i in self._source_prim_model.as_string.split(",")] if not prim_names: prim_names = get_selection() if not prim_names: # TODO: "Can't clone" message pass # Get the UsdContext we are attached to usd_context = omni.usd.get_context() transforms = scatter( count=[m.as_int for m in self._scatter_count_models], distance=[m.as_float for m in self._scatter_distance_models], randomization=[m.as_float for m in self._scatter_random_models], id_count=len(prim_names), seed=self._scatter_seed_model.as_int, ) duplicate_prims( transforms=transforms, prim_names=prim_names, target_path=self._scatter_prim_model.as_string, mode=self._scatter_type_model.get_current_item().as_string, ) ``` ### Step 6.5: Get the Stage Below `usd_context` declaration, **add** `stage = usd_context.get_stage()` ``` python # Store the UsdContext we are attached to usd_context = omni.usd.get_context() # Get the stage from the current UsdContext stage = usd_context.get_stage() ``` The stage variable will use USD to get the current stage. The `Stage` is where your prims are nested in the hierarchy. ### Step 6.6: Get Source Prim from Stage On the next line, **add** `prim = stage.GetPrimAtPath(self._source_prim_model.as_string)` ``` python # Store the UsdContext we are attached to usd_context = omni.usd.get_context() # Get the stage from the current UsdContext stage = usd_context.get_stage() # Store the Prim that is currently referenced in the extension prim = stage.GetPrimAtPath(self._source_prim_model.as_string) ``` ### Step 6.7: Get Source Prim's Translation Next we will **store** the prim's positional data by adding, `position = prim.GetAttribute('xformOp:translate').Get()`. After checking your work below **save** `window.py`. ``` python # Store the UsdContext we are attached to usd_context = omni.usd.get_context() # Get the stage from the current UsdContext stage = usd_context.get_stage() # Store the Prim that is currently referenced in the extension prim = stage.GetPrimAtPath(self._source_prim_model.as_string) # Get the focused Prim's positional data position = prim.GetAttribute('xformOp:translate').Get() ``` In order to get the location of the prim, we needed the translate value which is stored in the Xform. This gives us a X, Y, and Z of the selected prim. > **Note** The Transform (Xform) is the fundamental element of all objects in Omniverse, the Location. Check your work, it should look like this: ``` python def _on_scatter(self): """Called when the user presses the "Scatter" button""" prim_names = [i.strip() for i in self._source_prim_model.as_string.split(",")] if not prim_names: prim_names = get_selection() if not prim_names: # TODO: "Can't clone" message pass # Store the UsdContext we are attached to usd_context = omni.usd.get_context() # Get the stage from the current UsdContext stage = usd_context.get_stage() # Store the Prim that is currently referenced in the extension prim = stage.GetPrimAtPath(self._source_prim_model.as_string) # Get the focused Prim's positional data position = prim.GetAttribute('xformOp:translate').Get() transforms = scatter( count=[m.as_int for m in self._scatter_count_models], distance=[m.as_float for m in self._scatter_distance_models], randomization=[m.as_float for m in self._scatter_random_models], id_count=len(prim_names), seed=self._scatter_seed_model.as_int, source_prim_location=Gf.Vec3((0,0,-500)) ) duplicate_prims( transforms=transforms, prim_names=prim_names, target_path=self._scatter_prim_model.as_string, mode=self._scatter_type_model.get_current_item().as_string, ) ``` ## Step 7: Use the Selected Prim's Location as the Scatter Origin After updating the scatter functionality we can pass the location of the source prim that we calculated from before. ### Step 7.1: Open window.py **Open** `window.py` and locate where `transforms` is declared in `_on_scatter()` ``` python transforms = scatter( count=[m.as_int for m in self._scatter_count_models], distance=[m.as_float for m in self._scatter_distance_models], randomization=[m.as_float for m in self._scatter_random_models], id_count=len(prim_names), seed=self._scatter_seed_model.as_int ) ``` ### Step 7.2: Pass the Location to `scatter()` After `seed=self._scatter_seed_model.as_int`, **replace** the line `source_prim_location=Gf.Vec3d(0,0,-500)` with `source_prim_location=position` ``` python transforms = scatter( count=[m.as_int for m in self._scatter_count_models], distance=[m.as_float for m in self._scatter_distance_models], randomization=[m.as_float for m in self._scatter_random_models], id_count=len(prim_names), seed=self._scatter_seed_model.as_int, source_prim_location=position ) ``` ### Step 7.3: Test it out Save `window.py` and head back into Omniverse. **Scatter** a prim in the stage. Then **scatter** a different prim. Notice how they will only scatter to the corresponding prim's location. ### Step 7.4: Hit Play Play out the scene! ## Challenge Step 8.1: Add Randomization to Scatter Currently, when the *Scatter button* is pressed it will scatter uniformly. Try to change up the code to allow for random distrubtion. Expand the *Hint* section if you get stuck. > **Hint** Use `random.random()` <details> <summary>Hint</summary> ### Challenge Step 8.1.1: Open `scatter.py` **Open** `scatter.py` and *locate* `scatter()`. ### Challenge Step 8.1.2: Add Random Value **Locate** where we generate our Vec3d / `result.SetTranslate()`. **Modify** the first passed parameter as `source_prim_location[0] + (x + random.random() * randomization[0]),` ``` python result.SetTranslate( Gf.Vec3d( source_prim_location[0] + (x + random.random() * randomization[0]), source_prim_location[1] + y, source_prim_location[2] + z, ) ) ``` `randomization[0]` refers to the element in the UI of the *Scatter Extension Window* labeled *Random*. ### Challenge Step 8.1.3: Apply to Y and Z Values **Modify** the Y and Z values that get passed into *Vec3d* constructor similar to the previous step. ``` python result.SetTranslate( Gf.Vec3d( source_prim_location[0] + (x + random.random() * randomization[0]), source_prim_location[1] + (y + random.random() * randomization[1]), source_prim_location[2] + (z + random.random() * randomization[2]), ) ) ``` ### Challenge Step 8.1.4: Change Random Value **Save** `scatter.py` and **go back** to Omniverse. **Modify** the *Random* parameter in the *Scatter Window*. ![](https://github.com/NVIDIA-Omniverse/kit-workshop-siggraph2022/blob/workshop_1/exts/omni.example.scene_auth_scatter/workshop/images/random.png?raw=true) ### Challenge Step 8.1.5: Scatter Prims **Click** the *Scatter button* and see how the Prims scatter. > **Note:** Make your Random values high if you are scattering in a small area. ![](https://github.com/NVIDIA-Omniverse/kit-workshop-siggraph2022/blob/workshop_1/exts/omni.example.scene_auth_scatter/workshop/images/scatterbutton.png?raw=true) ![](https://github.com/NVIDIA-Omniverse/kit-workshop-siggraph2022/blob/workshop_1/exts/omni.example.scene_auth_scatter/workshop/images/randomscatter.png?raw=true) </details> <br> # Section III <video width="560" height="315" controls> <source src="https://dli-lms.s3.amazonaws.com/assets/x-ov-02-v1/3DLayoutToolsWorkshop3.mp4" type="video/mp4"> </video> # Scatter the Objects ## Step 9: Scatter a Marble The stage has a few marbles we can use to scatter around. ### Step 9.1: Select a Marble in the *Stage* Go to *Stage* and **expand** Marbles, then **select** any marble. ![](https://github.com/NVIDIA-Omniverse/kit-workshop-siggraph2022/blob/workshop_1/exts/omni.example.scene_auth_scatter/workshop/images/marbleselect.png?raw=true) ### Step 9.2: Copy the Selected Marble's Path to the Scatter Extension With a marble selected, **click** on the *S button* in the *Scatter Window*. ![](https://github.com/NVIDIA-Omniverse/kit-workshop-siggraph2022/blob/workshop_1/exts/omni.example.scene_auth_scatter/workshop/images/clickS.png?raw=true) ### Step 9.3: Change Distance Value for X Axis **Change** the *Distance* in the *X Axis* to 10. ![](https://github.com/NVIDIA-Omniverse/kit-workshop-siggraph2022/blob/workshop_1/exts/omni.example.scene_auth_scatter/workshop/images/distance10.png?raw=true) ### Step 9.4: Click the Scatter Button **Click** the *Scatter* button at the bottom of the window. > **Note**: If you do not see the *Scatter button* **scroll down** in the *extension window* or **expand** the *extension window* using the right corner. ![](https://github.com/NVIDIA-Omniverse/kit-workshop-siggraph2022/blob/workshop_1/exts/omni.example.scene_auth_scatter/workshop/images/scatterbutton.png?raw=true) Your scene should look similar to this after clicking the *Scatter button*. ![](https://github.com/NVIDIA-Omniverse/kit-workshop-siggraph2022/blob/workshop_1/exts/omni.example.scene_auth_scatter/workshop/images/marbleScattered.png?raw=true) ## Step 10: Watch the Scene Play The play button is used for more than playing animations or movies. We can also use the play button to simulate physics. ### Step 10.1: Hit the Play Button With the marbles scattered we can watch it in action. **Click** the *Play button* to watch the scene. ![](https://github.com/NVIDIA-Omniverse/kit-workshop-siggraph2022/blob/workshop_1/exts/omni.example.scene_auth_scatter/workshop/images/playbutton.png?raw=true) What happens when we press play: ![](https://github.com/NVIDIA-Omniverse/kit-workshop-siggraph2022/blob/workshop_1/exts/omni.example.scene_auth_scatter/workshop/images/playbuttonaction.gif?raw=true) > **Note:** To reset the scene **click** the *Stop button*. ### Step 10.2: Select a Different Prim **Select** a diferent Prim in the *Stage*. It could be another marble, the jar, bowl, etc. We recommend using any of these Prims: ![](https://github.com/NVIDIA-Omniverse/kit-workshop-siggraph2022/blob/workshop_1/exts/omni.example.scene_auth_scatter/workshop/images/primstoselect.png?raw=true) ### Step 10.3: Copy Selected Prim to Scatter Window With the Prim selected, **Click** the *S button* to copy the Prim Path into the *Scatter Extension Window*. ![](https://github.com/NVIDIA-Omniverse/kit-workshop-siggraph2022/blob/workshop_1/exts/omni.example.scene_auth_scatter/workshop/images/clickS.png?raw=true) ### Step 10.4: Change Scatter Parameters **Change** some of the parameters in the *Scatter Window*. I.e. In *Y Axis* **change** *Object Count* to 20 and *Distance* to 5. ![](https://github.com/NVIDIA-Omniverse/kit-workshop-siggraph2022/blob/workshop_1/exts/omni.example.scene_auth_scatter/workshop/images/params.png?raw=true) ### Step 10.5: Scatter New Prims **Click** the *Scatter button* at the bottom of the *Scatter Window*. ![](https://github.com/NVIDIA-Omniverse/kit-workshop-siggraph2022/blob/workshop_1/exts/omni.example.scene_auth_scatter/workshop/images/scatterbutton.png?raw=true) ### Step 10.6: Hit the Play Button **Click** the *Play button* and watch the scene play out. ![](https://github.com/NVIDIA-Omniverse/kit-workshop-siggraph2022/blob/workshop_1/exts/omni.example.scene_auth_scatter/workshop/images/playbutton.png?raw=true) Try to Scatter many items in the scene and play around with the extension. ## Challenge Step 11: Scale Scatter Prims based on Provided Scale You will notice that there is a *Scale* option. However, this does not work. Try to get it working. Expand the *Hint* section if you get stuck. ![](https://github.com/NVIDIA-Omniverse/kit-workshop-siggraph2022/blob/workshop_1/exts/omni.example.scene_auth_scatter/workshop/images/scale.png?raw=true) > **Tip:** Look into `window.py` to see where the value get's used. <details> <summary>Hint</summary> ### Challenge Step 11.1: Locate `duplicate_prims()` in `window.py` **Find** `duplicate_prims()` in `window.py`. ``` python duplicate_prims( transforms=transforms, prim_names=prim_names, target_path=self._scatter_prim_model.as_string, mode=self._scatter_type_model.get_current_item().as_string ) ``` `duplicate_prims()` will take all of the transforms and depending on the mode selected duplicate's the selected prim. This is ideal for adding in a scale parameter. ### Challenge Step 11.2: Pass Scale values in `duplicate_prims()` `self._scale_models` holds each scale set in the *Scatter Window*. **Add** `scale=[self._scale_models[0].as_float, self._scale_models[1].as_float, self._scale_models[2].as_float]` in `duplicate_prims()`. ``` python duplicate_prims( transforms=transforms, prim_names=prim_names, target_path=self._scatter_prim_model.as_string, mode=self._scatter_type_model.get_current_item().as_string, scale=[self._scale_models[0].as_float, self._scale_models[1].as_float, self._scale_models[2].as_float] ) ``` ### Challenge Step 11.3: Locate `duplicate_prims()` in `utils.py` **Open** `utils.py` from `ext/omni.example.scene_auth_scatter > omni/example/ui_scatter_tool > utils.py`. **Locate** `duplicate_prims()`. ``` python def duplicate_prims(transforms: List = [], prim_names: List[str] = [], target_path: str = "", mode: str = "Copy"): ``` ### Challenge Step 11.4: Add new parameter to `duplicate_prims()` **Add** `scale: List[float] = [1,1,1]` as a parmeter for `duplicate_prims()`. ``` python def duplicate_prims(transforms: List = [], prim_names: List[str] = [], target_path: str = "", mode: str = "Copy", scale: List[float] = [1,1,1]): ``` ### Challenge Step 11.5: Pass Scale Parameter into Kit Command **Scroll down** to find `omni.kit.commands.execute("TransformPrimSRT", path=path_to, new_translation=new_transform)` **Add** `new_scale=scale` to Kit Command. ``` python omni.kit.commands.execute("TransformPrimSRT", path=path_to, new_translation=new_transform, new_scale=scale) ``` ### Challenge Step 11.6: Save and Test **Save** the files and try to Scatter Prims with a different scale. ![](images/scatterscale.gif) ![](https://github.com/NVIDIA-Omniverse/kit-workshop-siggraph2022/blob/workshop_1/exts/omni.example.scene_auth_scatter/workshop/images/scatterscale.gif?raw=true) </details> ## Congratulations! You have completed this workshop! We hope you have enjoyed learning and playing with Omniverse! [Join us on Discord to extend the conversation!](https://discord.com/invite/nvidiaomniverse)
29,675
Markdown
38.515313
340
0.71171
NVIDIA-Omniverse/kit-workshop-siggraph2022/exts/omni.example.scene_auth_scatter/workshop/CN_SceneLayout_Workshop.md
![](https://github.com/NVIDIA-Omniverse/kit-workshop-siggraph2022/blob/workshop_1/exts/omni.example.scene_auth_scatter/workshop/images/logo.png?raw=true) # NVIDIA OMNIVERSE # 通过 NVIDIA Omniverse 轻松开发高级 3D 设计工具 了解如何仅借助数行 Python 脚本,通过模块化 Omniverse 平台轻松创建您自己的自定义场景布局工具。在本课程中,您将在 Omniverse 中使用 Python 构建您的自定义场景布局。 # 学习目标 - 了解如何启用扩展功能 - 使用命令执行 - 创建一个从基元的原点散布对象的功能 <video width="560" height="315" controls> <source src="https://dli-lms.s3.amazonaws.com/assets/x-ov-02-v1-zh/3DLayoutToolsIntro_CN_v1.mp4" type="video/mp4"> </video> # 第 I 部分 打开 Stage,并从社区(或第三方)获取扩展功能 <video width="560" height="315" controls> <source src="https://dli-lms.s3.amazonaws.com/assets/x-ov-02-v1-zh/3DLayoutToolsSection1_CN_v1.mp4" type="video/mp4"> </video> ## 第 1 步:打开 Workshop Stage ### <b>第 1.1 步:从下面提供的链接下载 Stage </b> [下载 Stage](https://dli-lms.s3.amazonaws.com/assets/x-ov-05-v1/Stage.zip) ### <b>第 1.2 步:使用 “Extract All...”(提取所有文件...)解压 Stage </b> 此操作会创建一个名为 `Stage` 的解压文件夹。 ### <b>第 1.3 步:在 Omniverse 中打开 Stage </b> 在 Omniverse Code 的 `Content`(内容)选项卡中,找到系统中存放 Stage 文件的位置。 (即 C:/Users/yourName/Downloads/Stage) 在 Omniverse Code 控制台底部的 `Content` (内容)选项卡中,**双击**中间窗格中的 `Stage.usd`,即可在视图区中打开该 Stage。 ## 第 2 步:添加扩展功能 我们将从“Extension Manager”(扩展功能管理器)的`Community/Third Party`(社区/第三方)部分获取扩展功能。此外,在`NVIDIA`部分可以获取 NVIDIA 开发的其他扩展功能。 ### 第 2.1 步:打开 `Extensions`(扩展功能)选项卡 单击 `Extensions`(扩展功能)管理器选项卡 ### 第 2.2 步:对来自社区或第三方的扩展功能进行筛选 选择 `Community/Third Party`(社区/第三方)选项卡 <br> ![](https://github.com/NVIDIA-Omniverse/kit-workshop-siggraph2022/blob/workshop_1/exts/omni.example.scene_auth_scatter/workshop/images/filtercommunity.png?raw=true) 在`Community/Third Party`(社区/第三方)部分,您可以找到由社区中的其他开发者提供的扩展功能。 ### 第 2.3 步:搜索 Scatter(散布)工具 在搜索框中搜索“scatter”,然后**单击**副标题为 *omni.example.scene_auth_scatter* 的扩展功能。 > **注意:**可以找到两个不同的 Scatter 工具。请仔细核对,确保您安装的 Scatter 工具的副标题为:*omni.example.scene_auth_scatter*。 ![](https://github.com/NVIDIA-Omniverse/kit-workshop-siggraph2022/blob/workshop_1/exts/omni.example.scene_auth_scatter/workshop/images/communitysearch.png?raw=true) ### 第 2.4 步:安装/启动扩展程序 **单击`Install`(安装)按钮,下载该扩展功能。如果您已经下载了该扩展功能,请单击`Disable`(禁用)旁边的切换按钮。** ![](https://github.com/NVIDIA-Omniverse/kit-workshop-siggraph2022/blob/workshop_1/exts/omni.example.scene_auth_scatter/workshop/images/installext.png?raw=true) ## 第 3 步:使用扩展功能 启用扩展功能后,请尝试执行以下步骤。 ### 第 3.1 步:选择一个 Prim(基元) 在 Stage 中选择一个 prim。 > **注意:Prim(基元)是 primitive 的简写,它是 Omniverse 中的基本单元。在 USD 场景中导入或创建的任何对象,都是一个基元,例如镜头、声音、光线、网格等等。从技术角度看,Prim 是元数据、属性和其他基元的容器。您可以在官方文档中了解有关 USD 基元的更多的信息。** 我们建议使用下面圈出的任意基元: ![](https://github.com/NVIDIA-Omniverse/kit-workshop-siggraph2022/blob/workshop_1/exts/omni.example.scene_auth_scatter/workshop/images/primstoselect.png?raw=true) ### 第 3.2 步:在 `Scatter Window`(散布窗口)中设置基元的路径 选择好基元后,**单击**`Scatter Window`(散布窗口)中的`S`按钮。 ![](https://github.com/NVIDIA-Omniverse/kit-workshop-siggraph2022/blob/workshop_1/exts/omni.example.scene_auth_scatter/workshop/images/clickS.png?raw=true) ### 第 3.3 步:使用选定的基元执行散布操作 在`Scatter Window`(散布窗口)底部,**单击** `Scatter`(散布)按钮。 ![](https://github.com/NVIDIA-Omniverse/kit-workshop-siggraph2022/blob/workshop_1/exts/omni.example.scene_auth_scatter/workshop/images/scatterbutton.png?raw=true) ### 第 3.4 步:撤消散布操作 在 `Stage` 选项卡下面,找到 `Scatter01` 文件夹并左键单击该文件夹,然后单击鼠标右键选择“Delete”(删除)或按下键盘上的 `delete` 按钮,即可将其删除。 在 `Stage` 面板中,您可以看到当前 `USD` (Universal Scene Description) 中的所有素材。它会按层次顺序列出基元。 ![](https://github.com/NVIDIA-Omniverse/kit-workshop-siggraph2022/blob/workshop_3/exts/omni.example.ui_scatter_tool/Workshop/images/deletescatter.gif?raw=true) ## 第 4 步(自我挑战):您还可以使用散布扩展功能执行哪些其他操作? 下面是*可选的*自我挑战。 ### 第 4.1 步(自我挑战):用例 通过 5 个用例了解如何进一步使用散布扩展功能。 ### 第 4.2 步(自我挑战):一次对多个基元执行散布操作 尝试一次对多个大理石基元执行散布操作。 <details> <summary>提示</summary> #### 第 4.2.1 步(自我挑战):一次对多个基元执行散布操作 在`Stage`里,**按住** `Ctrl` 键**选择**多个基元。 ![](https://github.com/NVIDIA-Omniverse/kit-workshop-siggraph2022/blob/workshop_1/exts/omni.example.scene_auth_scatter/workshop/images/multiprim.png?raw=true) #### 第 4.2.2 步(自我挑战):一次对多个基元执行散布操作 **重复**第 `3.2` 步和第 `2.3` 步。 </details> # 第 II 部分 相对于源基元的散布操作 <video width="560" height="315" controls> <source src="https://dli-lms.s3.amazonaws.com/assets/x-ov-02-v1-zh/3DLayoutToolsSection2Intro_CN_v1.mp4" type="video/mp4"> </video> <video width="560" height="315" controls> <source src="https://dli-lms.s3.amazonaws.com/assets/x-ov-02-v1-zh/3DLayoutToolsWorkshop2_CN_v1.mp4" type="video/mp4"> </video> ## 第 5 步:更改散布功能,以支持任意给定的原点 要将散布功能用于任意原点,我们需要对其进行修改,使其能够接收位置数据。当前的散布工具将散布功能设置在 Stage 的原点 (0,0,0)。要是有一些基元位于距原点很远的位置,就会非常不便。 ### 第 5.1 步:在 Visual Studio Code 中打开扩展功能 从 `Scatter Extension`(散布扩展功能)中,**单击** `Visual Studio` 图标。 ![](https://github.com/NVIDIA-Omniverse/kit-workshop-siggraph2022/blob/workshop_1/exts/omni.example.scene_auth_scatter/workshop/images/open_vs.png?raw=true) 系统将打开一个新的 *Visual Studio Code* 实例。 ![](https://github.com/NVIDIA-Omniverse/kit-workshop-siggraph2022/blob/workshop_1/exts/omni.example.scene_auth_scatter/workshop/images/vs_code.png?raw=true) ### 第 5.2 步:打开 `scatter.py` 在 `exts/omni.example.scene_auth_scatter > omni/example/ui_scatter_tool > scatter.py` 中,**找到**并**打开** `scatter.py`。 ![](https://github.com/NVIDIA-Omniverse/kit-workshop-siggraph2022/blob/workshop_1/exts/omni.example.scene_auth_scatter/workshop/images/scatterpy.png?raw=true) ### 第 5.3 步:向 `scatter()` 添加新原点参数 **将** `source_prim_location: List[float] = (0,0,0)` 作为参数,添加到 `scatter()` ``` python def scatter( count: List[int], distance: List[float], randomization: List[float], id_count: int = 1, seed: Optional[int] = None, source_prim_location: List[float] = (0,0,0) ): ``` `source_prim_location` 将包含我们选定执行散布操作的prim(基元)的 x 轴、y 轴和 z 轴坐标。 ### 第 5.4 步:找到 `result.SetTranslate` 在 `scatter.py` 的底部,**找到**如下代码片段。 ``` python result.SetTranslate( Gf.Vec3d( x, y, z, ) ) ``` `Vec3d` 会创建一个三维向量。每个prim(基元)的位置都是通过上面这段代码生成的。 ### 第 5.5 步:计算新原点 在 `Vec3d` 创建过程中,将 `source_prim_location` 中存储的各个坐标值**添加**到生成的坐标,例如:`x` 应改为 `source_prim_location[0] + x`。 ``` python result.SetTranslate( Gf.Vec3d( source_prim_location[0] + x, source_prim_location[1] + y, source_prim_location[2] + z, ) ) ``` `scatter()` 应类似下面的示例代码: ``` python def scatter( count: List[int], distance: List[float], randomization: List[float], id_count: int = 1, seed: Optional[int] = None, source_prim_location: List[float] = (0,0,0) ): """ 使用包含变换矩阵和 ID 的数据对返回生成器, 以排列多个对象。 ### 参数: `count: List[int]` 每个坐标轴上要生成的矩阵的数量 `distance: List[float]` 每个坐标轴上各个对象之间的距离 `randomization: List[float]` 每个坐标轴的随机距离 `id_count: int` 不同 ID 的数量 `seed: int` 如果不设置 seed 或将 seed 设置为“None”,则使用当前系统时间。如果将 seed 设置为 int 类型,则直接使用它。 """ # 初始化随机数字生成器。 random.seed(seed) for i in range(count[0]): x = (i - 0.5 * (count[0] - 1)) * distance[0] for j in range(count[1]): y = (j - 0.5 * (count[1] - 1)) * distance[1] for k in range(count[2]): z = (k - 0.5 * (count[2] - 1)) * distance[2] # 创建矩阵 result = Gf.Matrix4d(1) result.SetTranslate( Gf.Vec3d( source_prim_location[0] + x, source_prim_location[1] + y, source_prim_location[2] + z, ) ) id = int(random.random() * id_count) yield (result, id) ``` ### 第 5.6 步:保存 `scatter.py` 并打开 `window.py` **保存** `scatter.py`,然后从 `ext/omni.example.scene_auth_scatter > omni/example/ui_scatter_tool > window.py` **打开** `window.py`。 ![](https://github.com/NVIDIA-Omniverse/kit-workshop-siggraph2022/blob/workshop_1/exts/omni.example.scene_auth_scatter/workshop/images/windowpy.png?raw=true) ### 第 5.7 步:添加 Gf 模块 在导入代码部分,在 `LABEL_WIDTH` 的上方,**添加**一行代码:`from pxr import Gf`。 ``` python import omni.ui as ui from .style import scatter_window_style from .utils import get_selection from .combo_box_model import ComboBoxModel from .scatter import scatter from .utils import duplicate_prims from pxr import Gf LABEL_WIDTH = 120 SPACING = 4 ``` ### 第 5.8 步:找到 `transforms` **找到** `_on_scatter()` 中声明 `transforms` 的位置。 ``` python transforms = scatter( count=[m.as_int for m in self._scatter_count_models], distance=[m.as_float for m in self._scatter_distance_models], randomization=[m.as_float for m in self._scatter_random_models], id_count=len(prim_names), seed=self._scatter_seed_model.as_int ) ``` ### 第 5.9 步:硬编码原点位置 在 `seed=self._scatter_seed_model.as_int` 后面,**添加** `source_prim_location=Gf.Vec3d((0,0,-500))`。 > **注意:**请别忘记在 `seed=self._scatter_seed_model.as_int` 后面添加逗号。 ``` python transforms = scatter( count=[m.as_int for m in self._scatter_count_models], distance=[m.as_float for m in self._scatter_distance_models], randomization=[m.as_float for m in self._scatter_random_models], id_count=len(prim_names), seed=self._scatter_seed_model.as_int, source_prim_location=Gf.Vec3d((0,0,-500)) ) ``` `Gf.Vec3d((0,0,-500))` 会创建一个三坐标向量,坐标值为 x = 0、y = 0、z = -500。由于 Y 值代表stage上下方向的坐标,所以 X 值和 Z 值相当于位于地面上。通过将 Z 值设置为 -500,即可将散布位置设置到沿 Z 轴移动 -500 单位的位置。 ### 第 5.10 步:在*Stage*中选择一块大理石 **保存** `window.py`,然后回到 *Omniverse Code*。转到*Stage*部分,**展开**“Marbles”(大理石),然后**选择**任意大理石素材。 ![](https://github.com/NVIDIA-Omniverse/kit-workshop-siggraph2022/blob/workshop_1/exts/omni.example.scene_auth_scatter/workshop/images/marbleselect.png?raw=true) ### 第 5.11 步:在散布扩展中设置所选大理石的路径 选择好大理石素材后,**单击**`Scatter Window`(散布窗口)中的`S`按钮。 ![](https://github.com/NVIDIA-Omniverse/kit-workshop-siggraph2022/blob/workshop_1/exts/omni.example.scene_auth_scatter/workshop/images/clickS.png?raw=true) ### 第 5.12 步:对大理石执行散布操作 **滚动**到扩展功能的底部,然后**单击**`Scatter`(散布)按钮。 > **注意:**如果看不到`Scatter`(散布)按钮,请在*扩展程序窗口*中**向下滚动**,或者拉动右下角**扩大***扩展程序窗口*。 ![](https://github.com/NVIDIA-Omniverse/kit-workshop-siggraph2022/blob/workshop_1/exts/omni.example.scene_auth_scatter/workshop/images/scatterbutton.png?raw=true) 注意观察大理石如何在Stage的右侧进行散布。该位置也就是 Z 轴上 -500 单位的位置。尝试更改 Y 轴和/或 X 轴的某些值,看看大理石会改在哪里进行散布。 ![](https://github.com/NVIDIA-Omniverse/kit-workshop-siggraph2022/blob/workshop_1/exts/omni.example.scene_auth_scatter/workshop/images/sidescatter.png?raw=true) ## 第 6 步:获取源 prim 的位置 在这一步中,我们将更改对 prim 执行散布操作的原点。首先,我们需要获取源 prim 的位置。 ### 第 6.1 步:打开 `window.py` 从 `ext/omni.example.scene_auth_scatter > omni/example/ui_scatter_tool > window.py` **打开** `window.py` ![](https://github.com/NVIDIA-Omniverse/kit-workshop-siggraph2022/blob/workshop_1/exts/omni.example.scene_auth_scatter/workshop/images/windowpy.png?raw=true) ### 第 6.2 步:添加 `omni.usd` 模块 在 `import omni.ui as ui` 下面,**添加**一行代码:`import omni.usd` ``` python # 导入 omni.usd 模型 import omni.usd ``` 此时,代码顶部应包含以下内容: ``` python import omni.ui as ui import omni.usd from .style import scatter_window_style from .utils import get_selection from .combo_box_model import ComboBoxModel from .scatter import scatter from .utils import duplicate_prims from pxr import Gf ``` `omni.usd` 模块是核心 API 之一,通过它可以实现对 USD 和与 USD 相关的应用服务的访问。 ### 第 6.3 步:找到 `_on_scatter()` **向下滚动**,找到`_on_scatter()`,然后在 `transforms` 的变量声明代码前**添加**一行新代码。 ![](https://github.com/NVIDIA-Omniverse/kit-workshop-siggraph2022/blob/workshop_1/exts/omni.example.scene_auth_scatter/workshop/images/newline.png?raw=true) `_on_scatter()` 会在用户按下扩展功能窗口中的`Scatter`按钮时调用。 ### 第 6.4 步:获取 USD 上下文 在新添加的行下面,**声明** `usd_context`。请确保此行代码与 `if not prim_names:` 代码行齐头缩进。 ``` python usd_context = omni.usd.get_context() ``` 完成添加后,您的代码应类似于如下示例: ``` python def _on_scatter(self): """当用户按下“"Scatter"”(散布)按钮时调用""" prim_names = [i.strip() for i in self._source_prim_model.as_string.split(",")] if not prim_names: prim_names = get_selection() if not prim_names: # 待办事项:添加 “Can't clone”(无法复制)消息 pass # 获取要锚定的 UsdContext usd_context = omni.usd.get_context() transforms = scatter( count=[m.as_int for m in self._scatter_count_models], distance=[m.as_float for m in self._scatter_distance_models], randomization=[m.as_float for m in self._scatter_random_models], id_count=len(prim_names), seed=self._scatter_seed_model.as_int, ) duplicate_prims( transforms=transforms, prim_names=prim_names, target_path=self._scatter_prim_model.as_string, mode=self._scatter_type_model.get_current_item().as_string, ) ``` ### 第 6.5 步:获取 Stage 在 `usd_context` 声明下,**添加** `stage = usd_context.get_stage()`。 ``` python # 存储要锚定的 UsdContext usd_context = omni.usd.get_context() # 从当前 UsdContext 获取 Stage stage = usd_context.get_stage() ``` 变量stage将使用 USD 获取当前的 Stage。Stage 的层次结构中嵌着多个 prims。 ### 第 6.6 步:从Stage获取源 Prim 在下一行中,**添加** `prim = stage.GetPrimAtPath(self._source_prim_model.as_string)`。 ``` python # 存储要锚定的 UsdContext usd_context = omni.usd.get_context() # 从当前 UsdContext 获取stage stage = usd_context.get_stage() # 将当前扩展功能中被引用的 Prim保存起来 prim = stage.GetPrimAtPath(self._source_prim_model.as_string) ``` ### 第 6.7 步:获取源Prim的转换数据 接下来,我们需要添加 `position = prim.GetAttribute('xformOp:translate').Get()`,以**存储**prim的位置数据。检查了下面的示例代码后,请**保存** `window.py`。 ``` python # 存储要锚定的 UsdContext usd_context = omni.usd.get_context() # 从当前 UsdContext 获取stage stage = usd_context.get_stage() # 存储扩展程序中当前引用的prim(基元) prim = stage.GetPrimAtPath(self._source_prim_model.as_string) # 获取焦点基元的位置数据 position = prim.GetAttribute('xformOp:translate').Get() ``` 为了获得prim的位置,我们需要获取 Xform 中存储的转换值,从而得到选定的prim的 X 轴、Y 轴和 Z 轴坐标。 > **注意:**转换参数 (Xform) 是 Omniverse 中的所有对象的基本元素,决定了对象的位置。 检查您的代码,应该像下面的示例: ``` python def _on_scatter(self): """当用户按下“"Scatter"”(散布)按钮时调用""" prim_names = [i.strip() for i in self._source_prim_model.as_string.split(",")] if not prim_names: prim_names = get_selection() if not prim_names: # 待办事项:添加 “Can't clone”(无法复制)消息 pass # 存储要锚定的 UsdContext usd_context = omni.usd.get_context() # 从当前 UsdContext 获取stage stage = usd_context.get_stage() # 保存扩展功能当前所引用的prim prim = stage.GetPrimAtPath(self._source_prim_model.as_string) # 获取聚焦的prim的位置数据 position = prim.GetAttribute('xformOp:translate').Get() transforms = scatter( count=[m.as_int for m in self._scatter_count_models], distance=[m.as_float for m in self._scatter_distance_models], randomization=[m.as_float for m in self._scatter_random_models], id_count=len(prim_names), seed=self._scatter_seed_model.as_int, source_prim_location=Gf.Vec3((0,0,-500)) ) duplicate_prims( transforms=transforms, prim_names=prim_names, target_path=self._scatter_prim_model.as_string, mode=self._scatter_type_model.get_current_item().as_string, ) ``` ## 第 7 步:使用选定的 Prim(基元)的位置作为散布原点 更新散布功能后,我们就可以传递前面计算的源prim的位置值了。 ### 第 7.1 步:打开 window.py **打开** `window.py`,在 `_on_scatter()` 中找到声明 `transforms` 的位置。 ``` python transforms = scatter( count=[m.as_int for m in self._scatter_count_models], distance=[m.as_float for m in self._scatter_distance_models], randomization=[m.as_float for m in self._scatter_random_models], id_count=len(prim_names), seed=self._scatter_seed_model.as_int ) ``` ### 第 7.2 步:将位置值传递到 `scatter()` 在 `seed=self._scatter_seed_model.as_int` 后面,将代码 `source_prim_location=Gf.Vec3d(0,0,-500)` **替换为** `source_prim_location=position`。 ``` python transforms = scatter( count=[m.as_int for m in self._scatter_count_models], distance=[m.as_float for m in self._scatter_distance_models], randomization=[m.as_float for m in self._scatter_random_models], id_count=len(prim_names), seed=self._scatter_seed_model.as_int, source_prim_location=position ) ``` ### 第 7.3 步:进行测试 保存 `window.py` 并返回到 Omniverse。在stage中对某个prim执行**散布**操作。然后,再对另一个prim执行**散布**操作。注意观察它们如何仅在相应prim的位置处进行散布。 ### 第 7.4 步:点击 `Play`(播放) 运行您的stage! ## 第 8.1 步(自我挑战):为散布扩展功能添加随机化功能 现在,按下`Scatter`(散布)按钮后,对象会均匀地散布到stage中。请尝试更改代码,以实现随机分布。如果您找不到思路,请展开*提示*部分。 > **提示:**使用 `random.random()`。 <details> <summary>提示</summary> ### 第 8.1.1 步(自我挑战):打开 `scatter.py` **打开** `scatter.py`,并*找到* `scatter()`。 ### 第 8.1.2 步(自我挑战):添加随机值 **找到**用于生成 Vec3d 的 `result.SetTranslate()` 代码。将传递的第一个参数**修改**为 `source_prim_location[0] + (x + random.random() * randomization[0]),`。 ``` python result.SetTranslate( Gf.Vec3d( source_prim_location[0] + (x + random.random() * randomization[0]), source_prim_location[1] + y, source_prim_location[2] + z, ) ) ``` `randomization[0]` 指的是 Scatter 扩展功能窗口中标记为 Random 的选项。 ### 第 8.1.3 步(自我挑战):同样修改 Y 值和 Z 值 按照上一步中的操作,对传递到 *Vec3d* 构造的 Y 值和 Z 值进行相同的**修改**。 ``` python result.SetTranslate( Gf.Vec3d( source_prim_location[0] + (x + random.random() * randomization[0]), source_prim_location[1] + (y + random.random() * randomization[1]), source_prim_location[2] + (z + random.random() * randomization[2]), ) ) ``` ### 第 8.1.4 步(自我挑战):更改随机值 **保存** `scatter.py`,然后**返回到** Omniverse。**修改**“*Scatter Window*”(散布窗口)中的“*Random*”(随机)参数。 ![](https://github.com/NVIDIA-Omniverse/kit-workshop-siggraph2022/blob/workshop_1/exts/omni.example.scene_auth_scatter/workshop/images/random.png?raw=true) ### 第 8.1.5 步(自我挑战):对多个基元执行散布操作 **单击**`Scatter`(散布)按钮,并查看基元的散布情况。 > **注意:**如果散布范围很小,请增大“Random”(随机)值。 ![](https://github.com/NVIDIA-Omniverse/kit-workshop-siggraph2022/blob/workshop_1/exts/omni.example.scene_auth_scatter/workshop/images/scatterbutton.png?raw=true) ![](https://github.com/NVIDIA-Omniverse/kit-workshop-siggraph2022/blob/workshop_1/exts/omni.example.scene_auth_scatter/workshop/images/randomscatter.png?raw=true) </details> # 第 III 部分 散布物体 <video width="560" height="315" controls> <source src="https://dli-lms.s3.amazonaws.com/assets/x-ov-02-v1-zh/3DLayoutToolsWorkshop3_CN_v1.mp4" type="video/mp4"> </video> ## 第 9 步:对一个大理石 Prim(基元) 执行散布操作 Stage 中包含多个大理石 prims(基元),可用于四处散布。 ### 第 9.1 步:在 *Stage* 中选择一个大理石基元 转到 `Stage` 部分,**展开** “Marbles”(大理石),然后**选择**任意大理石基元。 ![](https://github.com/NVIDIA-Omniverse/kit-workshop-siggraph2022/blob/workshop_1/exts/omni.example.scene_auth_scatter/workshop/images/marbleselect.png?raw=true) ### 第 9.2 步:将所选大理石的路径复制到散布扩展功能 选择好大理石素材后,**单击** `Scatter Window` (散布窗口)中的 `S` 按钮。 ![](https://github.com/NVIDIA-Omniverse/kit-workshop-siggraph2022/blob/workshop_1/exts/omni.example.scene_auth_scatter/workshop/images/clickS.png?raw=true) ### 第 9.3 步:更改 X 轴的距离值 将`X Axis`(X 轴)的 `Distance`(距离)值**更改**为 10 ![](https://github.com/NVIDIA-Omniverse/kit-workshop-siggraph2022/blob/workshop_1/exts/omni.example.scene_auth_scatter/workshop/images/distance10.png?raw=true) ### 第 9.4 步:单击`Scatter`(散布)按钮 **单击**窗口底部的 `Scatter`(散布)按钮。 > **注意**:如果看不到 `Scatter`(散布)按钮,请在 `Extentions` 窗口中向下滚动,或者拉动右下角**扩大** `Extentions`窗口。 ![](https://github.com/NVIDIA-Omniverse/kit-workshop-siggraph2022/blob/workshop_1/exts/omni.example.scene_auth_scatter/workshop/images/scatterbutton.png?raw=true) 单击 `Scatter`(散布)按钮后,您的 stage 应该与下面的示例类似。 ![](https://github.com/NVIDIA-Omniverse/kit-workshop-siggraph2022/blob/workshop_1/exts/omni.example.scene_auth_scatter/workshop/images/marbleScattered.png?raw=true) ## 第 10 步:观看 Stage 里的动画 `Play`(播放)按钮的作用不仅是播放动画或影片,我们也可以用它进行物理学仿真。 ### 第 10.1 步:单击 `Play`(播放)按钮 对大理石基元设置了散布功能后,我们可以观看散布的动画效果。**单击** `Play`(播放)按钮观看 stage。 ![](https://github.com/NVIDIA-Omniverse/kit-workshop-siggraph2022/blob/workshop_1/exts/omni.example.scene_auth_scatter/workshop/images/playbutton.png?raw=true) 按下 `Play`(播放)按钮后的效果: ![](https://github.com/NVIDIA-Omniverse/kit-workshop-siggraph2022/blob/workshop_1/exts/omni.example.scene_auth_scatter/workshop/images/playbuttonaction.gif?raw=true) > **注意**:要**重置** stage,请**单击** `Stop`(停止)按钮。 ### 第 10.2 步:选择其他的 Prims(基元) 在 `Stage` 选项下,**选择**另一个 prim(基元)。您可以选择另一个大理石 prim(基元),也可以选择瓶、碗或其他 prim(基元)。 我们建议使用下面圈出的任意 prim: ![](https://github.com/NVIDIA-Omniverse/kit-workshop-siggraph2022/blob/workshop_1/exts/omni.example.scene_auth_scatter/workshop/images/primstoselect.png?raw=true) ### 第 10.3 步:将选定的 Prim 复制到散布窗口 选好 prim 后,**单击** `S` 按钮,将 prim 的路径复制到 `Scatter` 窗口里。 ![](https://github.com/NVIDIA-Omniverse/kit-workshop-siggraph2022/blob/workshop_1/exts/omni.example.scene_auth_scatter/workshop/images/clickS.png?raw=true) ### 第 10.4 步:更改散布参数 **更改** `Scatter Window`(散布窗口)中的某些参数。例如:在 `Y Axis`(Y 轴)部分,分别将 `Object Count`(对象数量)和 `Distance` (距离)的值**更改**为 20 和 5。 ![](https://github.com/NVIDIA-Omniverse/kit-workshop-siggraph2022/blob/workshop_1/exts/omni.example.scene_auth_scatter/workshop/images/params.png?raw=true) ### 第 10.5 步:对新 Prim(基元)执行散布操作 **单击** `Scatter Window`(散布窗口)底部的 `Scatter`(散布)按钮。 ![](https://github.com/NVIDIA-Omniverse/kit-workshop-siggraph2022/blob/workshop_1/exts/omni.example.scene_auth_scatter/workshop/images/scatterbutton.png?raw=true) ### 第 10.6 步:单击 `Play`(播放)按钮 **单击** `Play`(播放)按钮,并观看Stage的动画效果。 ![](https://github.com/NVIDIA-Omniverse/kit-workshop-siggraph2022/blob/workshop_1/exts/omni.example.scene_auth_scatter/workshop/images/playbutton.png?raw=true) 尝试使用散布扩展功能在 stage 中散布多种物品,并进行播放。 ## 第 11 步(自我挑战):按照给定的缩放倍数对散布的 Prim 进行缩放 您可能注意到,窗口中有一个 `Scale`(缩放)选项。但是,这个选项未发挥任何作用。我们来试着让它派上用场。如果您找不到思路,请展开*提示*部分。 ![](https://github.com/NVIDIA-Omniverse/kit-workshop-siggraph2022/blob/workshop_1/exts/omni.example.scene_auth_scatter/workshop/images/scale.png?raw=true) > **提醒:**可以查看 `window.py`,看看这个值是在哪里使用的。 <details> <summary>提示</summary> ### 第 11.1 步(自我挑战):在 `window.py` 中,找到 `duplicate_prims()` 在 `window.py` 中,**找到** `duplicate_prims()`。 ``` python duplicate_prims( transforms=transforms, prim_names=prim_names, target_path=self._scatter_prim_model.as_string, mode=self._scatter_type_model.get_current_item().as_string ) ``` `duplicate_prims()` 会接收所有转换参数,并根据选定的模式复制选定的基元。它非常适合添加到 scale 参数中。 ### 第 11.2 步(自我挑战):在 `duplicate_prims()` 中传递范围值 `self._scale_models` 储存了“*Scatter Window*”(散布窗口)中的每一项范围设置。在 `duplicate_prims()` 中,**添加** `scale=[self._scale_models[0].as_float, self._scale_models[1].as_float, self._scale_models[2].as_float]`。 ``` python duplicate_prims( transforms=transforms, prim_names=prim_names, target_path=self._scatter_prim_model.as_string, mode=self._scatter_type_model.get_current_item().as_string, scale=[self._scale_models[0].as_float, self._scale_models[1].as_float, self._scale_models[2].as_float] ) ``` ### 第 11.3 步(自我挑战):在 `utils.py` 中,找到 `duplicate_prims()` 从 `ext/omni.example.scene_auth_scatter > omni/example/ui_scatter_tool > utils.py` **打开** `utils.py`。**找到** `duplicate_prims()`。 ``` python def duplicate_prims(transforms: List = [], prim_names: List[str] = [], target_path: str = "", mode: str = "Copy"): ``` ### 第 11.4 步(自我挑战):向 `duplicate_prims()` 添加新参数 向 `duplicate_prims()` **添加**新参数 `scale: List[float] = [1,1,1]`。 ``` python def duplicate_prims(transforms: List = [], prim_names: List[str] = [], target_path: str = "", mode: str = "Copy", scale: List[float] = [1,1,1]): ``` ### 第 11.5 步(自我挑战):将缩放倍数参数传递到 Kit Command **向下滚动**,找到 `omni.kit.commands.execute("TransformPrimSRT", path=path_to, new_translation=new_transform)`。 将 `new_scale=scale` **添加**到 Kit Command。 ``` python omni.kit.commands.execute("TransformPrimSRT", path=path_to, new_translation=new_transform, new_scale=scale) ``` ### 第 11.6 步(自我挑战):保存并测试 **保存**文件,然后尝试使用不同的缩放值对基元执行散布操作。 ![](images/scatterscale.gif) ![](https://github.com/NVIDIA-Omniverse/kit-workshop-siggraph2022/blob/workshop_1/exts/omni.example.scene_auth_scatter/workshop/images/scatterscale.gif?raw=true) </details> ## 恭喜! 您已完成本培训!希望您在学习和使用 Omniverse 的过程中找到乐趣! [欢迎在 Discord 上加入我们,进行更深入的交流!](https://discord.com/invite/nvidiaomniverse)
23,799
Markdown
30.903485
194
0.690449
NVIDIA-Omniverse/kit-workshop-siggraph2022/exts/omni.example.ui_scene.manipulator_tool/Workshop/CN_SceneManipulator_Workshop.md
![](https://github.com/NVIDIA-Omniverse/kit-workshop-siggraph2022/blob/workshop_2/exts/omni.example.ui_scene.widget_info/Workshop/images/logo.png?raw=true) # NVIDIA OMNIVERSE # 通过 NVIDIA Omniverse 构建自定义 3D 场景操作工具 了解如何在易于扩展的模块化的 Omniverse 平台上构建高级工具。Omniverse 开发者团队将向您展示如何扩展并增强您所熟悉且喜爱的 3D 工具。 # 学习目标 - 启用扩展程序 - 将 `scale` 函数附加至滑块小组件上 <video width="560" height="315" controls> <source src="https://dli-lms.s3.amazonaws.com/assets/x-ov-06-v1-zh/sceneManipulatorIntro_CN_v1.mp4" type="video/mp4"> </video> # UI Scene_Widget Info ## 第 I 部分 <video width="560" height="315" controls> <source src="https://dli-lms.s3.amazonaws.com/assets/x-ov-06-v1-zh/sceneManipulator1_CN_v1.mp4" type="video/mp4"> </video> ### 第 1 步:打开 Workshop 场景 #### <b>第 1.1 步:从下面提供的链接下载 Stage</b> [Stage 下载链接](https://dli-lms.s3.amazonaws.com/assets/x-ov-05-v1/Stage.zip) #### <b>第 1.2 步:使用“Extract All...”(提取所有文件...)选项解压 Stage 文件 此操作会创建一个名为 `Stage` 的解压文件夹。 #### <b>第 1.3 步:在 Omniverse 中打开 Stage 在 Omniverse Code 的 `Content` 选项卡,找到系统中存放 Stage 文件的位置。 (即 C:/Users/yourName/Downloads/Stage) 在 Omniverse Code 控制台底部的 `Content` 选项卡中,**双击**中间窗格中的 `Stage.usd` 即可在视图(Viewport)中打开该 Stage。 ### 第 2 步:安装小组件扩展功能 #### <b>第 2.1 步:打开`Extensions`(扩展功能)选项卡</b> 单击 `Extensions`(扩展功能)管理器选项卡。 #### <b>第 2.2 步:对社区/第三方的扩展功能进行筛选</b> 选择 `Community/Third Party`(社区/第三方)选项卡 <br> ![](https://github.com/NVIDIA-Omniverse/kit-workshop-siggraph2022/blob/workshop_2/exts/omni.example.ui_scene.widget_info/Workshop/images/extensionCommunity.PNG?raw=true) <br> #### <b>第 2.3 步:搜索小组件信息</b> 搜索 `Widget Info` 并单击 `Omni UI Scene Object Info With Widget Example` ![](https://github.com/NVIDIA-Omniverse/kit-workshop-siggraph2022/blob/workshop_2/exts/omni.example.ui_scene.widget_info/Workshop/images/widgetExt.png?raw=true) #### <b>第 2.4 步:安装/启用扩展程序</b> 单击选中的扩展程序,然后在右侧控制台中单击 `Install`(安装)。安装后,启用扩展程序。 ><span>❗</span>您可能会收到一个警告,指明此扩展程序未经验证。您可以安全地安装此扩展程序。 <br> #### <b>第 2.5 步:检查小组件是否起作用</b> 前往 `Viewport`(视图),然后在层次结构中选择一个 `prim`(基元)。 `prim` 是“primitive”(基元)的缩写。基元是 Omniverse 中的基本单元。在 `USD`(Universal Scene Description) 场景中导入或创建的任何对象都是一个基元。这包括:镜头、声音、光线、网格等等。 您会在视图中的 `prim` 上方看到以下小组件: <br> ![](https://github.com/NVIDIA-Omniverse/kit-workshop-siggraph2022/blob/workshop_2/exts/omni.example.ui_scene.widget_info/Workshop/images/viewportWidgetEnabled.PNG?raw=true) <br> ><span>❓</span> 您注意到了吗? >- 基元的路径显示在小组件中。 >- 小组件中有一个缩放滑块,但它不起作用!我们将在下一部分中修复此问题。 <br> #### <b>第 3 步:找到播放按钮</b> 在视口中找到 `Play`(按钮),并看看单击它时会发生什么!别忘了在完成后按 `Stop`(停止)按钮。 <details> <summary>单击此处可查看按钮所在的位置</summary> ![](https://github.com/NVIDIA-Omniverse/kit-workshop-siggraph2022/blob/workshop_2/exts/omni.example.ui_scene.widget_info/Workshop/images/playButton.png?raw=true) </details> <br> >#### <span>🧠</span><b>第 4 步(自我挑战):头脑风暴用例</b> ><i>本培训中的所有挑战都是可选的。</i> > >思考小组件的 3 种使用方式。例如,您注意到它可用来显示 prim 的路径,那么您还可以在小组件中显示 prim 的其它信息吗?与同行进行头脑风暴,并思考如何将小组件应用于您所从事的行业!稍后我们将就此进行小组讨论。 <br> <br> >### <span>⛔</span>建议在此处停留,思考一下,再继续学习第 II 部分 <br> ## 第 II 部分 <video width="560" height="315" controls> <source src="https://dli-lms.s3.amazonaws.com/assets/x-ov-06-v1-zh/sceneManipulator2Intro_CN_v1.mp4" type="video/mp4"> </video> <video width="560" height="315" controls> <source src="https://dli-lms.s3.amazonaws.com/assets/x-ov-06-v1-zh/sceneManipulator2_CN_v1.mp4" type="video/mp4"> </video> ### 第 5 步:找到您的工作文件 #### <b>第 5.1 步:打开 Visual Studio</b> 转至 `Extensions`(扩展功能)选项卡。 单击 `Widget Info`(小组件信息)扩展功能以在右侧打开扩展功能概述。 单击文件夹图标旁边的 `VS Code` 图标: <br> ![](https://github.com/NVIDIA-Omniverse/kit-workshop-siggraph2022/blob/workshop_2/exts/omni.example.ui_scene.widget_info/Workshop/images/vsCodeIcon.PNG?raw=true) <br> 系统将弹出单独的 `VS Code` 窗口,如下所示: ![](https://github.com/NVIDIA-Omniverse/kit-workshop-siggraph2022/blob/workshop_2/exts/omni.example.ui_scene.widget_info/Workshop/images/vsCodeopened.png?raw=true) <br> #### <b>第 5.2 步:找到操控器脚本</b> 在左列下拉菜单中的以下位置找到此会话所需的文件: `exts -> omni.example.ui_scene.widget_info\omni\example\ui_scene\widget_info` 您当前位于: `widget_info_manipulator.py` <br> ![](https://github.com/NVIDIA-Omniverse/kit-workshop-siggraph2022/blob/workshop_2/exts/omni.example.ui_scene.widget_info/Workshop/images/fileStructLocation.gif?raw=true) <br> ### 第 6 步:修复损坏的滑块 >#### 第 6.1 步:添加新导入 在脚本顶部找到 `imports`。 添加新导入: ```python from pxr import Gf ``` 现在,导入的库将如下所示: ![](https://github.com/NVIDIA-Omniverse/kit-workshop-siggraph2022/blob/workshop_2/exts/omni.example.ui_scene.widget_info/Workshop/images/newImport.png?raw=true) <br> 在以下步骤中,您将使用 `Graphics Foundation`(简称 Gf),它是一个包含基础图形类和操作的软件包。 #### <b>第 6.2 步:找到函数 `update_scale`</b> 在脚本底部找到以下函数: ```python # 更新滑块 def update_scale(prim_name, value): ``` 此函数会更新小组件中的滑块。但是,它目前没有任何代码用来更新缩放比例。让我们开始添加所需的代码来实现这一点! #### <b>第 6.3 步:获取当前场景</b> 在 `update_scale` 函数内部,找到 `print` 调用。 定义`stage` 变量,例如: ```python stage = self.model.usd_context.get_stage() ``` 从 USD 上下文中,我们抓取当前活动的stage,并将其存储到 `stage` 变量中。 `Stage` 是您的 prims 在层次结构中嵌套的地方。 现在,`update_scale` 应如下所示: ![](https://github.com/NVIDIA-Omniverse/kit-workshop-siggraph2022/blob/workshop_2/exts/omni.example.ui_scene.widget_info/Workshop/images/GetStage.png?raw=true) <br> ><span>❗</span>请确保新的 stage 变量与 print 调用的缩进列是对齐的。否则,请添加或删除制表符(tab键),直到实现对齐。 <br> #### <b>第 6.4 步:获取已选择的 prim(基元)</b> 接下来,在stage 变量的下面为当前选择的 prim 添加变量: ```python prim = stage.GetPrimAtPath(self.model._current_path) ``` `update_scale` 现在如下所示: ![](https://github.com/NVIDIA-Omniverse/kit-workshop-siggraph2022/blob/workshop_2/exts/omni.example.ui_scene.widget_info/Workshop/images/getPrim.png?raw=true) ><span>❗</span> 此 prim 变量应与其上方的 stage 和 print 调用保持对齐。 <br> #### <b>第 6.5 步:更新 `scale`</b> 在下一行中添加新的 `scale` 变量。 在此变量中,您将获得`xform` 的 `scale`(缩放比例)属性,然后设置 `scale` 的 `Vector3` 值,如下所示: ```python scale = prim.GetAttribute("xformOp:scale") scale.Set(Gf.Vec3d(value, value, value)) ``` 现在,您已完成,`update_scale` 函数将如下所示: ![](https://github.com/NVIDIA-Omniverse/kit-workshop-siggraph2022/blob/workshop_2/exts/omni.example.ui_scene.widget_info/Workshop/images/setScale.png?raw=true) ><span>❗</span>`scale` 变量应与其上方的变量保持对齐。 <br> ### 第 7 步:它起作用了吗? #### <b>第 7.1 步:保存并测试!</b> 保存操控器脚本,并检查缩放滑块在小组件中是否起作用! ><span>❗</span> 保存时,您可能会注意到小组件在视口中消失。这是预期行为,再次单击基元即可显示小组件。 ![](https://github.com/NVIDIA-Omniverse/kit-workshop-siggraph2022/blob/workshop_2/exts/omni.example.ui_scene.widget_info/Workshop/images/scaleWorking.gif?raw=true) 函数 `update_scale` 正在更新您的滑块,在此函数中,您添加了可获取 `stage` 和当前所选择的 `prim`(小组件显示在其上方)的属性,然后在滑块移动时调用 scale 的 Vector3,以在各个方向上改变 prim(基元)的大小。 ><span>❗</span>不起作用? 查看 `Console`(控制台)以调试任何错误。 > >![](https://github.com/NVIDIA-Omniverse/kit-workshop-siggraph2022/blob/workshop_2/exts/omni.example.ui_scene.widget_info/Workshop/images/Console.png?raw=true) <br> >#### &#128161; <b>第 8 步(自我挑战):更大的缩放比例</b> ><i>本培训中的所有挑战都是可选的。</i> > >您能否更改函数,实现对一个 prim(基元)以大于 1.0 的比例进行缩放? > ><details> ><summary>单击此处获取答案</summary> > >设置 `value` 变量,并将其值乘以一个数字。 > >例如: > >```python > def update_scale(prim_name, value): > if value <= 0: > value = 0.01 > print(f"changing scale of {prim_name}, {value}") > ## 新的值变量添加在下方 > value = 10*value > stage = self.model.usd_context.get_stage() > prim = stage.GetPrimAtPath(self.model._current_path) > scale = prim.GetAttribute("xformOp:scale") > scale.Set(Gf.Vec3d(value, value, value)) > if self._slider_model: > self._slider_subscription = None > self._slider_model.as_float = 1.0 > self._slider_subscription = self._slider_model.subscribe_value_changed_fn( > lambda m, p=self.model.get_item("name"): update_scale(p, m.as_float) > ) >``` > ></details> <br> >#### <span>&#129504;</span><b>第 9 步(自我挑战):您希望使用小组件控制其他哪些属性?</b> ><i>本培训中的所有挑战都是可选的。</i> > > 针对您可能要添加到此小组件的其他 3-5 个属性展开头脑风暴。稍后我们将就此进行公开讨论。 <br> >### <span>⛔</span> 建议在此处停留,思考一下,再继续学习第 III 部分。 <br> ## 第 III 部分: <video width="560" height="315" controls> <source src="https://dli-lms.s3.amazonaws.com/assets/x-ov-06-v1-zh/sceneManipulator3_CN_v1.mp4" type="video/mp4"> </video> ### 第 10 步:创建您的场景 #### <b>第 10.1 步:缩放各种物品!</b> 在您的场景中随意选取一个 prim(基元)并缩放它,例如变出非常大的大理石或很小的罐子。 如何打造独特的场景? ><span>&#11088;</span>请在完成后按 `Play`(播放)按钮! > >![](https://github.com/NVIDIA-Omniverse/kit-workshop-siggraph2022/blob/workshop_2/exts/omni.example.ui_scene.widget_info/Workshop/images/playButton.png?raw=true) <br> ![](https://github.com/NVIDIA-Omniverse/kit-workshop-siggraph2022/blob/workshop_2/exts/omni.example.ui_scene.widget_info/Workshop/images/section3.gif?raw=true) <br> >#### <span>&#129504;</span><b>第 11 步(自我挑战):在一个轴上缩放</b> ><i>本培训中的所有挑战都是可选的。</i> > >您能否更改函数,实现仅在一个坐标轴的方向上对基元进行缩放? > ><details> ><summary>单击此处获取答案</summary> > >对于您不希望进行缩放的轴方向,在 `scale.Set(Gf.Vec3d(value,value,value))` 中将对应该坐标轴的值更改为 1。 > >例如: > >```python >scale.Set(Gf.Vec3d(value,1,1)) >``` > >这会将缩放更改为仅在 X 轴上进行,因为 Y 轴和 Z 轴的值保留为 1,而 X 轴会更改。 > ></details> <br> >#### <span>&#129504;</span><b>第 12 步(自我挑战):打开光线操控器</b> ><i>本培训中的所有挑战都是可选的。</i> > >打开光线操控器扩展程序,然后单击面光源。 > >如何使用此工具更改光线强度? > ><details> ><summary>单击此处获取答案</summary> > >在 `Extensions`(扩展功能)选项卡中,在 `Community/Third Party`(社区/第三方)中搜索“Light”(光线),然后安装/启用 `Omni.Ui Scene Sample for Manipulating Select Light` 扩展程序。 > >![](https://github.com/NVIDIA-Omniverse/kit-workshop-siggraph2022/blob/workshop_2/exts/omni.example.ui_scene.widget_info/Workshop/images/LightExt.png?raw=true) > ><br> > >在层次结构中选择一个面光源。 > >![](https://github.com/NVIDIA-Omniverse/kit-workshop-siggraph2022/blob/workshop_2/exts/omni.example.ui_scene.widget_info/Workshop/images/RectLight.png?raw=true) > ><br> > >使用光标抓取光线工具的边,然后通过向前或向后拖动来更改光线强度。 > >![](https://github.com/NVIDIA-Omniverse/kit-workshop-siggraph2022/blob/workshop_2/exts/omni.example.ui_scene.widget_info/Workshop/images/RectIntensity.png?raw=true) > ></details> <br> ## 恭喜! 您已完成本培训!希望您喜欢学习和使用 Omniverse! [欢迎在 Discord 上加入我们,进行更深入的交流!](https://discord.com/invite/nvidiaomniverse)
10,032
Markdown
23.772839
172
0.69986
NVIDIA-Omniverse/kit-workshop-siggraph2022/exts/omni.example.ui_scene.manipulator_tool/Workshop/Siggraph2022_Manipulator_Tools_Workshop.md
![](https://github.com/NVIDIA-Omniverse/kit-workshop-siggraph2022/blob/workshop_2/exts/omni.example.ui_scene.widget_info/Workshop/images/logo.png?raw=true) # NVIDIA OMNIVERSE # How to Build Custom 3D Scene Manipulator Tools on NVIDIA Omniverse See how you can build advanced tools on the modular, easily extensible Omniverse platform. You’ll learn from the Omniverse developer ecosystem team how you can extend and enhance the 3D tools you know and love today.​ # Learning Objectives - Enable Extension - Attach `scale` function to Slider Widget <video width="560" height="315" controls> <source src="https://d36m44n9vdbmda.cloudfront.net/assets/x-ov-06-v1/sceneManipulatorIntro.mp4" type="video/mp4"> </video> # UI Scene_Widget Info ## Section I <video width="560" height="315" controls> <source src="https://d36m44n9vdbmda.cloudfront.net/assets/x-ov-06-v1/sceneManipulator1.mp4" type="video/mp4"> </video> ### Step 1: Open the Workshop Stage #### <b>Step 1.1: Download the Stage from the Link Provided</b> [Stage Link](https://dli-lms.s3.amazonaws.com/assets/x-ov-06-v1/Stage.zip) #### <b> Step 1.2: Unzip Stage Using Extract All... This creates an unzipped file folder called `Stage`. #### <b> Step 1.3: Open Stage in Omniverse Navigate inside Omniverse Code's `Content tab` to the stage file's location on your system. (i.e. C:/Users/yourName/Downloads/Stage) **Double Click** `Stage.usd` in the center window pane of the `Content tab` at the bottom of the Omniverse Code Console and it will appear in the viewport. ### Step 2: Install the Widget Extension #### <b>Step 2.1: Open the Extensions Tab</b> Click on `Extensions` Manager Tab #### <b>Step 2.2: Filter by Community / Third Party Extensions</b> Select `Community / Third Party` tab <br> ![](https://github.com/NVIDIA-Omniverse/kit-workshop-siggraph2022/blob/workshop_2/exts/omni.example.ui_scene.widget_info/Workshop/images/extensionCommunity.PNG?raw=true) <br> #### <b>Step 2.3: Search for Widget Info</b> Search for `Widget Info` and click on `Omni UI Scene Object Info With Widget Example` ![](https://github.com/NVIDIA-Omniverse/kit-workshop-siggraph2022/blob/workshop_2/exts/omni.example.ui_scene.widget_info/Workshop/images/widgetExt.png?raw=true) #### <b>Step 2.4: Install/Enable the Extension</b> Click on the extension and then click `Install` in the right console. Once installed, enable the extension. ><span>&#10071;</span> You may get a warning that this extension is not verified. It is safe to install this extension. <br> #### <b>Step 2.5: Check that the Widget is Working</b> Navigate to `Viewport` then select a `prim` in the hierarchy. A `prim` is short for primitive. The prim is the fundamental unit in Omniverse. Anything imported or created in a `USD`, Universal Scene Description, scene. This includes camera, sounds, lights, meshes, etc. You should see the following widget appear in the viewport above the `prim`: <br> ![](https://github.com/NVIDIA-Omniverse/kit-workshop-siggraph2022/blob/workshop_2/exts/omni.example.ui_scene.widget_info/Workshop/images/viewportWidgetEnabled.PNG?raw=true) <br> ><span>&#10067;</span> Did you notice? >- The path of the prim is displayed in the widget. >- There is a scale slider in the widget but it doesn't work! We will fix this in the next section. <br> #### <b>Step 3: Find the Play Button</b> Locate the `Play` button in the viewport and see what happens when you click it! Don't forget to hit the `Stop` button when you are finished. <details> <summary>Click here to see where the button is located </summary> ![](https://github.com/NVIDIA-Omniverse/kit-workshop-siggraph2022/blob/workshop_2/exts/omni.example.ui_scene.widget_info/Workshop/images/playButton.png?raw=true) </details> <br> >#### <span>&#129504;</span><b>Challenge Step 4: Brainstorm Use Cases</b> ><i>All Challenges in this workshop are optional</i> > >Think of 3 ways a widget could be used. For example, you noticed that the path of the prim is displayed, what else could you display about the prim in the widget? Brain storm with your peers and think of how it can be used for your industry! We will have a group discussion about this later on. <br> <br> >### <span>&#9940;</span> Stop here and wait to move on to Section II <br> ## Section II <video width="560" height="315" controls> <source src="https://d36m44n9vdbmda.cloudfront.net/assets/x-ov-06-v1/sceneManipulator2Intro.mp4" type="video/mp4"> </video> <video width="560" height="315" controls> <source src="https://d36m44n9vdbmda.cloudfront.net/assets/x-ov-06-v1/sceneManipulator2.mp4" type="video/mp4"> </video> ### Step 5: Find your Work Files #### <b>Step 5.1: Open Visual Studio</b> Go to the `Extensions` tab. Click the `Widget Info` extension to open the extension overview to the right. Click the `VS Code` icon next to the folder icon: <br> ![](https://github.com/NVIDIA-Omniverse/kit-workshop-siggraph2022/blob/workshop_2/exts/omni.example.ui_scene.widget_info/Workshop/images/vsCodeIcon.PNG?raw=true) <br> `VS Code` will pop up separately and look like this: ![](https://github.com/NVIDIA-Omniverse/kit-workshop-siggraph2022/blob/workshop_2/exts/omni.example.ui_scene.widget_info/Workshop/images/vsCodeopened.png?raw=true) <br> #### <b>Step 5.2: Locate Manipulator Script</b> Locate the files you need for this session in the left column drop-down menus at: `exts -> omni.example.ui_scene.widget_info\omni\example\ui_scene\widget_info` You are working in `widget_info_manipulator.py` <br> ![](https://github.com/NVIDIA-Omniverse/kit-workshop-siggraph2022/blob/workshop_2/exts/omni.example.ui_scene.widget_info/Workshop/images/fileStructLocation.gif?raw=true) <br> ### Step 6: Fix the Broken Slider >#### Step 6.1: Add a New Import Locate the `imports` at the top of the script. Add the new import: ```python from pxr import Gf ``` The imports will now look like this: ![](https://github.com/NVIDIA-Omniverse/kit-workshop-siggraph2022/blob/workshop_2/exts/omni.example.ui_scene.widget_info/Workshop/images/newImport.png?raw=true) <br> In the following steps, you will use `Graphics Foundation`, or Gf, which is a package of fundamental graphics types and operations. #### <b>Step 6.2: Find the Function Update_Scale</b> Locate the following function at the bottom of the script: ```python # Update the slider def update_scale(prim_name, value): ``` This function updates the slider in the Widget. However, it currently does not have any logic to update the scale. Let's start adding the code we need to get that working! #### <b>Step 6.3: Get the Current Stage</b> Inside of `update_scale` function, find the `print` call. Define the `stage` variable underneath this call, like so: ```python stage = self.model.usd_context.get_stage() ``` From the USD context we grab the active stage and store it into the stage variable. The `Stage` is where your prims are nested in the hierarchy. So now, `update_scale` should look like this: ![](https://github.com/NVIDIA-Omniverse/kit-workshop-siggraph2022/blob/workshop_2/exts/omni.example.ui_scene.widget_info/Workshop/images/GetStage.png?raw=true) <br> ><span>&#10071;</span> Make sure your new stage variable is lined up with the print call. If it is not, add or delete tabs until it is. <br> #### <b>Step 6.4: Get the Selected Prim</b> Next, add a variable underneath the stage variable for the currently selected prim: ```python prim = stage.GetPrimAtPath(self.model._current_path) ``` `update_scale` will now look like this: ![](https://github.com/NVIDIA-Omniverse/kit-workshop-siggraph2022/blob/workshop_2/exts/omni.example.ui_scene.widget_info/Workshop/images/getPrim.png?raw=true) ><span>&#10071;</span> This prim variable should be lined up with the stage and print call above it. <br> #### <b>Step 6.5: Update the Scale </b> Add a new scale variable on the next line. In this variable you will get the scale `attribute` of the `xform` and the scale's Vector3 value, like so: ```python scale = prim.GetAttribute("xformOp:scale") scale.Set(Gf.Vec3d(value, value, value)) ``` Now, your completed `update_scale` function will look like this: ![](https://github.com/NVIDIA-Omniverse/kit-workshop-siggraph2022/blob/workshop_2/exts/omni.example.ui_scene.widget_info/Workshop/images/setScale.png?raw=true) ><span>&#10071;</span>The scale variable should be lined up with the variables above it. <br> ### Step 7: Did it work? #### <b>Step 7.1: Save and Test! </b> Save your manipulator script and check that the scale slider works in your widget! ><span>&#10071;</span> When you save, you may notice that the widget disappears in the viewport. This is to be expected, click the prim again to show the widget. ![](https://github.com/NVIDIA-Omniverse/kit-workshop-siggraph2022/blob/workshop_2/exts/omni.example.ui_scene.widget_info/Workshop/images/scaleWorking.gif?raw=true) Your slider is now being udpated by the function `update_scale`, where you added properties that grab the `Stage` and the currently selected `prim` that the widget is displayed on, then calls the scale vector3 when the slider is moved to scale the prim in all directions. ><span>&#10071;</span> Not Working? Check the `Console` to debug any errors. > >![](https://github.com/NVIDIA-Omniverse/kit-workshop-siggraph2022/blob/workshop_2/exts/omni.example.ui_scene.widget_info/Workshop/images/Console.png?raw=true) <br> >#### :bell:<b>Challenge Step 8: Scale Larger</b> ><i>All Challenges in this workshop are optional</i> > >Can you change the function to scale the prim larger than 1.0? > ><details> ><summary> Click here for the answer </summary> > >Set a `value` variable and multiply a number by value. > >For example: > >```python > def update_scale(prim_name, value): > if value <= 0: > value = 0.01 > print(f"changing scale of {prim_name}, {value}") > ## NEW VALUE VARIABLE ADDED BELOW > value = 10*value > stage = self.model.usd_context.get_stage() > prim = stage.GetPrimAtPath(self.model._current_path) > scale = prim.GetAttribute("xformOp:scale") > scale.Set(Gf.Vec3d(value, value, value)) > if self._slider_model: > self._slider_subscription = None > self._slider_model.as_float = 1.0 > self._slider_subscription = self._slider_model.subscribe_value_changed_fn( > lambda m, p=self.model.get_item("name"): update_scale(p, m.as_float) > ) >``` > ></details> <br> >#### <span>&#129504;</span><b>Challenge Step 9: What other properties might you want to control with the widget?</b> ><i>All Challenges in this workshop are optional</i> > > Brainstorm 3-5 other properties that you could add to this widget. We will have an open discussion later on. <br> >### <span>&#9940;</span> Stop here and wait to move on to Section III <br> ## Section III: <video width="560" height="315" controls> <source src="https://d36m44n9vdbmda.cloudfront.net/assets/x-ov-06-v1/sceneManipulator3.mp4" type="video/mp4"> </video> ### Step 10: Create your scene #### <b>Step 10.1: Scale Everything!</b> Play around in your scene and scale the prims in various sizes, such as a very large marble or a tiny jar. How can you make your scene unique? ><span>&#11088;</span> Press the `Play` button when you are finished! > >![](https://github.com/NVIDIA-Omniverse/kit-workshop-siggraph2022/blob/workshop_2/exts/omni.example.ui_scene.widget_info/Workshop/images/playButton.png?raw=true) <br> ![](https://github.com/NVIDIA-Omniverse/kit-workshop-siggraph2022/blob/workshop_2/exts/omni.example.ui_scene.widget_info/Workshop/images/section3.gif?raw=true) <br> >#### <span>&#129504;</span><b>Challenge Step 11: Scale in One Axis</b> ><i>All Challenges in this workshop are optional</i> > >Can you change the function to scale the prim in only one axis? > ><details> ><summary> Click here for the answer </summary> > >Change the value's to 1 in `scale.Set(Gf.Vec3d(value,value,value))` of the axes that you do not want to scale in. > >For example: > >```python >scale.Set(Gf.Vec3d(value,1,1)) >``` > >Which, would change the scale in the X axis as the Y and Z axis will remain at a value of 1 and the X axis will change. > ></details> <br> >#### <span>&#129504;</span><b>Challenge Step 12: Turn on the Light Manipulator</b> ><i>All Challenges in this workshop are optional</i> > >Turn on the Light Manipulator Extension and click on the Rect Light. > >How can you change the intensity of the light using the tool? > ><details> ><summary>Click here for the answer</summary> > >In the `Extensions` tab, search for Light in the `Community / Third Party` and install/enable the `Omni.Ui Scene Sample for Manipulating Select Light` extension. > >![](https://github.com/NVIDIA-Omniverse/kit-workshop-siggraph2022/blob/workshop_2/exts/omni.example.ui_scene.widget_info/Workshop/images/LightExt.png?raw=true) > ><br> > >Select one of the Rect Lights in the hierarchy. > >![](https://github.com/NVIDIA-Omniverse/kit-workshop-siggraph2022/blob/workshop_2/exts/omni.example.ui_scene.widget_info/Workshop/images/RectLight.png?raw=true) > ><br> > >Use your cursor to grab the edges of the Light tool and change the intensity by dragging forward or backward. > >![](https://github.com/NVIDIA-Omniverse/kit-workshop-siggraph2022/blob/workshop_2/exts/omni.example.ui_scene.widget_info/Workshop/images/RectIntensity.png?raw=true) > ></details> <br> ## Congratulations! You have completed this workshop! We hope you have enjoyed learning and playing with Omniverse! [Join us on Discord to extend the conversation!](https://discord.com/invite/nvidiaomniverse)
13,812
Markdown
33.5325
295
0.72437
NVIDIA-Omniverse/kit-workshop-siggraph2022/exts/omni.example.ui_scene.manipulator_tool/config/extension.toml
[package] version = "1.0.1" authors = ["NVIDIA"] title = "Omni.UI Scene Object Info with Widget Example" description = "This example show an 3d info pophover type tool tip scene object" readme = "docs/README.md" repository = "https://gitlab-master.nvidia.com/omniverse/kit-extensions/kit-scene" category = "Documentation" keywords = ["ui", "example", "scene", "docs", "documentation", "popover"] changelog = "docs/CHANGELOG.md" preview_image = "data/preview.png" icon = "data/icon.png" [dependencies] "omni.kit.viewport.utility" = { } "omni.ui.scene" = { } "omni.usd" = { } [[python.module]] name = "omni.example.ui_scene.manipulator_tool" [[test]] args = [ "--/app/window/dpiScaleOverride=1.0", "--/app/window/scaleToMonitor=false", "--no-window" ] dependencies = [ "omni.kit.renderer.core", "omni.kit.renderer.capture", ]
850
TOML
25.593749
82
0.68
NVIDIA-Omniverse/kit-workshop-siggraph2022/exts/omni.example.ui_scene.manipulator_tool/omni/example/ui_scene/manipulator_tool/widget_info_manipulator.py
## Copyright (c) 2018-2021, 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__ = ["WidgetInfoManipulator"] from omni.ui import color as cl from omni.ui import scene as sc import omni.ui as ui class _ViewportLegacyDisableSelection: """Disables selection in the Viewport Legacy""" def __init__(self): self._focused_windows = None focused_windows = [] try: # For some reason is_focused may return False, when a Window is definitely in fact is the focused window! # And there's no good solution to this when mutliple Viewport-1 instances are open; so we just have to # operate on all Viewports for a given usd_context. import omni.kit.viewport_legacy as vp vpi = vp.acquire_viewport_interface() for instance in vpi.get_instance_list(): window = vpi.get_viewport_window(instance) if not window: continue focused_windows.append(window) if focused_windows: self._focused_windows = focused_windows for window in self._focused_windows: # Disable the selection_rect, but enable_picking for snapping window.disable_selection_rect(True) except Exception: pass class _DragPrioritize(sc.GestureManager): """Refuses preventing _DragGesture.""" def can_be_prevented(self, gesture): # Never prevent in the middle of drag return gesture.state != sc.GestureState.CHANGED def should_prevent(self, gesture, preventer): if preventer.state == sc.GestureState.BEGAN or preventer.state == sc.GestureState.CHANGED: return True class _DragGesture(sc.DragGesture): """"Gesture to disable rectangle selection in the viewport legacy""" def __init__(self): super().__init__(manager=_DragPrioritize()) def on_began(self): # When the user drags the slider, we don't want to see the selection # rect. In Viewport Next, it works well automatically because the # selection rect is a manipulator with its gesture, and we add the # slider manipulator to the same SceneView. # In Viewport Legacy, the selection rect is not a manipulator. Thus it's # not disabled automatically, and we need to disable it with the code. self.__disable_selection = _ViewportLegacyDisableSelection() def on_ended(self): # This re-enables the selection in the Viewport Legacy self.__disable_selection = None class WidgetInfoManipulator(sc.Manipulator): def __init__(self, **kwargs): super().__init__(**kwargs) self.destroy() self._radius = 2 self._distance_to_top = 5 self._thickness = 2 self._radius_hovered = 20 def destroy(self): self._root = None self._slider_subscription = None self._slider_model = None self._name_label = None def _on_build_widgets(self): with ui.ZStack(): ui.Rectangle( style={ "background_color": cl(0.2), "border_color": cl(0.7), "border_width": 2, "border_radius": 4, } ) with ui.VStack(style={"font_size": 24}): ui.Spacer(height=4) with ui.ZStack(style={"margin": 1}, height=30): ui.Rectangle( style={ "background_color": cl(0.0), } ) ui.Line(style={"color": cl(0.7), "border_width": 2}, alignment=ui.Alignment.BOTTOM) ui.Label("Hello world, I am a scene.Widget!", height=0, alignment=ui.Alignment.CENTER) ui.Spacer(height=4) self._name_label = ui.Label("", height=0, alignment=ui.Alignment.CENTER) # setup some model, just for simple demonstration here self._slider_model = ui.SimpleFloatModel() ui.Spacer(height=10) with ui.HStack(): ui.Spacer(width=10) ui.Label("scale", height=0, width=0) ui.Spacer(width=5) ui.FloatSlider(self._slider_model) ui.Spacer(width=10) ui.Spacer(height=4) ui.Spacer() self.on_model_updated(None) # Additional gesture that prevents Viewport Legacy selection self._widget.gestures += [_DragGesture()] def on_build(self): """Called when the model is chenged and rebuilds the whole slider""" self._root = sc.Transform(visible=False) with self._root: with sc.Transform(scale_to=sc.Space.SCREEN): with sc.Transform(transform=sc.Matrix44.get_translation_matrix(0, 100, 0)): # Label with sc.Transform(look_at=sc.Transform.LookAt.CAMERA): self._widget = sc.Widget(500, 150, update_policy=sc.Widget.UpdatePolicy.ON_MOUSE_HOVERED) self._widget.frame.set_build_fn(self._on_build_widgets) def on_model_updated(self, _): # if we don't have selection then show nothing if not self.model or not self.model.get_item("name"): self._root.visible = False return # Update the shapes position = self.model.get_as_floats(self.model.get_item("position")) if self._root: self._root.transform = sc.Matrix44.get_translation_matrix(*position) self._root.visible = True ## Step 6.2 Start ## # Update the slider def update_scale(prim_name, value): if value <= 0: value = 0.01 print(f"changing scale of {prim_name}, {value}") if self._slider_model: self._slider_subscription = None self._slider_model.as_float = 1.0 self._slider_subscription = self._slider_model.subscribe_value_changed_fn( lambda m, p=self.model.get_item("name"): update_scale(p, m.as_float) ) # Update the shape name if self._name_label: self._name_label.text = f"Prim:{self.model.get_item('name')}"
6,755
Python
37.827586
117
0.579867
NVIDIA-Omniverse/kit-workshop-siggraph2022/exts/omni.example.ui_scene.manipulator_tool/omni/example/ui_scene/manipulator_tool/widget_info_extension.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__ = ["WidgetInfoExtension"] from .widget_info_scene import WidgetInfoScene from omni.kit.viewport.utility import get_active_viewport_window import carb import omni.ext class WidgetInfoExtension(omni.ext.IExt): """The entry point to the extension""" def on_startup(self, ext_id): # Get the active (which at startup is the default Viewport) viewport_window = get_active_viewport_window() # Issue an error if there is no Viewport if not viewport_window: carb.log_warn(f"No Viewport Window to add {ext_id} scene to") self._widget_info_viewport = None return # Build out the scene self._widget_info_viewport = WidgetInfoScene(viewport_window, ext_id) def on_shutdown(self): if self._widget_info_viewport: self._widget_info_viewport.destroy() self._widget_info_viewport = None
1,340
Python
35.243242
77
0.706716
NVIDIA-Omniverse/kit-workshop-siggraph2022/exts/omni.example.ui_scene.manipulator_tool/omni/example/ui_scene/manipulator_tool/__init__.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__ = ["WidgetInfoExtension"] from .widget_info_extension import WidgetInfoExtension
518
Python
42.249996
76
0.803089
NVIDIA-Omniverse/kit-workshop-siggraph2022/exts/omni.example.ui_scene.manipulator_tool/omni/example/ui_scene/manipulator_tool/widget_info_scene.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__ = ["WidgetInfoScene"] import omni.ui as ui from omni.ui import scene as sc from .widget_info_model import WidgetInfoModel from .widget_info_manipulator import WidgetInfoManipulator class WidgetInfoScene(): """The Object Info Manupulator, placed into a Viewport""" def __init__(self, viewport_window, ext_id: str): self._scene_view = None self._viewport_window = viewport_window # Create a unique frame for our SceneView with self._viewport_window.get_frame(ext_id): # Create a default SceneView (it has a default camera-model) self._scene_view = sc.SceneView() # Add the manipulator into the SceneView's scene with self._scene_view.scene: WidgetInfoManipulator(model=WidgetInfoModel()) # Register the SceneView with the Viewport to get projection and view updates self._viewport_window.viewport_api.add_scene_view(self._scene_view) def __del__(self): self.destroy() def destroy(self): if self._scene_view: # Empty the SceneView of any elements it may have self._scene_view.scene.clear() # Be a good citizen, and un-register the SceneView from Viewport updates if self._viewport_window: self._viewport_window.viewport_api.remove_scene_view(self._scene_view) # Remove our references to these objects self._viewport_window = None self._scene_view = None
1,936
Python
38.530611
89
0.681818
NVIDIA-Omniverse/kit-workshop-siggraph2022/exts/omni.example.ui_scene.manipulator_tool/omni/example/ui_scene/manipulator_tool/widget_info_model.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__ = ["WidgetInfoModel"] from omni.ui import scene as sc from pxr import UsdGeom from pxr import Usd from pxr import UsdShade from pxr import Tf from pxr import UsdLux import omni.usd import omni.kit.commands class WidgetInfoModel(sc.AbstractManipulatorModel): """ User part. The model tracks the position and info of the selected object. """ class PositionItem(sc.AbstractManipulatorItem): """ The Model Item represents the position. It doesn't contain anything because because we take the position directly from USD when requesting. """ def __init__(self): super().__init__() self.value = [0, 0, 0] class ValueItem(sc.AbstractManipulatorItem): """The Model Item contains a single float value about some attibute""" def __init__(self, value=0): super().__init__() self.value = [value] def __init__(self): super().__init__() self.material_name = "" self.position = WidgetInfoModel.PositionItem() # The distance from the bounding box to the position the model returns self._offset = 0 # Current selection self._prim = None self._current_path = "" self._stage_listener = None # Save the UsdContext name (we currently only work with single Context) self._usd_context_name = '' self.usd_context = self._get_context() # Track selection self._events = self.usd_context.get_stage_event_stream() self._stage_event_sub = self._events.create_subscription_to_pop( self._on_stage_event, name="Object Info Selection Update" ) def _get_context(self) -> Usd.Stage: # Get the UsdContext we are attached to return omni.usd.get_context(self._usd_context_name) def _notice_changed(self, notice, stage): """Called by Tf.Notice""" for p in notice.GetChangedInfoOnlyPaths(): if self._current_path in str(p.GetPrimPath()): self._item_changed(self.position) def get_item(self, identifier): if identifier == "position": return self.position if identifier == "name": return self._current_path if identifier == "material": return self.material_name def get_as_floats(self, item): if item == self.position: # Requesting position return self._get_position() if item: # Get the value directly from the item return item.value return [] def set_floats(self, item, value): if not self._current_path: return if not value or not item or item.value == value: return # Set directly to the item item.value = value # This makes the manipulator updated self._item_changed(item) def _on_stage_event(self, event): """Called by stage_event_stream""" if event.type == int(omni.usd.StageEventType.SELECTION_CHANGED): self._on_kit_selection_changed() def _on_kit_selection_changed(self): # selection change, reset it for now self._current_path = "" usd_context = self._get_context() stage = usd_context.get_stage() if not stage: return prim_paths = usd_context.get_selection().get_selected_prim_paths() if not prim_paths: self._item_changed(self.position) # Revoke the Tf.Notice listener, we don't need to update anything if self._stage_listener: self._stage_listener.Revoke() self._stage_listener = None return prim = stage.GetPrimAtPath(prim_paths[0]) if prim.IsA(UsdLux.Light): print("Light") self.material_name = "I am a Light" elif prim.IsA(UsdGeom.Imageable): material, relationship = UsdShade.MaterialBindingAPI(prim).ComputeBoundMaterial() if material: self.material_name = str(material.GetPath()) else: self.material_name = "N/A" else: self._prim = None return self._prim = prim self._current_path = prim_paths[0] # Add a Tf.Notice listener to update the position if not self._stage_listener: self._stage_listener = Tf.Notice.Register(Usd.Notice.ObjectsChanged, self._notice_changed, stage) (old_scale, old_rotation_euler, old_rotation_order, old_translation) = omni.usd.get_local_transform_SRT(prim) # Position is changed self._item_changed(self.position) def _get_position(self): """Returns position of currently selected object""" stage = self._get_context().get_stage() if not stage or not self._current_path: return [0, 0, 0] # Get position directly from USD prim = stage.GetPrimAtPath(self._current_path) box_cache = UsdGeom.BBoxCache(Usd.TimeCode.Default(), includedPurposes=[UsdGeom.Tokens.default_]) bound = box_cache.ComputeWorldBound(prim) range = bound.ComputeAlignedBox() bboxMin = range.GetMin() bboxMax = range.GetMax() position = [(bboxMin[0] + bboxMax[0]) * 0.5, bboxMax[1] + self._offset, (bboxMin[2] + bboxMax[2]) * 0.5] return position
5,849
Python
33.011628
117
0.612241
NVIDIA-Omniverse/kit-workshop-siggraph2022/exts/omni.example.ui_scene.manipulator_tool/omni/example/ui_scene/manipulator_tool/tests/test_info.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__ = ["TestInfo"] from omni.example.ui_scene.widget_info.widget_info_manipulator import WidgetInfoManipulator from omni.ui import scene as sc 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 WidgetInfoTestModelItem(sc.AbstractManipulatorItem): pass class WidgetInfoTestModel(sc.AbstractManipulatorModel): def __init__(self): super().__init__() self.position = WidgetInfoTestModelItem() def get_item(self, identifier): if identifier == "position": return self.position if identifier == "name": return "Name" if identifier == "material": return "Material" def get_as_floats(self, item): if item == self.position: return [0, 0, 0] class TestInfo(OmniUiTest): async def test_general(self): """Testing general look of the item""" window = await self.create_test_window(width=256, height=256) with window.frame: # Camera matrices projection = [1e-2, 0, 0, 0] projection += [0, 1e-2, 0, 0] projection += [0, 0, -2e-7, 0] projection += [0, 0, 1, 1] view = sc.Matrix44.get_translation_matrix(0, 0, 0) scene_view = sc.SceneView(sc.CameraModel(projection, view)) with scene_view.scene: # The manipulator model = WidgetInfoTestModel() WidgetInfoManipulator(model=model) await omni.kit.app.get_app().next_update_async() model._item_changed(None) for _ in range(10): await omni.kit.app.get_app().next_update_async() await self.finalize_test(threshold=100, golden_img_dir=TEST_DATA_PATH, golden_img_name="general.png")
2,430
Python
32.763888
115
0.653909
NVIDIA-Omniverse/kit-workshop-siggraph2022/exts/omni.example.ui_scene.manipulator_tool/omni/example/ui_scene/manipulator_tool/tests/__init__.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. # from .test_info import TestInfo
459
Python
50.111106
76
0.810458
NVIDIA-Omniverse/kit-workshop-siggraph2022/exts/omni.example.ui_scene.manipulator_tool/docs/CHANGELOG.md
# Changelog omni.ui.scene.object_info ## [1.0.1] - 2022-06-01 ### Changed - It doesn't recreate sc.Widget to avoid crash ## [1.0.0] - 2022-5-1 ### Added - The initial version
178
Markdown
13.916666
46
0.646067
NVIDIA-Omniverse/kit-workshop-siggraph2022/exts/omni.example.ui_scene.manipulator_tool/docs/README.md
# Widget Info (omni.example.ui_scene.widget_info) ![](https://github.com/NVIDIA-Omniverse/kit-extension-sample-ui-scene/raw/main/exts/omni.example.ui_scene.widget_info/data/preview.png) ​ ## Overview In the example, we show how to leverage `ui.scene.Widget` item to create a `ui.Widget` that is in 3D space. The Widget can have any type of `omni.ui` element, including being interactive, as shown with the slider. ​ ## [Tutorial](https://github.com/NVIDIA-Omniverse/kit-extension-sample-ui-scene/blob/main/exts/omni.example.ui_scene.widget_info/Tutorial/object.info.widget.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. In the tutorial you will learn how to build from existing modules to create a Widget. A Widget is a useful utility in `Omniverse Kit` that can be used to add features such as buttons and sliders. ​[Get started with the tutorial here.](https://github.com/NVIDIA-Omniverse/kit-extension-sample-ui-scene/blob/main/exts/omni.example.ui_scene.widget_info/Tutorial/object.info.widget.tutorial.md) ## Usage Once the extension is enabled in the `Extension Manager`, go to your `Viewport` and right-click to create a primitive - such as a cube, sphere, cyclinder, etc. Then, left-click/select the primitive to view the Object Info. The Path and Type of the Object will be displayed inside of a Widget. ​ ## The extension showcases view concepts Similarly to the other `ui.scene` example it shows you how to set up the viewport scene in `viewport_scene.py`. Then there is the Manipulator object that manages the presentation of the item `widget_info_manipulator.py`. Finally, the `widget_info_model.py` contains the model that connects the world with the manipulator. ## Overlaying with the viewport We use `sc.Manipulator` with `sc.Widget` to draw `omni.ui` widgets in 3D view. To show it in the viewport, we overlay `sc.SceneView` with our `sc.Manipulator` on top of the viewport window. ```python from omni.kit.viewport.utility import get_active_viewport_window viewport_window = get_active_viewport_window() # Create a unique frame for our SceneView with viewport_window.get_frame(ext_id): # Create a default SceneView (it has a default camera-model) self._scene_view = sc.SceneView() # Add the manipulator into the SceneView's scene with self._scene_view.scene: WidgetInfoManipulator(model=WidgetInfoModel()) ``` To synchronize the projection and view matrices, `omni.kit.viewport.utility` has the method `add_scene_view`, which replaces the camera model, and the manipulator visually looks like it's in the main viewport. ```python # Register the SceneView with the Viewport to get projection and view updates viewport_window.viewport_api.add_scene_view(self._scene_view) ```
2,840
Markdown
47.982758
292
0.772183
NVIDIA-Omniverse/kit-workshop-siggraph2022/exts/omni.example.ui_scene.manipulator_tool/docs/index.rst
omni.example.ui_scene.widget_info ######################################## Example of Python only extension .. toctree:: :maxdepth: 1 README CHANGELOG
164
reStructuredText
12.749999
40
0.530488
NVIDIA-Omniverse/deep-dive-into-microservices/README.md
# Companion Code to *A Deep Dive into Building Microservices with Omniverse* This companion code project contains the resources developed during the [*Deep Dive into Building Microservices with Omniverse*](https://www.nvidia.com/en-us/on-demand/session/gtcfall21-a31204/) session presented during GTC November 2021. While there is no better way to learn that to jump in an try writing your own microservice from the sample template for Kit extensions, we also know that having an example to get started can be a valuable resource. Our hope is that these sample extensions, along with the background information of the GTC session, will fast-forward you on your development journey in Omniverse. [![Deep Dive into Building Microservices with Omniverse GTC 2021](./docs/deep-dive-into-microservices-with-omniverse-session-poster.jpg)](https://www.nvidia.com/en-us/on-demand/session/gtcfall21-a31204/) Let us know about what this inspired you to create! [We'd love to hear from you!](https://forums.developer.nvidia.com/c/omniverse/showcase/362) ## About This project contains the 2 extensions created during the conversation on microservices, which serve as a demonstration of the flexibility of this architecture. Using the example of a 3D asset pipeline, these extensions illustrate the scalability and reusability of loosely coupled components by: 1. **Creating a microservice to validate conformity of a USD scene.** This illustrates how a studio may scale and distribute automated tasks, allowing creators to focus on doing what they excel at, and relieve them from manual tasks. 2. **Exposing a microservice to convert 3D assets from one format to another.** Independently from the previous microservice, this service can be configured to be as broad or as narrow as necessary to adapt to the needs a studio may have. Separate teams could even reuse and deploy the microservice to serve their unique needs: while artists may need UI integrated into their favorite content creation tools, pipeline developers may also automate the batch import of content shared by partners. 3. **Assembling both services together and recording the status of conversion tasks.** By storing the result of conversion tasks in a database, one can imagine evolving this simple pipeline into an automated system exposing a dashboard where artists could monitor the status of their conversions tasks processing in the background, or adding features such as notifications when a task is completed. ## Configuration To get started: 1. Download a copy of this repository to your machine. 2. From the [Omniverse Launcher](https://www.nvidia.com/en-us/omniverse), download *Create* and *Farm Queue*. To load this project in *Create* (or any *Omniverse Kit*-based application such as *View*, *Machinima* or *Isaac Sim*), add a link from this repository to the application using the provided `link_app` script: **On Windows:** ```batch link_app.bat C:/Users/<username>/AppData/Local/ov/pkg/create-2021.3.7 ``` **On Linux:** ```bash ./link_app.sh ~/.local/share/ov/pkg/create-2021.3.7 ``` If the operation completed successfully, an *./app* folder should appear, linking the root of this repository to the install location of the Kit-based application from the Omniverse Launcher. ## Executing the sample Once configured, this sample project can be executed by launching an instance of Create or any Kit-based application, and submitting a task to the endpoint exposed by the `omni.service.assets.convert` service. **On Windows:** ```batch REM Launch Create, with the extension enabled: app/omni.create.bat ^ --ext-folder C:\Users\<username>\AppData\Local\ov\pkg\farm-queue-102.1.0\exts-farm-queue ^ --ext-folder ./exts ^ --enable omni.services.assets.convert ``` **On Linux:** ```shell # Launch Create, with the extension enabled: ./app/omni.create.sh \ --ext-folder ~/.local/share/ov/pkg/farm-queue-102.1.0/exts-farm-queue \ --ext-folder ./exts \ --enable omni.services.assets.convert ``` Once the application is launched, a conversion task can be submitted to the service by using the web interface listing all the exposed microservices. This interactive interface is exposed at the following location: * For *Kit*: http://localhost:8011/docs * For *Create*: http://localhost:8111/docs * For *Isaac Sim*: http://localhost:8211/docs ## Additional resources * [Presentation slides](https://drive.google.com/file/d/1lThTzjQqnGOgVE6GddwKhsl_f4f1vVsm/view?usp=sharing) * [NVIDIA Omniverse Platform](https://developer.nvidia.com/nvidia-omniverse-platform) * [NVIDIA Omniverse Developer Resource Center](https://developer.nvidia.com/nvidia-omniverse-developer-resource-center) * *Getting started* documentation: * [NVIDIA Omniverse Microservices](https://docs.omniverse.nvidia.com/services) * [NVIDIA Omniverse Farm](https://docs.omniverse.nvidia.com/farm)
4,887
Markdown
64.173332
495
0.777369
NVIDIA-Omniverse/deep-dive-into-microservices/tools/scripts/link_app.py
# Copyright (c) 2021, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. import argparse import os import packmanapi if __name__ == "__main__": parser = argparse.ArgumentParser(description="Create folder link to Kit App installed from Omniverse Launcher.") parser.add_argument( "path", help="Path to Kit App installed from Omniverse Launcher, e.g.: 'C:/Users/bob/AppData/Local/ov/pkg/create-2021.3.4'", ) args = parser.parse_args() if not os.path.exists(args.path): print(f"Provided path doesn't exist: \"{args.path}\"") else: SCRIPT_ROOT = os.path.dirname(os.path.realpath(__file__)) packmanapi.link(f"{SCRIPT_ROOT}/../../app", args.path)
1,062
Python
36.964284
124
0.711864
NVIDIA-Omniverse/deep-dive-into-microservices/tools/packman/config.packman.xml
<config remotes="cloudfront"> <remote2 name="cloudfront"> <transport actions="download" protocol="https" packageLocation="d4i3qtqj3r0z5.cloudfront.net/${name}@${version}" /> </remote2> </config>
211
XML
34.333328
123
0.691943
NVIDIA-Omniverse/deep-dive-into-microservices/tools/packman/bootstrap/install_package.py
# Copyright 2019 NVIDIA CORPORATION # 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 logging import zipfile import tempfile import sys import shutil __author__ = "hfannar" logging.basicConfig(level=logging.WARNING, format="%(message)s") logger = logging.getLogger("install_package") class TemporaryDirectory: def __init__(self): self.path = None def __enter__(self): self.path = tempfile.mkdtemp() return self.path def __exit__(self, type, value, traceback): # Remove temporary data created shutil.rmtree(self.path) def install_package(package_src_path, package_dst_path): with zipfile.ZipFile( package_src_path, allowZip64=True ) as zip_file, TemporaryDirectory() as temp_dir: zip_file.extractall(temp_dir) # Recursively copy (temp_dir will be automatically cleaned up on exit) try: # Recursive copy is needed because both package name and version folder could be missing in # target directory: shutil.copytree(temp_dir, package_dst_path) except OSError as exc: logger.warning( "Directory %s already present, packaged installation aborted" % package_dst_path ) else: logger.info("Package successfully installed to %s" % package_dst_path) install_package(sys.argv[1], sys.argv[2])
1,888
Python
31.568965
103
0.68697
NVIDIA-Omniverse/deep-dive-into-microservices/exts/omni.services.assets.convert/config/extension.toml
[package] version = "1.0.0" title = "Asset conversion service" description = "A simple demonstration of an asset conversion microservice." authors = ["Omniverse Kit Team"] preview_image = "data/preview_image.png" readme = "docs/README.md" changelog = "docs/CHANGELOG.md" repository = "" category = "Example" keywords = ["kit", "service", "asset", "conversion", "example"] [dependencies] "omni.client" = {} "omni.kit.asset_converter" = {} "omni.kit.pip_archive" = {} "omni.services.assets.validate" = {} "omni.services.core" = {} "omni.services.facilities.database.manager" = {} # The main Python module this extension provides, it will be publicly available as # "import omni.services.assets.convert": [[python.module]] name = "omni.services.assets.convert" [settings.exts."omni.services.assets.convert"] # URL prefix where the conversion service will be mounted: url_prefix = "/assets" # Database settings, using an SQLite database for demonstration purposes: [settings.exts."omni.services.assets.convert".dbs.asset-conversions] connection_string = "sqlite:///${data}/asset-conversions.db"
1,095
TOML
32.21212
82
0.73516
NVIDIA-Omniverse/deep-dive-into-microservices/exts/omni.services.assets.convert/omni/services/assets/convert/extension.py
# Copyright (c) 2021, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. import asyncio import carb import omni.ext from omni.services.core import main from omni.services.facilities.database.manager import DatabaseManagerFacility from .services import router class AssetConversionServiceExtension(omni.ext.IExt): """Asset conversion extension.""" def on_startup(self, ext_id) -> None: ext_name = ext_id.split("-")[0] url_prefix = carb.settings.get_settings_interface().get(f"exts/{ext_name}/url_prefix") # Setup the database facility: self._database_facility = DatabaseManagerFacility(ext_name=ext_name) self._db_ready = asyncio.ensure_future(self._initialize_db()) # Register the database facility with the router, so it can be used by service endpoints: router.register_facility("db_manager", self._database_facility) main.register_router(router=router, prefix=url_prefix, tags=["Assets"]) main.get_app().title = "Omniverse Farm" main.get_app().description = "A microservice-based framework for distributed task execution." tags_metadata = { "name": "Assets", "description": "Manage assets submitted to the Queue." } if not main.get_app().openapi_tags: main.get_app().openapi_tags = [] main.get_app().openapi_tags.append(tags_metadata) def on_shutdown(self) -> None: if self._db_ready: self._db_ready.cancel() self._db_ready = None main.deregister_router(router=router) async def _initialize_db(self) -> None: """Initialize the database to be used to store asset conversion results.""" async with self._database_facility.get("asset-conversions") as db: table_columns = [ "id INTEGER PRIMARY KEY AUTOINCREMENT", "source_asset VARCHAR(256) NOT NULL", "destination_asset VARCHAR(256) NOT NULL", "success BOOLEAN NOT NULL", ] await db.execute(query=f"CREATE TABLE IF NOT EXISTS AssetConversions ({', '.join(table_columns)});")
2,511
Python
39.516128
112
0.66826
NVIDIA-Omniverse/deep-dive-into-microservices/exts/omni.services.assets.convert/omni/services/assets/convert/__init__.py
# Copyright (c) 2021, 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. from .extension import *
452
Python
44.299996
76
0.807522
NVIDIA-Omniverse/deep-dive-into-microservices/exts/omni.services.assets.convert/omni/services/assets/convert/services/__init__.py
# Copyright (c) 2021, 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. from .convert import *
450
Python
44.099996
76
0.806667
NVIDIA-Omniverse/deep-dive-into-microservices/exts/omni.services.assets.convert/omni/services/assets/convert/services/convert.py
# Copyright (c) 2021, 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. from typing import Dict from pydantic import BaseModel, Field from omni.services.client import AsyncClient from omni.services.core import routers import omni.usd router = routers.ServiceAPIRouter() class ConversionRequestModel(BaseModel): """Model describing the request to convert a given asset to a different format.""" import_path: str = Field( ..., title="Path of the source asset to be converted", description="Location where the asset to convert can be located by an Agent.", ) output_path: str = Field( ..., title="Output path where to store the converted asset", description="Location where to place the converted asset.", ) converter_settings: Dict = Field( {}, title="Converter settings", description="Settings to provide to the Kit Asset Converter extension in order to perform the conversion.", ) class ConversionResponseModel(BaseModel): """Model describing the response to the request to convert a given USD asset.""" status: str = Field( ..., title="Conversion status", description="Status of the conversion of the given asset.", ) @router.post( path="/convert", summary="Convert assets to a different format", description="Convert the given asset into a different format.", response_model=ConversionResponseModel, ) @router.post("/convert") async def run( req: ConversionRequestModel, db_manager=router.get_facility("db_manager"), ) -> ConversionResponseModel: # Convert the given asset: task = omni.kit.asset_converter.get_instance().create_converter_task( import_path=req.import_path, output_path=req.output_path, progress_callback=lambda current, total: print(f"Conversion progress: {current/total*100.0}%"), asset_converter_context=req.converter_settings,) success = await task.wait_until_finished() if not success: detailed_status_code = task.get_status() detailed_status_error_string = task.get_detailed_error() raise Exception(f"Failed to convert \"{req.import_path}\". Error: {detailed_status_code}, {detailed_status_error_string}") # Execute the validation service exposed by the "omni.service.assets.validate" extension: client = AsyncClient("local://") validation_result = await client.assets.validate( scene_path=req.import_path, expected_camera_count=5, ) # Record the result of the validation in the database: query = """ INSERT INTO AssetConversions (source_asset, destination_asset, success) VALUES (:source_asset, :destination_asset, :success) """ values = { "source_asset": req.import_path, "destination_asset": req.output_path, "success": 1 if validation_result["success"] else 0, } async with db_manager.get("asset-conversions") as db: await db.execute(query=query, values=values) return ConversionResponseModel(status="finished")
3,449
Python
35.315789
130
0.696724
NVIDIA-Omniverse/deep-dive-into-microservices/exts/omni.services.assets.convert/docs/CHANGELOG.md
# Changelog All notable changes to this project will be documented in this file. The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/), and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). ## [1.0.0] - 2021-11-10 ### Added - Initial release for GTC November 2021.
328
Markdown
31.899997
168
0.728659
NVIDIA-Omniverse/deep-dive-into-microservices/exts/omni.services.assets.convert/docs/README.md
# Asset Conversion Service [omni.services.assets.convert] ## About A simple extension demonstrating writing a microservice to convert assets using Omniverse Kit-based applications. ## Usage Once enabled, the extension will expose a `/assets/convert` service endpoint, which can be explored from the list of available microservice endpoints exposed by the application: * For *Kit*: http://localhost:8011/docs * For *Create*: http://localhost:8111/docs * For *Isaac Sim*: http://localhost:8211/docs ## Running the extension To enable and execute the extension, from the root of the repository: **On Windows:** ```batch REM Link the extension against a Kit-based application from the Launcher: link_app.bat C:/Users/<username>/AppData/Local/ov/pkg/create-2021.3.7 REM Launch Create, with the extension enabled: app/omni.create.bat ^ --ext-folder C:\Users\<username>\AppData\Local\ov\pkg\farm-queue-102.1.0\exts-farm-queue ^ --ext-folder ./exts ^ --enable omni.services.assets.convert ``` **On Linux:** ```shell # Link the extension against a Kit-based application from the Launcher: ./link_app.sh ~/.local/share/ov/pkg/create-2021.3.7 # Launch Create, with the extension enabled: ./app/omni.create.sh \ --ext-folder ~/.local/share/ov/pkg/farm-queue-102.1.0/exts-farm-queue \ --ext-folder ./exts \ --enable omni.services.assets.convert ``` To launch this small demo pipeline, all that remains is integrating some UI components to let Users submit tasks to the service, or start one from the command-line: ```shell curl -X 'POST' \ 'http://localhost:8011/assets/convert' \ -H 'Accept: application/json' \ -H 'Content-Type: application/json' \ -d '{ "import_path": "/full/path/to/source_content.usd", "output_path": "/full/path/to/destination_content.obj", "converter_settings": {} }' ```
1,836
Markdown
32.399999
177
0.724401
NVIDIA-Omniverse/deep-dive-into-microservices/exts/omni.services.assets.validate/config/extension.toml
[package] version = "1.0.0" title = "Asset validation service" description = "A simple demonstration of an asset validation microservice." authors = ["Omniverse Kit Team"] preview_image = "data/preview_image.png" readme = "docs/README.md" changelog = "docs/CHANGELOG.md" repository = "" category = "Example" keywords = ["kit", "service", "asset", "validation", "example"] [dependencies] "omni.services.core" = {} "omni.usd" = {} # The main Python module this extension provides, it will be publicly available as # "import omni.services.assets.validate": [[python.module]] name = "omni.services.assets.validate" [settings.exts."omni.services.assets.validate"] # URL prefix where the validation service will be mounted: url_prefix = "/assets"
744
TOML
28.799999
82
0.729839