file_path
stringlengths
21
202
content
stringlengths
13
1.02M
size
int64
13
1.02M
lang
stringclasses
9 values
avg_line_length
float64
5.43
98.5
max_line_length
int64
12
993
alphanum_fraction
float64
0.27
0.91
NVIDIA-Omniverse/OpenUSD-Code-Samples/CONTRIBUTING.md
## OpenUSD Code Samples OSS Contribution Rules #### Issue Tracking * All enhancement, bugfix, or change requests must begin with the creation of a [OpenUSD Code Samples Issue Request](https://github.com/NVIDIA-Omniverse/OpenUSD-Code-Samples/issues). * The issue request must be reviewed by OpenUSD Code Samples engineers and approved prior to code review. #### Coding Guidelines - All source code contributions must strictly adhere to the [OpenUSD Code Samples Guidelines](CODE-SAMPLE-GUIDELINES.md). - In addition, please follow the existing conventions in the relevant file, submodule, module, and project when you add new code or when you extend/fix existing functionality. - Avoid introducing unnecessary complexity into existing code so that maintainability and readability are preserved. - All development should happen against the "main" branch of the repository. Please make sure the base branch of your pull request is set to the "main" branch when filing your pull request. - Try to keep pull requests (PRs) as concise as possible: - Avoid committing commented-out code. - Wherever possible, each PR should address a single concern. If there are several otherwise-unrelated things that should be fixed to reach a desired endpoint, our recommendation is to open several PRs and indicate the dependencies in the description. The more complex the changes are in a single PR, the more time it will take to review those changes. - Write commit titles using imperative mood and [these rules](https://chris.beams.io/posts/git-commit/), and reference the Issue number corresponding to the PR. Following is the recommended format for commit texts: ``` Issue #<Issue Number> - <Commit Title> <Commit Body> ``` - Ensure that the Sphinx build log is clean, meaning no warnings or errors should be present. - Ensure that all code blocks execute correctly prior to submitting your code. - All OSS components must contain accompanying documentation (READMEs) describing the functionality, dependencies, and known issues. - See `README.md` for existing samples and plugins for reference. - All OSS components must have an accompanying test. - If introducing a new component, such as a plugin, provide a test sample to verify the functionality. - Make sure that you can contribute your work to open source (no license and/or patent conflict is introduced by your code). You will need to [`sign`](#signing-your-work) your commit. - Thanks in advance for your patience as we review your contributions; we do appreciate them! #### Pull Requests Developer workflow for code contributions is as follows: 1. Developers must first [fork](https://help.github.com/en/articles/fork-a-repo) the [upstream](https://github.com/NVIDIA-Omniverse/OpenUSD-Code-Samples) OpenUSD Code Samples repository. 2. Git clone the forked repository. ```bash git clone https://github.com/YOUR_USERNAME/YOUR_FORK.git OpenUSD-Code-Samples ``` 3. Create a branch off of the "main" branch and commit changes. See [Coding Guidelines](#coding-guidelines) for commit formatting rules. ```bash # Create a branch off of the "main" branch git checkout -b <local-branch> <remote-branch> git add <path-to-files> # -s flag will "sign-off" on your commit, we require all contributors to sign-off on their commits. See below for more git commit -s -m "Issue #<Issue Number> - <Commit Title>" ``` 4. Push Changes to the personal fork. ```bash # Push the commits to a branch on the fork (remote). git push -u origin <local-branch>:<remote-branch> ``` 5. Please make sure that your pull requests are clean. Use the rebase and squash git facilities as needed to ensure that the pull request is as clean as possible. 6. Once the code changes are staged on the fork and ready for review, a [Pull Request](https://help.github.com/en/articles/about-pull-requests) (PR) can be [requested](https://help.github.com/en/articles/creating-a-pull-request) to merge the changes from your branch to the upstream "main" branch. * Exercise caution when selecting the source and target branches for the PR. * Creation of a PR creation kicks off the code review process. * At least one OpenUSD Code Samples engineer will be assigned for the review. * While under review, mark your PRs as work-in-progress by prefixing the PR title with [WIP]. 7. Since there is no CI/CD process in place yet, the PR will be accepted and the corresponding issue closed only after adequate testing has been completed, manually, by the developer and/or OpenUSD Code Samples engineer reviewing the code. #### Signing Your Work * We require that all contributors "sign-off" on their commits. This certifies that the contribution is your original work, or you have rights to submit it under the same license, or a compatible license. * Any contribution which contains commits that are not Signed-Off will not be accepted. * To sign off on a commit you simply use the `--signoff` (or `-s`) option when committing your changes: ```bash $ git commit -s -m "Add cool feature." ``` This will append the following to your commit message: ``` Signed-off-by: Your Name <[email protected]> ``` * Full text of the DCO: ``` Developer Certificate of Origin Version 1.1 Copyright (C) 2004, 2006 The Linux Foundation and its contributors. Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. Developer's Certificate of Origin 1.1 By making a contribution to this project, I certify that: (a) The contribution was created in whole or in part by me and I have the right to submit it under the open source license indicated in the file; or (b) The contribution is based upon previous work that, to the best of my knowledge, is covered under an appropriate open source license and I have the right under that license to submit that work with modifications, whether created in whole or in part by me, under the same open source license (unless I am permitted to submit under a different license), as indicated in the file; or (c) The contribution was provided directly to me by some other person who certified (a), (b) or (c) and I have not modified it. (d) I understand and agree that this project and the contribution are public and that a record of the contribution (including all personal information I submit with it, including my sign-off) is maintained indefinitely and may be redistributed consistent with this project or the open source license(s) involved. ```
6,676
Markdown
48.095588
354
0.75
NVIDIA-Omniverse/OpenUSD-Code-Samples/build_docs.py
# SPDX-FileCopyrightText: Copyright (c) 2023 NVIDIA CORPORATION & AFFILIATES. All rights reserved. # SPDX-License-Identifier: Apache-2.0 import argparse import logging import os from pathlib import Path import shutil from rstcloth import RstCloth import sphinx.cmd.build import toml REPO_ROOT = Path(__file__).parent SOURCE_DIR = REPO_ROOT / "source" SPHINX_DIR = REPO_ROOT / "sphinx" SPHINX_CODE_SAMPLES_DIR = SPHINX_DIR / "usd" # 0 = normal toctree, 1 = :doc: tags TOCTREE_STYLE = 0 REPLACE_USDA_EXT = True STRIP_COPYRIGHTS = True IMAGE_TYPES = {".jpg" , ".gif"} logger = logging.getLogger(__name__) def main(): # flush build dir if os.path.exists(SPHINX_CODE_SAMPLES_DIR): shutil.rmtree(SPHINX_CODE_SAMPLES_DIR) SPHINX_CODE_SAMPLES_DIR.mkdir(exist_ok=False) samples = {} # each config.toml should be a sample for config_file in SOURCE_DIR.rglob("config.toml"): category_name = config_file.parent.parent.name sample_name = config_file.parent.name if category_name not in samples: samples[category_name] = [] logger.info(f"processing: {sample_name}") sample_source_dir = config_file.parent sample_output_dir = SPHINX_CODE_SAMPLES_DIR / sample_source_dir.parent.relative_to(SOURCE_DIR) / f"{sample_name}" # make sure category dir exists category_output_dir = SPHINX_CODE_SAMPLES_DIR / sample_source_dir.parent.relative_to(SOURCE_DIR) if not os.path.exists(category_output_dir): category_output_dir.mkdir(exist_ok=False) sample_rst_out = category_output_dir / f"{sample_name}.rst" with open(config_file) as f: content = f.read() config = toml.loads(content) title = config["core"]["title"] samples[category_name].append([sample_name, title]) sample_output_dir.mkdir(exist_ok=True) with open(sample_rst_out, "w") as f: doc = RstCloth(f) if TOCTREE_STYLE == 1: doc._add(":orphan:") doc.newline() doc.directive("meta", fields=[ ('description', config["metadata"]["description"]), ('keywords', ", ".join(config["metadata"]["keywords"])) ]) doc.newline() doc.title(config["core"]["title"], overline=False) doc.newline() md_file_path = sample_source_dir / "header.md" new_md_name = sample_name + "_header.md" out_md = category_output_dir / new_md_name prepend_include_path(md_file_path, out_md, sample_name) fields = [("parser" , "myst_parser.sphinx_")] doc.directive( "include", new_md_name, fields) doc.newline() doc.newline() doc.directive("tab-set") doc.newline() code_flavors = {"USD Python" : "py_usd.md", "Python omni.usd" : "py_omni_usd.md", "Python Kit Commands" : "py_kit_cmds.md", "USD C++" : "cpp_usd.md", "C++ omni.usd" : "cpp_omni_usd.md", "C++ Kit Commands" : "cpp_kit_cmds.md", "usdview": "py_usdview.md", "USDA" : "usda.md", } for tab_name in code_flavors: md_file_name = code_flavors[tab_name] md_file_path = sample_source_dir / code_flavors[tab_name] if md_file_path.exists(): doc.directive("tab-item", tab_name, None, None, 3) doc.newline() # make sure all md flavor names are unique new_md_name = sample_name + "_" + md_file_name category_output_dir out_md = category_output_dir / new_md_name prepend_include_path(md_file_path, out_md, sample_name) fields = [("parser" , "myst_parser.sphinx_")] doc.directive( "include", new_md_name, fields, None, 6) doc.newline() # copy all samples ignore=shutil.ignore_patterns('*.md', 'config.toml') if REPLACE_USDA_EXT: ignore=shutil.ignore_patterns('*.md', 'config.toml', '*.usda') shutil.copytree(sample_source_dir, sample_output_dir, ignore=ignore, dirs_exist_ok=True ) # copy any usda's to .py if REPLACE_USDA_EXT: for filename in os.listdir(sample_source_dir): base_file, ext = os.path.splitext(filename) if ext == ".usda": orig = str(sample_source_dir) + "/" + filename newname = str(sample_output_dir) + "/" + str(base_file) + ".py" shutil.copy(orig, newname) # strip out copyright comments in output files if STRIP_COPYRIGHTS: for filename in os.listdir(sample_output_dir): full_path = os.path.join(sample_output_dir, filename) strip_copyrights(full_path) doc.newline() generate_sphinx_index(samples) sphinx.cmd.build.main([str(SPHINX_DIR), str(SPHINX_DIR / "_build"), "-b", "html"]) def strip_copyrights(filename): base_file, ext = os.path.splitext(filename) if ext in IMAGE_TYPES: print(f"strip_copyrights, skip image :: {filename}") return with open(filename) as sample_file: sample_lines = sample_file.readlines() # strip copyrights # .py while sample_lines[0].startswith("# SPDX-"): sample_lines.pop(0) # .cpp while sample_lines[0].startswith("// SPDX-"): sample_lines.pop(0) # get rid of empty spacer line if len(sample_lines[0].strip()) < 1: sample_lines.pop(0) with open(filename, "w") as sample_file: for line in sample_lines: sample_file.write(line) def prepend_include_path(in_file_path: str, out_file_path: str, dir_path: str): with open(in_file_path) as mdf: md_data = mdf.read() md_lines = md_data.split("\n") lc = 0 for line in md_lines: inc_str ="``` {literalinclude}" sp = line.split(inc_str) if len(sp) > 1: filename = sp[1].strip() if REPLACE_USDA_EXT: sfn = filename.split(".") if len(sfn) > 1 and sfn[1] == "usda": filename = sfn[0] + ".py" newl = inc_str + " " + dir_path + "/" + filename md_lines[lc] = newl lc += 1 with open(out_file_path,"w") as nmdf: for line in md_lines: nmdf.writelines(line + "\n") def generate_sphinx_index(samples): cat_names_path = SOURCE_DIR / "category-display-names.toml" cat_names = toml.load(cat_names_path)["name_mappings"] print(f"CAT_NAMES: {cat_names}") ref_links = {"variant-sets" : "variant_sets_ref"} index_rst = SPHINX_DIR / "usd.rst" with open(index_rst, "w") as f: doc = RstCloth(f) doc.directive("include", "usd_header.rst") doc.newline() #doc.title("OpenUSD Code Samples") for category, cat_samples in samples.items(): if category in ref_links: doc.ref_target(ref_links[category]) doc.newline() human_readable = readable_from_category_dir_name(category) if category in cat_names.keys(): human_readable = cat_names[category] doc.h2(human_readable) fields = [ #("caption", human_readable), ("titlesonly", ""), ] doc.newline() if TOCTREE_STYLE == 0: sample_paths = [f"usd/{category}/{sample[0]}" for sample in cat_samples] doc.directive("toctree", None, fields, sample_paths) doc.newline() elif TOCTREE_STYLE == 1: #doc.h2(human_readable) doc.newline() for sample, title in cat_samples: doc._add("- :doc:`" + title + f" <usd/{category}/" + sample + ">`") doc.newline() doc.directive("include", "usd_footer.rst") doc.newline() def readable_from_category_dir_name(category): sub_strs = category.split("-") readable = "" for sub in sub_strs: readable += sub.capitalize() + " " return readable.strip() if __name__ == "__main__": # Create an argument parser parser = argparse.ArgumentParser(description='Build rST documentation from code sample source.') # Parse the arguments args = parser.parse_args() logging.basicConfig(level=logging.INFO) main()
9,545
Python
34.225092
122
0.503929
NVIDIA-Omniverse/OpenUSD-Code-Samples/README.md
# OpenUSD Code Samples [![License](https://img.shields.io/badge/License-Apache%202.0-blue.svg)](https://opensource.org/licenses/Apache-2.0) [![See the Code Samples](https://img.shields.io/badge/OpenUSD-Code_Samples-green )](https://docs.omniverse.nvidia.com/dev-guide/latest/programmer_ref/usd.html) This repository contains useful Universal Scene Description (OpenUSD) code samples in Python, C++, and USDA. If you want to browse the code samples to use them, you can see them fully rendered in the [OpenUSD Code Samples documentation](https://docs.omniverse.nvidia.com/dev-guide/latest/programmer_ref/usd.html) page. ## Configuration This repository uses [Poetry](https://python-poetry.org/docs/) for dependency management. If you're new to Poetry, you don't need to know much more than the commands we use in the [build instructions](#How-to-Build). To make it easier when authoring code samples and contributing, we recommend installing: 1. Install any version of Python between versions 3.8-3.10 . 1. [Install Poetry](https://python-poetry.org/docs/#installation) ## How to Build 1. `poetry install` 1. `poetry run python build_docs.py` 1. In a web browser, open `sphinx/_build/index.html` ## Have an Idea for a New Code Sample? Ideas for new code samples that could help other developers are always welcome. Please [create a new issue](https://github.com/NVIDIA-Omniverse/OpenUSD-Code-Samples/issues) requesting a new code sample and add the _new request_ label. Someone from the NVIDIA team or OpenUSD community will pick it up. If you can contribute it yourself, even better! ## Find a Typo or an Error? Please let us know if you find any mistakes or non-working code samples. [File an issue](https://github.com/NVIDIA-Omniverse/OpenUSD-Code-Samples/issues) with a _bug_ label to let us know and so we can address it. ## Contributing Contributions are welcome! If you would like to contribute, please read our [Contributing Guidelines](./CONTRIBUTING.md) to understand how to contribute. Also, check out the [Code Sample Guidelines](CODE-SAMPLE-GUIDELINES.md) to understand how code samples file and folders are structured in this repository and how to adhere to follow our code samples style. ## Disclosures The goal of this repository is to help developers learn OpenUSD and be more productive. To that end, NVIDIA reserves the right to use the source code and documentation in this repository for the purpose of training and/or benchmarking of an AI code assistant for OpenUSD developers.
2,507
Markdown
88.571425
359
0.780614
NVIDIA-Omniverse/OpenUSD-Code-Samples/example-category/example-code-sample/py_kit_cmds.md
Here you can add any info specific to the code sample flavor and introduce the code sample. You should include your code sample as a separate source code file like this: ``` {literalinclude} py_kit_cmds.py :language: py ``` You should use these includes instead of putting code in markdown code blocks. The first source code file should be named the same as the markdown file. If you want to show any variations of the code sample of expand it, you should then include source code files with the suffix `_var#`. Variations are not required and you generally won't need them, but it's available if you find you code sample could benefit from showing variations.
663
Markdown
65.399993
287
0.785822
NVIDIA-Omniverse/OpenUSD-Code-Samples/example-category/example-code-sample/py_usd.py
# SPDX-FileCopyrightText: Copyright (c) 2023 NVIDIA CORPORATION & AFFILIATES. All rights reserved. # SPDX-License-Identifier: Apache-2.0 # Add all the imports that you need for you snippets from pxr import Usd, Sdf, UsdGeom def descriptive_code_sample_name(stage: Usd.Stage, prim_path: str="/World/MyPerspCam") -> UsdGeom.Camera: """Docstring is optional. Use Google style docstrings if you choose to add them. The code sample should be defined as a function. As a descriptive name for the function. Use function arguments to: - Pass in any objects that your code sample expects to exist (e.g. a Stage) - Pass in Paths rather than hard-coding them. Use type-hinting to help learners understand what type every variable is. Don't assume they'll know. Args: stage (Usd.Stage): _description_ prim_path (str, optional): _description_. Defaults to "/World/MyPerspCam". Returns: UsdGeom.Camera: _description_ """ camera_path = Sdf.Path(prim_path) usd_camera: UsdGeom.Camera = UsdGeom.Camera.Define(stage, camera_path) usd_camera.CreateProjectionAttr().Set(UsdGeom.Tokens.perspective) return usd_camera ############# # Full Usage ############# # Here you will show your code sample in context. Add any additional imports # that you may need for your "Full Usage" code # You can create an in-memory stage and do any stage setup before calling # you code sample. stage: Usd.Stage = Usd.Stage.CreateInMemory() default_prim = UsdGeom.Xform.Define(stage, Sdf.Path("/World")) stage.SetDefaultPrim(default_prim.GetPrim()) cam_path = default_prim.GetPath().AppendPath("MyPerspCam") # Call your code sample function camera = descriptive_code_sample_name(stage, cam_path) # print out the result usda = stage.GetRootLayer().ExportToString() print(usda) # Do some basic asserts to show learners how to interact with the results. prim = camera.GetPrim() assert prim.IsValid() assert camera.GetPath() == Sdf.Path(cam_path) assert prim.GetTypeName() == "Camera" projection = camera.GetProjectionAttr().Get() assert projection == UsdGeom.Tokens.perspective
2,131
Python
35.75862
105
0.725481
NVIDIA-Omniverse/OpenUSD-Code-Samples/example-category/example-code-sample/py_omni_usd.py
# SPDX-FileCopyrightText: Copyright (c) 2023 NVIDIA CORPORATION & AFFILIATES. All rights reserved. # SPDX-License-Identifier: Apache-2.0 """ Source code for code block in the py_omni_usd flavor. See the py_usd.py for a full example of writing a code sample. You should use omni.usd.get_stage() instead of creating an in-memory stage for the Full Usage part since this is meant to run in Omniverse. """
403
Python
39.399996
98
0.764268
NVIDIA-Omniverse/OpenUSD-Code-Samples/example-category/example-code-sample/usda.md
Here you can say something before showing the USDA example. You can use the usda string generated by the py_usd flavor. ``` {literalinclude} usda.usda :language: c++ ```
170
Markdown
41.74999
119
0.747059
NVIDIA-Omniverse/OpenUSD-Code-Samples/example-category/example-code-sample/config.toml
[core] # The title for this code sample. Used to name the page. title = "My Code Example Code Sample" [metadata] #A concise description of the code sample for SEO. description = "Universal Scene Description (OpenUSD) code samples to show how to contribute." # Put in SEO keywords relevant to this code sample. keywords = ["OpenUSD", "USD", "code sample", "snippet", "Python", "C++", "example"]
394
TOML
42.888884
93
0.725888
NVIDIA-Omniverse/OpenUSD-Code-Samples/example-category/example-code-sample/py_usd_var1.py
# SPDX-FileCopyrightText: Copyright (c) 2023 NVIDIA CORPORATION & AFFILIATES. All rights reserved. # SPDX-License-Identifier: Apache-2.0 """ Source code for another code block in the py_usd flavor. See the py_usd.py for a full example of writing a code sample. """
265
Python
36.999995
98
0.758491
NVIDIA-Omniverse/OpenUSD-Code-Samples/source/category-display-names.toml
[name_mappings] hierarchy-traversal = "Hierarchy & Traversal" references-payloads = "References & Payloads"
108
TOML
26.249993
45
0.777778
NVIDIA-Omniverse/OpenUSD-Code-Samples/source/cameras/create-orthographic-camera/py_kit_cmds.md
The `CreatePrimWithDefaultXform` command in Kit can create a Camera prim and you can optionally set camera attributes values during creation. You must use the attribute token names as the keys for the `attributes` dictionary. In Omniverse applications, you can explore the names by hovering over a property label in the Property Window and reading it from the tooltip. ``` {literalinclude} py_kit_cmds.py :language: py ```
423
Markdown
83.799983
368
0.799054
NVIDIA-Omniverse/OpenUSD-Code-Samples/source/cameras/create-orthographic-camera/py_usd.py
# SPDX-FileCopyrightText: Copyright (c) 2023 NVIDIA CORPORATION & AFFILIATES. All rights reserved. # SPDX-License-Identifier: Apache-2.0 from pxr import Sdf, Usd, UsdGeom def create_orthographic_camera(stage: Usd.Stage, prim_path: str="/World/MyOrthoCam") -> UsdGeom.Camera: """Create an orthographic camera Args: stage (Usd.Stage): A USD Stage to create the camera on. prim_path (str, optional): The prim path for where to create the camera. Defaults to "/World/MyOrthoCam". """ camera_path = Sdf.Path(prim_path) usd_camera = UsdGeom.Camera.Define(stage, camera_path) usd_camera.CreateProjectionAttr().Set(UsdGeom.Tokens.orthographic) return usd_camera ############# # Full Usage ############# cam_path = "/World/MyOrthoCam" stage: Usd.Stage = Usd.Stage.CreateInMemory() root_prim = UsdGeom.Xform.Define(stage, Sdf.Path("/World")) stage.SetDefaultPrim(root_prim.GetPrim()) camera = create_orthographic_camera(stage, cam_path) usda = stage.GetRootLayer().ExportToString() print(usda) # Check that the camera was created prim = camera.GetPrim() assert prim.IsValid() assert camera.GetPath() == Sdf.Path(cam_path) assert prim.GetTypeName() == "Camera" projection = camera.GetProjectionAttr().Get() assert projection == UsdGeom.Tokens.orthographic
1,298
Python
31.474999
113
0.718028
NVIDIA-Omniverse/OpenUSD-Code-Samples/source/cameras/create-orthographic-camera/py_usd.md
``` {literalinclude} py_usd.py :language: py ```
50
Markdown
9.199998
30
0.62
NVIDIA-Omniverse/OpenUSD-Code-Samples/source/cameras/create-orthographic-camera/py_kit_cmds.py
# SPDX-FileCopyrightText: Copyright (c) 2023 NVIDIA CORPORATION & AFFILIATES. All rights reserved. # SPDX-License-Identifier: Apache-2.0 import omni.kit.commands from pxr import UsdGeom def create_orthographic_camera(prim_path: str="/World/MyOrthoCam"): """Create an orthographic camera Args: prim_path (str, optional): The prim path where the camera should be created. Defaults to "/World/MyOrthoCam". """ omni.kit.commands.execute("CreatePrimWithDefaultXform", prim_type="Camera", prim_path="/World/MyOrthoCam", attributes={"projection": UsdGeom.Tokens.orthographic} ) ############# # Full Usage ############# import omni.usd # Create an orthographic camera at /World/MyOrthoCam path = "/World/MyOrthoCam" create_orthographic_camera(path) # Check that the camera was created stage = omni.usd.get_context().get_stage() prim = stage.GetPrimAtPath(path) assert prim.IsValid() == True assert prim.GetTypeName() == "Camera" projection = prim.GetAttribute("projection").Get() assert projection == UsdGeom.Tokens.orthographic
1,082
Python
28.27027
117
0.711645
NVIDIA-Omniverse/OpenUSD-Code-Samples/source/cameras/create-orthographic-camera/usda.md
This is an example USDA result from creating a Camera and setting the `projection` to `orthographic`. All other Properties are using the default values from the `UsdGeomCamera` schema definition. ``` {literalinclude} usda.usda :language: usd ```
246
Markdown
60.749985
195
0.780488
NVIDIA-Omniverse/OpenUSD-Code-Samples/source/cameras/create-orthographic-camera/config.toml
[core] title = "Create an Orthographic Camera" [metadata] description = "Universal Scene Description (OpenUSD) code samples for creating an orthographic camera prim." keywords = ["OpenUSD", "USD", "Python", "snippet", "code sample", "prim", "camera", "UsdGeom", "Orthographic"]
278
TOML
45.499992
110
0.726619
NVIDIA-Omniverse/OpenUSD-Code-Samples/source/cameras/create-orthographic-camera/header.md
You can define a new camera on a stage using `UsdGeom.Camera`. The Camera prim has a `projection` attribute that can be set to `orthographic`.
143
Markdown
70.999965
142
0.769231
NVIDIA-Omniverse/OpenUSD-Code-Samples/source/cameras/create-perspective-camera/py_usd.py
# SPDX-FileCopyrightText: Copyright (c) 2023 NVIDIA CORPORATION & AFFILIATES. All rights reserved. # SPDX-License-Identifier: Apache-2.0 from pxr import Usd, Sdf, UsdGeom def create_perspective_camera(stage: Usd.Stage, prim_path: str="/World/MyPerspCam") -> UsdGeom.Camera: camera_path = Sdf.Path(prim_path) usd_camera: UsdGeom.Camera = UsdGeom.Camera.Define(stage, camera_path) usd_camera.CreateProjectionAttr().Set(UsdGeom.Tokens.perspective) return usd_camera ############# # Full Usage ############# # 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 the perspective camera at /World/MyPerspCam cam_path = default_prim.GetPath().AppendPath("MyPerspCam") camera = create_perspective_camera(stage, cam_path) # Export the complete Stage as a string and print it. usda = stage.GetRootLayer().ExportToString() print(usda) # Check that the camera was created prim = camera.GetPrim() assert prim.IsValid() assert camera.GetPath() == Sdf.Path(cam_path) assert prim.GetTypeName() == "Camera" projection = camera.GetProjectionAttr().Get() assert projection == UsdGeom.Tokens.perspective
1,288
Python
33.837837
102
0.743789
NVIDIA-Omniverse/OpenUSD-Code-Samples/source/cameras/create-perspective-camera/py_usd.md
With the USD API, you can use `UsdGeom.Camera.CreateProjectionAttr()` to create the `projection` attribute and then set the value with `Usd.Attribute.Set()`. ``` {literalinclude} py_usd.py :language: py ``` Here is how to you can set some other common attributes on the camera: ``` {literalinclude} py_usd_var1.py :language: py ```
335
Markdown
32.599997
157
0.728358
NVIDIA-Omniverse/OpenUSD-Code-Samples/source/cameras/create-perspective-camera/py_kit_cmds.py
# SPDX-FileCopyrightText: Copyright (c) 2023 NVIDIA CORPORATION & AFFILIATES. All rights reserved. # SPDX-License-Identifier: Apache-2.0 import omni.kit.commands from pxr import UsdGeom def create_perspective_camera(prim_path: str="/World/MyPerspCam"): """Create a perspective camera Args: prim_path (str, optional): The prim path where the camera should be created. Defaults to "/World/MyPerspCam". """ omni.kit.commands.execute("CreatePrimWithDefaultXform", prim_type="Camera", prim_path=prim_path, attributes={ "projection": UsdGeom.Tokens.perspective, "focalLength": 35, "horizontalAperture": 20.955, "verticalAperture": 15.2908, "clippingRange": (0.1, 100000) } ) ############# # Full Usage ############# import omni.usd # Create a perspective camera at /World/MyPerspCam path = "/World/MyPerspCam" create_perspective_camera(path) # Check that the camera was created stage = omni.usd.get_context().get_stage() prim = stage.GetPrimAtPath(path) assert prim.IsValid() == True assert prim.GetTypeName() == "Camera" projection = prim.GetAttribute("projection").Get() assert projection == UsdGeom.Tokens.perspective
1,239
Python
27.181818
117
0.673123
NVIDIA-Omniverse/OpenUSD-Code-Samples/source/cameras/create-perspective-camera/config.toml
[core] title = "Create a Perspective Camera" [metadata] description = "Universal Scene Description (OpenUSD) code sample to create a perspective camera." keywords = ["OpenUSD", "USD", "Python", "snippet", "code sample", "prim", "camera", "perspective"]
253
TOML
41.333326
98
0.719368
NVIDIA-Omniverse/OpenUSD-Code-Samples/source/cameras/create-perspective-camera/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, Sdf, UsdGeom def create_perspective_35mm_camera(stage: Usd.Stage, prim_path: str="/World/MyPerspCam") -> UsdGeom.Camera: camera_path = Sdf.Path(prim_path) usd_camera: UsdGeom.Camera = UsdGeom.Camera.Define(stage, camera_path) usd_camera.CreateProjectionAttr().Set(UsdGeom.Tokens.perspective) usd_camera.CreateFocalLengthAttr().Set(35) # Set a few other common attributes too. usd_camera.CreateHorizontalApertureAttr().Set(20.955) usd_camera.CreateVerticalApertureAttr().Set(15.2908) usd_camera.CreateClippingRangeAttr().Set((0.1,100000)) return usd_camera ############# # Full Usage ############# # 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 the perspective camera at path /World/MyPerspCam with 35mm # set for the focal length. cam_path = default_prim.GetPath().AppendPath("MyPerspCam") camera = create_perspective_35mm_camera(stage, cam_path) # Export the complete Stage as a string and print it. usda = stage.GetRootLayer().ExportToString() print(usda) # Check the camera attributes focal_len = camera.GetFocalLengthAttr().Get() assert focal_len == 35.0 clip_range = camera.GetClippingRangeAttr().Get() assert clip_range == (0.1,100000)
1,533
Python
34.674418
107
0.740378
NVIDIA-Omniverse/OpenUSD-Code-Samples/source/visibility/show-hide-prim/py_kit_cmds.md
You can use the `ChangeProperty` command from the `omni.kit.commands` extension to change the attribute of any prim. In Omniverse applications, you can discover the attribute name by hovering over the label in the Property Window and inspecting the tooltip. You can find more information about the Kit command API at the [omni.kit.commands extension documentation](https://docs.omniverse.nvidia.com/kit/docs/omni.kit.commands/latest/API.html). ``` {literalinclude} py_kit_cmds.py :language: py ```
499
Markdown
70.428561
257
0.791583
NVIDIA-Omniverse/OpenUSD-Code-Samples/source/visibility/show-hide-prim/py_usd.py
# SPDX-FileCopyrightText: Copyright (c) 2023 NVIDIA CORPORATION & AFFILIATES. All rights reserved. # SPDX-License-Identifier: Apache-2.0 from typing import Union from pxr import Sdf, Usd, UsdGeom def get_visibility_attribute( stage: Usd.Stage, prim_path: str ) -> Union[Usd.Attribute, None]: """Return the visibility attribute of a prim""" path = Sdf.Path(prim_path) prim = stage.GetPrimAtPath(path) if not prim.IsValid(): return None visibility_attribute = prim.GetAttribute("visibility") return visibility_attribute def hide_prim(stage: Usd.Stage, prim_path: str): """Hide a prim Args: stage (Usd.Stage, required): The USD Stage prim_path (str, required): The prim path of the prim to hide """ visibility_attribute = get_visibility_attribute(stage, prim_path) if visibility_attribute is None: return visibility_attribute.Set("invisible") def show_prim(stage: Usd.Stage, prim_path: str): """Show a prim Args: stage (Usd.Stage, required): The USD Stage prim_path (str, required): The prim path of the prim to show """ visibility_attribute = get_visibility_attribute(stage, prim_path) if visibility_attribute is None: return visibility_attribute.Set("inherited") ############# # Full Usage ############# # Here you will show your code sample in context. Add any additional imports # that you may need for your "Full Usage" code # Create a simple in-memory stage with a Cube stage: Usd.Stage = Usd.Stage.CreateInMemory() default_prim_path = Sdf.Path("/World") default_prim = UsdGeom.Xform.Define(stage, default_prim_path) stage.SetDefaultPrim(default_prim.GetPrim()) cube_path = default_prim_path.AppendPath("Cube") cube = UsdGeom.Cube.Define(stage, cube_path) # The prim is initially visible. Assert so and then demonstrate how to toggle # it off and on assert get_visibility_attribute(stage, cube_path).Get() == "inherited" hide_prim(stage, cube_path) assert get_visibility_attribute(stage, cube_path).Get() == "invisible" show_prim(stage, cube_path) assert get_visibility_attribute(stage, cube_path).Get() == "inherited" # Print the USDA out usda = stage.GetRootLayer().ExportToString() print(usda)
2,246
Python
30.647887
98
0.702137
NVIDIA-Omniverse/OpenUSD-Code-Samples/source/visibility/show-hide-prim/py_usd.md
You can use the USD API [Usd.Prim.GetAttribute()](https://openusd.org/release/api/class_usd_prim.html#a31225ac7165f58726f000ab1d67e9e61) to get an attribute of a prim and then use [Usd.Attribute.Set()](https://openusd.org/release/api/class_usd_attribute.html#a151e6fde58bbd911da8322911a3c0079) to change the value. The attribute name for visibility is `visibility` and you can set it to the value of `inherited` or `invisible`. ``` {literalinclude} py_usd.py :language: py ```
477
Markdown
94.599981
427
0.779874
NVIDIA-Omniverse/OpenUSD-Code-Samples/source/visibility/show-hide-prim/py_kit_cmds.py
# SPDX-FileCopyrightText: Copyright (c) 2023 NVIDIA CORPORATION & AFFILIATES. All rights reserved. # SPDX-License-Identifier: Apache-2.0 import omni.kit.commands import omni.usd from pxr import Sdf def hide_prim(prim_path: str): """Hide a prim Args: prim_path (str, required): The prim path of the prim to hide """ set_prim_visibility_attribute(prim_path, "invisible") def show_prim(prim_path: str): """Show a prim Args: prim_path (str, required): The prim path of the prim to show """ set_prim_visibility_attribute(prim_path, "inherited") def set_prim_visibility_attribute(prim_path: str, value: str): """Set the prim visibility attribute at prim_path to value Args: prim_path (str, required): The path of the prim to modify value (str, required): The value of the visibility attribute """ # You can reference attributes using the path syntax by appending the # attribute name with a leading `.` prop_path = f"{prim_path}.visibility" omni.kit.commands.execute( "ChangeProperty", prop_path=Sdf.Path(prop_path), value=value, prev=None ) """ Full Usage """ # Path to a prim in the open stage prim_path = "/World/Cube" stage = omni.usd.get_context().get_stage() prim = stage.GetPrimAtPath(prim_path) assert prim.IsValid() # Manually confirm that the prim is not visible in the viewport after calling # hide_prim. You should comment out the below show_prim call and assert. hide_prim(prim_path) assert prim.GetAttribute("visibility").Get() == "invisible" # Manually confirm that the prim is visible in the viewport after calling # show_prim show_prim(prim_path) assert prim.GetAttribute("visibility").Get() == "inherited"
1,738
Python
27.508196
98
0.698504
NVIDIA-Omniverse/OpenUSD-Code-Samples/source/visibility/show-hide-prim/usda.md
This is an example USDA result from creating a Cube and setting the visibility property to `inherited`. You can edit the value to `invisible` to hide the prim. ``` {literalinclude} usda.usda :language: usd ```
211
Markdown
41.399992
159
0.753554
NVIDIA-Omniverse/OpenUSD-Code-Samples/source/visibility/show-hide-prim/config.toml
[core] # The title for this code sample. Used to name the page. title = "Show or Hide a Prim" [metadata] #A concise description of the code sample for SEO. description = "Universal Scene Description (OpenUSD) code samples that demonstrates how to a show or hide a prim." # Put in SEO keywords relevant to this code sample. keywords = ["OpenUSD", "USD", "Python", "visibility", "show prim", "hide prim"]
403
TOML
43.888884
114
0.73201
NVIDIA-Omniverse/OpenUSD-Code-Samples/source/layers/add-sublayer/py_kit_cmds.md
``` {literalinclude} py_kit_cmds.py :language: py ```
53
Markdown
16.999994
35
0.660377
NVIDIA-Omniverse/OpenUSD-Code-Samples/source/layers/add-sublayer/py_usd.py
# SPDX-FileCopyrightText: Copyright (c) 2023 NVIDIA CORPORATION & AFFILIATES. All rights reserved. # SPDX-License-Identifier: Apache-2.0 from pxr import Sdf def add_sub_layer(sub_layer_path: str, root_layer) -> Sdf.Layer: sub_layer: Sdf.Layer = Sdf.Layer.CreateNew(sub_layer_path) # You can use standard python list.insert to add the subLayer to any position in the list root_layer.subLayerPaths.append(sub_layer.identifier) return sub_layer ############# # Full Usage ############# from pxr import Usd # Get the root layer stage: Usd.Stage = Usd.Stage.CreateInMemory() root_layer: Sdf.Layer = stage.GetRootLayer() # Add the sub layer to the root layer sub_layer = add_sub_layer(r"C:/path/to/sublayer.usd", root_layer) usda = stage.GetRootLayer().ExportToString() print(usda) # Check to see if the sublayer is loaded loaded_layers = root_layer.GetLoadedLayers() assert sub_layer in loaded_layers
921
Python
28.741935
98
0.726384
NVIDIA-Omniverse/OpenUSD-Code-Samples/source/layers/add-sublayer/py_kit_cmds.py
# SPDX-FileCopyrightText: Copyright (c) 2023 NVIDIA CORPORATION & AFFILIATES. All rights reserved. # SPDX-License-Identifier: Apache-2.0 import omni.kit.commands omni.kit.commands.execute("CreateSublayer", layer_identifier=stage.GetRootLayer().identifier, # This example prepends to the subLayers list sublayer_position=0, new_layer_path=r"C:/path/to/sublayer.usd", transfer_root_content=False, # When True, it will create the layer file for you too. create_or_insert=True )
506
Python
30.687498
98
0.741107
NVIDIA-Omniverse/OpenUSD-Code-Samples/source/layers/add-sublayer/config.toml
[core] title = "Add a SubLayer" [metadata] description = "Universal Scene Description (OpenUSD) code samples for adding an Inherit composition arc to a prim." keywords = ["OpenUSD", "USD", "Python", "snippet", "code sample", "layer", "SubLayer", "composition", "composition arc"]
280
TOML
45.833326
120
0.717857
NVIDIA-Omniverse/OpenUSD-Code-Samples/source/references-payloads/create-payload/py_kit_cmds.md
The `CreatePayload` command is a convenient wrapper that creates an Xform prim and adds a Payload to it all at once. If you don't need the two steps batched together, you may want to [add a Payload](add-payload) to an existing prim via Kit Commands or USD Python API. ``` {literalinclude} py_kit_cmds.py :language: py ```
322
Markdown
63.599987
267
0.757764
NVIDIA-Omniverse/OpenUSD-Code-Samples/source/references-payloads/create-payload/py_kit_cmds.py
# SPDX-FileCopyrightText: Copyright (c) 2023 NVIDIA CORPORATION & AFFILIATES. All rights reserved. # SPDX-License-Identifier: Apache-2.0 import omni.kit.commands import omni.usd from pxr import Usd, Sdf def create_payload(usd_context: omni.usd.UsdContext, path_to: Sdf.Path, asset_path: str, prim_path: Sdf.Path) -> Usd.Prim: omni.kit.commands.execute("CreatePayload", usd_context=usd_context, path_to=path_to, # Prim path for where to create the prim with the payload asset_path=asset_path, # The file path to the payload USD. Relative paths are accepted too. prim_path=prim_path # OPTIONAL: Prim path to a prim in the payloaded USD, if not provided the default prim is used ) return usd_context.get_stage().GetPrimAtPath(path_to) ############# # Full Usage ############# # Get the USD context from kit context: omni.usd.UsdContext = omni.usd.get_context() # Create and add external payload to specific prim payload_prim: Usd.Prim = create_payload(context, Sdf.Path("/World/payload_prim"), "C:/path/to/file.usd", Sdf.Path("/World/some/target")) # Get the existing USD stage from kit stage: Usd.Stage = context.get_stage() usda = stage.GetRootLayer().ExportToString() print(usda) # Check that the payload prims were created assert payload_prim.IsValid() assert payload_prim.GetPrimStack()[0].payloadList.prependedItems[0] == Sdf.Payload(assetPath="file:/C:/path/to/file.usd", primPath=Sdf.Path("/World/some/target"))
1,469
Python
39.833332
162
0.721579
NVIDIA-Omniverse/OpenUSD-Code-Samples/source/references-payloads/create-payload/usda.md
This is an example USDA result from creating a reference with the `CreateReference` command. ``` {literalinclude} usda.usda :language: usd ```
143
Markdown
34.999991
92
0.762238
NVIDIA-Omniverse/OpenUSD-Code-Samples/source/references-payloads/create-payload/config.toml
[core] title = "Create a Payload" [metadata] description = "Universal Scene Description (OpenUSD) code samples for creating an Xform prim and adding a Payload in Omniverse Kit in one step." keywords = ["OpenUSD", "USD", "Python", "snippet", "code sample", "prim", "payload", "CreatePayload"]
292
TOML
47.833325
144
0.726027
NVIDIA-Omniverse/OpenUSD-Code-Samples/source/references-payloads/add-payload/py_kit_cmds.md
The `AddPayload` command in Kit can add payloads to a prim. ``` {literalinclude} py_kit_cmds.py :language: py ```
113
Markdown
27.499993
59
0.716814
NVIDIA-Omniverse/OpenUSD-Code-Samples/source/references-payloads/add-payload/py_usd.py
# SPDX-FileCopyrightText: Copyright (c) 2023 NVIDIA CORPORATION & AFFILIATES. All rights reserved. # SPDX-License-Identifier: Apache-2.0 from pxr import Usd, Sdf def add_payload(prim: Usd.Prim, payload_asset_path: str, payload_target_path: Sdf.Path) -> None: payloads: Usd.Payloads = prim.GetPayloads() payloads.AddPayload( assetPath=payload_asset_path, primPath=payload_target_path # OPTIONAL: Payload a specific target prim. Otherwise, uses the payloadd layer's defaultPrim. ) ############# # Full Usage ############# from pxr import UsdGeom # Create new USD stage for this sample stage: Usd.Stage = Usd.Stage.CreateInMemory() # Create and define default prim default_prim = UsdGeom.Xform.Define(stage, Sdf.Path("/World")) stage.SetDefaultPrim(default_prim.GetPrim()) # Create an xform which should hold all payloads in this sample payload_prim: Usd.Prim = UsdGeom.Xform.Define(stage, Sdf.Path("/World/payload_prim")).GetPrim() # Add an external payload add_payload(payload_prim, "C:/path/to/file.usd", Sdf.Path("/World/some/target")) # Add other external payload to default prim add_payload(payload_prim, "C:/path/to/other/file.usd", Sdf.Path.emptyPath) usda = stage.GetRootLayer().ExportToString() print(usda) # Get a list of all prepended payloads payloads = [] for prim_spec in payload_prim.GetPrimStack(): payloads.extend(prim_spec.payloadList.prependedItems) # Check that the payload prim was created and that the payloads are correct assert payload_prim.IsValid() assert payloads[0] == Sdf.Payload(assetPath="C:/path/to/file.usd", primPath=Sdf.Path("/World/some/target")) assert payloads[1] == Sdf.Payload(assetPath="C:/path/to/other/file.usd")
1,698
Python
35.148935
130
0.73616
NVIDIA-Omniverse/OpenUSD-Code-Samples/source/references-payloads/add-payload/py_usd.md
With the USD API, you can use `Usd.Prim.GetPayloads()` to receive the payloads and add a new one with `Usd.Payloads.AddPayload()`. ``` {literalinclude} py_usd.py :language: py ```
179
Markdown
43.999989
130
0.72067
NVIDIA-Omniverse/OpenUSD-Code-Samples/source/references-payloads/add-payload/py_kit_cmds.py
# SPDX-FileCopyrightText: Copyright (c) 2023 NVIDIA CORPORATION & AFFILIATES. All rights reserved. # SPDX-License-Identifier: Apache-2.0 import omni.kit.commands from pxr import Usd, Sdf def add_payload(prim: Usd.Prim, payload_asset_path: str, payload_target_path: Sdf.Path) -> None: omni.kit.commands.execute("AddPayload", stage=prim.GetStage(), prim_path = prim.GetPath(), # an existing prim to add the payload to. payload=Sdf.Payload( assetPath = payload_asset_path, primPath = payload_target_path ) ) ############# # Full Usage ############# from pxr import UsdGeom import omni.usd # Create new USD stage for this sample in OV context: omni.usd.UsdContext = omni.usd.get_context() success: bool = context.new_stage() stage: Usd.Stage = context.get_stage() # Create and define default prim, so this file can be easily payloaderenced again default_prim = UsdGeom.Xform.Define(stage, Sdf.Path("/World")) stage.SetDefaultPrim(default_prim.GetPrim()) # Create a xform which should hold all payloads in this sample payload_prim: Usd.Prim = UsdGeom.Xform.Define(stage, Sdf.Path("/World/payload_prim")).GetPrim() # Add an payload specific prim add_payload(payload_prim, "C:/path/to/file.usd", Sdf.Path("/World/some/target")) # Add other payload to default prim add_payload(payload_prim, "C:/path/to/other/file.usd", Sdf.Path.emptyPath) usda = stage.GetRootLayer().ExportToString() print(usda) # Get a list of all prepended payloads payloads = [] for prim_spec in payload_prim.GetPrimStack(): payloads.extend(prim_spec.payloadList.prependedItems) # Check that the payload prim was created and that the payloads are correct assert payload_prim.IsValid() assert payloads[0] == Sdf.Payload(assetPath="C:/path/to/file.usd", primPath=Sdf.Path("/World/some/target")) assert payloads[1] == Sdf.Payload(assetPath="C:/path/to/other/file.usd")
1,908
Python
35.018867
107
0.719078
NVIDIA-Omniverse/OpenUSD-Code-Samples/source/references-payloads/add-payload/usda.md
This is an example USDA result from creating an `Xform` and adding two `Payloads` to it. The first payload target prim in this case is in the file `C:/path/to/file.usd` with the prim path `/World/some/target` and the second is the default prim in the file `C:/path/to/other/file.usd`. ``` {literalinclude} usda.usda :language: usd ```
335
Markdown
82.999979
284
0.737313
NVIDIA-Omniverse/OpenUSD-Code-Samples/source/references-payloads/add-payload/config.toml
[core] title = "Add a Payload" [metadata] description = "Universal Scene Description (OpenUSD) code samples for adding a Payload to a prim." keywords = ["OpenUSD", "USD", "Python", "snippet", "code sample", "prim", "payload", "AddPayload"]
240
TOML
39.16666
98
0.7
NVIDIA-Omniverse/OpenUSD-Code-Samples/source/references-payloads/create-reference/py_kit_cmds.md
The `CreateReference` command is a convenient wrapper that creates an Xform prim and adds a Reference to it all at once. If you don't need the two steps batched together, you may want to [add a Reference](add-reference) to an existing prim via Kit Commands or USD API. ``` {literalinclude} py_kit_cmds.py :language: py ```
323
Markdown
63.799987
268
0.76161
NVIDIA-Omniverse/OpenUSD-Code-Samples/source/references-payloads/create-reference/config.toml
[core] title = "Create a Reference" [metadata] description = "Universal Scene Description (OpenUSD) code samples for creating an Xform prim and adding a Reference in Omniverse Kit in one step." keywords = ["OpenUSD", "USD", "Python", "snippet", "code sample", "prim", "reference", "CreateReference"]
300
TOML
49.166658
146
0.733333
NVIDIA-Omniverse/OpenUSD-Code-Samples/source/references-payloads/add-reference/py_kit_cmds.md
The `AddReference` command in Kit can add internal and external references to a prim. ``` {literalinclude} py_kit_cmds.py :language: py ```
139
Markdown
33.999992
85
0.748201
NVIDIA-Omniverse/OpenUSD-Code-Samples/source/references-payloads/add-reference/py_usd.py
# SPDX-FileCopyrightText: Copyright (c) 2023 NVIDIA CORPORATION & AFFILIATES. All rights reserved. # SPDX-License-Identifier: Apache-2.0 from pxr import Usd, Sdf def add_int_reference(prim: Usd.Prim, ref_target_path: Sdf.Path) -> None: references: Usd.References = prim.GetReferences() references.AddInternalReference(ref_target_path) def add_ext_reference(prim: Usd.Prim, ref_asset_path: str, ref_target_path: Sdf.Path) -> None: references: Usd.References = prim.GetReferences() references.AddReference( assetPath=ref_asset_path, primPath=ref_target_path # OPTIONAL: Reference a specific target prim. Otherwise, uses the referenced layer's defaultPrim. ) ############# # Full Usage ############# from pxr import UsdGeom # Create new USD stage for this sample stage: Usd.Stage = Usd.Stage.CreateInMemory() # Create and define default prim, so this file can be easily referenced again default_prim = UsdGeom.Xform.Define(stage, Sdf.Path("/World")) stage.SetDefaultPrim(default_prim.GetPrim()) # Create an xform which should hold all references in this sample ref_prim: Usd.Prim = UsdGeom.Xform.Define(stage, Sdf.Path("/World/ref_prim")).GetPrim() # Add an internal reference intern_target_path: Sdf.Path = Sdf.Path("/World/intern_target") target_prim: Usd.Prim = UsdGeom.Xform.Define(stage, intern_target_path).GetPrim() add_int_reference(ref_prim, intern_target_path) # Add an external reference to specific prim add_ext_reference(ref_prim, "C:/path/to/file.usd", Sdf.Path("/World/some/target")) # Add other external reference to default prim add_ext_reference(ref_prim, "C:/path/to/other/file.usd", Sdf.Path.emptyPath) usda = stage.GetRootLayer().ExportToString() print(usda) # Get a list of all prepended references references = [] for prim_spec in ref_prim.GetPrimStack(): references.extend(prim_spec.referenceList.prependedItems) # Check that the reference prim was created and that the references are correct assert ref_prim.IsValid() assert references[0] == Sdf.Reference(primPath=intern_target_path) assert references[1] == Sdf.Reference(assetPath="C:/path/to/file.usd", primPath=Sdf.Path("/World/some/target")) assert references[2] == Sdf.Reference(assetPath="C:/path/to/other/file.usd")
2,250
Python
38.491227
130
0.744
NVIDIA-Omniverse/OpenUSD-Code-Samples/source/references-payloads/add-reference/py_usd.md
With the USD API, you can use `Usd.Prim.GetReferences()` to receive the references and add a new one with `Usd.References.AddReference()`. ``` {literalinclude} py_usd.py :language: py ```
187
Markdown
45.999989
138
0.73262
NVIDIA-Omniverse/OpenUSD-Code-Samples/source/references-payloads/add-reference/config.toml
[core] title = "Add a Reference" [metadata] description = "Universal Scene Description (OpenUSD) code samples for adding a Reference to a prim." keywords = ["OpenUSD", "USD", "Python", "snippet", "code sample", "prim", "reference", "AddReference"]
248
TOML
40.499993
102
0.709677
NVIDIA-Omniverse/OpenUSD-Code-Samples/source/variant-sets/author-variant-data/py_usd.py
# SPDX-FileCopyrightText: Copyright (c) 2023 NVIDIA CORPORATION & AFFILIATES. All rights reserved. # SPDX-License-Identifier: Apache-2.0 shading_varset = prim.GetVariantSets().GetVariantSet("shading") selected_variant = shading_varset.GetVariantSelection() shading_varset.SetVariantSelection(variant_name) with shading_varset.GetVariantEditContext(): # Specs authored within this context are authored just for the variant. ... # Set the variant selection back to the previously selected variant. # Alternatively, you can use Usd.VariantSet.ClearVariantSelection() # if you know that there isn't a variant selection in the current EditTarget. if selected_variant: shading_varset.SetVariantSelection(selected_variant)
731
Python
42.058821
98
0.79617
NVIDIA-Omniverse/OpenUSD-Code-Samples/source/variant-sets/author-variant-data/header.md
Opinions (i.e. data) for a particular variant can be authored on different layers. This shows how you can author opinions for an existing variant that might have been authored on a different layer.
197
Markdown
97.999951
150
0.807107
NVIDIA-Omniverse/OpenUSD-Code-Samples/source/variant-sets/select-variant/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 select_variant_from_varaint_set(prim: Usd.Prim, variant_set_name: str, variant_name: str) -> None: variant_set = prim.GetVariantSets().GetVariantSet(variant_set_name) variant_set.SetVariantSelection(variant_name) ############# # 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 the Variant Set shading_varset: Usd.VariantSet = default_prim.GetVariantSets().AddVariantSet("shading") # Add Variants to the Variant Set shading_varset.AddVariant("cell_shading") shading_varset.AddVariant("realistic") select_variant_from_varaint_set(default_prim, "shading", "realistic") usda = stage.GetRootLayer().ExportToString() print(usda) assert default_prim.GetVariantSets().GetVariantSet("shading").GetVariantSelection() == "realistic"
1,150
Python
33.878787
102
0.753043
NVIDIA-Omniverse/OpenUSD-Code-Samples/source/variant-sets/select-variant/usda.md
This is an example USDA result from creating a Variant Set, adding two Variants to the set, and selecting the current Variant to `realistic`. ``` {literalinclude} usda.usda :language: usd ```
192
Markdown
47.249988
141
0.760417
NVIDIA-Omniverse/OpenUSD-Code-Samples/source/variant-sets/create-variant-set/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 create_variant_set(prim: Usd.Prim, variant_set_name: str, variants: list) -> Usd.VariantSet: variant_set = prim.GetVariantSets().AddVariantSet(variant_set_name) for variant in variants: variant_set.AddVariant(variant) return variant_set ############# # 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 the variant set and add your variants to it. variants = ["red", "blue", "green"] shading_varset: Usd.VariantSet = create_variant_set(default_prim, "shading", variants) usda = stage.GetRootLayer().ExportToString() print(usda) assert default_prim.GetVariantSets().HasVariantSet("shading")
1,027
Python
33.266666
98
0.730282
NVIDIA-Omniverse/OpenUSD-Code-Samples/source/variant-sets/create-variant-set/usda.md
This is an example USDA result from creating a Variant Set and adding Variants to the Set. ``` {literalinclude} usda.usda :language: usd ```
141
Markdown
34.499991
90
0.751773
NVIDIA-Omniverse/OpenUSD-Code-Samples/source/variant-sets/create-variant-set/config.toml
[core] title = "Create a Variant Set" [metadata] description = "Universal Scene Description (OpenUSD) code samples showing how to create a variant set." keywords = ["OpenUSD", "USD", "Python", "snippet", "code sample", "variant set", "composition", "create variant set", "variant"]
282
TOML
46.166659
128
0.716312
NVIDIA-Omniverse/OpenUSD-Code-Samples/source/specializes/add-specialize/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 add_specialize_to(base_prim: Usd.Prim, specializes: Usd.Specializes) -> bool: return specializes.AddSpecialize(base_prim.GetPath()) ############# # 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) prim: Usd.Prim = UsdGeom.Xform.Define(stage, default_prim.GetPath().AppendPath("prim")).GetPrim() base: Usd.Prim = UsdGeom.Xform.Define(stage, default_prim.GetPath().AppendPath("base")).GetPrim() specializes: Usd.Specializes = prim.GetSpecializes() added_successfully = add_specialize_to(base, specializes) usda = stage.GetRootLayer().ExportToString() print(usda) assert added_successfully
999
Python
34.714284
98
0.746747
NVIDIA-Omniverse/OpenUSD-Code-Samples/source/specializes/add-specialize/usda.md
This is an example USDA result adding an Specialize Arc to a prim. ``` {literalinclude} usda.usda :language: usd ```
117
Markdown
28.499993
66
0.735043
NVIDIA-Omniverse/OpenUSD-Code-Samples/source/specializes/add-specialize/config.toml
[core] title = "Add a Specialize" [metadata] description = "Universal Scene Description (OpenUSD) code samples for adding a Specialize composition arc to a prim." keywords = ["OpenUSD", "USD", "Python", "snippet", "code sample", "specialize", "composition", "composition arc"]
277
TOML
45.333326
117
0.729242
NVIDIA-Omniverse/OpenUSD-Code-Samples/source/prims/select-prim-by-path/py_omni_usd.py
# SPDX-FileCopyrightText: Copyright (c) 2023 NVIDIA CORPORATION & AFFILIATES. All rights reserved. # SPDX-License-Identifier: Apache-2.0 import omni.usd prim_path = "/World/My/Prim" ctx = omni.usd.get_context() # The second arg is unused. Any boolean can be used. ctx.get_selection().set_selected_prim_paths([prim_path], True)
328
Python
35.555552
98
0.75
NVIDIA-Omniverse/OpenUSD-Code-Samples/source/prims/select-prim-by-path/py_kit_cmds.py
# SPDX-FileCopyrightText: Copyright (c) 2023 NVIDIA CORPORATION & AFFILIATES. All rights reserved. # SPDX-License-Identifier: Apache-2.0 import omni.kit.commands import omni.usd prim_path = "/World/My/Prim" ctx = omni.usd.get_context() old_selection = ctx.get_selection().get_selected_prim_paths() omni.kit.commands.execute('SelectPrimsCommand', old_selected_paths=old_selection, new_selected_paths=[prim_path], expand_in_stage=True) #DEPRECATED: Used only for backwards compatibility.
500
Python
34.785712
98
0.76
NVIDIA-Omniverse/OpenUSD-Code-Samples/source/prims/select-prim-by-path/config.toml
[core] title = "Select a Prim by Prim Path" [metadata] description = "Universal Scene Description (OpenUSD) code samples showing how to select a prim using its prim path." keywords = ["OpenUSD", "USD", "Python", "code sample", "prim", "selection", "by path", "path", "prim path"]
281
TOML
45.999992
116
0.697509
NVIDIA-Omniverse/OpenUSD-Code-Samples/source/prims/select-prim-by-path/py_omni_usd.md
``` {literalinclude} py_omni_usd.py :language: py ```
53
Markdown
16.999994
35
0.660377
NVIDIA-Omniverse/OpenUSD-Code-Samples/source/prims/check-prim-exists/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 check_prim_exists(prim: Usd.Prim) -> bool: if prim.IsValid(): return True return False ############# # 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 one prim and cube: Usd.Prim = UsdGeom.Cube.Define(stage, Sdf.Path("/World/Cube")).GetPrim() empty_prim = Usd.Prim() usda = stage.GetRootLayer().ExportToString() print(usda) # Check if prims exist assert check_prim_exists(default_prim) assert check_prim_exists(cube) assert not check_prim_exists(empty_prim)
893
Python
26.937499
98
0.718925
NVIDIA-Omniverse/OpenUSD-Code-Samples/source/prims/check-prim-exists/py_usd.md
``` {literalinclude} py_usd.py :language: py ``` Alternatively, `Usd.Object` overrides the boolean operator so you can check with a simple boolean expression. ``` {literalinclude} py_usd_var1.py :language: py ```
214
Markdown
22.888886
109
0.728972
NVIDIA-Omniverse/OpenUSD-Code-Samples/source/prims/check-prim-exists/config.toml
[core] title = "Check if a Prim Exists" [metadata] description = "Universal Scene Description (OpenUSD) code samples for checking if a Prim exists on a Stage." keywords = ["OpenUSD", "USD", "Python", "snippet", "code sample", "prim", "exists", "IsValid", "valid"]
264
TOML
43.166659
108
0.69697
NVIDIA-Omniverse/OpenUSD-Code-Samples/source/prims/get-prim/py_usd.py
# SPDX-FileCopyrightText: Copyright (c) 2023 NVIDIA CORPORATION & AFFILIATES. All rights reserved. # SPDX-License-Identifier: Apache-2.0 from typing import Union from pxr import Usd, Sdf def get_prim_by_path(stage: Usd.Stage, prim_path: Union[str, Sdf.Path]) -> Usd.Prim: return stage.GetPrimAtPath(prim_path) ############## # Full Usage ############## from pxr import UsdGeom # 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 prims UsdGeom.Xform.Define(stage, "/World/Group") UsdGeom.Cube.Define(stage, "/World/Group/Foo") # Get a prim using a str object group_prim_path = "/World/Group" group_prim = get_prim_by_path(stage, group_prim_path) # Get a prim using an Sdf.Path object foo_prim_path = Sdf.Path("/World/Group/Foo") foo_prim = get_prim_by_path(stage, foo_prim_path) # Print the prim objects that were retrieved print(group_prim) print(foo_prim) # Check that the prims retrieve match the paths provided assert group_prim.GetPath() == Sdf.Path(group_prim_path) assert foo_prim.GetPath() == foo_prim_path
1,214
Python
30.973683
98
0.729819
NVIDIA-Omniverse/OpenUSD-Code-Samples/source/prims/get-prim/py_usd.md
Get a prim by using the prim’s path: ``` {literalinclude} py_usd.py :language: py ```
86
Markdown
16.399997
36
0.674419
NVIDIA-Omniverse/OpenUSD-Code-Samples/source/prims/get-prim/config.toml
[core] title = "Get a Prim" [metadata] description = "Universal Scene Description (OpenUSD) code samples for accessing or getting a Prim on the Stage." keywords = ["OpenUSD", "USD", "Python", "code sample", "prim", "get prim", "accessing", "IsValid", "valid"]
260
TOML
42.499993
112
0.696154
NVIDIA-Omniverse/OpenUSD-Code-Samples/source/prims/get-current-selected-prims/py_usdview.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 prims: List[Usd.Prim] = usdviewApi.selectedPrims
231
Python
32.142853
98
0.792208
NVIDIA-Omniverse/OpenUSD-Code-Samples/source/prims/get-current-selected-prims/py_omni_usd.py
# SPDX-FileCopyrightText: Copyright (c) 2023 NVIDIA CORPORATION & AFFILIATES. All rights reserved. # SPDX-License-Identifier: Apache-2.0 import omni.usd prim_path = "/World/My/Prim" ctx = omni.usd.get_context() # returns a list of prim path strings selection = ctx.get_selection().get_selected_prim_paths()
308
Python
33.33333
98
0.756494
NVIDIA-Omniverse/OpenUSD-Code-Samples/source/prims/get-current-selected-prims/py_usdview.md
*usdview* Python interpreter has a built-in object called `usdviewApi` that gives you access to the currently selected prims. ``` {literalinclude} py_usdview.py :language: py ```
178
Markdown
43.749989
125
0.769663
NVIDIA-Omniverse/OpenUSD-Code-Samples/source/prims/get-current-selected-prims/config.toml
[core] title = "Get the Currently Selected Prims" [metadata] description = "Universal Scene Description (OpenUSD) code samples for getting the currently selected prim(s)." keywords = ["OpenUSD", "USD", "Python", "code sample", "prim", "selection", "selected", "prims", "usdview"]
281
TOML
45.999992
110
0.715302
NVIDIA-Omniverse/OpenUSD-Code-Samples/source/inherits/add-inherit/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 add_inherit(stage: Usd.Stage, prim: Usd.Prim, class_prim: Usd.Prim): inherits: Usd.Inherits = prim.GetInherits() inherits.AddInherit(class_prim.GetPath()) ############# # 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) # The base prim typically uses the "class" Specifier to designate that it # is meant to be inherited and skipped in standard stage traversals tree_class: Usd.Prim = stage.CreateClassPrim("/_class_Tree") tree_prim: Usd.Prim = UsdGeom.Mesh.Define(stage, default_prim.GetPath().AppendPath("TreeA")).GetPrim() add_inherit(stage, tree_prim, tree_class) usda = stage.GetRootLayer().ExportToString() print(usda) # Check to see if the inherit was added inherits_list = tree_prim.GetInherits().GetAllDirectInherits() assert tree_class.GetPath() in inherits_list
1,190
Python
35.090908
102
0.743697
NVIDIA-Omniverse/OpenUSD-Code-Samples/source/inherits/add-inherit/py_usd.md
This code sample shows how to add an Inherit arc to a prim. A single prim can have multiple Inherits. ``` {literalinclude} py_usd.py :language: py ```
152
Markdown
24.499996
101
0.730263
NVIDIA-Omniverse/OpenUSD-Code-Samples/source/inherits/add-inherit/usda.md
This is an example USDA result adding an Inherit Arc to a prim. ``` {literalinclude} usda.usda :language: usd ```
114
Markdown
27.749993
63
0.72807
NVIDIA-Omniverse/OpenUSD-Code-Samples/source/data-types/convert-vtarray-numpy/py_usd.py
# SPDX-FileCopyrightText: Copyright (c) 2023 NVIDIA CORPORATION & AFFILIATES. All rights reserved. # SPDX-License-Identifier: Apache-2.0 import numpy from pxr import Vt def convert_vt_to_np(my_array: Vt.Vec3fArray) -> numpy.ndarray: return numpy.array(my_vec3_array) ############# # Full Usage ############# # Create a Vt.Vec3fArray and convert it to a numpy array my_vec3_array = Vt.Vec3fArray([(1,2,3),(4,5,6),(7,8,9)]) np_array: numpy.ndarray = convert_vt_to_np(my_vec3_array) # print the numpy array to check the values print(np_array) # check the size and length of the numpy array assert np_array.size == 9 assert len(np_array) == 3
651
Python
24.076922
98
0.695853
NVIDIA-Omniverse/OpenUSD-Code-Samples/source/data-types/convert-vtarray-numpy/py_usd.md
**Convert to Numpy Array** To convert a VtArray to a Numpy Array, simply pass the VtArray object to `numpy.array` constructor. ``` {literalinclude} py_usd.py :language: py ``` **Convert from Numpy Array** To convert a Numpy Array to a VtArray, you can use `FromNumpy()` from the VtArray class you want to convert to. ``` {literalinclude} py_usd_var1.py :language: py ```
377
Markdown
24.199998
111
0.71618
NVIDIA-Omniverse/OpenUSD-Code-Samples/source/data-types/convert-vtarray-numpy/config.toml
[core] title = "Convert Between VtArray and Numpy Array" [metadata] description = "Universal Scene Description (OpenUSD) code samples for converting between VtArray classes and Numpy." keywords = ["OpenUSD", "USD", "Python", "snippet", "code sample", "types", "array", "numpy", "VtArray"]
289
TOML
47.333325
116
0.726644
NVIDIA-Omniverse/OpenUSD-Code-Samples/source/data-types/convert-vtarray-numpy/py_usd_var1.py
# SPDX-FileCopyrightText: Copyright (c) 2023 NVIDIA CORPORATION & AFFILIATES. All rights reserved. # SPDX-License-Identifier: Apache-2.0 import numpy from pxr import Vt def convert_np_to_vt(my_array: numpy.ndarray) -> Vt.Vec3fArray: return Vt.Vec3fArray.FromNumpy(my_array) ############# # Full Usage ############# # Create a numpy array and convert it into a Vt.Vec3fArray np_array = numpy.array([(1,2,3),(4,5,6),(7,8,9)]) from_numpy: Vt.Vec3fArray = convert_np_to_vt(np_array) # Print the Vt.Vec3fArray to check the values print(from_numpy) # Check the length of the numpy array assert len(np_array) == 3
618
Python
24.791666
98
0.700647
NVIDIA-Omniverse/OpenUSD-Code-Samples/source/data-types/convert-vtarray-numpy/header.md
Some Attributes store array type data which are accessed using the VtArray classes. You can find a list of the VtArray classes in our [USD Data Types documentation](https://docs.omniverse.nvidia.com/dev-guide/latest/dev_usd/quick-start/usd-types.html) If you need to manipulate the arrays using Python, it is advantageous to use Numpy to benefit from it's speed and efficiency. These code samples show how you can convert between the VtArray objects and Numpy Array objects. ```{note} These examples show how to convert using only the Vt.Vec3fArray class, but the same can be applied to any VtArray class. See what other VtArray classes exist in the [USD Data Types documentation](https://docs.omniverse.nvidia.com/dev-guide/latest/dev_usd/quick-start/usd-types.html). ```
778
Markdown
76.899992
283
0.790488
NVIDIA-Omniverse/OpenUSD-Code-Samples/source/paths/concatenate-property-with-prim-path/py_usd.py
# SPDX-FileCopyrightText: Copyright (c) 2023 NVIDIA CORPORATION & AFFILIATES. All rights reserved. # SPDX-License-Identifier: Apache-2.0 from pxr import Sdf def concat_property_with_prim_path(prim_path: Sdf.Path, prop) -> Sdf.Path: prop_path = prim_path.AppendProperty(prop) return prop_path ############# # Full Usage ############# # e.g., get path to "points" attribute on a mesh prim from pxr import UsdGeom, Usd stage: Usd.Stage = Usd.Stage.CreateInMemory() default_prim: Usd.Prim = UsdGeom.Xform.Define(stage, Sdf.Path("/World")).GetPrim() stage.SetDefaultPrim(default_prim) mesh_prim: Usd.Prim = UsdGeom.Xform.Define(stage, Sdf.Path("/World/Mesh")).GetPrim() prop_path: Sdf.Path = concat_property_with_prim_path(mesh_prim.GetPrimPath(), UsdGeom.Tokens.points) #nothing happend so did it get added? usda = stage.GetRootLayer().ExportToString() print(usda) assert Sdf.Path.IsValidPathString(prop_path.pathString)
932
Python
33.555554
138
0.73176
NVIDIA-Omniverse/OpenUSD-Code-Samples/source/paths/concatenate-property-with-prim-path/config.toml
[core] title = "Concatenate a Property Name with a Prim Path" [metadata] description = "Universal Scene Description (OpenUSD) code samples showing how to concatenate a property name with a prim path." keywords = ["OpenUSD", "USD", "Python", "snippet", "code sample", "prim", "property", "path", "AppendProperty"]
313
TOML
51.333325
127
0.728435
NVIDIA-Omniverse/OpenUSD-Code-Samples/source/paths/get-parent-path/py_usd.py
# SPDX-FileCopyrightText: Copyright (c) 2023 NVIDIA CORPORATION & AFFILIATES. All rights reserved. # SPDX-License-Identifier: Apache-2.0 from pxr import Sdf def get_parent_path(prim_path: Sdf.Path) -> Sdf.Path: parent_path = prim_path.GetParentPath() return parent_path ############# # Full Usage ############# from pxr import Usd, 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) cone_prim = UsdGeom.Cone.Define(stage, Sdf.Path("/World/Cone")).GetPrim() # Given Sdf.Path('/World/Cone') for my_prim_path, parent_path will contain Sdf.Path('/World') parent_path = get_parent_path(cone_prim.GetPrimPath()) usda = stage.GetRootLayer().ExportToString() print(usda) assert parent_path == default_prim.GetPrimPath()
918
Python
33.037036
98
0.724401
NVIDIA-Omniverse/OpenUSD-Code-Samples/source/paths/get-parent-path/usda.md
This is an example USDA result from adding a Cone to the a World Prim. ``` {literalinclude} usda.usda :language: usd ```
121
Markdown
29.499993
70
0.727273
NVIDIA-Omniverse/OpenUSD-Code-Samples/source/paths/get-parent-path/config.toml
[core] title = "Get the Parent Path for a Prim Path" [metadata] description = "Universal Scene Description (OpenUSD) code samples for getting the parent path from a prim path." keywords = ["OpenUSD", "USD", "Python", "snippet", "code sample", "prim", "path", "GetParentPath"]
276
TOML
45.166659
112
0.713768
NVIDIA-Omniverse/OpenUSD-Code-Samples/source/paths/concatenate-prim-path/py_usd.py
# SPDX-FileCopyrightText: Copyright (c) 2023 NVIDIA CORPORATION & AFFILIATES. All rights reserved. # SPDX-License-Identifier: Apache-2.0 from pxr import Sdf def concat_prim_path(prim_path: Sdf.Path, path_to_add: str) -> Sdf.Path: concat_path = prim_path.AppendPath(path_to_add) return concat_path ############# # Full Usage ############# from pxr import Usd, 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) # Concatenate the Paths concatenated_prim_path: Sdf.Path = concat_prim_path(default_prim.GetPrimPath(), "Kitchen_set/Props_grp/North_grp/NorthWall_grp/MeasuringSpoon_1") usda = stage.GetRootLayer().ExportToString() print(usda) assert concatenated_prim_path.pathString == "/World/Kitchen_set/Props_grp/North_grp/NorthWall_grp/MeasuringSpoon_1"
960
Python
34.592591
145
0.742708
NVIDIA-Omniverse/OpenUSD-Code-Samples/source/paths/concatenate-prim-path/config.toml
[core] title = "Concatenate a Prim Path" [metadata] description = "Universal Scene Description (OpenUSD) code samples for concatenating prim paths." keywords = ["OpenUSD", "USD", "Python", "snippet", "code sample", "concatenate", "prim", "path", "AppendPath"]
261
TOML
42.66666
111
0.712644
NVIDIA-Omniverse/OpenUSD-Code-Samples/source/properties/get-relationship-targets/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 # For example, getting the proxy prim on an Imageable proxy_prim_rel: Usd.Relationship = UsdGeom.Imageable(myprim).GetProxyPrimRel() proxyPrimTargets = proxy_prim_rel.GetForwardedTargets()
356
Python
43.624995
98
0.797753
NVIDIA-Omniverse/OpenUSD-Code-Samples/source/properties/get-relationship-targets/config.toml
[core] # The title for this code sample. Used to name the page. title = "Get the Targets of a Relationship" [metadata] #A concise description of the code sample for SEO. description = "Universal Scene Description (OpenUSD) code samples for getting the targets of a Relationship taking into account relationship forwarding." # Put in SEO keywords relevant to this code sample. keywords = ["OpenUSD", "USD", "code sample", "snippet", "Python", "C++", "relationship", "targets", "relationship forwarding"]
503
TOML
54.999994
153
0.751491
NVIDIA-Omniverse/OpenUSD-Code-Samples/source/properties/check-property-exists/py_usd.py
# SPDX-FileCopyrightText: Copyright (c) 2023 NVIDIA CORPORATION & AFFILIATES. All rights reserved. # SPDX-License-Identifier: Apache-2.0 from pxr import Usd pts_attr: Usd.Attribute = mesh_prim.GetAttribute("points") if pts_attr.IsValid(): print("Attribute exists!")
271
Python
32.999996
98
0.756458
NVIDIA-Omniverse/OpenUSD-Code-Samples/source/properties/check-property-exists/config.toml
[core] # The title for this code sample. Used to name the page. title = "Check if a Property Exists" [metadata] #A concise description of the code sample for SEO. description = "Universal Scene Description (OpenUSD) code samples for checking if a Property exists." # Put in SEO keywords relevant to this code sample. keywords = ["OpenUSD", "USD", "code sample", "snippet", "Python", "C++", "property", "relationship", "attribute", "IsValid", "exists", "valid"]
461
TOML
50.333328
143
0.720174
NVIDIA-Omniverse/OpenUSD-Code-Samples/source/properties/check-property-exists/header.md
Certain functions may return a `Usd.Property` object, but the Property may not exist due to an incorrect path or because of changes on the Stage. You can use [Usd.Object.IsValid()](https://openusd.org/release/api/class_usd_object.html#ac532c4b500b1a85ea22217f2c65a70ed) to check if the Property is valid or exists. ```{note} Remember, that Properties consist of `Usd.Attribute` and `Usd.Relationship`. You can perform this check on both types of objects. ```
464
Markdown
76.499987
314
0.773707
NVIDIA-Omniverse/OpenUSD-Code-Samples/source/properties/create-relationship/py_usd.py
# SPDX-FileCopyrightText: Copyright (c) 2023 NVIDIA CORPORATION & AFFILIATES. All rights reserved. # SPDX-License-Identifier: Apache-2.0 from pxr import Usd prim: Usd.Prim = stage.GetPrimAtPath("/World/MyPrim") custom_relationship: Usd.Relationship = prim.CreateRelationship("myCustomRelationship") # You can also use Usd.Relationship.AddTarget() to add targets to an existing Relationship. custom_relationship.SetTargets(["/World/TargetA", "/World/TargetB"])
461
Python
50.333328
98
0.789588
NVIDIA-Omniverse/OpenUSD-Code-Samples/source/properties/create-relationship/config.toml
[core] # The title for this code sample. Used to name the page. title = "Create a Relationship" [metadata] #A concise description of the code sample for SEO. description = "Universal Scene Description (OpenUSD) code samples for creating a Relationship." # Put in SEO keywords relevant to this code sample. keywords = ["OpenUSD", "USD", "code sample", "snippet", "Python", "C++", "property", "relationship", "create", "create relationship"]
440
TOML
47.999995
133
0.731818
NVIDIA-Omniverse/OpenUSD-Code-Samples/source/properties/create-attribute/py_kit_cmds.md
The `CreateUsdAttributeCommand` command in Kit can create an Attribute on a prim. The Attribute name and type are required. ``` {literalinclude} py_kit_cmds.py :language: py ```
180
Markdown
35.199993
125
0.755556
NVIDIA-Omniverse/OpenUSD-Code-Samples/source/properties/create-attribute/py_usd.py
# SPDX-FileCopyrightText: Copyright (c) 2023 NVIDIA CORPORATION & AFFILIATES. All rights reserved. # SPDX-License-Identifier: Apache-2.0 from pxr import Gf, Sdf, Usd, UsdGeom """ Find all relevant data types at: https://openusd.org/release/api/_usd__page__datatypes.html """ def create_float_attribute(prim: Usd.Prim, attribute_name: str) -> Usd.Attribute: """Creates attribute for a prim that holds a float. See: https://openusd.org/release/api/class_usd_prim.html Args: prim (Usd.Prim): A Prim for holding the attribute. attribute_name (str): The name of the attribute to create. Returns: Usd.Attribute: An attribute created at specific prim. """ attr: Usd.Attribute = prim.CreateAttribute(attribute_name, Sdf.ValueTypeNames.Float) return attr def create_vector_attribute(prim: Usd.Prim, attribute_name: str) -> Usd.Attribute: """Creates attribute for a prim that holds a vector. See: https://openusd.org/release/api/class_usd_prim.html Args: prim (Usd.Prim): A Prim for holding the attribute. attribute_name (str): The name of the attribute to create. Returns: Usd.Attribute: An attribute created at specific prim. """ attr: Usd.Attribute = prim.CreateAttribute( attribute_name, Sdf.ValueTypeNames.Float3 ) return attr ############# # Full Usage ############# # Create an in-memory Stage stage: Usd.Stage = Usd.Stage.CreateInMemory() # Create a prim named /World (type Xform) and make it the default prim. prim_path = "/World" xform: UsdGeom.Xform = UsdGeom.Xform.Define(stage, prim_path) prim: Usd.Prim = xform.GetPrim() stage.SetDefaultPrim(prim) # Create a float attribute on /World float_attr: Usd.Attribute = create_float_attribute(prim, "my_float_attr") # Create a vector attribute on /World vector_attr: Usd.Attribute = create_vector_attribute(prim, "my_vector_attr") # Set and query values print(float_attr.Get()) float_attr.Set(0.1) print(float_attr.Get()) vector_value: Gf.Vec3f = Gf.Vec3f(0.1, 0.2, 0.3) print(vector_attr.Get()) vector_attr.Set(vector_value) print(vector_attr.Get()) # Optionally preview the usd # print(stage.GetRootLayer().ExportToString())
2,205
Python
30.514285
98
0.702041
NVIDIA-Omniverse/OpenUSD-Code-Samples/source/properties/create-attribute/py_usd.md
With the USD API, you can use `Usd.Prim.CreateAttribute()` to create `attributes` on `Usd.Prim` objects. You can set the value using `Usd.Attribute.Set()` and query the value using `Usd.Attribute.Get()` ``` {literalinclude} py_usd.py :language: py ```
253
Markdown
35.285709
104
0.719368
NVIDIA-Omniverse/OpenUSD-Code-Samples/source/properties/create-attribute/py_kit_cmds.py
# SPDX-FileCopyrightText: Copyright (c) 2023 NVIDIA CORPORATION & AFFILIATES. All rights reserved. # SPDX-License-Identifier: Apache-2.0 import omni.kit.commands import omni.usd from pxr import Gf, Sdf, Usd, UsdGeom def create_float_attribute(prim: Usd.Prim, attribute_name: str) -> Usd.Attribute: """Creates attribute for a prim that holds a float. See: https://openusd.org/release/api/class_usd_prim.html See: https://docs.omniverse.nvidia.com/kit/docs/omni.usd/latest/omni.usd.commands/omni.usd.commands.CreateUsdAttributeCommand.html Args: prim (Usd.Prim): A Prim for holding the attribute. attribute_name (str): The name of the attribute to create. Returns: Usd.Attribute: An attribute created at specific prim. """ omni.kit.commands.execute( "CreateUsdAttributeCommand", prim=prim, attr_name=attribute_name, attr_type=Sdf.ValueTypeNames.Float, ) attr: Usd.Attribute = prim.GetAttribute(attribute_name) return attr def create_vector_attribute(prim: Usd.Prim, attribute_name: str) -> Usd.Attribute: """Creates attribute for a prim that holds a vector. See: https://openusd.org/release/api/class_usd_prim.html See: https://docs.omniverse.nvidia.com/kit/docs/omni.usd/latest/omni.usd.commands/omni.usd.commands.CreateUsdAttributeCommand.html Args: prim (Usd.Prim): A Prim for holding the attribute. attribute_name (str): The name of the attribute to create. Returns: Usd.Attribute: An attribute created at specific prim. """ omni.kit.commands.execute( "CreateUsdAttributeCommand", prim=prim, attr_name=attribute_name, attr_type=Sdf.ValueTypeNames.Float3, ) attr: Usd.Attribute = prim.GetAttribute(attribute_name) return attr ############# # Full Usage ############# # Get the current stage stage: Usd.Stage = omni.usd.get_context().get_stage() # Get the default prim prim: Usd.Prim = stage.GetDefaultPrim() # Create a float attribute on /World float_attr: Usd.Attribute = create_float_attribute(prim, "my_float_attr") # Create a vector attribute on /World vector_attr: Usd.Attribute = create_vector_attribute(prim, "my_vector_attr") # Set and query values print(float_attr.Get()) float_attr.Set(0.1) print(float_attr.Get()) vector_value: Gf.Vec3f = Gf.Vec3f(0.1, 0.2, 0.3) print(vector_attr.Get()) vector_attr.Set(vector_value) print(vector_attr.Get()) # Optionally preview the usd # print(stage.GetRootLayer().ExportToString())
2,539
Python
31.151898
134
0.700276
NVIDIA-Omniverse/OpenUSD-Code-Samples/source/properties/create-attribute/usda.md
This is an example USDA result from creating an Xform and Cube prim. Where the Cube prim is a child of the Xform and the Xform has it's own Translation Ops. ``` {literalinclude} usda.usda :language: usd ```
207
Markdown
50.999987
156
0.753623
NVIDIA-Omniverse/OpenUSD-Code-Samples/source/properties/create-attribute/config.toml
[core] # The title for this code sample. Used to name the page. title = "Create an Attribute" [metadata] description = "Universal Scene Description (OpenUSD) code samples to create an attribute." keywords = ["OpenUSD", "USD", "Python", "snippet", "code sample", "attribute", "property", "create"]
297
TOML
41.571423
100
0.717172