file_path
stringlengths
20
207
content
stringlengths
5
3.85M
size
int64
5
3.85M
lang
stringclasses
9 values
avg_line_length
float64
1.33
100
max_line_length
int64
4
993
alphanum_fraction
float64
0.26
0.93
md84419/kit-app-title-menu-logo-experiment/VERSION.md
104.0
6
Markdown
2.499999
5
0.666667
md84419/kit-app-title-menu-logo-experiment/repo.toml
######################################################################################################################## # Repo tool base settings ######################################################################################################################## [repo] # Use the Kit Template repo configuration as a base. Only override things specific to the repo. import_configs = [ "${root}/_repo/deps/repo_kit_tools/kit-template/repo.toml", "${root}/_repo/deps/repo_kit_tools/kit-template/repo-app.toml" ] # Repository Name name = "kit-app-template" [repo_kit_link_app] app_name = "create" # App name. app_version = "" # App version. Empty means latest. Specify to lock version, e.g. "2022.2.0-rc.3" ######################################################################################################################## # Documentation building ######################################################################################################################## [repo_docs] #name = "Kit App Template" # kit-manual doc [[repo_docs.kit.custom_project]] name = "kit-app-template" root = "${root}" config_path = "${root}/docs/docs.toml" [repo_docs.kit] extensions = [ ]
1,204
TOML
29.897435
120
0.407807
md84419/kit-app-title-menu-logo-experiment/README.md
# Omniverse kit-app-title-menu-logo-experiment [robotica.example.app.logo] A scratch space for exploring and experimenting with an app logo that spans the title and menu bars. ![](./source/extensions/robotica.example.app.logo/data/preview.png) # Getting Started ## Requirements - NVIDIA Omniverse Launcher - An Omniverse App (Create, Code, etc) - Kit 104.1 or later - Tested with Create 2022.3.3 ``` > .\link_app.bat > .\runbuild.bat ``` # Background ## User Story As a marketing exec, I want to brand our company apps so that they are visually distinctive and easily identifiable, delivering 5 key benefits: - Brand recognition - establish and reinforce brand identify, as a visual representation of our company and its values - Professionalism and credibility, emphasising that we pay attention to detail and instilling confidence in users, allowing them to trust and engage with the app - Differentiation and memorability, building a connection with our target audience ## The solution Omniverse currently provides limited ability to control the [chrome](https://www.nngroup.com/articles/browser-and-gui-chrome/) for applications. This experiment provides a way to work around those limitations to create a more distinctive app design. This should be considered a temporary workaround until Omniverse provides a better solution: we're taking advantage of undocumented features about the way that Omniverse currently works, which results in fragile code which is likely to break in future Omniverse releases. This experiment is designed for and only works when running on Microsoft Windows. This is example code. It is not ready for production use and has not been optimised. It is unlikely to scale well. # Feature tracking Two feature requests have been logged related to this ticket. - [OVC-2561 - Positioning of title in main window](https://nvidia-omniverse.atlassian.net/servicedesk/customer/portal/4/OVC-2561) - [Forum discussion 254770 - UI Apps - Finer-grained control of main window chrome](https://forums.developer.nvidia.com/t/ui-apps-finer-grained-control-of-main-window-chrome/254770) # Contributing The source code for this repository is provided as-is. We only accept outside contributions from individuals who have signed an Individual Contributor License Agreement.
2,313
Markdown
44.372548
181
0.792045
md84419/kit-app-title-menu-logo-experiment/LICENSE-kit-app-template.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 2022 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.
11,348
Markdown
55.183168
77
0.732376
md84419/kit-app-title-menu-logo-experiment/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 (c), ROBOTICA MACHINE LEARNING LIMITED, 2023. Portions Copyright 2022 NVIDIA CORPORATION: - This app is based on the NVIDIA Kit App template: https://github.com/NVIDIA-Omniverse/kit-app-template 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,527
Markdown
54.961165
107
0.732628
md84419/kit-app-title-menu-logo-experiment/deps/repo-deps.packman.xml
<project toolsVersion="5.0"> <dependency name="repo_man" linkPath="../_repo/deps/repo_man"> <package name="repo_man" version="1.10.1"/> </dependency> <dependency name="repo_build" linkPath="../_repo/deps/repo_build"> <package name="repo_build" version="0.27.1"/> </dependency> <dependency name="repo_changelog" linkPath="../_repo/deps/repo_changelog"> <package name="repo_changelog" version="0.2.20"/> </dependency> <dependency name="repo_docs" linkPath="../_repo/deps/repo_docs"> <package name="repo_docs" version="0.9.17"/> </dependency> <dependency name="repo_kit_tools" linkPath="../_repo/deps/repo_kit_tools"> <package name="repo_kit_tools" version="0.8.13"/> </dependency> <dependency name="repo_source" linkPath="../_repo/deps/repo_source"> <package name="repo_source" version="0.3.0" /> </dependency> <dependency name="repo_package" linkPath="../_repo/deps/repo_package"> <package name="repo_package" version="5.6.8" /> </dependency> <dependency name="repo_docs" linkPath="../_repo/deps/repo_docs"> <package name="repo_docs" version="0.10.1" /> </dependency> </project>
1,143
XML
41.370369
76
0.661417
md84419/kit-app-title-menu-logo-experiment/deps/host-deps.packman.xml
<project toolsVersion="5.0"> <dependency name="premake" linkPath="../_build/host-deps/premake"> <package name="premake" version="5.0.0-alpha15.dev+pipeline3388156.1f299ea4-${platform}"/> </dependency> <dependency name="msvc" linkPath="../_build/host-deps/msvc"> <package name="msvc" version="2019-16.7.6-license" platforms="windows-x86_64"/> </dependency> <dependency name="winsdk" linkPath="../_build/host-deps/winsdk"> <package name="winsdk" version="10.0.18362.0-license" platforms="windows-x86_64"/> </dependency> </project>
555
XML
38.714283
94
0.693694
md84419/kit-app-title-menu-logo-experiment/deps/kit-sdk-deps.packman.xml
<project toolsVersion="5.0"> <!-- Only edit this file to pull kit depedencies. --> <!-- Put all extension-specific dependencies in `ext-deps.packman.xml`. --> <!-- This file contains shared Kit SDK dependencies used by most kit extensions. --> <!-- Import Kit SDK all-deps xml file to steal some deps from it: --> <import path="../_build/${platform}/${config}/kit/dev/all-deps.packman.xml"> <filter include="pybind11" /> <filter include="fmt" /> <filter include="python" /> <filter include="carb_sdk_plugins" /> </import> <!-- Pull those deps of the same version as in Kit SDK. Override linkPath to point correctly, other properties can also be override, including version. --> <dependency name="carb_sdk_plugins" linkPath="../_build/target-deps/carb_sdk_plugins" tags="non-redist" /> <dependency name="pybind11" linkPath="../_build/target-deps/pybind11" /> <dependency name="fmt" linkPath="../_build/target-deps/fmt" /> <dependency name="python" linkPath="../_build/target-deps/python" /> </project>
1,041
XML
51.099997
157
0.682997
md84419/kit-app-title-menu-logo-experiment/deps/ext-deps.packman.xml
<project toolsVersion="5.0"> <!-- Use this file to include any dependencies for your extension beyond those in `kit-sdk-deps.packman.xml`. --> </project>
157
XML
30.599994
115
0.713376
md84419/kit-app-title-menu-logo-experiment/tools/repoman/repoman.py
import os import sys import io import contextlib import packmanapi REPO_ROOT = os.path.join(os.path.dirname(os.path.realpath(__file__)), "../..") REPO_DEPS_FILE = os.path.join(REPO_ROOT, "deps/repo-deps.packman.xml") def bootstrap(): """ Bootstrap all omni.repo modules. Pull with packman from repo.packman.xml and add them all to python sys.path to enable importing. """ #with contextlib.redirect_stdout(io.StringIO()): deps = packmanapi.pull(REPO_DEPS_FILE) for dep_path in deps.values(): if dep_path not in sys.path: sys.path.append(dep_path) if __name__ == "__main__": bootstrap() import omni.repo.man omni.repo.man.main(REPO_ROOT)
703
Python
23.275861
100
0.661451
md84419/kit-app-title-menu-logo-experiment/tools/packman/packmanconf.py
# Use this file to bootstrap packman into your Python environment (3.7.x). Simply # add the path by doing sys.insert to where packmanconf.py is located and then execute: # # >>> import packmanconf # >>> packmanconf.init() # # It will use the configured remote(s) and the version of packman in the same folder, # giving you full access to the packman API via the following module # # >> import packmanapi # >> dir(packmanapi) import os import platform import sys def init(): """Call this function to initialize the packman configuration. Calls to the packman API will work after successfully calling this function. Note: This function only needs to be called once during the execution of your program. Calling it repeatedly is harmless but wasteful. Compatibility with your Python interpreter is checked and upon failure the function will report what is required. Example: >>> import packmanconf >>> packmanconf.init() >>> import packmanapi >>> packmanapi.set_verbosity_level(packmanapi.VERBOSITY_HIGH) """ major = sys.version_info[0] minor = sys.version_info[1] if major != 3 or minor != 7: raise RuntimeError( f"This version of packman requires Python 3.7.x, but {major}.{minor} was provided" ) conf_dir = os.path.dirname(os.path.abspath(__file__)) os.environ["PM_INSTALL_PATH"] = conf_dir packages_root = get_packages_root(conf_dir) version = get_version(conf_dir) module_dir = get_module_dir(conf_dir, packages_root, version) sys.path.insert(1, module_dir) def get_packages_root(conf_dir: str) -> str: root = os.getenv("PM_PACKAGES_ROOT") if not root: platform_name = platform.system() if platform_name == "Windows": drive, _ = os.path.splitdrive(conf_dir) root = os.path.join(drive, "packman-repo") elif platform_name == "Darwin": # macOS root = os.path.join( os.path.expanduser("~"), "/Library/Application Support/packman-cache" ) elif platform_name == "Linux": try: cache_root = os.environ["XDG_HOME_CACHE"] except KeyError: cache_root = os.path.join(os.path.expanduser("~"), ".cache") return os.path.join(cache_root, "packman") else: raise RuntimeError(f"Unsupported platform '{platform_name}'") # make sure the path exists: os.makedirs(root, exist_ok=True) return root def get_module_dir(conf_dir, packages_root: str, version: str) -> str: module_dir = os.path.join(packages_root, "packman-common", version) if not os.path.exists(module_dir): import tempfile tf = tempfile.NamedTemporaryFile(delete=False) target_name = tf.name tf.close() url = f"http://bootstrap.packman.nvidia.com/packman-common@{version}.zip" print(f"Downloading '{url}' ...") import urllib.request urllib.request.urlretrieve(url, target_name) from importlib.machinery import SourceFileLoader # import module from path provided script_path = os.path.join(conf_dir, "bootstrap", "install_package.py") ip = SourceFileLoader("install_package", script_path).load_module() print("Unpacking ...") ip.install_package(target_name, module_dir) os.unlink(tf.name) return module_dir def get_version(conf_dir: str): path = os.path.join(conf_dir, "packman") if not os.path.exists(path): # in dev repo fallback path += ".sh" with open(path, "rt", encoding="utf8") as launch_file: for line in launch_file.readlines(): if line.startswith("PM_PACKMAN_VERSION"): _, value = line.split("=") return value.strip() raise RuntimeError(f"Unable to find 'PM_PACKMAN_VERSION' in '{path}'")
3,930
Python
35.398148
94
0.632316
md84419/kit-app-title-menu-logo-experiment/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
md84419/kit-app-title-menu-logo-experiment/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 os import stat import time from typing import Any, Callable RENAME_RETRY_COUNT = 100 RENAME_RETRY_DELAY = 0.1 logging.basicConfig(level=logging.WARNING, format="%(message)s") logger = logging.getLogger("install_package") def remove_directory_item(path): if os.path.islink(path) or os.path.isfile(path): try: os.remove(path) except PermissionError: # make sure we have access and try again: os.chmod(path, stat.S_IRWXU) os.remove(path) else: # try first to delete the dir because this will work for folder junctions, otherwise we would follow the junctions and cause destruction! clean_out_folder = False try: # make sure we have access preemptively - this is necessary because recursing into a directory without permissions # will only lead to heart ache os.chmod(path, stat.S_IRWXU) os.rmdir(path) except OSError: clean_out_folder = True if clean_out_folder: # we should make sure the directory is empty names = os.listdir(path) for name in names: fullname = os.path.join(path, name) remove_directory_item(fullname) # now try to again get rid of the folder - and not catch if it raises: os.rmdir(path) class StagingDirectory: def __init__(self, staging_path): self.staging_path = staging_path self.temp_folder_path = None os.makedirs(staging_path, exist_ok=True) def __enter__(self): self.temp_folder_path = tempfile.mkdtemp(prefix="ver-", dir=self.staging_path) return self def get_temp_folder_path(self): return self.temp_folder_path # this function renames the temp staging folder to folder_name, it is required that the parent path exists! def promote_and_rename(self, folder_name): abs_dst_folder_name = os.path.join(self.staging_path, folder_name) os.rename(self.temp_folder_path, abs_dst_folder_name) def __exit__(self, type, value, traceback): # Remove temp staging folder if it's still there (something went wrong): path = self.temp_folder_path if os.path.isdir(path): remove_directory_item(path) def rename_folder(staging_dir: StagingDirectory, folder_name: str): try: staging_dir.promote_and_rename(folder_name) except OSError as exc: # if we failed to rename because the folder now exists we can assume that another packman process # has managed to update the package before us - in all other cases we re-raise the exception abs_dst_folder_name = os.path.join(staging_dir.staging_path, folder_name) if os.path.exists(abs_dst_folder_name): logger.warning( f"Directory {abs_dst_folder_name} already present, package installation already completed" ) else: raise def call_with_retry( op_name: str, func: Callable, retry_count: int = 3, retry_delay: float = 20 ) -> Any: retries_left = retry_count while True: try: return func() except (OSError, IOError) as exc: logger.warning(f"Failure while executing {op_name} [{str(exc)}]") if retries_left: retry_str = "retry" if retries_left == 1 else "retries" logger.warning( f"Retrying after {retry_delay} seconds" f" ({retries_left} {retry_str} left) ..." ) time.sleep(retry_delay) else: logger.error("Maximum retries exceeded, giving up") raise retries_left -= 1 def rename_folder_with_retry(staging_dir: StagingDirectory, folder_name): dst_path = os.path.join(staging_dir.staging_path, folder_name) call_with_retry( f"rename {staging_dir.get_temp_folder_path()} -> {dst_path}", lambda: rename_folder(staging_dir, folder_name), RENAME_RETRY_COUNT, RENAME_RETRY_DELAY, ) def install_package(package_path, install_path): staging_path, version = os.path.split(install_path) with StagingDirectory(staging_path) as staging_dir: output_folder = staging_dir.get_temp_folder_path() with zipfile.ZipFile(package_path, allowZip64=True) as zip_file: zip_file.extractall(output_folder) # attempt the rename operation rename_folder_with_retry(staging_dir, version) print(f"Package successfully installed to {install_path}") if __name__ == "__main__": executable_paths = os.getenv("PATH") paths_list = executable_paths.split(os.path.pathsep) if executable_paths else [] target_path_np = os.path.normpath(sys.argv[2]) target_path_np_nc = os.path.normcase(target_path_np) for exec_path in paths_list: if os.path.normcase(os.path.normpath(exec_path)) == target_path_np_nc: raise RuntimeError(f"packman will not install to executable path '{exec_path}'") install_package(sys.argv[1], target_path_np)
5,776
Python
36.270968
145
0.645083
md84419/kit-app-title-menu-logo-experiment/source/extensions/robotica.example.app.logo/robotica/example/app/logo/logo_menu.py
# Copyright (c), ROBOTICA MACHINE LEARNING LIMITED, 2022. # License: Apache 2.0 from pathlib import Path import omni.client from omni.kit.menu.utils import MenuItemDescription, MenuAlignment import omni.ext import omni.kit.app import omni.ui as ui import omni.kit.menu.utils from typing import Union import omni.kit.window.modifier.titlebar DATA_PATH = Path(__file__).parent.parent.parent.parent.parent class RoboticaLogoDelegate(ui.MenuDelegate): def destroy(self): pass def build_item(self, item: ui.MenuHelper): with ui.HStack(width=0): ui.Spacer(width=0) with ui.HStack(content_clipping=1, width=0): with ui.Placer(offset_x=-36, offset_y=-1): with ui.Frame(width=80, horizontal_clipping=True): ui.Image( f"{DATA_PATH}/data/icon.png", width=90, height=32, alignment=ui.Alignment.BOTTOM, fill_policy=ui.FillPolicy.PRESERVE_ASPECT_CROP ) ui.Spacer(width=6) def get_menu_alignment(self): return MenuAlignment.DEFAULT def update_menu_item(self, menu_item: Union[ui.Menu, ui.MenuItem], menu_refresh: bool): if isinstance(menu_item, ui.MenuItem): menu_item.visible = False class LogoMenu: """ Place the bottom half of the Robotica logo as the first item in the menu, so it lines up with the top half of the Robotica logo from the title bar. """ def __init__(self): self._live_menu_name = "Robotica logo Widget" self._menu_list = [MenuItemDescription(name="placeholder", show_fn=lambda: False)] def register_menu_widgets(self): self._cache_state_delegate = RoboticaLogoDelegate() omni.kit.menu.utils.add_menu_items(self._menu_list, name=self._live_menu_name, menu_index=-98, delegate=self._cache_state_delegate) self._cache_state_delegate.build_item(self._live_menu_name) def unregister_menu_widgets(self): omni.kit.menu.utils.remove_menu_items(self._menu_list, self._live_menu_name) if self._cache_state_delegate: self._cache_state_delegate.destroy() self._cache_state_delegate = None self._menu_list = None
2,350
Python
34.621212
139
0.624255
md84419/kit-app-title-menu-logo-experiment/source/extensions/robotica.example.app.logo/robotica/example/app/logo/__init__.py
from .setup import *
21
Python
9.999995
20
0.714286
md84419/kit-app-title-menu-logo-experiment/source/extensions/robotica.example.app.logo/robotica/example/app/logo/setup.py
# Copyright (c), ROBOTICA MACHINE LEARNING LIMITED, 2022. # License: Apache 2.0 import asyncio from pathlib import Path import carb.imgui as _imgui import carb.settings import carb.tokens import omni.ext import omni.kit.ui as ui import omni.kit.menu.utils from omni.kit.menu.utils import MenuLayout from omni.kit.quicklayout import QuickLayout from omni.kit.window.title import get_main_window_title from .logo_menu import LogoMenu async def _load_layout(layout_file: str): """this private methods just help loading layout, you can use it in the Layout Menu""" await omni.kit.app.get_app().next_update_async() QuickLayout.load_file(layout_file) # This extension is mostly loading the Layout updating menu class SetupExtension(omni.ext.IExt): # ext_id is current extension id. It can be used with extension manager to query additional information, like where # this extension is located on filesystem. def on_startup(self, ext_id): # get the settings self._settings = carb.settings.get_settings() self._await_layout = asyncio.ensure_future(self._delayed_layout()) # setup the menu and their layout self._setup_menu() # setup the Application Title window_title = get_main_window_title() window_title.set_app_version(self._settings.get("/app/titleVersion")) # setup some imgui Style overide imgui = _imgui.acquire_imgui() imgui.push_style_color(_imgui.StyleColor.ScrollbarGrab, carb.Float4(0.4, 0.4, 0.4, 1)) imgui.push_style_color(_imgui.StyleColor.ScrollbarGrabHovered, carb.Float4(0.6, 0.6, 0.6, 1)) imgui.push_style_color(_imgui.StyleColor.ScrollbarGrabActive, carb.Float4(0.8, 0.8, 0.8, 1)) imgui.push_style_var_float(_imgui.StyleVar.DockSplitterSize, 1) self._is_darker_mode = False self._toggle_darker_mode() self._logo_menu = LogoMenu() self._logo_menu.register_menu_widgets() def _toggle_darker_mode(self): """Update Imgui to be on its darker Mode state vs the default Create/View mode""" self._is_darker_mode = not self._is_darker_mode if self._is_darker_mode: black = carb.Float4(0.0, 0.0, 0.0, 1) dark0 = carb.Float4(0.058, 0.058, 0.058, 1) # title bar colour dark1 = carb.Float4(0.09, 0.094, 0.102, 1) # dark2 = carb.Float4(0.122, 0.129, 0.149, 1) # carb.Float4(0.129, 0.129, 0.149, 1) # mid1 = carb.Float4(0.157, 0.157, 0.157, 1) # carb.Float4(0.157, 0.157, 0.18, 1) mid2 = carb.Float4(0.22, 0.22, 0.22, 1) # colour of the bottom info bar blue = carb.Float4(0.058, 0.058, 1, 1) menu_bar = dark0 title_bar = dark0 background = dark0 popup_bg = black tab = dark0 tab_unfocussed = dark0 frame = dark1 window_bg = mid2 else: menu_bar = carb.Float4(0.27, 0.27, 0.27, 1) title_bar = carb.Float4(0.12, 0.12, 0.12, 1) popup_bg = carb.Float4(0.22, 0.22, 0.22, 1) tab = carb.Float4(0.192, 0.192, 0.192, 1) background = menu_bar tab_unfocussed = carb.Float4(0.27 / 1.5, 0.27 / 1.5, 0.27 / 1.5, 1) frame = title_bar imgui = _imgui.acquire_imgui() imgui.push_style_color(_imgui.StyleColor.MenuBarBg, menu_bar) imgui.push_style_color(_imgui.StyleColor.TitleBg, title_bar) imgui.push_style_color(_imgui.StyleColor.TitleBgActive, title_bar) imgui.push_style_color(_imgui.StyleColor.PopupBg, popup_bg) imgui.push_style_color(_imgui.StyleColor.FrameBg, frame) imgui.push_style_color(_imgui.StyleColor.NavHighlight, blue) imgui.push_style_color(_imgui.StyleColor.NavWindowingDimBg, blue) imgui.push_style_color(_imgui.StyleColor.WindowBg, window_bg) imgui.push_style_color(_imgui.StyleColor.Border, window_bg) imgui.push_style_color(_imgui.StyleColor.ChildBg, background) imgui.push_style_color(_imgui.StyleColor.Tab, tab) imgui.push_style_color(_imgui.StyleColor.TabActive, tab) imgui.push_style_color(_imgui.StyleColor.TabUnfocusedActive, tab_unfocussed) imgui.push_style_color(_imgui.StyleColor.TabUnfocused, tab_unfocussed) imgui.push_style_color(_imgui.StyleColor.TabHovered, tab) async def _delayed_layout(self): # few frame delay to allow automatic Layout of window that want their own positions for i in range(4): await omni.kit.app.get_app().next_update_async() settings = carb.settings.get_settings() # setup the Layout for your app layouts_path = carb.tokens.get_tokens_interface().resolve("${robotica.example.app.logo}/layouts") layout_file = Path(layouts_path).joinpath(f"{settings.get('/app/layout/name')}.json") asyncio.ensure_future(_load_layout(f"{layout_file}")) # using imgui directly to adjust some color and Variable imgui = _imgui.acquire_imgui() # DockSplitterSize is the variable that drive the size of the Dock Split connection imgui.push_style_var_float(_imgui.StyleVar.DockSplitterSize, 2) editor_menu = ui.get_editor_menu() editor_menu.set_priority("File", -96) def _setup_menu(self): editor_menu = ui.get_editor_menu() # you can have some file Menu self._file_open = editor_menu.add_item("File/Open", self._open_file) # some Menu Item self._help_menu = editor_menu.add_item("Help/Show", self._show_help) # from omni.kit.menu.utils import MenuLayout # self._menu_layout = [ # MenuLayout.Menu("Window", [ # MenuLayout.Item("MyWindow"), # ]), # ] # omni.kit.menu.utils.add_layout(self._menu_layout) def _show_help(self, menu, toggled): print("Help is Coming") def _open_file(self, menu, toggled): print("Open the File you want") def on_shutdown(self): editor_menu = ui.get_editor_menu() self._file_open = editor_menu.remove_item("File/Open") self._help_menu = editor_menu.remove_item("Help/Show") self._file_open = None self._help_menu = None self._logo_menu.unregister_menu_widgets() self._logo_menu = None self._settings = None self._await_layout = None
6,454
Python
39.597484
119
0.63387
md84419/kit-app-title-menu-logo-experiment/source/extensions/robotica.example.app.logo/config/extension.toml
[package] version = "1.0.0" authors = ["Robotica"] title = "robotica example app logo" description="A simple python extension example to use as a starting point for your extensions." category = "Example" keywords = ["kit", "example"] readme = "docs/README.md" repository = "" changelog="docs/CHANGELOG.md" preview_image = "data/preview.png" # icon = "data/icon.png" # Use omni.ui to build simple UI [dependencies] "omni.kit.quicklayout" = {} # Main python module this extension provides, it will be publicly available as "import omni.hello.world". [[python.module]] name = "robotica.example.app.logo"
604
TOML
27.809522
105
0.726821
md84419/kit-app-title-menu-logo-experiment/source/extensions/robotica.example.app.logo/docs/CHANGELOG.md
# Changelog The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/). ## [0.0.1] - 2021-04-26 - Initial version of extension UI template with a window
177
Markdown
21.249997
80
0.706215
md84419/kit-app-title-menu-logo-experiment/source/extensions/robotica.example.app.logo/docs/README.md
# Application Setup Extension Template This extension simply sets up the Application
85
Markdown
27.666657
45
0.847059
md84419/usd-experiements/README.md
# usd-experiements A scratch space for USD experments and testcases
69
Markdown
16.499996
48
0.811594
md84419/usd-experiements/tools/scripts/link_app.py
import argparse import json import os import sys 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,814
Python
32.117647
133
0.562189
md84419/usd-experiements/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
md84419/usd-experiements/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 shutil import sys import tempfile import zipfile __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,844
Python
33.166666
108
0.703362
md84419/usd-experiements/exts/robotica.usd.experiments/robotica/usd/experiments/extension.py
import os from pathlib import Path import omni.ext import omni.ui as ui from pxr import UsdShade, Tf, Sdf, Usd CURRENT_PATH = Path(__file__).parent PROJECT_ROOT = CURRENT_PATH.parent.parent.parent DATA_DIR = os.path.join(PROJECT_ROOT, 'data') TEST_USDA = os.path.join(DATA_DIR, 'usd-experiements.usda') # Functions and vars are available to other extension as usual in python: `example.python_ext.some_public_function(x)` def some_public_function(x: int): print("[robotica.usd.experiments] some_public_function was called with x: ", x) return x ** x # Any class derived from `omni.ext.IExt` in top level module (defined in `python.modules` of `extension.toml`) will be # instantiated when extension gets enabled and `on_startup(ext_id)` will be called. Later when extension gets disabled # on_shutdown() is called. class RoboticaUsdExperimentsExtension(omni.ext.IExt): def __init__(self): self._prim_path = None # ext_id is current extension id. It can be used with extension manager to query additional information, like where # this extension is located on filesystem. def on_startup(self, ext_id): print("[robotica.usd.experiments] robotica usd experiments startup") self._count = 0 self._window = ui.Window("My Window", width=300, height=300) with self._window.frame: with ui.VStack(): label = ui.Label("") def on_click(): self._count += 1 label.text = f"count: {self._count}" method1() method2() def method1(): # The following is based on code by Michal S in NVIDIA Omniverse Discord: # https://discord.com/channels/827959428476174346/989589513909203014/1108002804695572480 reference_path = TEST_USDA name = os.path.splitext(os.path.basename(reference_path))[0] stage = omni.usd.get_context().get_stage() if self._prim_path is None: if stage.HasDefaultPrim(): self._prim_path = omni.usd.get_stage_next_free_path( stage, stage.GetDefaultPrim().GetPath().pathString + "/" + Tf.MakeValidIdentifier(name), False ) else: self._prim_path = omni.usd.get_stage_next_free_path(stage, "/" + Tf.MakeValidIdentifier(name), False) omni.kit.commands.execute("CreateReference", usd_context=omni.usd.get_context(), path_to=self._prim_path, asset_path=reference_path, instanceable=False) scale = 2.5 #some of my attempts if scale is not None and scale != 1: scale = float(scale) UsdShade.Material(stage.GetPrimAtPath(self._prim_path)).CreateInput("texture_scale", Sdf.ValueTypeNames.Float2).Set((scale, scale)) for prim in Usd.PrimRange(stage.GetPrimAtPath(self._prim_path)): if prim.IsA(UsdShade.Shader): prim = UsdShade.Shader(prim) inp = prim.GetInput("scale") if inp: inp.Set(tuple(scale * value for value in inp.Get())) else: prim.CreateInput("scale", Sdf.ValueTypeNames.Float2).Set((scale, scale)) return self._prim_path def method2(): ''' Read from the 'global' section of the usda: ``` #usda 1.0 ( customLayerData = { ... } endTimeCode = 100 metersPerUnit = 0.01 startTimeCode = 0 timeCodesPerSecond = 24 upAxis = "Y" ) ``` ''' return self._prim_path def on_reset(): self._count = 0 label.text = "empty" on_reset() with ui.HStack(): ui.Button("Experiment", clicked_fn=on_click) def on_shutdown(self): print("[robotica.usd.experiments] robotica usd experiments shutdown") self._window = None
4,659
Python
40.238938
176
0.509551
md84419/usd-experiements/exts/robotica.usd.experiments/robotica/usd/experiments/__init__.py
from .extension import *
25
Python
11.999994
24
0.76
md84419/usd-experiements/exts/robotica.usd.experiments/robotica/usd/experiments/tests/__init__.py
from .test_hello_world import *
31
Python
30.999969
31
0.774194
md84419/usd-experiements/exts/robotica.usd.experiments/robotica/usd/experiments/tests/test_hello_world.py
# NOTE: # omni.kit.test - std python's unittest module with additional wrapping to add suport for async/await tests # For most things refer to unittest docs: https://docs.python.org/3/library/unittest.html import omni.kit.test # Extnsion for writing UI tests (simulate UI interaction) import omni.kit.ui_test as ui_test # Import extension python module we are testing with absolute import path, as if we are external user (other extension) import robotica.usd.experiments # Having a test class dervived from omni.kit.test.AsyncTestCase declared on the root of module will make it auto-discoverable by omni.kit.test class Test(omni.kit.test.AsyncTestCase): # Before running each test async def setUp(self): pass # After running each test async def tearDown(self): pass # Actual test, notice it is "async" function, so "await" can be used if needed async def test_hello_public_function(self): result = robotica.usd.experiments.some_public_function(4) self.assertEqual(result, 256) async def test_window_button(self): # Find a label in our window label = ui_test.find("My Window//Frame/**/Label[*]") # Find buttons in our window add_button = ui_test.find("My Window//Frame/**/Button[*].text=='Add'") reset_button = ui_test.find("My Window//Frame/**/Button[*].text=='Reset'") # Click reset button await reset_button.click() self.assertEqual(label.widget.text, "empty") await add_button.click() self.assertEqual(label.widget.text, "count: 1") await add_button.click() self.assertEqual(label.widget.text, "count: 2")
1,684
Python
34.851063
142
0.684086
md84419/usd-experiements/exts/robotica.usd.experiments/config/extension.toml
[package] # Semantic Versioning is used: https://semver.org/ version = "1.0.0" # Lists people or organizations that are considered the "authors" of the package. authors = ["NVIDIA"] # The title and description fields are primarily for displaying extension info in UI title = "robotica usd experiments" description="A simple python extension example to use as a starting point for your extensions." # Path (relative to the root) or content of readme markdown file for UI. readme = "docs/README.md" # URL of the extension source repository. repository = "" # One of categories for UI. category = "Example" # Keywords for the extension keywords = ["kit", "example"] # Location of change log file in target (final) folder of extension, relative to the root. # More info on writing changelog: https://keepachangelog.com/en/1.0.0/ changelog="docs/CHANGELOG.md" # Preview image and icon. Folder named "data" automatically goes in git lfs (see .gitattributes file). # Preview image is shown in "Overview" of Extensions window. Screenshot of an extension might be a good preview image. preview_image = "data/preview.png" # Icon is shown in Extensions window, it is recommended to be square, of size 256x256. icon = "data/icon.png" # Use omni.ui to build simple UI [dependencies] "omni.kit.uiapp" = {} # Main python module this extension provides, it will be publicly available as "import robotica.usd.experiments". [[python.module]] name = "robotica.usd.experiments" [[test]] # Extra dependencies only to be used during test run dependencies = [ "omni.kit.ui_test" # UI testing extension ]
1,598
TOML
32.312499
118
0.74781
md84419/usd-experiements/exts/robotica.usd.experiments/docs/CHANGELOG.md
# Changelog The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/). ## [1.0.0] - 2021-04-26 - Initial version of extension UI template with a window
178
Markdown
18.888887
80
0.702247
md84419/usd-experiements/exts/robotica.usd.experiments/docs/README.md
# Python Extension Example [robotica.usd.experiments] This is an example of pure python Kit extension. It is intended to be copied and serve as a template to create new extensions.
183
Markdown
35.799993
126
0.79235
md84419/usd-experiements/exts/robotica.usd.experiments/docs/index.rst
robotica.usd.experiments ############################# Example of Python only extension .. toctree:: :maxdepth: 1 README CHANGELOG .. automodule::"robotica.usd.experiments" :platform: Windows-x86_64, Linux-x86_64 :members: :undoc-members: :show-inheritance: :imported-members: :exclude-members: contextmanager
349
reStructuredText
15.666666
43
0.630372
DigitalBotLab/App/README.md
# App Main App for Digital Bot Lab, Public # Start ```bash .\_build\windows-x86_64\release\dbl.app.bat cd _build\windows-x86_64\release kit\kit.exe apps/dbl.app.kit --ext-folder D:\\dbl\\App\\kit-app\\source\\extensions --enable omni.simready.explorer ```
259
Markdown
20.666665
115
0.718147
DigitalBotLab/App/kit-app/repo.toml
######################################################################################################################## # Repo tool base settings ######################################################################################################################## [repo] # Use the Kit Template repo configuration as a base. Only override things specific to the repo. import_configs = [ "${root}/_repo/deps/repo_kit_tools/kit-template/repo.toml", "${root}/_repo/deps/repo_kit_tools/kit-template/repo-external-app.toml", ] # Repository Name name = "kit-app-template" ######################################################################################################################## # Extensions precacher ######################################################################################################################## [repo_precache_exts] # Apps to run and precache apps = [ "${root}/source/apps/omni.usd_explorer.kit", "${root}/source/apps/my_name.my_app.kit", ] registries = [ { name = "kit/default", url = "https://ovextensionsprod.blob.core.windows.net/exts/kit/prod/shared" }, { name = "kit/sdk", url = "https://ovextensionsprod.blob.core.windows.net/exts/kit/prod/sdk/${kit_version_short}/${kit_git_hash}" }, ]
1,265
TOML
37.363635
136
0.422925
DigitalBotLab/App/kit-app/README.md
# Omniverse Kit App Template [Omniverse Kit App Template](https://github.com/NVIDIA-Omniverse/kit-app-template) - is the place to start learning about developing Omniverse Apps. This project contains everything necessary to develop and package an Omniverse App. ## Links * Recommended: [Tutorial](https://docs.omniverse.nvidia.com/kit/docs/kit-app-template) for getting started with application development. * [Developer Guide](https://docs.omniverse.nvidia.com/dev-guide/latest/index.html). ## Build 1. Clone [this repo](https://github.com/NVIDIA-Omniverse/kit-app-template) to your local machine. 2. Open a command prompt and navigate to the root of your cloned repo. 3. Run `build.bat` to bootstrap your dev environment and build an example app. 4. Run `_build\windows-x86_64\release\my_name.my_app.bat` (or other apps) to open an example kit application. You should have now launched your simple kit-based application! ## Contributing The source code for this repository is provided as-is and we are not accepting outside contributions.
1,048
Markdown
44.608694
148
0.781489
DigitalBotLab/App/kit-app/tools/VERSION.md
2023.2.0
9
Markdown
3.999998
8
0.666667
DigitalBotLab/App/kit-app/tools/deps/repo-deps.packman.xml
<project toolsVersion="5.0"> <dependency name="repo_man" linkPath="../../_repo/deps/repo_man"> <package name="repo_man" version="1.46.2"/> </dependency> <dependency name="repo_build" linkPath="../../_repo/deps/repo_build"> <package name="repo_build" version="0.52.0"/> </dependency> <dependency name="repo_ci" linkPath="../../_repo/deps/repo_ci"> <package name="repo_ci" version="0.6.0" /> </dependency> <dependency name="repo_changelog" linkPath="../../_repo/deps/repo_changelog"> <package name="repo_changelog" version="0.3.13"/> </dependency> <dependency name="repo_docs" linkPath="../../_repo/deps/repo_docs"> <package name="repo_docs" version="0.39.2"/> </dependency> <dependency name="repo_kit_tools" linkPath="../../_repo/deps/repo_kit_tools"> <package name="repo_kit_tools" version="0.14.2"/> </dependency> <dependency name="repo_test" linkPath="../_repo/deps/repo_test"> <package name="repo_test" version="2.16.1" /> </dependency> <dependency name="repo_source" linkPath="../../_repo/deps/repo_source"> <package name="repo_source" version="0.4.3" /> </dependency> <dependency name="repo_package" linkPath="../../_repo/deps/repo_package"> <package name="repo_package" version="5.9.3" /> </dependency> <dependency name="repo_format" linkPath="../../_repo/deps/repo_format"> <package name="repo_format" version="2.8.0" /> </dependency> <dependency name="repo_kit_template" linkPath="../../_repo/deps/repo_kit_template"> <package name="repo_kit_template" version="0.1.9" /> </dependency> </project>
1,592
XML
43.249999
85
0.648241
DigitalBotLab/App/kit-app/tools/deps/kit-sdk.packman.xml
<project toolsVersion="5.0"> <dependency name="kit_sdk_${config}" linkPath="../../_build/${platform}/${config}/kit" tags="${config} non-redist"> <package name="kit-kernel" version="105.1.0+release.51.a7407fb5.tc.${platform}.${config}"/> </dependency> </project>
270
XML
44.166659
117
0.659259
DigitalBotLab/App/kit-app/tools/deps/user.toml
[exts."omni.kit.registry.nucleus"] registries = [ { name = "kit/default", url = "https://ovextensionsprod.blob.core.windows.net/exts/kit/prod/shared" }, { name = "kit/sdk", url = "https://ovextensionsprod.blob.core.windows.net/exts/kit/prod/sdk/${kit_version_short}/${kit_git_hash}" }, ]
296
TOML
48.499992
136
0.675676
DigitalBotLab/App/kit-app/tools/deps/kit-sdk-deps.packman.xml
<project toolsVersion="5.0"> <!-- Only edit this file to pull kit depedencies. --> <!-- Put all extension-specific dependencies in `ext-deps.packman.xml`. --> <!-- This file contains shared Kit SDK dependencies used by most kit extensions. --> <!-- Import Kit SDK all-deps xml file to steal some deps from it: --> <import path="../../_build/${platform}/${config}/kit/dev/all-deps.packman.xml"> <filter include="pybind11" /> <filter include="fmt" /> <filter include="python" /> <filter include="carb_sdk_plugins" /> <filter include="winsdk" /> </import> <!-- Pull those deps of the same version as in Kit SDK. Override linkPath to point correctly, other properties can also be override, including version. --> <dependency name="carb_sdk_plugins" linkPath="../../_build/target-deps/carb_sdk_plugins" tags="non-redist" /> <dependency name="pybind11" linkPath="../../_build/target-deps/pybind11" /> <dependency name="fmt" linkPath="../../_build/target-deps/fmt" /> <dependency name="python" linkPath="../../_build/target-deps/python" /> <!-- Import host deps from Kit SDK to keep in sync --> <import path="../../_build/${platform}/${config}/kit/dev/deps/host-deps.packman.xml"> <filter include="premake" /> <filter include="msvc" /> <filter include="linbuild" /> </import> <dependency name="premake" linkPath="../../_build/host-deps/premake" /> <dependency name="msvc" linkPath="../../_build/host-deps/msvc" /> <dependency name="winsdk" linkPath="../../_build/host-deps/winsdk" /> <dependency name="linbuild" linkPath="../../_build/host-deps/linbuild" tags="non-redist"/> </project>
1,651
XML
49.060605
157
0.660206
DigitalBotLab/App/kit-app/tools/repoman/repoman.py
import os import sys import io import contextlib import packmanapi REPO_ROOT = os.path.join(os.path.dirname(os.path.realpath(__file__)), "../..") REPO_DEPS_FILE = os.path.join(REPO_ROOT, "tools/deps/repo-deps.packman.xml") def bootstrap(): """ Bootstrap all omni.repo modules. Pull with packman from repo.packman.xml and add them all to python sys.path to enable importing. """ #with contextlib.redirect_stdout(io.StringIO()): deps = packmanapi.pull(REPO_DEPS_FILE) for dep_path in deps.values(): if dep_path not in sys.path: sys.path.append(dep_path) if __name__ == "__main__": bootstrap() import omni.repo.man omni.repo.man.main(REPO_ROOT)
709
Python
23.482758
100
0.662905
DigitalBotLab/App/kit-app/tools/packman/packmanconf.py
# Use this file to bootstrap packman into your Python environment (3.7.x). Simply # add the path by doing sys.insert to where packmanconf.py is located and then execute: # # >>> import packmanconf # >>> packmanconf.init() # # It will use the configured remote(s) and the version of packman in the same folder, # giving you full access to the packman API via the following module # # >> import packmanapi # >> dir(packmanapi) import os import platform import sys def init(): """Call this function to initialize the packman configuration. Calls to the packman API will work after successfully calling this function. Note: This function only needs to be called once during the execution of your program. Calling it repeatedly is harmless but wasteful. Compatibility with your Python interpreter is checked and upon failure the function will report what is required. Example: >>> import packmanconf >>> packmanconf.init() >>> import packmanapi >>> packmanapi.set_verbosity_level(packmanapi.VERBOSITY_HIGH) """ major = sys.version_info[0] minor = sys.version_info[1] if major != 3 or minor != 10: raise RuntimeError( f"This version of packman requires Python 3.10.x, but {major}.{minor} was provided" ) conf_dir = os.path.dirname(os.path.abspath(__file__)) os.environ["PM_INSTALL_PATH"] = conf_dir packages_root = get_packages_root(conf_dir) version = get_version(conf_dir) module_dir = get_module_dir(conf_dir, packages_root, version) sys.path.insert(1, module_dir) def get_packages_root(conf_dir: str) -> str: root = os.getenv("PM_PACKAGES_ROOT") if not root: platform_name = platform.system() if platform_name == "Windows": drive, _ = os.path.splitdrive(conf_dir) root = os.path.join(drive, "packman-repo") elif platform_name == "Darwin": # macOS root = os.path.join( os.path.expanduser("~"), "Library/Application Support/packman-cache" ) elif platform_name == "Linux": try: cache_root = os.environ["XDG_HOME_CACHE"] except KeyError: cache_root = os.path.join(os.path.expanduser("~"), ".cache") return os.path.join(cache_root, "packman") else: raise RuntimeError(f"Unsupported platform '{platform_name}'") # make sure the path exists: os.makedirs(root, exist_ok=True) return root def get_module_dir(conf_dir, packages_root: str, version: str) -> str: module_dir = os.path.join(packages_root, "packman-common", version) if not os.path.exists(module_dir): import tempfile tf = tempfile.NamedTemporaryFile(delete=False) target_name = tf.name tf.close() url = f"http://bootstrap.packman.nvidia.com/packman-common@{version}.zip" print(f"Downloading '{url}' ...") import urllib.request urllib.request.urlretrieve(url, target_name) from importlib.machinery import SourceFileLoader # import module from path provided script_path = os.path.join(conf_dir, "bootstrap", "install_package.py") ip = SourceFileLoader("install_package", script_path).load_module() print("Unpacking ...") ip.install_package(target_name, module_dir) os.unlink(tf.name) return module_dir def get_version(conf_dir: str): path = os.path.join(conf_dir, "packman") if not os.path.exists(path): # in dev repo fallback path += ".sh" with open(path, "rt", encoding="utf8") as launch_file: for line in launch_file.readlines(): if line.startswith("PM_PACKMAN_VERSION"): _, value = line.split("=") return value.strip() raise RuntimeError(f"Unable to find 'PM_PACKMAN_VERSION' in '{path}'")
3,931
Python
35.407407
95
0.632663
DigitalBotLab/App/kit-app/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
DigitalBotLab/App/kit-app/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 os import stat import time from typing import Any, Callable RENAME_RETRY_COUNT = 100 RENAME_RETRY_DELAY = 0.1 logging.basicConfig(level=logging.WARNING, format="%(message)s") logger = logging.getLogger("install_package") def remove_directory_item(path): if os.path.islink(path) or os.path.isfile(path): try: os.remove(path) except PermissionError: # make sure we have access and try again: os.chmod(path, stat.S_IRWXU) os.remove(path) else: # try first to delete the dir because this will work for folder junctions, otherwise we would follow the junctions and cause destruction! clean_out_folder = False try: # make sure we have access preemptively - this is necessary because recursing into a directory without permissions # will only lead to heart ache os.chmod(path, stat.S_IRWXU) os.rmdir(path) except OSError: clean_out_folder = True if clean_out_folder: # we should make sure the directory is empty names = os.listdir(path) for name in names: fullname = os.path.join(path, name) remove_directory_item(fullname) # now try to again get rid of the folder - and not catch if it raises: os.rmdir(path) class StagingDirectory: def __init__(self, staging_path): self.staging_path = staging_path self.temp_folder_path = None os.makedirs(staging_path, exist_ok=True) def __enter__(self): self.temp_folder_path = tempfile.mkdtemp(prefix="ver-", dir=self.staging_path) return self def get_temp_folder_path(self): return self.temp_folder_path # this function renames the temp staging folder to folder_name, it is required that the parent path exists! def promote_and_rename(self, folder_name): abs_dst_folder_name = os.path.join(self.staging_path, folder_name) os.rename(self.temp_folder_path, abs_dst_folder_name) def __exit__(self, type, value, traceback): # Remove temp staging folder if it's still there (something went wrong): path = self.temp_folder_path if os.path.isdir(path): remove_directory_item(path) def rename_folder(staging_dir: StagingDirectory, folder_name: str): try: staging_dir.promote_and_rename(folder_name) except OSError as exc: # if we failed to rename because the folder now exists we can assume that another packman process # has managed to update the package before us - in all other cases we re-raise the exception abs_dst_folder_name = os.path.join(staging_dir.staging_path, folder_name) if os.path.exists(abs_dst_folder_name): logger.warning( f"Directory {abs_dst_folder_name} already present, package installation already completed" ) else: raise def call_with_retry( op_name: str, func: Callable, retry_count: int = 3, retry_delay: float = 20 ) -> Any: retries_left = retry_count while True: try: return func() except (OSError, IOError) as exc: logger.warning(f"Failure while executing {op_name} [{str(exc)}]") if retries_left: retry_str = "retry" if retries_left == 1 else "retries" logger.warning( f"Retrying after {retry_delay} seconds" f" ({retries_left} {retry_str} left) ..." ) time.sleep(retry_delay) else: logger.error("Maximum retries exceeded, giving up") raise retries_left -= 1 def rename_folder_with_retry(staging_dir: StagingDirectory, folder_name): dst_path = os.path.join(staging_dir.staging_path, folder_name) call_with_retry( f"rename {staging_dir.get_temp_folder_path()} -> {dst_path}", lambda: rename_folder(staging_dir, folder_name), RENAME_RETRY_COUNT, RENAME_RETRY_DELAY, ) def install_package(package_path, install_path): staging_path, version = os.path.split(install_path) with StagingDirectory(staging_path) as staging_dir: output_folder = staging_dir.get_temp_folder_path() with zipfile.ZipFile(package_path, allowZip64=True) as zip_file: zip_file.extractall(output_folder) # attempt the rename operation rename_folder_with_retry(staging_dir, version) print(f"Package successfully installed to {install_path}") if __name__ == "__main__": executable_paths = os.getenv("PATH") paths_list = executable_paths.split(os.path.pathsep) if executable_paths else [] target_path_np = os.path.normpath(sys.argv[2]) target_path_np_nc = os.path.normcase(target_path_np) for exec_path in paths_list: if os.path.normcase(os.path.normpath(exec_path)) == target_path_np_nc: raise RuntimeError(f"packman will not install to executable path '{exec_path}'") install_package(sys.argv[1], target_path_np)
5,776
Python
36.270968
145
0.645083
DigitalBotLab/App/kit-app/source/extensions/omni.simready.explorer/PACKAGE-LICENSES/omni.simready.explorer-LICENSE.md
Copyright (c) 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.
412
Markdown
57.999992
74
0.839806
DigitalBotLab/App/kit-app/source/extensions/omni.simready.explorer/config/extension.toml
[package] # Semantic Versionning is used: https://semver.org/ version = "1.0.26" # Lists people or organizations that are considered the "authors" of the package. authors = ["Jeffrey Qiu <[email protected]>", "John Kosnik <[email protected]>", "Attila Szabo <[email protected]"] # The title and description fields are primarly for displaying extension info in UI title = "Browser for SimReady Assets" description="A browser for SimReady Assets" # URL of the extension source repository. repository="https://gitlab-master.nvidia.com/omniverse/kit-extensions/kit-browsers" # Keywords for the extension keywords = ['browser', 'asset', 'simready', "explorer"] # Location of change log file in target (final) folder of extension, relative to the root. # More info on writing changelog: https://keepachangelog.com/en/1.0.0/ changelog="docs/CHANGELOG.md" category = "Rendering" readme = "docs/README.md" preview_image = "data/preview.png" icon = "data/icon.svg" feature = true [dependencies] "omni.kit.browser.folder.core" = {} "omni.kit.commands" = {} "omni.kit.menu.utils" = {} "omni.usd" = {} "omni.kit.viewport.utility" = {} "omni.kit.window.property" = {} "omni.kit.viewport.window" = {} # Main python module this extension provides, it will be publicly available as "import omni.simready.explorer". [[python.module]] name = "omni.simready.explorer" [settings.exts."omni.simready.explorer"] # The list of asset root folders to be browsed. folders = ["https://omniverse-content-staging.s3.us-west-2.amazonaws.com/Assets/simready_content"] default_physics = "RigidBody" [[trigger]] menu.name = "Window/Browsers/SimReady Explorer" menu.window = "SimReady Explorer" [[test]] dependencies = [ "omni.kit.renderer.core", "omni.kit.renderer.capture", ] args = [ "--no-window", "--/app/window/dpiScaleOverride=1.0", "--/app/window/scaleToMonitor=false", "--/app/menu/legacy_mode=false", ] [documentation] pages = [ "docs/Overview.md", "docs/CHANGELOG.md", ]
1,993
TOML
28.323529
115
0.717511
DigitalBotLab/App/kit-app/source/extensions/omni.simready.explorer/config/extension.gen.toml
[package] archivePath = "http://d4i3qtqj3r0z5.cloudfront.net/omni.simready.explorer-1.0.26.zip" [package.publish] kitVersion = "105.0.0+release.109326.bd6b456a.tc" date = 1687298400 buildNumber = "101.1.0+2023.1.1527.751de03b.tc" repoName = "kit-browsers"
298
TOML
28.899997
89
0.654362
DigitalBotLab/App/kit-app/source/extensions/omni.simready.explorer/omni/simready/explorer/empty_property_delegate.py
# Copyright (c) 2023, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. from typing import List, Optional import omni.ui as ui from .browser_model import AssetDetailItem from .browser_property_delegate import BrowserPropertyDelegate class EmptyPropertyDelegate(BrowserPropertyDelegate): """ A delegate to show when no asset selected. """ def accepted(self, asset: Optional[AssetDetailItem]) -> bool: """BrowserPropertyDelegate method override""" return asset is None def show(self, asset: Optional[AssetDetailItem], frame: ui.Frame) -> None: """BrowserPropertyDelegate method override""" if hasattr(self, "_container"): self._container.visible = True else: with frame: self._container = ui.VStack() with self._container: ui.Label("Please Select a SimReady Asset!", alignment=ui.Alignment.CENTER) def accepted_multiple(self, detail_items: List[AssetDetailItem]) -> bool: """BrowserPropertyDelegate method override""" return False def show_multiple(self, detail_items: List[AssetDetailItem], frame: ui.Frame) -> None: """BrowserPropertyDelegate method override""" pass
1,606
Python
36.372092
94
0.701121
DigitalBotLab/App/kit-app/source/extensions/omni.simready.explorer/omni/simready/explorer/prop_property_delegate.py
# Copyright (c) 2023, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. import asyncio from typing import List, Optional import omni.kit.app import omni.ui as ui from omni.kit.browser.core import TreeBrowserWidget from .asset import AssetType from .browser_model import AssetDetailItem from .browser_property_delegate import BrowserPropertyDelegate from .property_widgets import * class PropAssetPropertyDelegate(BrowserPropertyDelegate): """ A delegate to show properties of assets of type Prop. """ def accepted(self, item: Optional[AssetDetailItem]) -> bool: """BrowserPropertyDelegate method override""" return item and item.asset.asset_type == AssetType.PROP def show(self, item: Optional[AssetDetailItem], frame: ui.Frame) -> None: """BrowserPropertyDelegate method override""" if item is None: return asset = item.asset self._item = item if hasattr(self, "_container"): self._container.visible = True self._name_label.text = asset.name self._qcode_value.text = asset.qcode self._dimensions_value.text = asset.extent_as_str if hasattr(self, "h_buttons"): self._h_hstack.clear() with self._h_hstack: self._build_hierarchy_links() self._thumbnail_img.source_url = asset.thumbnail self._physx_combobox.model = item.physics_model self._tags_field.tags = asset.tags async def __delay_show_physics(): # Delay to show badge to make display correct if item.physics_model: await omni.kit.app.get_app().next_update_async() self._badge_container.visible = item.physics_model.current_index.as_int != 0 self._sub_physics = None self._sub_physics = item.physics_model.current_index.subscribe_value_changed_fn( self.__on_item_physics_changed ) asyncio.ensure_future(__delay_show_physics()) else: with frame: self._container = ui.VStack(height=0, spacing=5) with self._container: self._build_thumbnail(item) with ui.HStack(): ui.Spacer() self._name_label = ui.Label(asset.name, height=0, style_type_name_override="Asset.Title") ui.Spacer() with ui.CollapsableFrame("Behaviors"): self._physx_combobox = self._build_combobox("PhysicsVariant", item.physics_model) with ui.CollapsableFrame("Asset info"): self.collapse_info = self._build_info_widget() with ui.CollapsableFrame("Tags", height=ui.Percent(100)): self._tags_field = self._build_tags() ui.Spacer() def accepted_multiple(self, detail_items: List[AssetDetailItem]) -> bool: """BrowserPropertyDelegate method override""" return False def show_multiple(self, detail_items: List[AssetDetailItem], frame: ui.Frame) -> None: """BrowserPropertyDelegate method override""" pass def _build_info_widget(self): """Build the Asset information section""" with ui.VStack(spacing=10): with ui.HStack(): self._qcode_label = ui.Label("QCode:", style_type_name_override="Asset.Label", width=100) self._qcode_value = ui.Label( self._item.asset.qcode, alignment=ui.Alignment.LEFT_BOTTOM, style_type_name_override="Asset.Value" ) with ui.HStack(): self._dimensions_label = ui.Label("Dimensions:(m)", style_type_name_override="Asset.Label", width=100) self._dimensions_value = ui.Label( self._item.asset.extent_as_str, alignment=ui.Alignment.LEFT_BOTTOM, style_type_name_override="Asset.Value", ) self._h_hstack = ui.HStack(alignment=ui.Alignment.LEFT_BOTTOM) with self._h_hstack: self._hierachy_label = ui.Label("Hierarchy:", style_type_name_override="Asset.Label", width=100) self._build_hierarchy_links() ui.Spacer() def _build_tags(self): """Add the tag link section. must pass explorer instance""" from .extension import get_instance browser_widget: Optional[TreeBrowserWidget] = get_instance().browser_widget tag_widget = PropAssetTagsWidget(self._item.asset.tags, browser_widget) return tag_widget def _build_thumbnail(self, item: AssetDetailItem): """Builds thumbnail frame and resizes""" self._thumbnail_frame = ui.Frame(height=0) self._thumbnail_frame.set_computed_content_size_changed_fn(self._on_thumbnail_frame_size_changed) with self._thumbnail_frame: with ui.HStack(): ui.Spacer(width=ui.Percent(25)) self._thumbnail_container = ui.ZStack(height=ui.Fraction(1)) with self._thumbnail_container: self._thumbnail_img = ui.Image( item.asset.thumbnail, fill_policy=ui.FillPolicy.PRESERVE_ASPECT_FIT, alignment=ui.Alignment.CENTER_TOP, ) # Badge to indicate item physics ON, need to change visibility if physics status changed self._badge_container = ui.HStack( alignment=ui.Alignment.LEFT_BOTTOM, visible=item.physics != "None" ) with self._badge_container: ui.Spacer(width=ui.Percent(80)) with ui.VStack(): ui.Spacer(height=2) ui.ImageWithProvider( fill_policy=ui.IwpFillPolicy.IWP_PRESERVE_ASPECT_FIT, alignment=ui.Alignment.LEFT, style_type_name_override="GridView.Item.Badge.Image", ) if item.physics_model: self._sub_physics = item.physics_model.current_index.subscribe_value_changed_fn( self.__on_item_physics_changed ) ui.Spacer(width=ui.Percent(25)) def __on_item_physics_changed(self, model: ui.SimpleIntModel) -> None: self._badge_container.visible = model.as_int != 0 def _build_hierarchy_links(self): """build h links""" from .extension import get_instance browser_widget = get_instance().browser_widget def on_click(value): """set the browse search field with this tag Args: value (List): tag search value """ search_field = browser_widget.search_field search_field.search_words = value self.h_buttons = [] for i, h in enumerate(self._item.asset.hierarchy): text_v = "{}".format(h) new_button = ui.Button( text_v, alignment=ui.Alignment.LEFT_BOTTOM, click_fn=on_click, spacing=0, width=0, style_type_name_override="Asset.ButtonLinks", ) h_list = self._item.asset.hierarchy[0 : (i + 1)] new_button.set_clicked_fn(lambda value=h_list: on_click(value)) if i < (len(self._item.asset.hierarchy) - 1): new_label = ui.Label(" > ", width=0) def clear_buttons(self, buttons): for b in buttons: b.visible = False self.h_buttons = [] def _on_thumbnail_frame_size_changed(self): # Dynamic change thumbnail size to be half of frame width async def __change_thumbnail_size_async(): await omni.kit.app.get_app().next_update_async() image_size = self._thumbnail_frame.computed_width / 2 self._thumbnail_img.height = ui.Pixel(image_size) asyncio.ensure_future(__change_thumbnail_size_async())
8,681
Python
41.145631
118
0.570211
DigitalBotLab/App/kit-app/source/extensions/omni.simready.explorer/omni/simready/explorer/property_widgets.py
# Copyright (c) 2023, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. import omni.client import omni.ui as ui class PropAssetTagsWidget: """Class for building and maintaining tags chips""" def __init__(self, tags, browser_widget): """tag chips Args: tags (list): list of tags browser_widget(get_instance().browser_widget): instance of base browser widget """ self.browser_widget = browser_widget self._tags = tags self._tag_chips = [] self._tag_buttons = {} self.tag_stack = ui.Frame(spacing=5) self._frame_size = 50 def setFrame(): self._frame_size = int(self.tag_stack.computed_width / 8) self.clear_tags() with self.tag_stack: self.build_tag_chips() self.tag_stack.set_computed_content_size_changed_fn(setFrame) with self.tag_stack: self.build_tag_chips() @property def tags(self): """Property gor tag values Returns: List: tag values """ return self._tags @tags.setter def tags(self, tags): """Property Setter for adding tag also rebuilds tags buttons Args: tags (List): List tag values """ # Remove existing tags in frame self.clear_tags() # Set Tags Property self._tags = tags # Rebuild new tags with self.tag_stack: self.build_tag_chips() def clear_tags(self): """clears all tag button in the frame""" self.tag_stack.clear() def append_tag(self, tag): """Add a tag value to the existing tag list. Check for doubles""" if tag not in self.tags: add_tag = self.tag.append(tag) self._tag = add_tag def remove_chip(self, chip): """Remove this chip from the ui""" for c in chip: c.visible = False def build_tag_chips(self): """Build the tag chip ui and added link function to Browser Search Bar""" def on_click(value): """set the browse search field with this tag Args: value (str): tag search value """ search_field = self.browser_widget.search_field search_field.search_words = [value] row_list = [] row_count = 0 char_count = 0 list_of_rows = [] # each index is a list of tags that will fit in the row based on the size of the frame. for t in self.tags: new_chars = char_count + len(t) if new_chars < self._frame_size: row_list.append(t) char_count = new_chars else: list_of_rows.append(row_list) row_list = [] row_list.append(t) char_count = len(t) list_of_rows.append(row_list) # build the buttons with ui.VGrid(padding=5, row_height=30): for row in list_of_rows: with ui.HStack(spacing=5): for r in row: new_button = ui.Button(r, clicked_fn=on_click, height=0, width=0) new_button.set_clicked_fn(lambda value=r: on_click(value))
3,654
Python
29.974576
95
0.564039
DigitalBotLab/App/kit-app/source/extensions/omni.simready.explorer/omni/simready/explorer/combobox_model.py
# Copyright (c) 2023, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. import weakref from typing import Any, List, Optional import omni.ui as ui class ComboBoxItem(ui.AbstractItem): def __init__(self, text: str, value: Any) -> None: super().__init__() self.model = ui.SimpleStringModel(text) self.value = value class ComboBoxModel(ui.AbstractItemModel): """ The model used for combobox Args: texts (List[str]): Texts displayed in combobox kwargs: values (Optional[List[Any]]): Values for combobox list. Default None to use text as value current_value (Any): Current value displayed in combobox. Default None to use first one. """ def __init__(self, texts: List[str], values: Optional[List[Any]] = None, current_value: Any = None): super().__init__() # List items self._items = [] for index, text in enumerate(texts): value = values[index] if values else text self._items.append(ComboBoxItem(text, value)) # Current value current = self._get_current_index_by_value(current_value) self.current_index = ui.SimpleIntModel(current) self._sub = self.current_index.subscribe_value_changed_fn( lambda _, this=weakref.proxy(self): this.on_current_changed() ) def destroy(self): self._sub = None self.current_index = None self._items = [] @property def current_value(self) -> str: items = self.get_item_children(None) return items[self.current_index.as_int].value @current_value.setter def current_value(self, value: str) -> None: index = self._get_current_index_by_value(value) self.current_index.set_value(index) def get_item_children(self, item) -> List[ComboBoxItem]: return self._items def get_item_value_model(self, item, column_id): if item is None: return self.current_index if isinstance(item, ComboBoxItem): return item.model else: return ui.SimpleStringModel("Unknown") def on_current_changed(self): current_index = self.current_index.as_int items = self.get_item_children(None) self._on_current_item_changed(items[current_index]) self._item_changed(None) def _get_current_index_by_value(self, value: Any, default: int = 0) -> int: if value is None: current = default else: items = self.get_item_children(None) if isinstance(value, float): current = next((i for i, item in enumerate(items) if abs(item.value - value) < 0.0001), default) else: if isinstance(value, list): value = tuple(value) def compare_values(a, b): if isinstance(a, list): a = tuple(a) return a == b current = next((i for i, item in enumerate(items) if item.value == value), default) return current # noqa: R504 def _on_current_item_changed(self, item: ComboBoxItem) -> None: pass
3,537
Python
33.349514
112
0.615776
DigitalBotLab/App/kit-app/source/extensions/omni.simready.explorer/omni/simready/explorer/style.py
# Copyright (c) 2023, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. from pathlib import Path from omni.ui import color as cl CURRENT_PATH = Path(__file__).parent ICON_PATH = CURRENT_PATH.parent.parent.parent.joinpath("data/icons") SIMREADY_DRAG_PREFIX = "SimReady::" # Use same context menu style with content browser cl.context_menu_background = cl.shade(cl("#343432")) cl.context_menu_separator = cl.shade(0x449E9E9E) cl.context_menu_text = cl.shade(cl("#9E9E9E")) cl.simready_background = cl.shade(cl("#23211F")) CONTEXT_MENU_STYLE = { "Menu": {"background_color": cl.context_menu_background_color, "color": cl.context_menu_text, "border_radius": 2}, "Menu.Item": {"background_color": 0x0, "margin": 0}, "Separator": {"background_color": 0x0, "color": cl.context_menu_separator}, } UI_STYLES = { "ToolBar.Button": {"background_color": 0x0, "padding": 3, "margin": 0}, "ToolBar.Button:selected": {"background_color": cl.simready_background}, "Splitter": {"background_color": 0x0, "margin_width": 0}, "Splitter:hovered": {"background_color": 0xFFB0703B}, "Splitter:pressed": {"background_color": 0xFFB0703B}, "Property.Path": {"background_color": cl.simready_background}, "Property.Path::mixed": {"color": 0xFFCC9E61}, "Property.Frame": {"padding": 0}, "GridView.Item.Badge.Image": { "image_url": f"{ICON_PATH}/physx.png", }, "GridView.Item.Badge.Background": {"background_color": 0xFFC2C2C2}, } PROPERTY_STYLES = { "Asset.Title": {"font_size": 18, "color": 0xFF9E9E9E, "font-weight": 900}, "Asset.Label": {"font_size": 14, "font_weight": 1200, "text-align": "left"}, "Asset.Value": {"font_size": 14, "font_weight": 1, "text-align": "right"}, "Asset.ButtonLinks": {"background_color": "transparent", "padding": 0}, "Asset.ButtonLinks:hovered": {"background_color": 0xFF9E9E9E, "border_color": cl("#0078D7")}, "Asset.ButtonLinks:pressed": { "background_color": cl("#CCE4F7"), "border_color": cl("#005499"), "border_width": 1.0, }, }
2,414
Python
42.124999
118
0.680613
DigitalBotLab/App/kit-app/source/extensions/omni.simready.explorer/omni/simready/explorer/browser_api.py
# Copyright (c) 2023, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. from typing import Dict, List, Optional, Tuple import carb import omni.ext import omni.kit.app import omni.kit.commands import omni.kit.undo import omni.usd from pxr import Gf, Sdf, Usd, UsdGeom from .actions import _add_asset_to_stage_helper, configure_prim from .asset import SimreadyAsset from .browser_model import AssetDetailItem from .extension import SimReadyBrowserExtension, get_instance def get_selected_xformable_prim_paths(usd_context: omni.usd.UsdContext, stage: Usd.Stage) -> List[Sdf.Path]: """Get the list of selected Xformable prim paths in the stage. Args: usd_context (omni.usd.UsdContext): The USD context to get the selection from. stage (Usd.Stage): The stage to get the selection from. Returns: The list of prim paths of the selected Xformable prims in the stage, or an empty list if there's nothing selected. """ if usd_context is None or stage is None: return [] selection = usd_context.get_selection() return [ path for path in selection.get_selected_prim_paths() if stage.GetPrimAtPath(path) and stage.GetPrimAtPath(path).IsA(UsdGeom.Xformable) ] def get_average_position_of_prims(prims: List[Usd.Prim]) -> Gf.Vec3d: """Get the average position of a list of prims. Args: prims (List[Usd.Prim]): The list of prims to get the average position of. Returns: The average 3D position of the prims, or the origin if no prims provided. """ position = Gf.Vec3d(0) for prim in prims: if prim.IsA(UsdGeom.Xformable): position += omni.usd.get_world_transform_matrix(prim).ExtractTranslation() if len(prims) > 0: position /= len(prims) return position async def find_assets(search_words: Optional[List[str]] = None) -> List[SimreadyAsset]: """Search assets in the current asset library Filter the current asset library by a list of search words. Search words are not case sensitive, and are matched partially against asset names as tags. If no search words are provided, all assets are returned. Example: Analyzing the results of searching with ["residential", "chair", "wood"] will reveal that the found assets have "residential" and "chair" in their tags, and "wood" in their names. Args: search_words (Optional[List[str]]): List of search words to filter assets on. Returns: List[SimreadyAsset]: List of SimReady assets that match the search words. """ ext: SimReadyBrowserExtension = get_instance() collections = ext.browser_model.get_item_children(None) # Tree mode, only has a default collection # First get categories to force traverse assets categories = ext.browser_model.get_item_children(collections[0]) while True: for root_folder in ext.browser_model._root_folders: # Make sure all assets from all folders are loaded if not root_folder.prepared: await omni.kit.app.get_app().next_update_async() break else: # Reload categories after traverse done categories = ext.browser_model.get_item_children(collections[0]) # First category "ALL" has all assets all_asset_items: List[AssetDetailItem] = ext.browser_model.get_item_children(categories[0]) if search_words: filtered_assets: List[SimreadyAsset] = [] for asset_item in all_asset_items: if asset_item.filter(search_words): filtered_assets.append(asset_item.asset) return filtered_assets else: all_assets: List[SimreadyAsset] = [item.asset for item in all_asset_items] return all_assets def add_asset_to_stage( url: str, parent_path: Sdf.Path = Sdf.Path.emptyPath, position: Gf.Vec3d = Gf.Vec3d(0, 0, 0), variants: Optional[Dict[str, str]] = None, payload: bool = False, instanceable: bool = False, ) -> Tuple[bool, Sdf.Path]: """Adds an asset to the current stage. Args: url (str): Url of asset to add. parent_path (Sdf.Path): Path of parent prim to add asset to. If empty path, add to default prim or pseudo root. position (Gf.Vec3d): Position to add asset at. payload (bool): If True, add asset as payload, otherwise as reference. variants (Optional[Dict[str, str]]): Variants to set on added asset. Dictionary of variant set name and value. Returns: Tuple[bool, Sd.Path]: Tuple of success, and path to added prim. .. note:: The actions of this function are undoable. If you want to add an asset without undo, use the following: .. code-block:: python with omni.kit.undo.disabled(): add_asset_to_stage(...) """ if not url: carb.log_error("Failed to add asset since url not defined!") return False, "" usd_context: omni.usd.UsdContext = omni.usd.get_context() stage: Usd.Stage = usd_context.get_stage() if usd_context else None if stage is None: carb.log_error(f"No valid stage found; cannot add {url}.") return False, "" # Creation and translation of the prim is done in a single undo group with omni.kit.undo.group(): # Add the asset to the stage (added_prim_path, _, _) = _add_asset_to_stage_helper( usd_context, stage, url, prim_path=parent_path, payload=payload, instanceable=instanceable ) # Translate the added prim to the specified position omni.kit.commands.execute("TransformPrimSRTCommand", path=added_prim_path, new_translation=position) # Set the variants on the added prim if added_prim_path and variants: configure_prim(stage, added_prim_path, variants) return True, Sdf.Path(added_prim_path) def add_asset_to_stage_using_prims( usd_context: omni.usd.UsdContext, stage: Usd.Stage, url: str, variants: Optional[Dict[str, str]] = None, replace_prims: bool = False, prim_paths: List[Sdf.Path] = [], ) -> Tuple[bool, Sdf.Path]: """Add an asset to a stage using a list of prims. The asset will be added to the average position of the provided prims, or the origin if no prims supplied. The asset will be added as a reference or payload based on whether the first provided prim has authored references or payloads. If no prims specified, the setting at "/persistent/app/stage/dragDropImport" is used. If the new asset is to replace the prims, the asset's parent will be the common ancestor of all prims. If no prims specified, the default prim or pseudo root will be used as the parent prim of the added asset. Args: usd_context (omni.usd.UsdContext): UsdContext to add asset to. stage (Usd.Stage): Stage to add asset to. url (str): Url of asset to add. variants (Optional[Dict[str, str]]): Variants to set on the added prim. replace_prims (bool): If True, replace the selection with the new asset. prim_paths (List[Sdf.Path]): List of prims to use for adding the asset. Returns: Tuple of success and added prim path. .. note:: The actions of this function are undoable. If you want to add an asset without undo, use the following: .. code-block:: python with omni.kit.undo.disabled(): add_asset_to_stage_using_prims(...) """ if not url: carb.log_error("Failed to add asset since url not defined!") return False, "" if usd_context is None or stage is None: carb.log_error(f"No valid stage found; cannot add {url}.") return False, "" prims = [ stage.GetPrimAtPath(path) for path in prim_paths if stage.GetPrimAtPath(path) and stage.GetPrimAtPath(path).IsA(UsdGeom.Xformable) ] # If replacing prims, all prims must be deletable\replaceable if replace_prims: for prim in prims: if not prim.IsValid() or ( prim.GetMetadata("no_delete") is not None and prim.GetMetadata("no_delete") is True ): carb.log_error("Failed to add asset since cannot replace specified prims!") return False, "" # Get average position of prims position: Gf.Vec3d = get_average_position_of_prims(prims) # If prims specified, use the first prim's payload/reference status create_option = "" if prims and len(prims) > 0: for prim in prims: if prim.HasAuthoredReferences(): create_option = "reference" break if prim.HasAuthoredPayloads(): create_option = "payload" break # Determine parent path for new prim if replace_prims and prims and len(prims) > 0: parent_path: Sdf.Path = Sdf.Path.emptyPath for prim in prims: if parent_path == Sdf.Path.emptyPath: parent_path: Sdf.Path = prim.GetParent().GetPath() else: parent_path: Sdf.Path = parent_path.GetCommonPrefix(prim.GetParent().GetPath()) elif stage.HasDefaultPrim(): parent_path: Sdf.Path = stage.GetDefaultPrim().GetPath() else: parent_path: Sdf.Path = Sdf.Path.absoluteRootPath # Deletion, creation and translation of prims is done in a single undo group with omni.kit.undo.group(): # If replacing prims, delete them before adding new ones to prevent potential name collision if replace_prims and prim_paths and len(prim_paths) > 0: omni.kit.commands.execute("DeletePrimsCommand", paths=prim_paths) # Add asset to stage (added_prim_path, _, _) = _add_asset_to_stage_helper( usd_context, stage, url, prim_path=parent_path, payload=create_option, instanceable="" ) # Translate the added prim to the specified position omni.kit.commands.execute("TransformPrimSRTCommand", path=added_prim_path, new_translation=position) # Set the variants on the added prim if added_prim_path and variants: configure_prim(stage, added_prim_path, variants) return True, added_prim_path
10,652
Python
39.2
131
0.659501
DigitalBotLab/App/kit-app/source/extensions/omni.simready.explorer/omni/simready/explorer/browser_toolbar.py
# Copyright (c) 2023, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. from typing import Dict, List, Optional, Union from omni import ui from .style import ICON_PATH class BrowserToolBarButtonDesc: """ Represent a button in browser toolbar Args: image_url (Optional[str]): Image url of button. None means spacer. clicked_fn (callable): Function called when button clicked. Default None. Function signure: void clicked_fn() tooltips (Optinal[str]): Button tooltips. Default None. """ def __init__(self, image_url: Optional[str], clicked_fn: callable = None, tooltips: Optional[str] = None): self.image_url = image_url self.clicked_fn = clicked_fn self.tooltips = tooltips class BrowserToolBarBase: """ Represent a base tool bar for browser. Args: descs (List[BrowserToolBarButtonDesc]): Default buttons to show on tool bar. """ def __init__(self, descs: List[BrowserToolBarButtonDesc]): self._buttons: Dict[BrowserToolBarButtonDesc, ui.Button] = {} self._button_descs: List[BrowserToolBarButtonDesc] = [] self._button_descs.extend(descs) self.widget = ui.HStack(height=0, spacing=4) self._spacer_visible = True self._spacers: List[ui.Spacer] = [] self._build_buttons() @property def visible(self) -> bool: """ Toolbar visibility. """ return self.widget.visible @visible.setter def visible(self, value) -> None: self.widget.visible = value @property def computed_height(self): return self.widget.computed_height @property def spacer_visible(self) -> bool: """Visibility of spacers in toolbar""" return self._spacer_visible @spacer_visible.setter def spacer_visible(self, visible) -> None: if visible != self._spacer_visible: self._spacer_visible = visible for spacer in self._spacers: spacer.visible = visible @property def width(self): return self.widget.computed_width if self.widget else 0 @property def position_x(self): return self.widget.screen_position_x if self.widget else 0 def destroy(self) -> None: for desc in self._buttons: self._buttons[desc] = None self.widget = None def append_buttons(self, button_descs: Union[BrowserToolBarButtonDesc, List[BrowserToolBarButtonDesc]]) -> None: """ Append buttons to toolbar. Args: button_descs (Union[BrowserToolBarButtonDesc, \ List[BrowserToolBarButtonDesc]]): Desc of buttons to be appended. """ if isinstance(button_descs, list): self._button_descs.extend(button_descs) else: self._button_descs.append(button_descs) self._build_buttons() def get_button(self, desc: BrowserToolBarButtonDesc) -> Optional[ui.Button]: """ Get toolbar button by desc. Return None if not found. Args: desc (BrowserToolBarButtonDesc): Button description. """ return self._buttons[desc] if desc in self._buttons else None def _build_buttons(self): self.widget.clear() self._buttons.clear() self._spacers.clear() with self.widget: for desc in self._button_descs: if desc.image_url: with ui.VStack(width=26): ui.Spacer() self._buttons[desc] = ui.Button( image_url=desc.image_url, image_width=20, image_height=20, width=26, height=26, clicked_fn=desc.clicked_fn, style_type_name_override="ToolBar.Button", tooltip=desc.tooltips if desc.tooltips else "", ) ui.Spacer() else: spacer = ui.Spacer() self._spacers.append(spacer) class BrowserPropertyToolBar(BrowserToolBarBase): """ Represent a tool bar with a button to display a Property widget (window). Args: on_toggle_property_fn (callable): Function called when show/hide property button clicked. Function signure: void on_toggle_property_fn() """ def __init__(self, on_toggle_property_fn: callable): self._on_toggle_property_fn = on_toggle_property_fn self._property_button_desc = BrowserToolBarButtonDesc( f"{ICON_PATH}/property_dark.svg", clicked_fn=self._on_toggle_property_fn, tooltips="Show/Hide property widget", ) super().__init__([BrowserToolBarButtonDesc(""), self._property_button_desc]) def destroy(self): super().destroy() @property def btn_property(self) -> ui.Button: return self.get_button(self._property_button_desc)
5,439
Python
33.43038
116
0.600294
DigitalBotLab/App/kit-app/source/extensions/omni.simready.explorer/omni/simready/explorer/extension.py
# Copyright (c) 2023, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. from typing import List, Optional import carb.settings import omni.ext import omni.kit.menu.utils import omni.ui as ui from omni.kit.browser.core import TreeBrowserWidget from .actions import deregister_actions, register_actions from .browser_model import SimReadyBrowserModel from .empty_property_delegate import EmptyPropertyDelegate from .multi_property_delegate import MultiPropertyDelegate from .prop_property_delegate import PropAssetPropertyDelegate from .window import SIMREADY_EXPLORER_NAME, SimReadyBrowserWindow BROWSER_MENU_ROOT = "Window" SETTINGS_ROOT = "/exts/omni.simready.explorer/" SETTIGNS_VISIBLE = SETTINGS_ROOT + "visible_after_startup" _extension_instance = None class SimReadyBrowserExtension(omni.ext.IExt): @property def window(self) -> Optional[SimReadyBrowserWindow]: return self._window @property def browser_widget(self) -> Optional[TreeBrowserWidget]: return self._window._widget @property def browser_model(self) -> Optional[SimReadyBrowserModel]: return self._window._browser_model def on_startup(self, ext_id): try: self.__ext_id = omni.ext.get_extension_name(ext_id) except AttributeError: def get_extension_name(ext_id: str) -> str: """Convert 'omni.foo-tag-1.2.3' to 'omni.foo-tag'""" a, b, *_ = ext_id.split("-") + [""] if b and not b[0:1].isdigit(): return f"{a}-{b}" return a self.__ext_id = get_extension_name(ext_id) register_actions(self.__ext_id, self) self._window = None ui.Workspace.set_show_window_fn( SIMREADY_EXPLORER_NAME, self._show_window, # pylint: disable=unnecessary-lambda ) self._register_menuitem() visible = carb.settings.get_settings().get_as_bool(SETTIGNS_VISIBLE) if visible: self._show_window(True) # Instantiate the property delegates so they get registered with class BrowserPropertyDelegate self.__empty_property_delegate = EmptyPropertyDelegate() self.__propasset_property_delegate = PropAssetPropertyDelegate() self.__multi_property_delegate = MultiPropertyDelegate() global _extension_instance _extension_instance = self def on_shutdown(self): omni.kit.menu.utils.remove_menu_items(self._menu_entry, name=BROWSER_MENU_ROOT) if self._window is not None: self._window.destroy() self._window = None self.__empty_property_delegate = None self.__propasset_property_delegate = None deregister_actions(self.__ext_id) global _extension_instance _extension_instance = None def _show_window(self, visible) -> None: if visible: if self._window is None: self._window = SimReadyBrowserWindow(visible=True) self._window.set_visibility_changed_fn(self._on_visibility_changed) else: self._window.visible = True else: self._window.visible = False def _toggle_window(self): self._show_window(not self._is_visible()) def _register_menuitem(self): self._menu_entry = [ omni.kit.menu.utils.MenuItemDescription( name="Browsers", sub_menu=[ omni.kit.menu.utils.MenuItemDescription( name=SIMREADY_EXPLORER_NAME, ticked=True, ticked_fn=self._is_visible, onclick_action=(self.__ext_id, "toggle_window"), ) ], ) ] omni.kit.menu.utils.add_menu_items(self._menu_entry, BROWSER_MENU_ROOT) def _is_visible(self): return self._window.visible if self._window else False def _on_visibility_changed(self, visible): omni.kit.menu.utils.refresh_menu_items(BROWSER_MENU_ROOT) def get_instance() -> Optional[SimReadyBrowserExtension]: return _extension_instance
4,537
Python
34.453125
102
0.63985
DigitalBotLab/App/kit-app/source/extensions/omni.simready.explorer/omni/simready/explorer/__init__.py
# Copyright (c) 2023, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. """SimReady Explorer API This module contains the API for the SimReady Explorer extension. """ __all__ = [ "AssetType", "AssetFactory", "SimreadyAsset", "PropAsset", "find_assets", "add_asset_to_stage", "add_asset_to_stage_using_prims", "get_average_position_of_prims", "get_selected_xformable_prim_paths", ] from .asset import AssetFactory, AssetType, PropAsset, SimreadyAsset # noqa: F401, symbol is reexported from .browser_api import ( # noqa: F401, F403, symbol is reexported add_asset_to_stage, add_asset_to_stage_using_prims, find_assets, get_average_position_of_prims, get_selected_xformable_prim_paths, ) from .browser_model import SimReadyBrowserModel # noqa: F401, symbol is reexported from .extension import SimReadyBrowserExtension, get_instance # noqa: F401, symbol is reexported
1,284
Python
34.694443
104
0.744548
DigitalBotLab/App/kit-app/source/extensions/omni.simready.explorer/omni/simready/explorer/browser_folder.py
# Copyright (c) 2023, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. import json from typing import Dict, List, Optional import carb import carb.tokens import omni.client from omni.kit.browser.folder.core import FileSystemFolder from .asset import AssetFactory, SimreadyAsset ASSET_LIST_FILE = "asset_info.json" class AssetFolder(FileSystemFolder): """ Represent folder to traverse to find SimReady assets. """ def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self._asset_by_tags: Optional[Dict[str, List[SimreadyAsset]]] = None self._asset_by_labels: Optional[Dict[str, List[SimreadyAsset]]] = None @property def asset_by_tags(self) -> Dict[str, List[SimreadyAsset]]: """ All assets grouped by tag in this folder, comes from all SimReady assets """ if self._asset_by_tags is None: self._asset_by_tags = {} for asset in self.files: for tag in asset.tags: if tag not in self._asset_by_tags: self._asset_by_tags[tag] = [] self._asset_by_tags[tag].append(asset) for sub_folder in self.sub_folders: asset_by_tags = sub_folder.asset_by_tags for tag in asset_by_tags: if tag not in self._asset_by_tags: self._asset_by_tags[tag] = [] for asset in asset_by_tags[tag]: if asset not in self._asset_by_tags[tag]: self._asset_by_tags[tag].append(asset) return self._asset_by_tags @property def asset_by_labels(self) -> Dict[str, List[SimreadyAsset]]: """ All assets grouped by label in this folder, comes from all SimReady assets """ if self._asset_by_labels is None: self._asset_by_labels = {} for asset in self.files: for label in asset.labels: if label not in self._asset_by_labels: self._asset_by_labels[label] = [] self._asset_by_labels[label].append(asset) return self._asset_by_labels async def _traverse_folder_async(self, url: str, recurse: bool = True): # There will be a json file to list all assets in the folder # Here just read the json file to get assets instead of traverse folder self._asset_by_tags = None asset_json = await self._load_json() if asset_json: for asset_data in asset_json: asset_data["Root Path"] = self.url asset: SimreadyAsset = AssetFactory.create_asset(asset_data) if asset: self.files.append(asset) else: carb.log_warn(f"Couldn't create asset for url {url}.") self._on_traverse_async_done() async def _load_json(self) -> Optional[List[Dict]]: # Load json file to get assets list json_file = self.url + "/" + ASSET_LIST_FILE result, _ = await omni.client.stat_async(json_file) if result != omni.client.Result.OK: carb.log_error(f"Cannot find {json_file}, error: {result}") return None try: result, _, content = await omni.client.read_file_async(json_file) if result != omni.client.Result.OK: carb.log_error(f"Cannot read {json_file}, error: {result}") return None return json.loads(memoryview(content).tobytes().decode("utf-8")) except FileNotFoundError: carb.log_info(f"Failed to open {json_file}!") except PermissionError: carb.log_error(f"Cannot read {json_file}: permission denied!") except Exception as exc: carb.log_error(f"Unknown failure to read {json_file}: {exc}") return None
4,284
Python
38.311926
82
0.59127
DigitalBotLab/App/kit-app/source/extensions/omni.simready.explorer/omni/simready/explorer/asset.py
# Copyright (c) 2023, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. import abc import functools import os from enum import Enum from typing import Any, Callable, Dict, List, Optional, Type import carb from omni.kit.browser.folder.core import BrowserFile class AssetType(Enum): """SimReady asset types. An asset type derived from SimreadyAsset is expected to be of one of these types. The AssetType values are used when registering a new asset type with the AssetFactory, using the AssetFactory.register() decorator. The asset class should also set its _type attribute to the same AssetType value it registered itself with. Example: .. code-block:: python @AssetFactory.register(AssetType.CHARACTER) class CharacterAsset(SimreadyAsset): def __init__(self): self._type = AssetType.CHARACTER .. note:: The SimReady Explorer API does not fully support yet asset classes created by 3rd party developers. """ PROP = 1 """A non-deformable static object.""" VEHICLE = 2 """A vehicle with wheels and doors.""" CHARACTER = 3 """A skinned bipedal character with a rig and animations.""" SCENE = 4 """A scene with a number of static objects and a ground plane""" SIGN = 5 """Road sign""" ROADMARK = 6 """Marks on the road used to direct traffic""" GENERIC = 7 """Generic asset type""" UNKNOWN = 8 """Non-categorized asset""" class SimreadyAsset(BrowserFile, abc.ABC): """Base class for SimReady assets. SimreadyAsset is an abstract type that implements the common behavior of all SimReady assets. Derived classes can further refine and customize the semantics of a Simready asset. A SimReady asset is a collection of sublayers and other data files usually grouped in a folder. The SimReady Specification <todo: add link> defines the structure of a SimReady asset in detail. At a high level, a SimReady asset is comprised of: * Main file : {asset_name}.usd * Sublayers : {asset_name}_{description}.usd * Materials: all mdl or usd material data * Textures: all image data pertaining to materials * Thumbnails: thumbnail images of the asset SimReady assets expose a number of behaviors such as physics, appearance, etc. Assets can also have behaviors that are specific to their type. For example, vehicles may have the number of wheels and doors as part of their behavior. SimReady assets can be tagged. Tags are space delimited groups of words used in filtering assets in an asset library. SimReady assets can be labeled. Hierarchical labels can come from the Wiki Data database (https://www.wikidata.org) and are backed by a QCode. The SimReady Explorer displays the labels in the `Category Tree Window`. Labels, just like tags can be multi-word, and can be used to search for assets. .. note:: The SimReady Explorer API does not fully support yet asset classes created by 3rd party developers. """ def __init__(self, raw_asset_data: Dict): """Initialize a SimReady asset. SimReadyAsset instances are created by the AssetFactory. Developers don't need to instantiate this and derived classes directly. Args: raw_asset_data (Dict): Dictionary with data used to initialize the SimreadyAsset instance. """ self._type = AssetType.UNKNOWN self._name = raw_asset_data.get("Simple Name", "") rel_url = raw_asset_data.get("Relative Path") root_url = raw_asset_data.get("Root Path") if rel_url.startswith("/") or root_url.endswith("/"): url = root_url + rel_url else: url = root_url + "/" + rel_url path = os.path.dirname(url) thumbnail_path = raw_asset_data.get("Thumbnail Path", None) thumbnail = f"{path}/{thumbnail_path}" if thumbnail_path else None label_dict: Dict[str, Any] = raw_asset_data.get("Labels", {}) self._labels: List[str] = [label_dict.get("Hierarchy", "").strip()] self._hierarchy: List[str] = label_dict.get("Hierarchy", "").split("/") self._tags: List[str] = [tag.strip() for tag in raw_asset_data.get("Tags", [])] self._extent: List[float] = raw_asset_data.get("Extent", []) self._qcode: str = label_dict.get("QCode", "").strip() self._behaviors: List[Dict] = raw_asset_data.get("Behaviors", []) for behavior in self._behaviors: if "Value" in behavior: behavior["Value"] = behavior["Value"].strip() super().__init__(url, thumbnail=thumbnail) @classmethod @abc.abstractmethod def is_asset_data(cls, raw_asset_data: Dict) -> bool: """Returns true if the provided raw asset data is determined to represent this asset type. To be implemented by derived classes. """ return False @property def name(self) -> str: """The user readable name of this asset.""" return self._name @property def asset_type(self) -> AssetType: """The type of this asset. Must be one of the values in the AssetType enum. """ return self._type @property def main_url(self) -> str: """The full path to the main file representing the asset. This file represents the top-level USD composition arc for a SimReady asset. It may take other USD layers and combine them together into one USD file. The path is set by the AssetFactory when creating the asset based on the provided raw asset data. """ return self.url @property def thumbnail_url(self) -> Optional[str]: """The full path to the asset's thumbnail image file. The thumbnail path is set by the AssetFactory when creating the asset based on the provided raw asset data. """ return self.thumbnail @property def tags(self) -> List[str]: """The list of tags of this asset. Each tag can be a multi-word space delimited string. Examples: "car", "three wheeled car", etc """ return self._tags @property def labels(self) -> List[str]: """The labels of this asset as a list. Labels are hierarchical and can be used to group assets in a tree structure. The label hierarchy is determined by a Wiki Data QCode (see https://www.wikidata.org) Examples: ['furniture/seat/chair/armchair'], QCode: Q11285759 """ return self._labels @property def labels_as_str(self) -> List[str]: """The labels of this asset as a comma delimited string. Example: "furniture/seat/chair/armchair" """ return ",".join(self._labels) @property def tags_as_str(self) -> str: """List of comma delimited tag words. Note that tags, labels and the QCode are all part of the list of tags in order to make searching more effective. Example: "residential,furniture,seat,chair,armchair,Q11285759" """ return ",".join(self.tags) @property def extent_as_str(self) -> str: """The extent of this asset in 3D space. Example: "20x10.5x0.25" """ return "x".join([str(x) for x in self._extent]) @property def qcode(self) -> str: """The Wiki Data QCode of this asset. Every asset is identified by a QCode. The QCode is used to retrieve the labels from Wiki Data, which in effect, act as a classification of the asset. Example: "Q11285759" """ return self._qcode @property def hierarchy(self) -> str: """The Wiki Data label hierarchy of this asset. This is the same as the "labels" property. Examples: ['furniture', 'seat', 'chair', 'armchair'] """ return self._hierarchy @property def hierarchy_as_str(self): """The Wiki Data label hierarchy of this asset formatted as a '>' delimited string Example: "furniture > seat > chair > armchair" """ reform = " > ".join(self.hierarchy) return reform @property def physics_variant(self) -> Optional[Dict]: """The physics variant set for this asset. This dictionary has the following structure: {'Prim Path': <prim_path>, 'Values': ['None', 'RigidBody']} where <prim_path> is a string representing the path to the prim that contains the physics variant set. The name of the Physics variant set is always "PhysicsVariant". """ for behavior in self._behaviors: if "PhysicsVariant" in behavior: return behavior["PhysicsVariant"] return None @property def behaviors(self) -> Dict[str, List[str]]: """The behaviors of this asset. The behaviors of this asset is represented as a dictionary of variant set names as keys and lists of variant names as values. Example: {'PhysicsVariant': ['None', 'RigidBody']} """ behaviors: Dict[str, List[str]] = {} for behavior in self._behaviors: for variant_set, variant_data in behavior.items(): if variant_set not in behaviors: behaviors[variant_set] = variant_data["Values"] return behaviors def __repr__(self) -> str: return f"[SimReady Asset]{self.url}" class AssetFactory: """A factory of SimReady asset objects. Allows to register asset classes and create instances of them. .. note:: Currently only one asset class can be registered per asset type. The last registered asset class of a given type will be used. Asset classes created and registered by 3rd party developers are not fully supported yet. """ registry: Dict[AssetType, SimreadyAsset] = {} """The registry of asset types. Maps asset types to asset classes.""" @classmethod def register(cls, asset_type: AssetType) -> Callable: """Decorator. Registers a new asset class as asset_type with the AssetFactory. Example: Register MyAsset as AssetTypePROP with the AssetFactory .. code-block:: python @AssetFactory.register(AssetType.PROP) class MyMyAsset(BaseAsset): pass """ @functools.wraps(cls) def inner_wrapper(wrapped_asset_class: Type[SimreadyAsset]) -> Type[SimreadyAsset]: """ Register the wrapped asset class with the asset factory. Return the asset class unaltered. """ if asset_type in cls.registry: carb.log_warn("f{asset_type} already registered; will be replaced by {wrapped_asset_class}") cls.registry[asset_type] = wrapped_asset_class return wrapped_asset_class return inner_wrapper @classmethod def create_asset(cls, raw_asset_data: Dict) -> Optional[SimreadyAsset]: """Creates an asset based on a dictionary of data with content specific to the asset type.""" for asset_class in cls.registry.values(): if asset_class.is_asset_data(raw_asset_data): return asset_class(raw_asset_data) return None @classmethod def num_asset_types(cls) -> int: """Returns the number of registered asset types""" return len(cls.registry) @classmethod def dump_asset_types(cls): """Prints the list of registered asset types""" for asset_type, asset_class in cls.registry.items(): print(f"asset_type: {asset_type}, asset_class: {asset_class}") @AssetFactory.register(AssetType.PROP) class PropAsset(SimreadyAsset): """A SimReady prop asset. Props are physically based static objects that do not deform and don't have kinematic behavior. Examples include chairs, tools, equipment, containers, etc. """ def __init__(self, raw_asset_data: Dict): super().__init__(raw_asset_data) self._type = AssetType.PROP @classmethod def is_asset_data(cls, raw_asset_data: Dict) -> bool: """Returns true if the raw asset data is determined to represent a PROP type asset.""" asset_type: str = raw_asset_data.get("Asset Type", AssetType.UNKNOWN.name) return asset_type.upper() == AssetType.PROP.name
12,798
Python
35.155367
119
0.64346
DigitalBotLab/App/kit-app/source/extensions/omni.simready.explorer/omni/simready/explorer/context_menu.py
# Copyright (c) 2023, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. import asyncio from typing import List, Set import carb import omni.kit.ui as kitui import omni.ui as ui import omni.usd from carb import settings from pxr import Sdf, Usd from .browser_model import AssetDetailItem from .combobox_model import ComboBoxItem from .style import CONTEXT_MENU_STYLE class ContextMenu(ui.Menu): """ Context menu for simready asset browser. """ def __init__(self): super().__init__("SimReady Asset browser context menu", style=CONTEXT_MENU_STYLE) self._settings = settings.get_settings() def show_item(self, item: AssetDetailItem) -> None: self.clear() from .extension import get_instance selection: List[AssetDetailItem] = get_instance().browser_widget.selection if not selection and not item: return assets: List[AssetDetailItem] = selection if selection else [item] # Gather all physics variant values from all the selected assets possible_physics_values = set() for asset in assets: physics_items = asset.physics_model.get_item_children(None) if asset.physics_model else [] possible_physics_values.update(item.value for item in physics_items) # Compute common physics variant value all selected assets share common_physics_value = assets[0].physics for asset in assets: if asset.physics != common_physics_value: common_physics_value = None break with self: # Behavior menu (only physics for now) # Always create new menu items to match asset variant settings if len(possible_physics_values) > 1: with ui.MenuItemCollection(f"{kitui.get_custom_glyph_code('${glyphs}/none.svg')} Physics"): for physics_value in possible_physics_values: value = physics_value ui.MenuItem( value or "None", checked=(value == common_physics_value), checkable=True, triggered_fn=(lambda assets=assets, v=value: self.__set_item_physics(assets, v)), ) # Some right-click commands only make sense when only one asset is selected if len(assets) == 1: ui.Separator() has_collect = False try: # pylint: disable=redefined-outer-name import omni.kit.tool.collect # noqa: F401 has_collect = True ui.MenuItem( f"{kitui.get_custom_glyph_code('${glyphs}/upload.svg')} Collect", triggered_fn=(lambda asset=assets[0]: self.__collect(asset)), ) except ImportError: carb.log_warn("Please enable omni.kit.tool.collect first to collect.") if has_collect: ui.Separator() ui.MenuItem( f"{kitui.get_custom_glyph_code('${glyphs}/show.svg')} Open", triggered_fn=(lambda asset=assets[0]: self.__open_stage(asset, load_all=True)), ) ui.MenuItem( f"{kitui.get_custom_glyph_code('${glyphs}/show.svg')} Open with Payloads Disabled", triggered_fn=(lambda asset=assets[0]: self.__open_stage(asset, load_all=False)), ) ui.Separator() ui.MenuItem( f"{kitui.get_custom_glyph_code('${glyphs}/plus.svg')} Add at Current Selection", triggered_fn=(lambda assets=assets: self.__add_using_selection(assets, False)), ) if len(assets) == 1: # If enabled for multi-selection, only the first asset would be placed at the position # where the selected prims were located, as these prims need to be deleted before any # new prims are added. Therefore, disabling this command for multi-selection. ui.MenuItem( f"{kitui.get_custom_glyph_code('${glyphs}/plus.svg')} Replace Current Selection", triggered_fn=(lambda assets=assets: self.__add_using_selection(assets, True)), ) ui.Separator() ui.MenuItem( f"{kitui.get_custom_glyph_code('${glyphs}/share.svg')} Copy URL Link", triggered_fn=(lambda assets=assets: self.__copy_url_link(assets)), ) self.show() def __set_item_physics(self, assets: List[AssetDetailItem], physics: str) -> None: for asset in assets: asset.physics = physics def __copy_url_link(self, assets: List[AssetDetailItem]) -> None: try: import omni.kit.clipboard omni.kit.clipboard.copy("\n".join(asset.url for asset in assets)) except ImportError: carb.log_warn("Warning: Could not import 'omni.kit.clipboard'.") async def __open_stage_async(self, url: str, load_all: bool): try: import omni.kit.window.file if load_all: loadset = omni.usd.UsdContextInitialLoadSet.LOAD_ALL else: loadset = omni.usd.UsdContextInitialLoadSet.LOAD_NONE omni.kit.window.file.open_stage(url, open_loadset=loadset) except ImportError: carb.log_warn("Warning: Could not import 'omni.kit.window.file'.") except Exception as e: carb.log_error(str(e)) else: carb.log_info(f"Opened '{url}'.\n") def __open_stage(self, item: AssetDetailItem, load_all: bool = True) -> None: """ Open a stage in the current context. Args: item (AssetDetailItem): The asset to open. load_all (bool): Whether to load all payloads. """ asyncio.ensure_future(self.__open_stage_async(item.url, load_all)) def __add_using_selection(self, assets: List[AssetDetailItem], replace_selection: bool) -> None: from .browser_api import add_asset_to_stage_using_prims, get_selected_xformable_prim_paths usd_context: omni.usd.UsdContext = omni.usd.get_context() stage: Usd.Stage = usd_context.get_stage() if usd_context else None prim_paths: List[Sdf.Path] = get_selected_xformable_prim_paths(usd_context, stage) for asset in assets: add_asset_to_stage_using_prims( usd_context, stage, asset.url, variants={ "PhysicsVariant": asset.physics if asset.physics != "None" else "" }, # Hardcoded to physics variant for now replace_prims=replace_selection, prim_paths=prim_paths, ) def __collect(self, asset: AssetDetailItem) -> None: try: # pylint: disable=redefined-outer-name import omni.kit.tool.collect collect_instance = omni.kit.tool.collect.get_instance() collect_instance.collect(asset.url) collect_instance = None except ImportError: carb.log_warn("Failed to import collect module (omni.kit.tool.collect). Please enable it first.") except AttributeError: carb.log_warn("Require omni.kit.tool.collect v2.0.5 or later!")
7,892
Python
42.368132
109
0.58515
DigitalBotLab/App/kit-app/source/extensions/omni.simready.explorer/omni/simready/explorer/browser_with_property_widget.py
# Copyright (c) 2023, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. import asyncio import math from typing import List, Optional import carb import omni.kit.app import omni.ui as ui from omni.kit.browser.folder.core import FileDetailItem, TreeFolderBrowserWidget from .browser_property_view import BrowserPropertyView from .browser_toolbar import BrowserPropertyToolBar from .style import UI_STYLES # Layout are dynmiac changed when window size changed: small to V mode otherwise to H mode class Layout: # V mode, max window width. If window width is bigger, switch to H mode V_MAX_WINDOW_WIDTH = 400 # V mode, min view height, at least show one row V_MIN_VIEW_HEIGHT = 156 # V model, min property view height V_MIN_PROPERTY_HEIGHT = 20 # V mode, default toolkits height V_DEFAULT_TOOLKITS_HEIGHT = 280 # Vmode, search bar width V_SEARCH_BAR_WIDTH = ui.Pixel(400) # H mode, default toolkits width H_DEFAULT_TOOLKITS_WIDTH = 450 # H mode, min view width, at least show one column H_MIN_VIEW_WIDTH = 200 # H mode, min property view width H_MIN_PROPERTY_WIDTH = 75 class BrowserWithPropertyWidget(TreeFolderBrowserWidget): """ The Browser View (V in the MDV achitecture). Responsible for creating the frames for Category view, Search bar, Browser area, Property view. Takes care of updating the layout when user resizes windows. """ def __init__(self, *args, **kwargs): self._frame_width: Optional[float] = None self._frame_height: Optional[float] = None # Default horizontal layout sice docked bottom along with Content self._layout_vertical = False self._last_toolkits_width = 0 self._last_toolkits_height = 0 super().__init__(*args, **kwargs) self._switch_layout(self._layout_vertical) def build_widgets(self) -> None: """ Build widgets with property view. """ self._frame = ui.Frame() with self._frame: with ui.VStack(spacing=4, style=UI_STYLES): self._build_search_toolbar() self._build_browser_widgets() # Need change layout and children size if widget size changed self._frame.set_computed_content_size_changed_fn(self._on_size_changed) def _build_search_toolbar(self): with ui.ZStack(height=0): self._build_search_bar() self._h_toolbar_container = ui.HStack(height=0) with self._h_toolbar_container: ui.Spacer() self._toolbar = BrowserPropertyToolBar(self._toggle_property_view) def _build_browser_widgets(self): self._browser_container = ui.Stack(ui.Direction.TOP_TO_BOTTOM, spacing=4) with self._browser_container: self._browser_view_container = ui.ZStack(height=0) with self._browser_view_container: self._build_browser_widget() # Draggable splitter for H/V layout mode self._v_splitter = ui.Placer(offset_y=0, draggable=True, drag_axis=ui.Axis.Y) with self._v_splitter: ui.Rectangle(height=4, style_type_name_override="Splitter") self._h_splitter = ui.Placer(offset_x=0, draggable=True, drag_axis=ui.Axis.X) with self._h_splitter: ui.Rectangle(width=4, style_type_name_override="Splitter") # Toolkits self._toolkits_container = ui.VStack(spacing=4) with self._toolkits_container: # Toolbar with property button self._v_toolbar_frame = ui.Frame(height=0) self._v_toolbar_frame.add_child(self._toolbar.widget) # Property View self._property_view = BrowserPropertyView() self._v_splitter.set_offset_y_changed_fn(self._splitter_offset_y_changed) self._h_splitter.set_offset_x_changed_fn(self._splitter_offset_x_changed) self._toolbar.btn_property.selected = self._property_view.visible self._browser_widget._detail_view.set_selection_changed_fn(self._on_detail_selection_changed) # Default show property view async def __show_property_view_async(): await omni.kit.app.get_app().next_update_async() self._toggle_property_view() asyncio.ensure_future(__show_property_view_async()) def _splitter_offset_y_changed(self, offset_y: ui.Length) -> None: if self._property_view.visible: if offset_y.value < Layout.V_MIN_VIEW_HEIGHT: self._v_splitter.offset_y = Layout.V_MIN_VIEW_HEIGHT return available_property_height = ( self._browser_container.computed_height - offset_y - self._toolbar.computed_height - 12 ) if available_property_height < Layout.V_MIN_PROPERTY_HEIGHT: self._last_toolkits_height = 0 self._toggle_property_view() if self._property_view.visible: self._last_toolkits_height = self._browser_container.computed_height - offset_y def _splitter_offset_x_changed(self, offset_x: ui.Length) -> None: if self._property_view.visible: if offset_x.value < Layout.H_MIN_VIEW_WIDTH: self._h_splitter.offset_x = Layout.H_MIN_VIEW_WIDTH return available_property_width = self._browser_container.computed_width - offset_x - 8 if available_property_width < Layout.H_MIN_PROPERTY_WIDTH: self._toggle_property_view() self._last_toolkits_width = 0 if self._property_view.visible: self._last_toolkits_width = self._browser_container.computed_width - offset_x def _switch_layout(self, vertical: bool) -> None: # toolbar visibility self._toolbar.spacer_visible = vertical self._toolbar.widget.width = ui.Fraction(1) if vertical else ui.Pixel(0) self._v_toolbar_frame.visible = vertical self._h_toolbar_container.visible = not vertical # searchbar self.__update_search_bar_width(vertical) # browser view and splitters self._browser_container.direction = ui.Direction.TOP_TO_BOTTOM if vertical else ui.Direction.LEFT_TO_RIGHT self._v_splitter.visible = vertical self._h_splitter.visible = not vertical if vertical: self._browser_view_container.width = ui.Fraction(1) self._toolkits_container.width = ui.Fraction(1) else: self._browser_view_container.height = ui.Fraction(1) self._toolkits_container.height = ui.Fraction(1) self._layout_vertical = vertical # Hide property if not enough space if self._property_view.visible and not self._has_space_for_property(): self._property_view.visible = False self._toolbar.btn_property.selected = False # Update widgets position asyncio.ensure_future(self._update_layout_async()) def _on_size_changed(self) -> None: # Widget size changed callback if self._frame_width is None or self._frame_height is None: self._frame_width = self._frame.computed_content_width self._frame_height = self._frame.computed_content_height else: if not math.isclose(self._frame_width, self._frame.computed_content_width): async def __delay_update_width(): await omni.kit.app.get_app().next_update_async() self._on_width_changed(self._frame.computed_content_width) asyncio.ensure_future(__delay_update_width()) self._frame_width = self._frame.computed_content_width if not math.isclose(self._frame_height, self._frame.computed_content_height): async def __delay_update_height(): await omni.kit.app.get_app().next_update_async() self._on_height_changed(self._frame.computed_content_height) asyncio.ensure_future(__delay_update_height()) self._frame_height = self._frame.computed_content_height def _on_width_changed(self, width) -> None: # Window width changed, adjust widgets layout vertical_layout = width < Layout.V_MAX_WINDOW_WIDTH if vertical_layout != self._layout_vertical: self._switch_layout(vertical_layout) if not self._layout_vertical and self._property_view.visible and self._last_toolkits_width != 0: self._h_splitter.offset_x = self._browser_container.computed_width - self._last_toolkits_width self.__update_search_bar_width(self._layout_vertical) def _on_height_changed(self, height) -> None: if self._layout_vertical and self._property_view.visible and self._last_toolkits_height != 0: self._v_splitter.offset_y = self._browser_container.computed_height - self._last_toolkits_height def _toggle_property_view(self) -> None: if not self._property_view.visible and not self._has_space_for_property(): carb.log_warn("Not enough space to show property!") return self._property_view.visible = not self._property_view.visible self._toolbar.btn_property.selected = self._property_view.visible asyncio.ensure_future(self._update_layout_async()) def __update_search_bar_width(self, vertical: bool): # Update width of search bar if vertical: self._search_bar.width = ui.Fraction(1) else: def __set_search_bar_width(): # Adjust search bar width to match the model panel bar self._search_bar.width = ui.Pixel( self._toolbar.position_x - self._search_bar._frame.screen_position_x - 10 ) if self._toolbar.width > 0: __set_search_bar_width() else: self._search_bar.width = Layout.V_SEARCH_BAR_WIDTH async def __delay_update(): while self._toolbar.width == 0: await omni.kit.app.get_app().next_update_async() await omni.kit.app.get_app().next_update_async() __set_search_bar_width() asyncio.ensure_future(__delay_update()) def _has_space_for_property(self) -> bool: if self._layout_vertical: if self._browser_container.computed_height > 0: available_property_height = ( self._browser_container.computed_height - Layout.V_MIN_VIEW_HEIGHT - self._toolbar.computed_height - 12 ) if available_property_height < Layout.V_MIN_PROPERTY_HEIGHT: carb.log_warn("Not enough space to show property!") return False else: available_property_width = self._browser_container.computed_width - Layout.H_MIN_VIEW_WIDTH - 12 if available_property_width < Layout.H_MIN_PROPERTY_WIDTH: return False return True async def _update_layout_async(self) -> None: if not self._property_view.visible: # property hidden if self._layout_vertical: # toolkits height fix, browser view height max await omni.kit.app.get_app().next_update_async() self._v_splitter.visible = False self._browser_view_container.height = ui.Fraction(1) self._toolkits_container.height = ui.Pixel(0) else: # toolkits width fix, browser view width max await omni.kit.app.get_app().next_update_async() self._h_splitter.visible = False self._browser_view_container.width = ui.Fraction(1) self._toolkits_container.width = ui.Pixel(0) else: # show property view if self._layout_vertical: # details view height changed by splitter, toolkits max self._toolkits_container.height = ui.Fraction(1) self._browser_view_container.height = ui.Pixel(0) self._v_splitter.visible = True await omni.kit.app.get_app().next_update_async() if self._last_toolkits_height == 0: offset_y = max( self._browser_container.computed_height - Layout.V_DEFAULT_TOOLKITS_HEIGHT, Layout.V_MIN_VIEW_HEIGHT, ) self._last_toolkits_height = self._browser_container.computed_height - offset_y self._v_splitter.offset_y = offset_y else: self._v_splitter.offset_y = self._browser_container.computed_height - self._last_toolkits_height else: # details view height changed by splitter, toolkits max self._toolkits_container.width = ui.Fraction(1) self._browser_view_container.width = ui.Pixel(0) self._h_splitter.visible = True await omni.kit.app.get_app().next_update_async() if self._last_toolkits_width == 0: offset_x = max( self._browser_container.computed_width - Layout.H_DEFAULT_TOOLKITS_WIDTH, Layout.H_MIN_VIEW_WIDTH, ) self._last_toolkits_width = self._browser_container.computed_width - offset_x self._h_splitter.offset_x = offset_x else: self._h_splitter.offset_x = self._browser_container.computed_width - self._last_toolkits_width def _on_detail_selection_changed(self, selections: List[FileDetailItem]) -> None: self.selection = selections if len(selections) > 1: self._property_view.show_detail_multi_item(selections) else: self._property_view.show_detail_item(selections[0] if selections else None)
14,533
Python
43.042424
116
0.606207
DigitalBotLab/App/kit-app/source/extensions/omni.simready.explorer/omni/simready/explorer/asset_property_delegate.py
# Copyright (c) 2023, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. import abc from typing import Optional import omni.ui as ui from .asset import SimreadyAsset from .browser_model import AssetDetailItem from .browser_property_delegate import BrowserPropertyDelegate class AssetPropertyDelegate(BrowserPropertyDelegate): """Base class for all asset property delegates.""" @abc.abstractmethod def asset_accepted(self, asset: Optional[SimreadyAsset]) -> bool: return False @abc.abstractmethod def show_asset(self, asset: Optional[SimreadyAsset], frame: ui.Frame) -> None: pass def accepted(self, detail_item: Optional[AssetDetailItem]) -> bool: """ Check if detail item could be shown by this delegate. Args: detail_item (AssetDetailItem): Detail item to be shown. """ return self.asset_accepted(detail_item.asset if detail_item else None) def show(self, detail_item: Optional[AssetDetailItem], frame: ui.Frame) -> None: """ Show detail item with this delegate. Args: detail_item (AssetDetailItem): Detail item to be shown. frame (ui.Frame): Parent frame to put widgets. """ self.show_asset(detail_item.asset if detail_item else None, frame)
1,667
Python
35.260869
84
0.711458
DigitalBotLab/App/kit-app/source/extensions/omni.simready.explorer/omni/simready/explorer/browser_property_delegate.py
# Copyright (c) 2023, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. __all__ = ["BrowserPropertyDelegate"] import abc import weakref from typing import List, Optional import omni.ui as ui from omni.kit.window.property.templates import HORIZONTAL_SPACING, LABEL_HEIGHT, LABEL_WIDTH from .browser_model import AssetDetailItem class BrowserPropertyDelegate(abc.ABC): """Base class for item property delegates and registry of these same delegate instances. Whenever an instance of this class is created, it is automatically registered. The BrowserPropertyView will show the Property widget, and will display into it all the registered delegates that accept the current item. This class is not meant to be instantiated directly, but rather to be subclassed. """ # Use a list to track drag-drop order so that it's deterministic in the event of clashes or cancelation. __g_registered = [] @classmethod def get_instances(cls) -> List["BrowserPropertyDelegate"]: remove = [] for wref in BrowserPropertyDelegate.__g_registered: obj = wref() if obj: yield obj else: remove.append(wref) for wref in remove: BrowserPropertyDelegate.__g_registered.remove(wref) def __init__(self): self.__g_registered.append(weakref.ref(self, lambda r: BrowserPropertyDelegate.__g_registered.remove(r))) def __del__(self): self.destroy() def destroy(self): for wref in BrowserPropertyDelegate.__g_registered: if wref() == self: BrowserPropertyDelegate.__g_registered.remove(wref) break @abc.abstractmethod def accepted(self, detail_item: Optional[AssetDetailItem]) -> bool: """ Check if detail item could be shown by this delegate. Args: detail_item (AssetDetailItem): Detail item to be shown. """ return False @abc.abstractmethod def show(self, detail_item: Optional[AssetDetailItem], frame: ui.Frame) -> None: """ Show detail item with this delegate. Args: detail_item (AssetDetailItem): Detail item to be shown. frame (ui.Frame): Parent frame to put widgets. """ pass @abc.abstractmethod def accepted_multiple(self, detail_items: List[AssetDetailItem]) -> bool: """ Check if details of multiple items could be shown by this delegate. Args: detail_items (List[AssetDetailItem]): Detail items to be shown. """ return False @abc.abstractmethod def show_multiple(self, detail_items: List[AssetDetailItem], frame: ui.Frame) -> None: """ Show details of multiple items with this delegate. The delegate may choose to show common properties of all items. Args: detail_items (List[AssetDetailItem]): Detail items to be shown. frame (ui.Frame): Parent frame to put widgets. """ pass def _build_label( self, text: str, width: Optional[ui.Length] = LABEL_WIDTH, alignment=ui.Alignment.LEFT_CENTER ) -> ui.Label: return ui.Label( text, name="label", word_wrap=True, width=width if width is not None else LABEL_WIDTH, height=LABEL_HEIGHT, alignment=alignment, ) def _build_combobox(self, text: str, *args, **kwargs) -> ui.ComboBox: with ui.HStack(spacing=HORIZONTAL_SPACING, padding=10): ui.Label(text, style_type_name_override="Asset.Label", width=100) return ui.ComboBox(*args, name="choices", **kwargs) def _build_checkbox(self, model: Optional[ui.AbstractValueModel] = None) -> ui.CheckBox: # Copy from UsdPropertiesWidgetBuilder._bool_builder with ui.VStack(width=10): ui.Spacer() widget_kwargs = {"width": 10, "height": 0, "name": "greenCheck", "model": model} with ui.ZStack(): with ui.Placer(offset_x=0, offset_y=-2): checkbox = ui.CheckBox(**widget_kwargs) with ui.Placer(offset_x=1, offset_y=-1): ui.Rectangle(height=8, width=8, name="mixed_overlay", alignment=ui.Alignment.CENTER, visible=False) ui.Spacer() return checkbox # noqa: R504 def _build_string_field(self, model: Optional[ui.SimpleStringModel] = None, text: str = "") -> ui.StringField: if text: with ui.HStack(spacing=HORIZONTAL_SPACING): self._build_label(text) field = ui.StringField(model, name="models") return field else: return ui.StringField(model, name="models") def _build_float_field(self, model: Optional[ui.SimpleFloatModel] = None) -> ui.FloatField: return ui.FloatField(model, name="models") def _build_float_drag(self, model: Optional[ui.AbstractValueModel] = None, name="models") -> ui.FloatDrag: drag = ui.FloatDrag(model, name=name, min=model.min, max=model.max) drag.step = max(0.1, (model.max - model.min) / 1000.0) return drag def _build_int_drag(self, model: Optional[ui.AbstractValueModel] = None, name="models") -> ui.IntDrag: kwargs = {} if model.min is not None: kwargs["min"] = model.min if model.max is not None: kwargs["max"] = model.max drag = ui.IntDrag(model, name="models", **kwargs) if model.min is not None and model.max is not None: drag.step = max(0.1, (model.max - model.min) / 1000.0) return drag def _build_float_slider(self, model: Optional[ui.AbstractValueModel] = None, name="models") -> ui.FloatSlider: slider = ui.FloatSlider(model, name=name, min=model.min, max=model.max) slider.step = max(0.1, (model.max - model.min) / 1000.0) return slider
6,332
Python
38.830188
119
0.630449
DigitalBotLab/App/kit-app/source/extensions/omni.simready.explorer/omni/simready/explorer/actions.py
# Copyright (c) 2023, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. import json import os from typing import Dict, List, Optional, Tuple import carb import carb.settings import omni.client import omni.kit.commands import omni.usd from pxr import Gf, Sdf, Tf, Usd, UsdGeom from .style import SIMREADY_DRAG_PREFIX def normalize_sdf_path(sdf_layer_path: str): return sdf_layer_path.replace("\\", "/") def make_relative_to_layer(stage: Usd.Stage, url: str) -> str: # XXX: PyBind omni::usd::UsdUtils::makePathRelativeToLayer stage_layer = stage.GetEditTarget().GetLayer() if not stage_layer.anonymous and not Sdf.Layer.IsAnonymousLayerIdentifier(url): stage_layer_path = stage_layer.realPath if normalize_sdf_path(stage_layer_path) == url: carb.log_warn(f"Cannot reference {url} onto itself") return url relative_url = omni.client.make_relative_url(stage_layer_path, url) if relative_url: # omniverse path can have '\' return relative_url.replace("\\", "/") return url def make_prim_path(stage: Usd.Stage, url: str, prim_path: Sdf.Path = None, prim_name: str = None): """Make a new/unique prim path for the given url""" if prim_path is None or prim_path.isEmpty: if stage.HasDefaultPrim(): prim_path = stage.GetDefaultPrim().GetPath() else: prim_path = Sdf.Path.absoluteRootPath if prim_name is None: prim_name = Tf.MakeValidIdentifier(os.path.basename(os.path.splitext(url)[0])) return Sdf.Path(omni.usd.get_stage_next_free_path(stage, prim_path.AppendChild(prim_name).pathString, False)) def _add_asset_to_stage_helper( usd_context: omni.usd.UsdContext, stage: Usd.Stage, url: str, prim_path: Sdf.Path = None, payload: str = "", instanceable: str = "", ) -> Tuple[Sdf.Path, Usd.EditContext, str]: """Add a Usd.Prim to an exiting Usd.Stage, pointing to the url Args: usd_context (omni.usd.UsdContext): Usd context to add asset to. stage (Usd.Stage): Usd stage to add asset to. url (str): Url to asset to add. Kwargs: prim_path (Sdf.Path): Parent prim path to add asset to. payload (str): "payload" or "reference". If empty, use the setting at "/persistent/app/stage/dragDropImport". instanceable (str): "instanceable" or "noninstanceable". If empty (default), use the setting at "/persistent/app/stage/instanceableOnCreatingReference". selected_prims (List[Usd.Prim]): List of selected prims. If not empty (default), use the first prim's payload/reference status. """ # Get a realtive URL if possible relative_url = make_relative_to_layer(stage, url) # When in auto authoring mode, don't create it in the current edit target # as it will be cleared each time to be moved to default edit layer. edit_context = None layers = usd_context.get_layers() if layers and layers.get_layer_edit_mode() == omni.usd.LayerEditMode.AUTO_AUTHORING: default_identifier = layers.get_default_edit_layer_identifier() edit_layer = Sdf.Layer.Find(default_identifier) if edit_layer is None: edit_layer = stage.GetRootLayer() edit_context = Usd.EditContext(stage, edit_layer) new_prim_path = make_prim_path(stage, url, prim_path=prim_path) if not instanceable: as_instanceable = carb.settings.get_settings().get("/persistent/app/stage/instanceableOnCreatingReference") else: as_instanceable = instanceable == "instanceable" # Determine if we should create a payload or reference if not payload: create_as_payload = carb.settings.get_settings().get("/persistent/app/stage/dragDropImport") == "payload" else: create_as_payload = payload == "payload" # Add asset to stage cmd_name = "CreatePayloadCommand" if create_as_payload else "CreateReferenceCommand" omni.kit.commands.execute( cmd_name, usd_context=usd_context, path_to=new_prim_path, asset_path=url, instanceable=as_instanceable ) return (new_prim_path, edit_context, relative_url) def set_prim_variants(stage: Usd.Stage, prim_path: Sdf.Path, variants: Dict[str, str]): """ Set the variants on the provided prim. """ prim = stage.GetPrimAtPath(prim_path) if prim: vsets = prim.GetVariantSets() for name, value in variants.items(): carb.log_info(f"Try to set variant for {prim_path}: {name} -> {value}") vset = vsets.GetVariantSet(name) if vset: vset.SetVariantSelection(value) def find_inst_prim(start_prim: Usd.Prim) -> Optional[Usd.Prim]: """Find the prim from the given prim path wose name ends in '_inst'.""" if not start_prim: return None if start_prim.GetName().endswith("_inst"): return start_prim for child in start_prim.GetChildren(): inst_prim = find_inst_prim(child) if inst_prim: return inst_prim return None def is_physics_variant_enabled(variants: Dict[str, str]) -> bool: """Check if the physics variant is found and enabled (not 'None'). Args: variants (Dict[str, str]): Dictionary of variant name and value. """ if variants and "PhysicsVariant" in variants and variants["PhysicsVariant"] != "": return True return False def configure_prim(stage: Usd.Stage, prim_path: Sdf.Path, variants: Dict[str, str]) -> None: """Configure the variants of the given prim.""" if not stage or not prim_path or prim_path.emptyPath or not variants: return # Set the variants on the prim at prim_path set_prim_variants(stage, prim_path, variants) def _add_asset_with_variant_to_stage( raw_data: dict, context: str = "", prim_path: Optional[Sdf.Path] = None ) -> Tuple[bool, str]: """ Add simready asset to stage from raw data. Args: raw_data (dict): Json data decribe asset to add. See more in SimReadyBrowserModel.get_drag_mime_data() Kwargs: context (str): Name of usd content. Default "" prim_path (Optional[Sdf.Path]): Parent prim path to add asset. Default None means default prim. Returns: Tuple of success and added prim path. """ usd_context = omni.usd.get_context(context) if not usd_context: carb.log_error("Failed to drop asset since usd context not found!") return False, "" stage = usd_context.get_stage() if not stage: carb.log_error("Failed to drop asset since usd stage not found!") return False, "" url = raw_data.get("url", "") if not url: carb.log_error("Failed to drop asset since url not defined!") return False, "" payload = raw_data.get("payload", "") instanceable = raw_data.get("instanceable", "") # Add the asset to stage (dropped_path, _, _) = _add_asset_to_stage_helper( usd_context, stage, url, prim_path=prim_path, payload=payload, instanceable=instanceable ) # Set variants on the added asset if dropped_path: variants = raw_data.get("variants", {}) configure_prim(stage, dropped_path, variants) return True, dropped_path def add_single_asset_from_drag(drag_mime_data: str, context: str = "", prim_path: Optional[Sdf.Path] = None) -> bool: """ Add simready asset to stage from drag mime data. Args: drag_mime_data (str): Mime data decribe asset to add. See more in SimReadyBrowserModel.get_drag_mime_data() Kwargs: context (str): Name of usd content. Default "" prim_path (Optional[Sdf.Path]): Parent prim path to add asset. Default None means default prim. """ if drag_mime_data.startswith(SIMREADY_DRAG_PREFIX): drag_mime_data = drag_mime_data[len(SIMREADY_DRAG_PREFIX) :] raw_data = json.loads(drag_mime_data) res, _ = _add_asset_with_variant_to_stage(raw_data, context=context, prim_path=prim_path) return res def add_asset_from_drag(drag_mime_data: str, context: str = "", prim_path: Optional[Sdf.Path] = None) -> bool: mime_datas = drag_mime_data.split("\n") for data in mime_datas: add_single_asset_from_drag(data, context=context, prim_path=prim_path) def register_actions(extension_id: str, extension_instance): """ Register actions. Args: extension_id (str): Extension ID whcih actions belongs to """ try: import omni.kit.actions.core action_registry = omni.kit.actions.core.get_action_registry() actions_tag = "SimReady" action_registry.register_action( extension_id, "toggle_window", lambda: extension_instance._toggle_window(), display_name="SimReady Explorer show/hide window", description="SimReady Explorer show/hide window", tag=actions_tag, ) action_registry.register_action( extension_id, "add_asset", lambda raw_data, context="", path_to=None: _add_asset_with_variant_to_stage(raw_data, context, path_to), display_name="SimReady->Add Asset", description="Add SimReady asset to stage", tag=actions_tag, ) action_registry.register_action( extension_id, "add_asset_from_drag", lambda drag_mime_data, context="", path_to=None: add_asset_from_drag(drag_mime_data, context, path_to), display_name="SimReady->Add Asset From Drag", description="Add SimReady asset to stage from dragging mime data", tag=actions_tag, ) except ImportError: pass def deregister_actions(extension_id: str): """ Deregister actions. Args: extension_id (str): Extension ID whcih actions belongs to """ try: import omni.kit.actions.core action_registry = omni.kit.actions.core.get_action_registry() action_registry.deregister_all_actions_for_extension(extension_id) except ImportError: pass
10,429
Python
37.205128
160
0.655959
DigitalBotLab/App/kit-app/source/extensions/omni.simready.explorer/omni/simready/explorer/multi_property_delegate.py
# Copyright (c) 2023, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. from typing import List, Optional import omni.ui as ui from .browser_model import AssetDetailItem from .browser_property_delegate import BrowserPropertyDelegate class MultiPropertyDelegate(BrowserPropertyDelegate): """ A delegate to show when multiple items are selected. """ def accepted(self, asset: Optional[AssetDetailItem]) -> bool: """BrowserPropertyDelegate method override""" return False def show(self, asset: Optional[AssetDetailItem], frame: ui.Frame) -> None: """BrowserPropertyDelegate method override""" pass def accepted_multiple(self, detail_items: List[AssetDetailItem]) -> bool: """BrowserPropertyDelegate method override""" return True def show_multiple(self, detail_items: List[AssetDetailItem], frame: ui.Frame) -> None: """BrowserPropertyDelegate method override""" label_text = f"Multiple SimReady Assets Selected [{len(detail_items)}]" if hasattr(self, "_container"): self._label.text = label_text self._container.visible = True else: with frame: self._container = ui.VStack() with self._container: self._label = ui.Label(label_text, alignment=ui.Alignment.CENTER)
1,720
Python
37.244444
90
0.695349
DigitalBotLab/App/kit-app/source/extensions/omni.simready.explorer/omni/simready/explorer/browser_delegate.py
# Copyright (c) 2023, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. from typing import Optional import omni.ui as ui from omni.kit.browser.folder.core import FolderDetailDelegate from .browser_model import AssetDetailItem, SimReadyBrowserModel from .context_menu import ContextMenu from .style import ICON_PATH from .viewport_drop_delegate import SimReadyDragDropObject class SimReadyDetailDelegate(FolderDetailDelegate): """ Delegate to show SimReady asset item in detail view (where the list of thumbnails is shown) Args: model (SimReadyBrowserModel): Asset browser model """ def __init__(self, model: SimReadyBrowserModel): super().__init__(model=model) # Context menu for detail item self._context_menu: Optional[ContextMenu] = None # Drop helper to handle dropping in viewport (only works for VP2) self._drop_helper = SimReadyDragDropObject() def destroy(self): self._drop_helper = None if self._context_menu: self._context_menu.destroy() self._context_menu = None super().destroy() def get_thumbnail(self, item: AssetDetailItem) -> str: """Set default thumbnail if thumbnail is None""" return item.thumbnail or f"{ICON_PATH}/usd_stage_256.png" def get_tooltip(self, item: AssetDetailItem) -> Optional[str]: """No tooltip for detail item as it interferes with the right-click menu""" return None def on_drag(self, item: AssetDetailItem) -> str: """Could be dragged to viewport window""" thumbnail = self.get_thumbnail(item) icon_size = 128 with ui.VStack(width=icon_size): if thumbnail: ui.Spacer(height=2) with ui.HStack(): ui.Spacer() ui.ImageWithProvider(thumbnail, width=icon_size, height=icon_size) ui.Spacer() ui.Label( item.name, word_wrap=False, elided_text=True, skip_draw_when_clipped=True, alignment=ui.Alignment.TOP, style_type_name_override="GridView.Item", ) return self._model.get_drag_mime_data(item) def on_multiple_drag(self, item: AssetDetailItem) -> str: """Could be dragged to viewport window""" thumbnail = self.get_thumbnail(item) icon_size = 32 with ui.HStack(height=icon_size): if thumbnail: ui.ImageWithProvider(thumbnail, width=icon_size, height=icon_size) ui.Spacer(width=8) ui.Label(item.name, style_type_name_override="GridView.Item") return self._model.get_drag_mime_data(item) def on_right_click(self, item: AssetDetailItem) -> None: """Show context menu""" if self._context_menu is None: self._context_menu = ContextMenu() self._context_menu.show_item(item) def build_widget( self, model: ui.AbstractItemModel, item: AssetDetailItem, index: int = 0, level: int = 0, expand: bool = False ): super().build_widget(model, item, index=index, level=level, expand=expand) tooltip = self.get_tooltip(item) if tooltip is not None: self._cached_thumbnail_widgets[item].set_tooltip(tooltip) def build_thumbnail(self, item: AssetDetailItem) -> Optional[ui.Image]: """ Display thumbnail per detail item Args: item (DetailItem): detail item to display """ with ui.ZStack(): thumbnail_image = ui.Image( self.get_thumbnail(item), fill_policy=ui.FillPolicy.STRETCH, style_type_name_override="GridView.Image" ) # Badge to indicate item physics ON, need to change visibility if physics status changed badge_container = ui.HStack(alignment=ui.Alignment.LEFT_BOTTOM, visible=item.physics != "None") with badge_container: ui.Spacer(width=ui.Percent(80)) with ui.VStack(): ui.Spacer(height=2) ui.ImageWithProvider( fill_policy=ui.IwpFillPolicy.IWP_PRESERVE_ASPECT_FIT, alignment=ui.Alignment.LEFT, style_type_name_override="GridView.Item.Badge.Image", ) badge_container.visible = item.physics != "None" if item.physics_model: item.physics_model.current_index.add_value_changed_fn( lambda m, w=badge_container: self.__on_item_physics_changed(m, w) ) return thumbnail_image # noqa: R504 def __on_item_physics_changed(self, model: ui.SimpleIntModel, badge_widget: ui.Widget) -> None: badge_widget.visible = model.as_int != 0
5,234
Python
38.360902
118
0.618647
DigitalBotLab/App/kit-app/source/extensions/omni.simready.explorer/omni/simready/explorer/browser_model.py
# Copyright (c) 2023, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. import json from itertools import chain from typing import Dict, List, Optional import carb.settings from omni.kit.browser.core import CategoryItem, DetailItem from omni.kit.browser.folder.core import ( FileDetailItem, FileSystemFolder, FolderCategoryItem, FolderCollectionItem, TreeFolderBrowserModel, ) from .actions import add_asset_from_drag from .asset import SimreadyAsset from .browser_folder import AssetFolder from .combobox_model import ComboBoxModel from .style import SIMREADY_DRAG_PREFIX SETTINGS_DEFAULT_PHYSICS = "/exts/omni.simready.explorer/default_physics" class AssetDetailItem(DetailItem): """ Represents a single asset detail item. Args: name (str): asset name. url (str): asset url. asset (SimreadyAsset): asset object linked to this item. thumbnail (Optional[str]): thumbnail url of file. Default is None. """ @classmethod def get_default_physics_value(cls) -> str: """Default physics variant value for all assets. This is used to initialize the physics model.""" return str(carb.settings.get_settings().get_as_string(SETTINGS_DEFAULT_PHYSICS) or "RigidBody") def __init__(self, asset: SimreadyAsset): super().__init__(asset.name, asset.url, asset.thumbnail) self.asset = asset # Physics model physics_values: List[str] = [] if self.asset.physics_variant: physics_values = self.asset.physics_variant.get("Values", []) default_value = AssetDetailItem.get_default_physics_value() if physics_values: # "None" is not in the physics variantset of the asset, so we need to add it "manually" physics_values.insert(0, "None") if AssetDetailItem.get_default_physics_value() not in physics_values: default_value = physics_values[0] self.physics_model = ComboBoxModel(physics_values, current_value=default_value) else: self.physics_model = None @property def physics(self) -> str: return self.physics_model.current_value if self.physics_model else "None" @physics.setter def physics(self, value: str) -> None: if self.physics_model: self.physics_model.current_value = value def filter(self, filter_words: Optional[List[str]]) -> bool: # noqa: A003 # Filter asset by not only name but also tag if filter_words is None: return True else: for word in filter_words: # Each search word should be in name or tag if word.lower() not in self.name.lower(): # No partial match in asset name, check tags for tag in self.asset.tags: if word.lower() in tag.lower(): break # Found a partial match in asset tag else: return False # No partial match in any of the tags, reject asset else: return True class SimReadyBrowserModel(TreeFolderBrowserModel): """ Represent browser model for SimReady assets. It show files(assets) by tags instead of folders. """ def __init__(self, *args, **kwargs): super().__init__( show_summary_folder=True, *args, **kwargs, ) # Folder for labels, used to show as category item self.__label_folders: Dict[str, FileSystemFolder] = {} def create_folder_object(self, *args, **kwargs): return AssetFolder(*args, **kwargs) def get_category_items(self, item: FolderCollectionItem) -> List[FolderCategoryItem]: # Traverse root folder if necessary for root_folder in self._root_folders: # Not in cache if not root_folder.prepared: # No traversed self.start_traverse(root_folder) # Create category item from labels category_items: List[FolderCategoryItem] = [] root_folders = [folder for folder in self.__label_folders.values() if folder.name.find("/") < 0] summary_count = 0 for folder in root_folders: if folder not in self._folder_cache: self._folder_cache[folder] = self._create_folder_category_item(folder) category_items.append(self._folder_cache[folder]) summary_count += self._folder_cache[folder].count self.sort_items(category_items) if self._show_summary_folder: category_items.insert(0, CategoryItem(self.SUMMARY_FOLDER_NAME, summary_count)) return category_items def get_detail_items(self, item: CategoryItem) -> List[FileDetailItem]: """Override to get list of detail items""" if item.name == self.SUMMARY_FOLDER_NAME: return self._get_summary_detail_items() else: # List files in item folder detail_items = self._get_folder_detail_items(item.folder) for child in item.children: detail_items += self.get_detail_items(child) self.sort_items(detail_items) return detail_items def get_drag_mime_data(self, item: AssetDetailItem = None) -> str: if item: drag_data = {"url": item.url, "variants": {}} if item.physics: drag_data["variants"]["PhysicsVariant"] = item.physics if item.physics != "None" else "" return SIMREADY_DRAG_PREFIX + json.dumps(drag_data) return super().get_drag_mime_data(item) def execute(self, item: DetailItem) -> None: drag_mime_data = self.get_drag_mime_data(item) add_asset_from_drag(drag_mime_data) def _on_folder_traversed(self, folder: AssetFolder, loading_completed=True, updated: bool = True) -> None: """ Folder traversed, - Update tags and view - Save data to cache """ carb.log_info(f"Traverse completed: {folder.url}, {loading_completed}") if updated and folder in self._root_folders: # Update tags self._update_labels(folder) # Refresh view self.folder_changed(None) def _update_labels(self, folder: AssetFolder) -> None: for label, assets in folder.asset_by_labels.items(): if not label: continue new_folder = False if label not in self.__label_folders: self.__label_folders[label] = AssetFolder(label, label) new_folder = True self.__label_folders[label].files.extend(assets) # Clean cache to re-generate category items self._folder_cache[self.__label_folders[label]] = None if new_folder: # Create parent label folders while True: pos = label.rfind("/") if pos > 0: parent_label = label[:pos] if parent_label not in self.__label_folders: self.__label_folders[parent_label] = AssetFolder(parent_label, parent_label) folder = self.__label_folders[label] if folder not in self.__label_folders[parent_label].sub_folders: self.__label_folders[parent_label].sub_folders.append(folder) self.sort_items(self.__label_folders[parent_label].sub_folders) label = parent_label else: break def _get_summary_detail_items(self) -> List[FileDetailItem]: # List all assets from label folder root_folders = [folder for folder in self.__label_folders.values() if folder.name.find("/") < 0] return list(chain.from_iterable([self.get_detail_items(self._folder_cache[f]) for f in root_folders])) def create_detail_item(self, asset: SimreadyAsset) -> FileDetailItem: """ Create detail item(s) from a file. A file may include multi detail items. Args: file (BrowserFile): File object to create detail item(s) """ return AssetDetailItem(asset)
8,686
Python
38.666666
110
0.605918
DigitalBotLab/App/kit-app/source/extensions/omni.simready.explorer/omni/simready/explorer/browser_widget.py
# Copyright (c) 2023, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. import asyncio from typing import List, Optional import omni.kit.app from omni.kit.browser.core import BrowserSearchBar from omni.kit.browser.folder.core import FolderCategoryItem from omni.kit.widget.searchfield import SearchField from .browser_with_property_widget import BrowserWithPropertyWidget class SimReadyBrowserWidget(BrowserWithPropertyWidget): def __init__(self, *args, **kwargs): self.__keep_search_words = False super().__init__(*args, multiple_drag=True, **kwargs) @property def search_field(self) -> SearchField: return self._search_bar._search_field @property def category_all(self) -> FolderCategoryItem: return self._browser_model.get_item_children(self._browser_model._root_collection_item)[0] def _build_search_bar(self): # Hide gear button in search bar self._search_bar = BrowserSearchBar(options_menu=None, style=self._extra_ui_style) def _build_browser_widget(self): super()._build_browser_widget() # Here hack the filter function to remove category labels before filter self._browser_widget.filter_details = self._filter_details def _on_category_selection_changed(self, category_item: FolderCategoryItem) -> None: # Set search words with labels from selected category if category_item is None: return if self.__keep_search_words: # Here selected category is changed along with search word self.__keep_search_words = False async def __delay_refresh_details_async(): await omni.kit.app.get_app().next_update_async() self.__refresh_detail_view(self.search_field.search_words) asyncio.ensure_future(__delay_refresh_details_async()) else: # Here user click category treeview and select a category self.search_field.search_words = self._get_search_words_from_category(category_item) self.search_field.suggestions = self._get_tags_from_category(category_item) def _filter_details(self, filter_words: Optional[List[str]]): """ Filter detail items. Args: filter_words: A string list to filter detail items. None means filtering nothing. """ async def __select_category_all_async() -> None: await omni.kit.app.get_app().next_update_async() self.__keep_search_words = True self.category_selection = [self.category_all] if filter_words: # Check if all labels of current selected category in search words # If yes, keep searching in selected category # If no, change selected category to ALL then search search_labels = set([w.lower() for w in filter_words]) selected_category = self.category_selection[0] if self.category_selection else None if selected_category and selected_category != self.category_all: selected_labels = set(l.lower() for l in self._get_search_words_from_category(selected_category)) if not selected_labels or not selected_labels.issubset(search_labels): asyncio.ensure_future(__select_category_all_async()) return for category_item in self.category_selection: words = self._get_search_words_from_category(category_item) filter_words = [w for w in filter_words if w not in words] else: # No search words, always select ALL selected_category = self.category_selection[0] if self.category_selection else None if selected_category != self.category_all: asyncio.ensure_future(__select_category_all_async()) return self.__refresh_detail_view(filter_words) def __refresh_detail_view(self, filter_words: Optional[List[str]]): if self._browser_widget._detail_view is not None: detail_view = self._browser_widget._detail_view detail_view.filter(filter_words) # Refresh suggestion words in search bar from results async def __refresh_suggestions_async(): await omni.kit.app.get_app().next_update_async() tags = [] count = 0 for item in detail_view._delegates: if detail_view._delegates[item].visible: tags.extend(list(item.asset.tags)) count += 1 tags = list(set(tags)) tags.sort() if True: self.search_field.suggestions = tags # TODO: Workaround for issue in omni.kit.widget.searchfield updated. if self.search_field._suggest_window: self.search_field._suggest_window.suggestions = tags asyncio.ensure_future(__refresh_suggestions_async()) def _get_search_words_from_category(self, category_item: FolderCategoryItem) -> List[str]: # Get preset search words from category if category_item.name == self._browser_model.SUMMARY_FOLDER_NAME: return [] else: # Use folder name (label) as preset search words return category_item.folder.name.split("/") def _get_tags_from_category(self, category_item: FolderCategoryItem) -> List[str]: if category_item.name == self._browser_model.SUMMARY_FOLDER_NAME: tags = [] for item in self._browser_model.get_category_items(self._browser_model._root_collection_item): if item.name != self._browser_model.SUMMARY_FOLDER_NAME: tags.extend(list(item.folder.asset_by_tags.keys())) tags = list(set(tags)) else: tags = list(category_item.folder.asset_by_tags.keys()) tags.sort() return tags
6,350
Python
43.725352
113
0.632598
DigitalBotLab/App/kit-app/source/extensions/omni.simready.explorer/omni/simready/explorer/viewport_drop_delegate.py
# Copyright (c) 2023, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. import json from typing import Tuple import omni.kit.commands import omni.usd from omni.kit.viewport.window.dragdrop.usd_file_drop_delegate import UsdFileDropDelegate from pxr import Usd from .actions import configure_prim from .style import SIMREADY_DRAG_PREFIX class SimReadyDragDropObject(UsdFileDropDelegate): """ SimReady drop delegate based on UsdFileDropDelegate in omni.kit.viewport.window with variants setting. """ def __init__(self): self._usd_prim_droped = None super().__init__() def drop_should_disable_preview(self): return True def get_raw_data(self, drop_data: dict) -> dict: return json.loads(drop_data.get("mime_data")[len(SIMREADY_DRAG_PREFIX) :]) def get_url(self, drop_data: dict): return self.get_raw_data(drop_data)["url"] def add_reference_to_stage(self, usd_context, stage: Usd.Stage, url: str) -> Tuple[str, Usd.EditContext, str]: (self._usd_prim_droped, edit_context, relative_url) = super().add_reference_to_stage(usd_context, stage, url) return (self._usd_prim_droped, edit_context, relative_url) def accepted(self, drop_data: dict): mime_data = drop_data["mime_data"] self._usd_prim_droped = None return mime_data.startswith(SIMREADY_DRAG_PREFIX) def dropped(self, drop_data: dict): super().dropped(drop_data) # Additionaly, set variants if required usd_prim_droped = drop_data.get("usd_prim_droped") or self._usd_prim_droped if usd_prim_droped is not None: raw_drop_data = self.get_raw_data(drop_data) variants = raw_drop_data.get("variants", {}) if variants: context_name = drop_data.get("usd_context_name", "") stage = omni.usd.get_context(context_name).get_stage() if stage: configure_prim(stage, usd_prim_droped, variants) return
2,369
Python
37.225806
117
0.678345
DigitalBotLab/App/kit-app/source/extensions/omni.simready.explorer/omni/simready/explorer/window.py
# Copyright (c) 2023, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. import omni.ui as ui from .browser_delegate import SimReadyDetailDelegate from .browser_model import SimReadyBrowserModel from .browser_widget import SimReadyBrowserWidget SETTING_COLLECTION_ROOTS = "/exts/omni.simready.explorer/folders" SIMREADY_EXPLORER_NAME = "SimReady Explorer" class SimReadyBrowserWindow(ui.Window): """ Represent a window to show SimReady Assets """ def __init__(self, visible=True): super().__init__(SIMREADY_EXPLORER_NAME, visible=visible) self.frame.set_build_fn(self._build_ui) self._browser_model = SimReadyBrowserModel(setting_folders=SETTING_COLLECTION_ROOTS) self._delegate = None self._widget = None # Dock it to the same space where Content is docked. self.deferred_dock_in("Content") def destroy(self): if self._widget: self._widget.destroy() if self._delegate: self._delegate.destroy() super().destroy() def _build_ui(self): self._delegate = SimReadyDetailDelegate(self._browser_model) with self.frame: with ui.VStack(spacing=15): self._widget = SimReadyBrowserWidget( self._browser_model, detail_delegate=self._delegate, )
1,726
Python
32.211538
92
0.680765
DigitalBotLab/App/kit-app/source/extensions/omni.simready.explorer/omni/simready/explorer/browser_property_view.py
# Copyright (c) 2023, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. from typing import Dict, List, Optional from omni import ui from omni.kit.browser.folder.core import FileDetailItem from omni.kit.window.property.style import get_style from .browser_property_delegate import BrowserPropertyDelegate from .style import PROPERTY_STYLES class BrowserPropertyView: """ View to show properties of an item from the browser. This view represents a container (frame) into which the delegates registered with class BrowserPropertyDelegate will be added. """ def __init__(self): self.__delegate_frames: Dict[BrowserPropertyDelegate, ui.Frame] = {} self._build_ui() def destroy(self): pass def _build_ui(self): self._property_container = ui.VStack(style=get_style()) with self._property_container: with ui.ScrollingFrame( vertical_scrollbar_policy=ui.ScrollBarPolicy.SCROLLBAR_AS_NEEDED, horizontal_scrollbar_policy=ui.ScrollBarPolicy.SCROLLBAR_ALWAYS_OFF, ): self.__delegate_container = ui.ZStack() @property def visible(self) -> bool: return self._property_container.visible @visible.setter def visible(self, value) -> None: self._property_container.visible = value def show_detail_item(self, detail_item: Optional[FileDetailItem]): """Various aspects of an item's properties can be shown by different delegates. The delegates that are registered with class BrowserPropertyDelegate will be asked to show the properties of the item. The delegates that accept the item will be shown, and the others will be hidden.""" delegates = BrowserPropertyDelegate.get_instances() for delegate in delegates: if delegate.accepted(detail_item): # Show delegate if delegate not in self.__delegate_frames: with self.__delegate_container: self.__delegate_frames[delegate] = ui.Frame(style=PROPERTY_STYLES) self.__delegate_frames[delegate].visible = True delegate.show(detail_item, self.__delegate_frames[delegate]) elif delegate in self.__delegate_frames: # Hide delegate self.__delegate_frames[delegate].visible = False def show_detail_multi_item(self, detail_item_list: List[FileDetailItem]): """Properties of a list of items can be shown in various ways. The delegates that are registered with class BrowserPropertyDelegate will be asked to show the properties of the items. The delegates that accept the items will be shown, and the others will be hidden.""" delegates = BrowserPropertyDelegate.get_instances() for delegate in delegates: if delegate.accepted_multiple(detail_item_list): # Show delegate if delegate not in self.__delegate_frames: with self.__delegate_container: self.__delegate_frames[delegate] = ui.Frame(style=PROPERTY_STYLES) self.__delegate_frames[delegate].visible = True delegate.show_multiple(detail_item_list, self.__delegate_frames[delegate]) elif delegate in self.__delegate_frames: # Hide delegate self.__delegate_frames[delegate].visible = False
3,832
Python
43.057471
90
0.666232
DigitalBotLab/App/kit-app/source/extensions/omni.simready.explorer/omni/simready/explorer/tests/__init__.py
# Copyright (c) 2023, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. from .browser_api_tests import BrowserApiTest # noqa: F401, symbol is reexported
509
Python
49.999995
81
0.807466
DigitalBotLab/App/kit-app/source/extensions/omni.simready.explorer/omni/simready/explorer/tests/browser_api_tests.py
# Copyright (c) 2023, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. import pathlib from typing import Dict, List, Optional import carb.settings import omni.kit.test import omni.kit.undo import omni.ui as ui import omni.usd from omni.simready.explorer import ( AssetFactory, AssetType, PropAsset, SimreadyAsset, SimReadyBrowserExtension, SimReadyBrowserModel, add_asset_to_stage, add_asset_to_stage_using_prims, find_assets, get_average_position_of_prims, get_instance, ) from omni.simready.explorer.actions import find_inst_prim, is_physics_variant_enabled from pxr import Gf, Sdf, Usd TEST_DATA_DIR = pathlib.Path(__file__).parent.joinpath("data") TEST_ASSETS_FILE = TEST_DATA_DIR.joinpath("asset_info.json") # Declare and register new asset types @AssetFactory.register(AssetType.GENERIC) class GenericTestAsset(SimreadyAsset): def __init__(self, raw_asset_data: Dict): super().__init__(raw_asset_data) self._type = AssetType.GENERIC @classmethod def is_asset_data(cls, raw_asset_data: Dict) -> bool: asset_type: str = raw_asset_data.get("Asset Type", AssetType.UNKNOWN.name) return asset_type.upper() == AssetType.GENERIC.name @AssetFactory.register(AssetType.VEHICLE) class VehicleTestAsset(SimreadyAsset): def __init__(self, raw_asset_data: Dict): super().__init__(raw_asset_data) self._type = AssetType.VEHICLE @classmethod def is_asset_data(cls, raw_asset_data: Dict) -> bool: asset_type: str = raw_asset_data.get("Asset Type", AssetType.UNKNOWN.name) return asset_type.upper() == AssetType.VEHICLE.name class BrowserApiTest(omni.kit.test.AsyncTestCase): async def setUp(self) -> None: super().setUp() # Create a browser model with the test data directory as the only folder # class FolderBrowserModel insists on prefixing the setting_folders with "persistent" settings_asset_folder_roots = "/persistent/exts/omni.simready.explorer.tests/folders" carb.settings.get_settings().set(settings_asset_folder_roots, [str(TEST_DATA_DIR)]) ui.Workspace.show_window("SimReady Explorer") await omni.kit.app.get_app().next_update_async() self._browser_model: SimReadyBrowserModel = SimReadyBrowserModel(setting_folders=settings_asset_folder_roots) self._browser_model.folder_changed(None) self._explorer: Optional[SimReadyBrowserExtension] = get_instance() if self._explorer: # Set the browser model on the SimReadyBrowserExtension instance # so the SimReadyBrowserExtension.find_assets() API uses it. self._original_browser_model = self._explorer.browser_model self._explorer.window._browser_model = self._browser_model else: self._original_browser_model = None def tearDown(self) -> None: super().tearDown() if self._original_browser_model and self._explorer: # Restore original browser model self._explorer.window._browser_model = self._original_browser_model self._explorer = None self._browser_model.destroy() ################################ # Tests for the find_assets() API ################################ async def test_filter_all_assets(self): """Test getting all assets through the SimReadyBrowserExtension.find_assets() API""" self.assertIsNotNone(self._explorer) assets = await find_assets() self.assertEqual(len(assets), 6) simready_assets = await find_assets(search_words=["SimReady"]) self.assertEqual(len(assets), len(simready_assets)) generic_asset_count = 0 vehicle_asset_count = 0 prop_asset_count = 0 # Verify the type and number of assets created for a in assets: self.assertIsNotNone(a) if isinstance(a, GenericTestAsset): generic_asset_count += 1 elif isinstance(a, VehicleTestAsset): vehicle_asset_count += 1 elif isinstance(a, PropAsset): # PropAsset is a type defined in the SimReady Explorer extension; # the test data contains PropAssets, so we can verify that they work prop_asset_count += 1 else: self.fail("Unknown asset type") self.assertEqual(prop_asset_count, 3) self.assertEqual(vehicle_asset_count, 2) self.assertEqual(generic_asset_count, 1) async def test_filter_tool_assets(self): """Test looking for tools""" assets = await find_assets(search_words=["tool"]) self.assertEqual(len(assets), 2) async def test_filter_vehicles_assets(self): """Test looking for vehicles""" assets = await find_assets(search_words=["truck"]) self.assertEqual(len(assets), 2) for a in assets: self.assertIsInstance(a, VehicleTestAsset) # Test looking for vehicles differently assets = await find_assets(search_words=["truck", "vehicle"]) self.assertEqual(len(assets), 2) for a in assets: self.assertIsInstance(a, VehicleTestAsset) async def test_filter_partial_asset_tag_match(self): """Tests that search words are matched on partial asset tags""" assets = await find_assets(search_words=["ti-tool"]) self.assertEqual(len(assets), 1) self.assertIsInstance(assets[0], GenericTestAsset) # Test looking for vehicles differently assets = await find_assets(search_words=["motor", "vehicle"]) self.assertEqual(len(assets), 2) for a in assets: self.assertIsInstance(a, VehicleTestAsset) async def test_filter_partial_asset_name_match(self): """Test that search words are matched on partial asset names""" assets = await find_assets(search_words=["tool1"]) self.assertEqual(len(assets), 1) self.assertIsInstance(assets[0], GenericTestAsset) async def test_filter_case_insensitive_match(self): """Test that search words are case insensitive""" assets = await find_assets(search_words=["ToOl1"]) self.assertEqual(len(assets), 1) self.assertIsInstance(assets[0], GenericTestAsset) assets = await find_assets(search_words=["PORT Unit"]) self.assertEqual(len(assets), 1) self.assertIsInstance(assets[0], PropAsset) async def test_filter_no_assets(self): """Test search that should return no assets""" assets = await find_assets(search_words=["equipment", "vehicle"]) self.assertEqual(len(assets), 0) # Test a filter that contains tags not in the database assets = await find_assets(search_words=["this_tag_is_not_used", "neither_is_this_one"]) self.assertEqual(len(assets), 0) ################################################# # Tests for accessing behavior list of assets API ################################################# async def test_asset_behavior(self): """Test getting the behaviors of an asset""" assets = await find_assets(search_words=["multi-tool"]) self.assertEqual(len(assets), 1) self.assertIsInstance(assets[0], GenericTestAsset) # omni.kit.debug.python.wait_for_client() self.assertEqual(len(assets[0].behaviors), 2) self.assertTrue("Features" in assets[0].behaviors) self.assertEqual(assets[0].behaviors["Features"], ["Five", "Seven", "Nine"]) self.assertTrue("Colors" in assets[0].behaviors) self.assertEqual(assets[0].behaviors["Colors"], ["Black", "Red", "Blue"]) ########################################### # Tests for the def add_asset_to_stage() API ########################################### def check_variant(self, prim: Usd.Prim, variantset_name: str, variant_name: str) -> None: """Helper function to check the variant value of a prim""" self.assertIsNotNone(prim) vsets: Usd.VariantSet = prim.GetVariantSets() vset: Usd.VariantSet = vsets.GetVariantSet(variantset_name) self.assertIsNotNone(vset) self.assertEqual(vset.GetVariantSelection(), variant_name) def check_instanceable(self, prim: Usd.Prim, variants: Dict[str, str]) -> None: """Helper function to check the instanceable value of the 'inst' prim""" self.assertIsNotNone(prim) inst_prim: Usd.Prim = find_inst_prim(prim) self.assertIsNotNone(inst_prim) self.assertTrue(inst_prim.IsInstanceable()) def check_added_asset(self, stage: Usd.Stage, asset_prim_path: str, parent_prim: Usd.Prim): """Helper function to check that an asset was added to a stage""" self.assertIsNotNone(stage) self.assertIsNotNone(parent_prim) self.assertTrue(asset_prim_path) prim: Usd.Prim = stage.GetPrimAtPath(asset_prim_path) self.assertIsNotNone(prim) self.assertEqual(prim.GetParent(), parent_prim) async def test_add_asset_to_stage(self): """Test adding an asset to a stage and setting its variant value""" assets = await find_assets(search_words=["box_a01"]) self.assertEqual(len(assets), 1) self.assertIsInstance(assets[0], PropAsset) # No undo needed in a unit test omni.kit.undo.begin_disabled() # Create a test stage with a default prim called "World" usd_context: omni.usd.UsdContext = omni.usd.get_context() usd_context.new_stage() stage: Usd.Stage = usd_context.get_stage() self.assertIsNotNone(stage) omni.kit.commands.execute("CreatePrim", prim_type="XFom", prim_path="/World", create_default_xform=True) world: Usd.Prim = stage.GetPrimAtPath("/World") stage.SetDefaultPrim(world) res, cube = omni.kit.commands.execute("CreatePrim", prim_type="Cube", prim_path="/World/Cube") cube: Usd.Prim = stage.GetPrimAtPath("/World/Cube") self.assertIsNotNone(cube) # Create the variant to set on the asset when adding it to the stage variantset_name = "PhysicsVariant" self.assertTrue(variantset_name in assets[0].behaviors) variants: Dict[str, str] = {variantset_name: assets[0].behaviors[variantset_name][0]} # Add the asset to the stage, under a specific prim res, asset_prim_path = add_asset_to_stage(assets[0].url, parent_path=Sdf.Path("/World/Cube"), variants=variants) self.assertTrue(res) # Verify that the asset was added to the stage as expected self.check_added_asset(stage, asset_prim_path, cube) # Check that the asset has the correct variant set self.check_variant( stage.GetPrimAtPath(asset_prim_path), variantset_name, assets[0].behaviors[variantset_name][0] ) # Check that the asset has the correct instanceable attribute set self.check_instanceable(stage.GetPrimAtPath(asset_prim_path), variants) usd_context.close_stage() omni.kit.undo.end_disabled() async def test_add_asset_to_stage_using_prims(self): """Test adding an asset to a stage using some existent prims, and setting its variant value""" assets = await find_assets(search_words=["box_a01"]) self.assertEqual(len(assets), 1) self.assertIsInstance(assets[0], PropAsset) # No undo needed in a unit test omni.kit.undo.begin_disabled() # Create a test stage with a default prim called "World" and some cubes usd_context: omni.usd.UsdContext = omni.usd.get_context() usd_context.new_stage() stage: Usd.Stage = usd_context.get_stage() self.assertIsNotNone(stage) omni.kit.commands.execute("CreatePrim", prim_type="XFom", prim_path="/World", create_default_xform=True) world: Usd.Prim = stage.GetPrimAtPath("/World") stage.SetDefaultPrim(world) prim_paths: List[Sdf.Path] = [] for i in range(3): prim_path: str = f"/World/Cube{i}" prim_paths.append(Sdf.Path(prim_path)) omni.kit.commands.execute("CreatePrim", prim_type="Cube", prim_path=prim_path) omni.kit.commands.execute("TransformPrimSRTCommand", path=prim_path, new_translation=Gf.Vec3d(0, 0, i * 20)) # Create the variant to set on the asset when adding it to the stage variantset_name = "PhysicsVariant" self.assertTrue(variantset_name in assets[0].behaviors) variants: Dict[str, str] = {variantset_name: assets[0].behaviors[variantset_name][0]} # Add the asset to the stage, using the prims created above, without replacing them res, asset_prim_path = add_asset_to_stage_using_prims( usd_context, stage, assets[0].url, variants=variants, replace_prims=False, prim_paths=prim_paths ) self.assertTrue(res) # Verify that the asset was added to the stage as expected self.check_added_asset(stage, asset_prim_path, world) # Check that the asset has the correct variant set self.check_variant( stage.GetPrimAtPath(asset_prim_path), variantset_name, assets[0].behaviors[variantset_name][0] ) # Check that the asset has the correct instanceable attribute set self.check_instanceable(stage.GetPrimAtPath(asset_prim_path), variants) # Verify that the cubes were not replaced for i in range(3): prim_path: str = f"/World/Cube{i}" prim: Usd.Prim = stage.GetPrimAtPath(prim_path) self.assertIsNotNone(prim) self.assertTrue(prim.IsValid()) self.assertEqual(prim.GetTypeName(), "Cube") self.assertEqual(prim.GetParent(), world) self.assertEqual(prim.GetAttribute("xformOp:translate").Get(), Gf.Vec3d(0, 0, i * 20)) # Verify that the newly added asset is at the correct position position: Gf.Vec3d = get_average_position_of_prims([stage.GetPrimAtPath(path) for path in prim_paths]) self.assertEqual(stage.GetPrimAtPath(asset_prim_path).GetAttribute("xformOp:translate").Get(), position) # Add the asset to the stage, using the prims created above, replacing them res, asset_prim_path = add_asset_to_stage_using_prims( usd_context, stage, assets[0].url, variants=variants, replace_prims=True, prim_paths=prim_paths ) # Verify that the asset was added to the stage as expected self.assertTrue(res) self.check_added_asset(stage, asset_prim_path, world) # Check that the asset has the correct variant set self.check_variant( stage.GetPrimAtPath(asset_prim_path), variantset_name, assets[0].behaviors[variantset_name][0] ) # Check that the asset has the correct instanceable attribute set self.check_instanceable(stage.GetPrimAtPath(asset_prim_path), variants) # Verify that the newly added asset's position is the average of the replaced cubes self.assertEqual(stage.GetPrimAtPath(asset_prim_path).GetAttribute("xformOp:translate").Get(), position) # Verify that the cubes are not in the stage for i in range(3): self.assertFalse(stage.GetPrimAtPath(f"/World/Cube{i}").IsValid()) usd_context.close_stage() omni.kit.undo.end_disabled()
15,779
Python
44.872093
120
0.651879
DigitalBotLab/App/kit-app/source/extensions/omni.simready.explorer/samples/simready_explorer_api_sample.py
# Copyright (c) 2023, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. # The following line is used to mark the start of the code that is to be pulled into the documentation # example-begin simready_explorer_api_sample import asyncio from typing import List, Tuple import omni.kit.app import omni.simready.explorer as sre import omni.usd from pxr import Gf, Sdf, Usd async def main(): # 1. Find all residential wooden chair assets. # We use multiple search terms, some will be matched in the tags, others in the asset names assets = await sre.find_assets(search_words=["residential", "chair", "wood"]) print(f"Found {len(assets)} chairs") # 2. Prepare to configure the assets # All SimReady Assets have a Physics behavior, which is implemented as a # variantset named PhysicsVariant. To enable rigid body physics on an asset, # this variantset needs to be set to "RigidBody". variants = {"PhysicsVariant": "RigidBody"} # 3. Add all assets found in step (1) to the current stage as a payload added_prim_paths: List[Sdf.Path] = [] for i, asset in enumerate(assets): pos = -200 + 200 * i res, prim_path = sre.add_asset_to_stage( asset.main_url, position=Gf.Vec3d(pos, 0, -pos), variants=variants, payload=True ) if res: print(f"Added '{prim_path}' from '{asset.main_url}'") # 4. Find an ottoman assets = await sre.find_assets(search_words=["ottoman"]) print(f"Found {len(assets)} ottomans") # 5. Replace the first chair with an ottoman if assets and added_prim_paths: usd_context: omni.usd.UsdContext = omni.usd.get_context() stage: Usd.Stage = usd_context.get_stage() if usd_context else None await omni.kit.app.get_app().next_update_async() res, prim_path = sre.add_asset_to_stage_using_prims( usd_context, stage, assets[0].main_url, variants=variants, replace_prims=True, prim_paths=[added_prim_paths[0]], ) if res: print(f"Replaced assets '{added_prim_paths[0]}' with '{prim_path}' from '{assets[0].main_url}'") asyncio.ensure_future(main()) # example-end simready_explorer_api_sample
2,607
Python
39.123076
108
0.678174
DigitalBotLab/App/kit-app/source/extensions/omni.simready.explorer/docs/CHANGELOG.md
Changelog ========= This document records all notable changes to ``omni.simready.explorer`` extension. This project adheres to `Semantic Versioning <https://semver.org/>`_. ## [1.0.26] - 2023-06-20 - OM-95538: Don't turn off the instanceable attribute on assets with PhysicsVariant set to RigidBody when drag-and-dropping them into the stage ## [1.0.25] - 2023-06-02 - OM-96886: Update screenshot used in extension registry ## [1.0.24] - 2023-06-01 - OM-96886: Update badge on SimReady asset thumbnails ## [1.0.23] - 2023-05-30 - OM-95406: Set default physics behavior of all assets to "RigidBody" ## [1.0.22] - 2023-05-17 - OM-94398: Removed superfluous print statement from class PropAsset constructor - OM-94290: Normalized asset paths to use single backslahs ('/') as directory separators ## [1.0.21] - 2023-04-25 - OM-90516: Exposed Collect command in asset right-click menu ## [1.0.20] - 2023-04-24 - OM-83563: Created developer docs and tweaked APIs ## [1.0.19] - 2023-04-20 - Get dropped prim path when preview disabled ## [1.0.18] - 2023-04-14 - OM-90136: Disable preview when drag and drop into viewport ## [1.0.17] - 2023-04-13 - OM-90440: Update UI style of property widget to be same as other property widgets ## [1.0.16] - 2023-03-24 OM-87776: Assets are browsed on AWS S3 staging - List of tags in asset details window resizes to fit the window ## [1.0.15] - 2023-03-24 OM-87028: "Replace Current Selection" doesn't apply to multiple asset selection - Fix leak of SimReadyDetailDelegate instance ## [1.0.14] - 2023-03-22 OM-87028: Right-click doesn't select assets, and right-click menu works with multiple assets selected ## [1.0.13] - 2023-03-21 - OM-87026: Simple message displayed in property window when multiple assets selected - OM-87032: Disabled tooltips since they were interfering with the right click menu ## [1.0.12] - 2023-03-18 - OM-85649: support of lazy load workflow in Create ## [1.0.11] - 2023-03-17 - OM-86101: Multiple drag items into viewport or stage window ## [1.0.10] - 2023-03-15 - OM-86315: Turn off instanceable attribute on _inst prim when adding an asset with Physics on, otherwise turn instanceable attribute on. - Fixed issue with physics badge update on thumbnails, where the badge would be visible in the assets detail view even if physics would be off (None) ## [1.0.9] - 2023-03-13 - OM-86077: Added Open, Open with Payloads Disabled, Add at Selection, Copy URL Link right-click menu commands - OM-85906: Renamed menu and tab to "SimReady Explorer" - OM-86315: Set PhysicsVariant to None by default ## [1.0.8] - 2023-03-08 - OM-84838: Added API for listing an asset's behaviors, and adding an asset to the current stage ## [1.0.7] - 2023-03-07 - OM-83352: Updated asset property panel ## [1.0.6] - 2023-03-02 - OM-84829: Fixed searching against tags with spaces (multi-word tags) ## [1.0.5] - 2023-02-28 - OM-84243: Always search all assets - OM-84245: Update tag list in search bar on search results ## [1.0.4] - 2023-02-16 - OM-66968: API for filtering assets - Updated asset database; now includes 539 assets ## [1.0.3] - 2023-02-15 - OM-52823: The explorer looks for the asset database (asset_info.json) on omniverse://simready.ov.nvidia.com/Projects/ - Updated asset database; now includes 487 assets ## [1.0.2] - 2023-02-13 - Assets can be dropped onto the stage from the asset browser (requires omni.kit.widget.stage v2.7.24 which has not been released yet) - Physics is enabled by default - New Physx thumbnail badge is displayed when physics is enabled - Updated asset database; now includes 317 assets (304 are simready) - OM-81970: Open property panel by default - OM-81973: Center widgets in property panel - OM-81977: SimReady Explorer is docked when it starts This required to not show the window after startup. Show from menu "Window/Browsers/Sim Ready". - OM-81962: Remove gear button from search bar omni.simready.explorer-1.0.2 requires the following extensions: - omni.kit.widget.stage-2.7.24 (not available as of 2023-02-13) - omni.kit.browser.core-2.2.2 - omni.kit.browser.folder.core-1.7.5 - omni.kit.widget.searchfield-1.1.0 ## [1.0.1] - 2023-02-09 - Assets can be pre-configured with right-click menu options, or in the properties view. - Drag-and-drop of pre-configured asset into the viewport - Asset properties panel shows the following properties name, QCode, thumbnail, tags, physics behavior - Asset properties panel updates when selected asset changes - Supporting 158 assets on omniverse://simready.ov.nvidia.com/Projects/simready_content/common_assets/props/ ## [1.0.0] - 2023-02-08 - Hierarchical Asset Categories are displayed - Asset thumbnails are displayed, with tooltip showing asset name, dimensions and tags - Asset property panel is displayed when user enables it through the top-right icon - Search bar is populated with categories as tags when user clicks on a category in the Asset Category panel, and the assets are filtered
4,952
Markdown
40.621848
149
0.743336
DigitalBotLab/App/kit-app/source/extensions/omni.simready.explorer/docs/README.md
# Simready Explorer Extension [omni.simready.explorer] A browser for SimReady Assets.
86
Markdown
27.999991
54
0.813953
DigitalBotLab/App/kit-app/source/extensions/omni.simready.explorer/docs/Overview.md
# SimReady Explorer Developer Guide ## Overview **SimReady Assets** are the building blocks of industrial virtual worlds. They are built on top of the Universal Scene Description (USD) platform and have accurate physical properties, behaviors, and connected data streams. They are comprised on multiple files such as USD layers, material description files (.mdl), textures, thumbnails, etc. The **SimReady Explorer extension** allows for working with libraries of SimReady Assets, by enabling users to: - Find assets by words matched against tags and asset names - Configure asset behavior, appearance, etc in the browser, before they are assembled into a scene - Assemble assets into virtual worlds through Omniverse applications such as USD Composer, DriveSim, Isaac Sim, etc. Through the [**SimReady Explorer API**](./API.rst), developers can: - Search for assets by matching search words against tags and asset names - Configure various aspects of assets, as defined by the asset class - Add the configured assets to a stage ## Finding assets SimReady Assets have a name, tags, and labels. The labels are derived from the [Wiki Data](https://www.wikidata.org) database, and as such are backed by QCodes. Note that the labels and the QCode of an asset are also part of its list of tags. Both tags and labels can consist of multiple, space separated words. Finding SimReady Assets is like querying a database. A list of search terms is each matched against the asset's name and tags. Partial matches of the search term in names, tags, and labels are also returned. For example, the search term "wood" would match names such as "recycledwoodpallete" and "crestwood_sofa". ```{eval-rst} See the :doc:`find_assets() <omni.simready.explorer/omni.simready.explorer.find_assets>` API for details on how to programmatically search for assets. ``` ## Configuring assets and adding them to a stage The `find_assets()` API returns a list of `SimreadyAsset` objects, which can be added to the current stage with the desired behaviors enabled. The behaviors supported currently are the USD variant sets exposed by the asset. When adding assets to a stage, they can be inserted at a given location, can be parented to another prim, or can be added at or even replace a list of prims. ```{eval-rst} See the :doc:`add_asset_to_stage() <omni.simready.explorer/omni.simready.explorer.add_asset_to_stage>`, and the :doc:`add_asset_to_stage_using_prims() <omni.simready.explorer/omni.simready.explorer.add_asset_to_stage_using_prims>` APIs for details on how to programmatically add assets to the current stage. ``` # SimReady Explorer API Tutorial The following code illustrates how to find assets, add them to the current scene, and even replace some of them with other assets. The code below can be executed from the Script Editor of any Omniverse application. ```{eval-rst} .. literalinclude:: ../../../../source/extensions/omni.simready.explorer/samples/simready_explorer_api_sample.py :language: python :start-after: example-begin simready_explorer_api_sample :end-before: example-end simready_explorer_api_sample :dedent: ``` ## Future enhancements The SimReady Explorer API will be extended in the near future to allow defining custom asset classes with specific behaviors.
3,289
Markdown
68.999999
342
0.779264
DigitalBotLab/App/kit-app/source/extensions/dbl.app.resources/dbl/app/resources/python_ext.py
import omni.ext # Functions and vars are available to other extension as usual in python: `example.python_ext.some_public_function(x)` def some_public_function(x: int): print(f"[dbl.app.resources] some_public_function was called with {x}") return x**x # Any class derived from `omni.ext.IExt` in top level module (defined in `python.modules` of `extension.toml`) will be # instantiated when extension gets enabled and `on_startup(ext_id)` will be called. Later when extension gets disabled # on_shutdown() is called. class HelloPythonExtension(omni.ext.IExt): # ext_id is current extension id. It can be used with extension manager to query additional information, like where # this extension is located on filesystem. def on_startup(self, ext_id): print("[dbl.app.resources] HelloPythonExtension startup") def on_shutdown(self): print("[dbl.app.resources] HelloPythonExtension shutdown")
934
Python
43.523807
119
0.739829
DigitalBotLab/App/kit-app/source/extensions/dbl.app.resources/dbl/app/resources/__init__.py
from .python_ext import *
26
Python
12.499994
25
0.730769
DigitalBotLab/App/kit-app/source/extensions/dbl.app.resources/dbl/app/resources/tests/test_hello.py
# NOTE: # omni.kit.test - std python's unittest module with additional wrapping to add suport for async/await tests # For most things refer to unittest docs: https://docs.python.org/3/library/unittest.html # Import extension python module we are testing with absolute import path, as if we are external user (other extension) import omni.kit.test import dbl.app.resources # Having a test class dervived from omni.kit.test.AsyncTestCase declared on the root of module will make it auto-discoverable by omni.kit.test class Test(omni.kit.test.AsyncTestCaseFailOnLogError): # Before running each test async def setUp(self): pass # After running each test async def tearDown(self): pass # Actual test, notice it is "async" function, so "await" can be used if needed async def test_hello_public_function(self): result = dbl.app.resources.some_public_function(4) self.assertEqual(result, 256)
950
Python
40.347824
142
0.735789
DigitalBotLab/App/kit-app/source/extensions/dbl.app.resources/dbl/app/resources/tests/__init__.py
from .test_hello import *
26
Python
12.499994
25
0.730769
DigitalBotLab/App/kit-app/source/extensions/dbl.app.resources/config/extension.toml
[package] # Semantic Versionning is used: https://semver.org/ version = "0.1.0" # Lists people or organizations that are considered the "authors" of the package. authors = [""] # The title and description fields are primarly for displaying extension info in UI title = "Python Extension Example" description="The simplest python extension example. Use it as a starting point for your extensions." # Path (relative to the root) or content of readme markdown file for UI. readme = "docs/README.md" # URL of the extension source repository. repository="" # One of categories for UI. category = "Example" # Keywords for the extension keywords = ["kit", "example"] # Location of change log file in target (final) folder of extension, relative to the root. # More info on writing changelog: https://keepachangelog.com/en/1.0.0/ changelog="docs/CHANGELOG.md" # Preview image and icon. Folder named "data" automatically goes in git lfs (see .gitattributes file). # Preview image is shown in "Overview" of Extensions window. Screenshot of an extension might be a good preview image. preview_image = "data/preview.png" # Icon is shown in Extensions window, it is recommended to be square, of size 256x256. icon = "data/icon.png" [dependencies] # none # Main python module this extension provides, it will be publicly available as "import omni.example.hello". [[python.module]] name = "dbl.app.resources" [documentation] pages = [ "docs/Overview.md", "docs/CHANGELOG.md", ]
1,484
TOML
30.595744
118
0.745283
DigitalBotLab/App/kit-app/source/extensions/dbl.app.resources/docs/CHANGELOG.md
# Changelog The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/). # [0.1.0] ### Added - Initial release
133
Markdown
15.749998
80
0.676692
DigitalBotLab/App/kit-app/source/extensions/dbl.app.resources/docs/README.md
# Python Extension Example [example.python_ext] This is an example of pure python Kit extension. It is intended to be copied and serve as a template to create new ones.
171
Markdown
33.399993
120
0.777778
DigitalBotLab/App/kit-app/source/extensions/dbl.app.resources/docs/Overview.md
# Overview
10
Markdown
9.99999
10
0.8
DigitalBotLab/App/kit-app/source/extensions/omni.usd_explorer.setup/config/extension.toml
[package] # Semantic Versionning is used: https://semver.org/ version = "1.0.0" # The title and description fields are primarily for displaying extension info in UI title = "Setup Extension for USD Explorer" description = "an extensions that Setup my App" # Path (relative to the root) or content of readme markdown file for UI. readme = "docs/README.md" # URL of the extension source repository. repository = "https://gitlab-master.nvidia.com/omniverse/usd_explorer" # One of categories for UI. category = "setup" # Keywords for the extension keywords = ["kit", "app", "setup"] # Icon to show in the extension manager icon = "data/icon.png" # Preview to show in the extension manager preview_image = "data/preview.png" # Use omni.ui to build simple UI [dependencies] "omni.kit.quicklayout" = {} "omni.kit.window.title" = {} "omni.kit.browser.asset" = {} "omni.kit.window.console" = {} "omni.kit.window.content_browser" = {} "omni.kit.window.material" = {} "omni.kit.window.toolbar" = {version = "1.5.4", exact = true} "omni.kit.property.bundle" = {} "omni.kit.property.layer" = {} "omni.kit.viewport.navigation.usd_explorer.bundle" = {} "omni.kit.window.preferences" = {} # from omni.view.app.setup "omni.kit.viewport.menubar.camera" = { optional=true } "omni.kit.widget.layers" = { optional=true } "omni.kit.widgets.custom" = {} "omni.kit.window.file" = {} # Main python module this extension provides, it will be publicly available as "import omni.hello.world". [[python.module]] name = "omni.usd_explorer.setup" [settings] app.layout.name = "viewport_only" app.application_mode = "review" exts."omni.kit.viewport.menubar.camera".expand = true # Expand the extra-camera settings by default exts."omni.kit.window.file".useNewFilePicker = true exts."omni.kit.tool.asset_importer".useNewFilePicker = true exts."omni.kit.tool.collect".useNewFilePicker = true exts."omni.kit.widget.layers".useNewFilePicker = true exts."omni.kit.renderer.core".imgui.enableMips = true exts."omni.kit.browser.material".enabled = false exts."omni.kit.window.material".load_after_startup = true exts."omni.kit.widget.cloud_share".require_access_code = false exts."omni.kit.mesh.raycast".bvhBuildOnFirstRequired = true # Avoids mesh raycast to initialize during stage open app.content.emptyStageOnStart = true app.viewport.createCameraModelRep = false # Disable creation of camera meshes in USD # USDRT app.usdrt.scene_delegate.enableProxyCubes = false app.usdrt.scene_delegate.geometryStreaming.enabled = true app.usdrt.scene_delegate.numFramesBetweenLoadBatches = 2 app.usdrt.scene_delegate.geometryStreaming.numberOfVerticesToLoadPerChunk = 600000 exts."omni.kit.viewport.navigation.camera_manipulator".defaultOperation = "" [[test]] dependencies = [ "omni.kit.core.tests", "omni.kit.ui_test", "omni.kit.mainwindow", "omni.kit.viewport.window", "omni.kit.viewport.utility", ] args = [ "--/app/file/ignoreUnsavedOnExit=true", # "--/renderer/enabled=pxr", # "--/renderer/active=pxr", "--/app/window/width=1280", "--/app/window/height=720", "--/app/window/dpiScaleOverride=1.0", "--/app/window/scaleToMonitor=false", "--/exts/omni.kit.viewport.window/startup/windowName=Viewport", "--reset-user", "--no-window", "--/app/fastShutdown=1" ]
3,293
TOML
33.3125
113
0.728515
DigitalBotLab/App/kit-app/source/extensions/omni.usd_explorer.setup/omni/usd_explorer/setup/menubar_helper.py
from pathlib import Path import carb import carb.settings import carb.tokens import omni.ui as ui from omni.ui import color as cl ICON_PATH = carb.tokens.get_tokens_interface().resolve("${omni.usd_explorer.setup}/data/icons") VIEW_MENUBAR_STYLE = { "MenuBar.Window": {"background_color": 0xA0000000}, "MenuBar.Item.Background": { "background_color": 0, }, "Menu.Item.Background": { "background_color": 0, } } VIEWPORT_CAMERA_STYLE = { "Menu.Item.Icon::Expand": {"image_url": f"{ICON_PATH}/caret_s2_right_dark.svg", "color": cl.viewport_menubar_light}, "Menu.Item.Icon::Expand:checked": {"image_url": f"{ICON_PATH}/caret_s2_left_dark.svg"}, } class MenubarHelper: def __init__(self) -> None: self._settings = carb.settings.get_settings() # Set menubar background and style try: from omni.kit.viewport.menubar.core import DEFAULT_MENUBAR_NAME from omni.kit.viewport.menubar.core import get_instance as get_menubar_instance instance = get_menubar_instance() if not instance: # pragma: no cover return default_menubar = instance.get_menubar(DEFAULT_MENUBAR_NAME) default_menubar.background_visible = True default_menubar.style.update(VIEW_MENUBAR_STYLE) default_menubar.show_separator = True except ImportError: # pragma: no cover carb.log_warn("Viewport menubar not found!") try: import omni.kit.viewport.menubar.camera self._camera_menubar_instance = omni.kit.viewport.menubar.camera.get_instance() if not self._camera_menubar_instance: # pragma: no cover return # Change expand button icon self._camera_menubar_instance._camera_menu._style.update(VIEWPORT_CAMERA_STYLE) # New menu item for camera speed self._camera_menubar_instance.register_menu_item(self._create_camera_speed, order=100) # OM-76591 - Removing "Create from view" item - Bob self._camera_menubar_instance.deregister_menu_item(self._camera_menubar_instance._camera_menu._build_create_camera) except ImportError: carb.log_warn("Viewport menubar not found!") self._camera_menubar_instance = None except AttributeError: # pragma: no cover self._camera_menubar_instance = None # Hide default render and settings menubar self._settings.set("/persistent/exts/omni.kit.viewport.menubar.render/visible", False) self._settings.set("/persistent/exts/omni.kit.viewport.menubar.settings/visible", False) def destroy(self) -> None: if self._camera_menubar_instance: self._camera_menubar_instance.deregister_menu_item(self._create_camera_speed) def _create_camera_speed(self, _vc, _r: ui.Menu) -> None: from omni.kit.viewport.menubar.core import SettingModel, SliderMenuDelegate ui.MenuItem( "Speed", hide_on_click=False, delegate=SliderMenuDelegate( model=SettingModel("/persistent/app/viewport/camMoveVelocity", draggable=True), min=self._settings.get_as_float("/persistent/app/viewport/camVelocityMin") or 0.01, max=self._settings.get_as_float("/persistent/app/viewport/camVelocityMax"), tooltip="Set the Fly Mode navigation speed", width=0, reserve_status=True, ), )
3,517
Python
42.974999
127
0.642593
DigitalBotLab/App/kit-app/source/extensions/omni.usd_explorer.setup/omni/usd_explorer/setup/__init__.py
from .setup import *
21
Python
9.999995
20
0.714286
DigitalBotLab/App/kit-app/source/extensions/omni.usd_explorer.setup/omni/usd_explorer/setup/setup.py
import asyncio import weakref from functools import partial import os from pathlib import Path from typing import cast, Optional import omni.client import omni.ext import omni.kit.menu.utils import omni.kit.app import omni.kit.context_menu import omni.kit.ui import omni.usd from omni.kit.quicklayout import QuickLayout from omni.kit.menu.utils import MenuLayout from omni.kit.window.title import get_main_window_title from omni.kit.usd.layers import LayerUtils from omni.kit.viewport.menubar.core import get_instance as get_mb_inst, DEFAULT_MENUBAR_NAME from omni.kit.viewport.menubar.core.viewport_menu_model import ViewportMenuModel from omni.kit.viewport.utility import get_active_viewport, get_active_viewport_window, disable_selection import carb import carb.settings import carb.dictionary import carb.events import carb.tokens import carb.input import omni.kit.imgui as _imgui from pxr import Sdf, Usd from .navigation import Navigation from .menu_helper import MenuHelper from .menubar_helper import MenubarHelper from .stage_template import SunnySkyStage from .ui_state_manager import UIStateManager SETTINGS_PATH_FOCUSED = "/app/workspace/currentFocused" APPLICATION_MODE_PATH = "/app/application_mode" MODAL_TOOL_ACTIVE_PATH = "/app/tools/modal_tool_active" CURRENT_TOOL_PATH = "/app/viewport/currentTool" ROOT_WINDOW_NAME = "DockSpace" ICON_PATH = carb.tokens.get_tokens_interface().resolve("${omni.usd_explorer.setup}/data/icons") SETTINGS_STARTUP_EXPAND_VIEWPORT = "/app/startup/expandViewport" VIEWPORT_CONTEXT_MENU_PATH = "/exts/omni.kit.window.viewport/showContextMenu" TELEPORT_VISIBLE_PATH = "/persistent/exts/omni.kit.viewport.navigation.teleport/visible" async def _load_layout_startup(layout_file: str, keep_windows_open: bool=False) -> None: try: # few frames delay to avoid the conflict with the layout of omni.kit.mainwindow for i in range(3): await omni.kit.app.get_app().next_update_async() # type: ignore QuickLayout.load_file(layout_file, keep_windows_open) # WOR: some layout don't happy collectly the first time await omni.kit.app.get_app().next_update_async() # type: ignore QuickLayout.load_file(layout_file, keep_windows_open) except Exception as exc: # pragma: no cover (Can't be tested because a non-existing layout file prints an log_error in QuickLayout and does not throw an exception) carb.log_warn(f"Failed to load layout {layout_file}: {exc}") async def _load_layout(layout_file: str, keep_windows_open:bool=False) -> None: try: # few frames delay to avoid the conflict with the layout of omni.kit.mainwindow for i in range(3): await omni.kit.app.get_app().next_update_async() # type: ignore QuickLayout.load_file(layout_file, keep_windows_open) except Exception as exc: # pragma: no cover (Can't be tested because a non-existing layout file prints an log_error in QuickLayout and does not throw an exception) carb.log_warn(f"Failed to load layout {layout_file}: {exc}") async def _clear_startup_scene_edits() -> None: try: for i in range(50): # This could possibly be a smaller value. I want to ensure this happens after RTX startup await omni.kit.app.get_app().next_update_async() # type: ignore omni.usd.get_context().set_pending_edit(False) except Exception as exc: # pragma: no cover carb.log_warn(f"Failed to clear stage edits on startup: {exc}") # This extension is mostly loading the Layout updating menu class SetupExtension(omni.ext.IExt): # ext_id is current extension id. It can be used with extension manager to query additional information, like where # this extension is located on filesystem. @property def _app(self): return omni.kit.app.get_app() @property def _settings(self): return carb.settings.get_settings() def on_startup(self, ext_id: str) -> None: self._ext_id = ext_id self._menubar_helper = MenubarHelper() self._menu_helper = MenuHelper() # using imgui directly to adjust some color and Variable imgui = _imgui.acquire_imgui() # match Create overides imgui.push_style_color(_imgui.StyleColor.ScrollbarGrab, carb.Float4(0.4, 0.4, 0.4, 1)) imgui.push_style_color(_imgui.StyleColor.ScrollbarGrabHovered, carb.Float4(0.6, 0.6, 0.6, 1)) imgui.push_style_color(_imgui.StyleColor.ScrollbarGrabActive, carb.Float4(0.8, 0.8, 0.8, 1)) # DockSplitterSize is the variable that drive the size of the Dock Split connection imgui.push_style_var_float(_imgui.StyleVar.DockSplitterSize, 2) # setup the Layout for your app self._layouts_path = carb.tokens.get_tokens_interface().resolve("${omni.usd_explorer.setup}/layouts") layout_file = Path(self._layouts_path).joinpath(f"{self._settings.get('/app/layout/name')}.json") self.__setup_window_task = asyncio.ensure_future(_load_layout_startup(f"{layout_file}", True)) self.review_layout_path = str(Path(self._layouts_path) / "comment_layout.json") self.default_layout_path = str(Path(self._layouts_path) / "default.json") self.layout_user_path = str(Path(self._layouts_path) / "layout_user.json") # remove the user defined layout so that we always load the default layout when startup if os.path.exists(self.layout_user_path): os.remove(self.layout_user_path) # setup the menu and their layout self._current_layout_priority = 0 self._layout_menu_items = [] self._layout_file_menu() self._menu_layout = [] if self._settings.get_as_bool('/app/view/debug/menus'): self._layout_menu() # setup the Application Title window_title = get_main_window_title() if window_title: window_title.set_app_version(self._settings.get_as_string("/app/titleVersion")) # self._context_menu() self._register_my_menu() self._navigation = Navigation() self._navigation.on_startup(ext_id) self._application_mode_changed_sub = self._settings.subscribe_to_node_change_events( APPLICATION_MODE_PATH, weakref.proxy(self)._on_application_mode_changed ) self._set_viewport_menubar_visibility(False) self._test = asyncio.ensure_future(_clear_startup_scene_edits()) # OM-95865: Ensure teleport on by default. self._usd_context = omni.usd.get_context() self._stage_event_sub = self._usd_context.get_stage_event_stream().create_subscription_to_pop( self._on_stage_open_event, name="TeleportDefaultOn" ) if self._settings.get_as_bool(SETTINGS_STARTUP_EXPAND_VIEWPORT): self._set_viewport_fill_on() self._stage_templates = [SunnySkyStage()] disable_selection(get_active_viewport()) self._ui_state_manager = UIStateManager() self._setup_ui_state_changes() omni.kit.menu.utils.add_layout([ MenuLayout.Menu("Window", [ MenuLayout.Item("Viewport", source="Window/Viewport/Viewport 1"), MenuLayout.Item("Playlist", remove=True), MenuLayout.Item("Layout", remove=True), MenuLayout.Item("" if any(v in self._app.get_app_version() for v in ("alpha", "beta")) else "Extensions", remove=True), MenuLayout.Sort(exclude_items=["Extensions"], sort_submenus=True), ]) ]) def show_documentation(*x): import webbrowser webbrowser.open("http://docs.omniverse.nvidia.com/explorer") self._help_menu_items = [ omni.kit.menu.utils.MenuItemDescription(name="Documentation", onclick_fn=show_documentation, appear_after=[omni.kit.menu.utils.MenuItemOrder.FIRST]) ] omni.kit.menu.utils.add_menu_items(self._help_menu_items, name="Help") def _on_stage_open_event(self, event: carb.events.IEvent) -> None: if event.type == int(omni.usd.StageEventType.OPENED): app_mode = self._settings.get_as_string(APPLICATION_MODE_PATH).lower() # exit all tools self._settings.set(CURRENT_TOOL_PATH, "none") # OM-95865, OMFP-1993: Activate Teleport upon scene load ... # OMFP-2743: ... but only when in Review mode. if app_mode == "review": asyncio.ensure_future(self._stage_post_open_teleport_toggle()) # toggle RMB viewport context menu based on application mode value = False if app_mode == "review" else True self._settings.set(VIEWPORT_CONTEXT_MENU_PATH, value) # teleport is activated after loading a stage and app is in Review mode async def _stage_post_open_teleport_toggle(self) -> None: await self._app.next_update_async() if hasattr(self, "_usd_context") and self._usd_context is not None and not self._usd_context.is_new_stage(): self._settings.set("/exts/omni.kit.viewport.navigation.core/activeOperation", "teleport") def _set_viewport_fill_on(self) -> None: vp_window = get_active_viewport_window() vp_widget = vp_window.viewport_widget if vp_window else None if vp_widget: vp_widget.expand_viewport = True def _set_viewport_menubar_visibility(self, show: bool) -> None: mb_inst = get_mb_inst() if mb_inst and hasattr(mb_inst, "get_menubar"): main_menubar = mb_inst.get_menubar(DEFAULT_MENUBAR_NAME) if main_menubar.visible_model.as_bool != show: main_menubar.visible_model.set_value(show) ViewportMenuModel()._item_changed(None) # type: ignore def _on_application_mode_changed(self, item: carb.dictionary.Item, _typ: carb.settings.ChangeEventType) -> None: if self._settings.get_as_string(APPLICATION_MODE_PATH).lower() == "review": omni.usd.get_context().get_selection().clear_selected_prim_paths() disable_selection(get_active_viewport()) current_mode: str = cast(str, item.get_dict()) asyncio.ensure_future(self.defer_load_layout(current_mode)) async def defer_load_layout(self, current_mode: str) -> None: keep_windows = True # Focus Mode Toolbar self._settings.set_bool(SETTINGS_PATH_FOCUSED, True) # current_mode not in ("review", "layout")) # Turn off all tools and modal self._settings.set_string(CURRENT_TOOL_PATH, "none") self._settings.set_bool(MODAL_TOOL_ACTIVE_PATH, False) if current_mode == "review": # save the current layout for restoring later if switch back QuickLayout.save_file(self.layout_user_path) # we don't want to keep any windows except the ones which are visible in self.review_layout_path await _load_layout(self.review_layout_path, False) else: # current_mode == "layout": # check if there is any user modified layout, if yes use that one layout_filename = self.layout_user_path if os.path.exists(self.layout_user_path) else self.default_layout_path await _load_layout(layout_filename, keep_windows) self._set_viewport_menubar_visibility(current_mode == "layout") def _setup_ui_state_changes(self) -> None: windows_to_hide_on_modal = ["Measure", "Section", "Waypoints"] self._ui_state_manager.add_hide_on_modal(window_names=windows_to_hide_on_modal, restore=True) window_titles = ["Markups", "Waypoints"] for window in window_titles: setting_name = f'/exts/omni.usd_explorer.setup/{window}/visible' self._ui_state_manager.add_window_visibility_setting(window, setting_name) # toggle icon visibilites based on window visibility self._ui_state_manager.add_settings_copy_dependency( source_path="/exts/omni.usd_explorer.setup/Markups/visible", target_path="/exts/omni.kit.markup.core/show_icons", ) self._ui_state_manager.add_settings_copy_dependency( source_path="/exts/omni.usd_explorer.setup/Waypoints/visible", target_path="/exts/omni.kit.waypoint.core/show_icons", ) def _custom_quicklayout_menu(self) -> None: # we setup a simple ways to Load custom layout from the exts def add_layout_menu_entry(name, parameter, key): import inspect editor_menu = omni.kit.ui.get_editor_menu() layouts_path = carb.tokens.get_tokens_interface().resolve("${omni.usd_explorer.setup}/layouts") menu_path = f"Layout/{name}" menu = editor_menu.add_item(menu_path, None, False, self._current_layout_priority) # type: ignore self._current_layout_priority = self._current_layout_priority + 1 if inspect.isfunction(parameter): # pragma: no cover (Never used, see commented out section below regarding quick save/load) menu_action = omni.kit.menu.utils.add_action_to_menu( menu_path, lambda *_: asyncio.ensure_future(parameter()), name, (carb.input.KEYBOARD_MODIFIER_FLAG_CONTROL, key), ) else: menu_action = omni.kit.menu.utils.add_action_to_menu( menu_path, lambda *_: asyncio.ensure_future(_load_layout(f"{layouts_path}/{parameter}.json")), name, (carb.input.KEYBOARD_MODIFIER_FLAG_CONTROL, key), ) self._layout_menu_items.append((menu, menu_action)) add_layout_menu_entry("Reset Layout", "default", carb.input.KeyboardInput.KEY_1) add_layout_menu_entry("Viewport Only", "viewport_only", carb.input.KeyboardInput.KEY_2) add_layout_menu_entry("Markup Editor", "markup_editor", carb.input.KeyboardInput.KEY_3) # add_layout_menu_entry("Waypoint Viewer", "waypoint_viewer", carb.input.KeyboardInput.KEY_4) # # you can enable Quick Save and Quick Load here # if False: # # create Quick Load & Quick Save # from omni.kit.quicklayout import QuickLayout # async def quick_save(): # QuickLayout.quick_save(None, None) # async def quick_load(): # QuickLayout.quick_load(None, None) # add_layout_menu_entry("Quick Save", quick_save, carb.input.KeyboardInput.KEY_7) # add_layout_menu_entry("Quick Load", quick_load, carb.input.KeyboardInput.KEY_8) def _register_my_menu(self) -> None: context_menu: Optional[omni.kit.context_menu.ContextMenuExtension] = omni.kit.context_menu.get_instance() if not context_menu: # pragma: no cover return def _layout_file_menu(self) -> None: self._menu_file_layout = [ MenuLayout.Menu( "File", [ MenuLayout.Item("New"), MenuLayout.Item("New From Stage Template"), MenuLayout.Item("Open"), MenuLayout.Item("Open Recent"), MenuLayout.Seperator(), MenuLayout.Item("Re-open with New Edit Layer"), MenuLayout.Seperator(), MenuLayout.Item("Share"), MenuLayout.Seperator(), MenuLayout.Item("Save"), MenuLayout.Item("Save As..."), MenuLayout.Item("Save With Options"), MenuLayout.Item("Save Selected"), MenuLayout.Item("Save Flattened As...", remove=True), MenuLayout.Seperator(), MenuLayout.Item("Collect As..."), MenuLayout.Item("Export"), MenuLayout.Seperator(), MenuLayout.Item("Import"), MenuLayout.Item("Add Reference"), MenuLayout.Item("Add Payload"), MenuLayout.Seperator(), MenuLayout.Item("Exit"), ] ) ] omni.kit.menu.utils.add_layout(self._menu_file_layout) def _layout_menu(self) -> None: self._menu_layout = [ MenuLayout.Menu( "Window", [ MenuLayout.SubMenu( "Animation", [ MenuLayout.Item("Timeline"), MenuLayout.Item("Sequencer"), MenuLayout.Item("Curve Editor"), MenuLayout.Item("Retargeting"), MenuLayout.Item("Animation Graph"), MenuLayout.Item("Animation Graph Samples"), ], ), MenuLayout.SubMenu( "Layout", [ MenuLayout.Item("Quick Save", remove=True), MenuLayout.Item("Quick Load", remove=True), ], ), MenuLayout.SubMenu( "Browsers", [ MenuLayout.Item("Content", source="Window/Content"), MenuLayout.Item("Materials"), MenuLayout.Item("Skies"), ], ), MenuLayout.SubMenu( "Rendering", [ MenuLayout.Item("Render Settings"), MenuLayout.Item("Movie Capture"), MenuLayout.Item("MDL Material Graph"), MenuLayout.Item("Tablet XR"), ], ), MenuLayout.SubMenu( "Simulation", [ MenuLayout.Group( "Flow", [ MenuLayout.Item("Presets", source="Window/Flow/Presets"), MenuLayout.Item("Monitor", source="Window/Flow/Monitor"), ], ), MenuLayout.Group( "Blast", [ MenuLayout.Item("Settings", source="Window/Blast/Settings"), MenuLayout.SubMenu( "Documentation", [ MenuLayout.Item("Kit UI", source="Window/Blast/Documentation/Kit UI"), MenuLayout.Item( "Programming", source="Window/Blast/Documentation/Programming" ), MenuLayout.Item( "USD Schemas", source="Window/Blast/Documentation/USD Schemas" ), ], ), ], ), MenuLayout.Item("Debug"), # MenuLayout.Item("Performance"), MenuLayout.Group( "Physics", [ MenuLayout.Item("Demo Scenes"), MenuLayout.Item("Settings", source="Window/Physics/Settings"), MenuLayout.Item("Debug"), MenuLayout.Item("Test Runner"), MenuLayout.Item("Character Controller"), MenuLayout.Item("OmniPVD"), MenuLayout.Item("Physics Helpers"), ], ), ], ), MenuLayout.SubMenu( "Utilities", [ MenuLayout.Item("Console"), MenuLayout.Item("Profiler"), MenuLayout.Item("USD Paths"), MenuLayout.Item("Statistics"), MenuLayout.Item("Activity Monitor"), ], ), # Remove 'Viewport 2' entry MenuLayout.SubMenu( "Viewport", [ MenuLayout.Item("Viewport 2", remove=True), ], ), MenuLayout.Sort(exclude_items=["Extensions"]), MenuLayout.Item("New Viewport Window", remove=True), ], ), # that is you enable the Quick Layout Menu MenuLayout.Menu( "Layout", [ MenuLayout.Item("Default", source="Reset Layout"), MenuLayout.Item("Viewport Only"), MenuLayout.Item("Markup Editor"), MenuLayout.Item("Waypoint Viewer"), MenuLayout.Seperator(), MenuLayout.Item("UI Toggle Visibility", source="Window/UI Toggle Visibility"), MenuLayout.Item("Fullscreen Mode", source="Window/Fullscreen Mode"), MenuLayout.Seperator(), MenuLayout.Item("Save Layout", source="Window/Layout/Save Layout..."), MenuLayout.Item("Load Layout", source="Window/Layout/Load Layout..."), # MenuLayout.Seperator(), # MenuLayout.Item("Quick Save", source="Window/Layout/Quick Save"), # MenuLayout.Item("Quick Load", source="Window/Layout/Quick Load"), ], ), MenuLayout.Menu("Tools", [MenuLayout.SubMenu("Animation", remove=True)]), ] omni.kit.menu.utils.add_layout(self._menu_layout) # type: ignore # if you want to support the Quick Layout Menu self._custom_quicklayout_menu() def on_shutdown(self): if self._menu_layout: omni.kit.menu.utils.remove_layout(self._menu_layout) # type: ignore self._menu_layout.clear() self._layout_menu_items.clear() self._navigation.on_shutdown() del self._navigation self._settings.unsubscribe_to_change_events(self._application_mode_changed_sub) del self._application_mode_changed_sub self._stage_event_sub = None # From View setup self._menubar_helper.destroy() if self._menu_helper and hasattr(self._menu_helper, "destroy"): self._menu_helper.destroy() self._menu_helper = None self._stage_templates = []
23,462
Python
45.005882
167
0.557753
DigitalBotLab/App/kit-app/source/extensions/omni.usd_explorer.setup/omni/usd_explorer/setup/navigation.py
import asyncio import carb import carb.settings import carb.tokens import carb.dictionary import omni.kit.app import omni.ext import omni.ui as ui import omni.kit.actions.core from omni.kit.viewport.navigation.core import ( NAVIGATION_TOOL_OPERATION_ACTIVE, ViewportNavigationTooltip, get_navigation_bar, ) __all__ = ["Navigation"] CURRENT_TOOL_PATH = "/app/viewport/currentTool" SETTING_NAVIGATION_ROOT = "/exts/omni.kit.tool.navigation/" NAVIGATION_BAR_VISIBLE_PATH = "/exts/omni.kit.viewport.navigation.core/isVisible" APPLICATION_MODE_PATH = "/app/application_mode" WALK_VISIBLE_PATH = "/persistent/exts/omni.kit.viewport.navigation.walk/visible" CAPTURE_VISIBLE_PATH = "/persistent/exts/omni.kit.viewport.navigation.capture/visible" MARKUP_VISIBLE_PATH = "/persistent/exts/omni.kit.viewport.navigation.markup/visible" MEASURE_VISIBLE_PATH = "/persistent/exts/omni.kit.viewport.navigation.measure/visible" SECTION_VISIBLE_PATH = "/persistent/exts/omni.kit.viewport.navigation.section/visible" TELEPORT_SEPARATOR_VISIBLE_PATH = "/persistent/exts/omni.kit.viewport.navigation.teleport/spvisible" WAYPOINT_VISIBLE_PATH = "/persistent/exts/omni.kit.viewport.navigation.waypoint/visible" VIEWPORT_CONTEXT_MENU_PATH = "/exts/omni.kit.window.viewport/showContextMenu" MENUBAR_APP_MODES_PATH = "/exts/omni.kit.usd_presenter.main.menubar/include_modify_mode" WELCOME_WINDOW_VISIBLE_PATH = "/exts/omni.kit.usd_presenter.window.welcome/visible" ACTIVE_OPERATION_PATH = "/exts/omni.kit.viewport.navigation.core/activeOperation" class Navigation: NAVIGATION_BAR_NAME = None # ext_id is current extension id. It can be used with extension manager to query additional information, like where # this extension is located on filesystem. def on_startup(self, ext_id: str) -> None: sections = ext_id.split("-") self._ext_name = sections[0] self._settings = carb.settings.get_settings() self._navigation_bar = get_navigation_bar() self._tool_bar_button = None self._dict = carb.dictionary.get_dictionary() self._panel_visible = True self._navigation_bar.show() self._settings.set(CURRENT_TOOL_PATH, "navigation") self._settings.set(NAVIGATION_TOOL_OPERATION_ACTIVE, "teleport") self._viewport_welcome_window_visibility_changed_sub = self._settings.subscribe_to_node_change_events( WELCOME_WINDOW_VISIBLE_PATH, self._on_welcome_window_visibility_change ) # OMFP-1799 Set nav bar visibility defaults. These should remain fixed now. self._settings.set(WALK_VISIBLE_PATH, False) self._settings.set(MARKUP_VISIBLE_PATH, True) self._settings.set(WAYPOINT_VISIBLE_PATH, True) self._settings.set(TELEPORT_SEPARATOR_VISIBLE_PATH, True) self._settings.set(CAPTURE_VISIBLE_PATH, True) self._settings.set(MEASURE_VISIBLE_PATH, True) self._settings.set(SECTION_VISIBLE_PATH, True) self._application_mode_changed_sub = self._settings.subscribe_to_node_change_events( APPLICATION_MODE_PATH, self._on_application_mode_changed ) self._show_tooltips = False self._nav_bar_visibility_sub = self._settings.subscribe_to_node_change_events( NAVIGATION_BAR_VISIBLE_PATH, self._delay_reset_tooltip) _prev_navbar_vis = None _prev_tool = None _prev_operation = None def _on_welcome_window_visibility_change(self, item: carb.dictionary.Item, *_) -> None: if not isinstance(self._dict, (carb.dictionary.IDictionary, dict)): return welcome_window_vis = self._dict.get(item) # preserve the state of the navbar upon closing the Welcome window if the app is in Layout mode if self._settings.get_as_string(APPLICATION_MODE_PATH).lower() == "layout": # preserve the state of the navbar visibility if welcome_window_vis: self._prev_navbar_vis = self._settings.get_as_bool(NAVIGATION_BAR_VISIBLE_PATH) self._settings.set(NAVIGATION_BAR_VISIBLE_PATH, not(welcome_window_vis)) self._prev_tool = self._settings.get(CURRENT_TOOL_PATH) self._prev_operation = self._settings.get(ACTIVE_OPERATION_PATH) else: # restore the state of the navbar visibility if self._prev_navbar_vis is not None: self._settings.set(NAVIGATION_BAR_VISIBLE_PATH, self._prev_navbar_vis) self._prev_navbar_vis = None if self._prev_tool is not None: self._settings.set(CURRENT_TOOL_PATH, self._prev_tool) if self._prev_operation is not None: self._settings.set(ACTIVE_OPERATION_PATH, self._prev_operation) return else: if welcome_window_vis: self._settings.set(NAVIGATION_TOOL_OPERATION_ACTIVE, "none") else: self._settings.set(NAVIGATION_TOOL_OPERATION_ACTIVE, "teleport") self._settings.set(NAVIGATION_BAR_VISIBLE_PATH, not(welcome_window_vis)) def _on_application_mode_changed(self, item: carb.dictionary.Item, *_) -> None: if not isinstance(self._dict, (carb.dictionary.IDictionary, dict)): return current_mode = self._dict.get(item) self._test = asyncio.ensure_future(self._switch_by_mode(current_mode)) async def _switch_by_mode(self, current_mode: str) -> None: await omni.kit.app.get_app().next_update_async() state = True if current_mode == "review" else False self._settings.set(NAVIGATION_BAR_VISIBLE_PATH, state) self._settings.set(VIEWPORT_CONTEXT_MENU_PATH, not(state)) # toggle RMB viewport context menu self._delay_reset_tooltip(None) # OM-92161: Need to reset the tooltip when change the mode def _delay_reset_tooltip(self, *_) -> None: async def delay_set_tooltip() -> None: for _i in range(4): await omni.kit.app.get_app().next_update_async() # type: ignore ViewportNavigationTooltip.set_visible(self._show_tooltips) asyncio.ensure_future(delay_set_tooltip()) def _on_showtips_click(self, *_) -> None: self._show_tooltips = not self._show_tooltips ViewportNavigationTooltip.set_visible(self._show_tooltips) def on_shutdown(self) -> None: self._navigation_bar = None self._viewport_welcome_window_visibility_changed_sub = None self._settings.unsubscribe_to_change_events(self._application_mode_changed_sub) # type:ignore self._application_mode_changed_sub = None self._dict = None
6,679
Python
45.713286
119
0.676898
DigitalBotLab/App/kit-app/source/extensions/omni.usd_explorer.setup/omni/usd_explorer/setup/ui_state_manager.py
import carb.dictionary import carb.settings import omni.ui as ui from functools import partial from typing import Any, Dict, List, Tuple, Union MODAL_TOOL_ACTIVE_PATH = "/app/tools/modal_tool_active" class UIStateManager: def __init__(self) -> None: self._settings = carb.settings.acquire_settings_interface() self._modal_changed_sub = self._settings.subscribe_to_node_change_events( MODAL_TOOL_ACTIVE_PATH, self._on_modal_setting_changed ) self._hide_on_modal: List[Tuple[str,bool]] = [] self._modal_restore_window_states: Dict[str,bool] = {} self._settings_dependencies: Dict[Tuple(str,str), Dict[Any, Any]] = {} self._settings_changed_subs = {} self._window_settings = {} self._window_vis_changed_id = ui.Workspace.set_window_visibility_changed_callback(self._on_window_vis_changed) def destroy(self) -> None: if self._settings: if self._modal_changed_sub: self._settings.unsubscribe_to_change_events(self._modal_changed_sub) self._settings = None self._hide_on_modal = [] self._modal_restore_window_states = {} self._settings_dependencies = {} self._window_settings = {} if self._window_vis_changed_id: ui.Workspace.remove_window_visibility_changed_callback(self._window_vis_changed_id) self._window_vis_changed_id = None def __del__(self) -> None: self.destroy() def add_hide_on_modal(self, window_names: Union[str, List[str]], restore: bool) -> None: if isinstance(window_names, str): window_names = [window_names] for window_name in window_names: if window_name not in self._hide_on_modal: self._hide_on_modal.append((window_name, restore)) def remove_hide_on_modal(self, window_names: Union[str, List[str]]) -> None: if isinstance(window_names, str): window_names = [window_names] self._hide_on_modal = [item for item in self._hide_on_modal if item[0] not in window_names] def add_window_visibility_setting(self, window_name: str, setting_path: str) -> None: window = ui.Workspace.get_window(window_name) if window is not None: self._settings.set(setting_path, window.visible) else: # handle the case when the window is created later self._settings.set(setting_path, False) if window_name not in self._window_settings.keys(): self._window_settings[window_name] = [] self._window_settings[window_name].append(setting_path) def remove_window_visibility_setting(self, window_name: str, setting_path: str) -> None: if window_name in self._window_settings.keys(): setting_list = self._window_settings[window_name] if setting_path in setting_list: setting_list.remove(setting_path) if len(setting_list) == 0: del self._window_settings[window_name] def remove_all_window_visibility_settings(self, window_name: str) -> None: if window_name in self._window_settings.keys(): del self._window_settings[window_name] def add_settings_dependency(self, source_path: str, target_path: str, value_map: Dict[Any, Any]) -> None: key = (source_path, target_path) if key in self._settings_dependencies.keys(): carb.log_error(f'Settings dependency {source_path} -> {target_path} already exists. Ignoring.') return self._settings_dependencies[key] = value_map self._settings_changed_subs[key] = self._settings.subscribe_to_node_change_events( source_path, partial(self._on_settings_dependency_changed, source_path) ) def add_settings_copy_dependency(self, source_path: str, target_path: str) -> None: self.add_settings_dependency(source_path, target_path, None) def remove_settings_dependency(self, source_path: str, target_path: str) -> None: key = (source_path, target_path) if key in self._settings_dependencies.keys(): del self._settings_dependencies[key] if key in self._settings_changed_subs.keys(): sub = self._settings_changed_subs.pop(key) self._settings.unsubscribe_to_change_events(sub) def _on_settings_dependency_changed(self, path: str, item, event_type) -> None: value = self._settings.get(path) # setting does not exist if value is None: return target_settings = [source_target[1] for source_target in self._settings_dependencies.keys() if source_target[0] == path] for target_setting in target_settings: value_map = self._settings_dependencies[(path, target_setting)] # None means copy everything if value_map is None: self._settings.set(target_setting, value) elif value in value_map.keys(): self._settings.set(target_setting, value_map[value]) def _on_modal_setting_changed(self, item, event_type) -> None: modal = self._settings.get_as_bool(MODAL_TOOL_ACTIVE_PATH) if modal: self._hide_windows() else: self._restore_windows() def _hide_windows(self) -> None: for window_info in self._hide_on_modal: window_name, restore_later = window_info[0], window_info[1] window = ui.Workspace.get_window(window_name) if window is not None: if restore_later: self._modal_restore_window_states[window_name] = window.visible window.visible = False def _restore_windows(self) -> None: for window_info in self._hide_on_modal: window_name, restore_later = window_info[0], window_info[1] if restore_later: if window_name in self._modal_restore_window_states.keys(): old_visibility = self._modal_restore_window_states[window_name] if old_visibility is not None: window = ui.Workspace.get_window(window_name) if window is not None: window.visible = old_visibility self._modal_restore_window_states[window_name] = None def _on_window_vis_changed(self, title: str, state: bool) -> None: if title in self._window_settings.keys(): for setting in self._window_settings[title]: self._settings.set_bool(setting, state)
6,634
Python
44.136054
128
0.611999
DigitalBotLab/App/kit-app/source/extensions/omni.usd_explorer.setup/omni/usd_explorer/setup/stage_template.py
import carb import omni.ext import omni.kit.commands from omni.kit.stage_templates import register_template, unregister_template from pxr import Gf, Sdf, Usd, UsdGeom, UsdLux class SunnySkyStage: def __init__(self): register_template("SunnySky", self.new_stage) def __del__(self): unregister_template("SunnySky") def new_stage(self, rootname, usd_context_name): # Create basic DistantLight usd_context = omni.usd.get_context(usd_context_name) stage = usd_context.get_stage() # get up axis up_axis = UsdGeom.GetStageUpAxis(stage) with Usd.EditContext(stage, stage.GetRootLayer()): # create Environment omni.kit.commands.execute( "CreatePrim", prim_path="/Environment", prim_type="Xform", select_new_prim=False, create_default_xform=True, context_name=usd_context_name ) texture_path = carb.tokens.get_tokens_interface().resolve("${omni.usd_explorer.setup}/data/light_rigs/HDR/partly_cloudy.hdr") # create Sky omni.kit.commands.execute( "CreatePrim", prim_path="/Environment/Sky", prim_type="DomeLight", select_new_prim=False, attributes={ UsdLux.Tokens.inputsIntensity: 1000, UsdLux.Tokens.inputsTextureFile: texture_path, UsdLux.Tokens.inputsTextureFormat: UsdLux.Tokens.latlong, UsdLux.Tokens.inputsSpecular: 1, UsdGeom.Tokens.visibility: "inherited", } if hasattr(UsdLux.Tokens, 'inputsIntensity') else \ { UsdLux.Tokens.intensity: 1000, UsdLux.Tokens.textureFile: texture_path, UsdLux.Tokens.textureFormat: UsdLux.Tokens.latlong, UsdGeom.Tokens.visibility: "inherited", }, create_default_xform=True, context_name=usd_context_name ) prim = stage.GetPrimAtPath("/Environment/Sky") prim.CreateAttribute("xformOp:scale", Sdf.ValueTypeNames.Double3, False).Set(Gf.Vec3d(1, 1, 1)) prim.CreateAttribute("xformOp:translate", Sdf.ValueTypeNames.Double3, False).Set(Gf.Vec3d(0, 0, 0)) if up_axis == "Y": prim.CreateAttribute("xformOp:rotateXYZ", Sdf.ValueTypeNames.Double3, False).Set(Gf.Vec3d(270, 0, 0)) else: prim.CreateAttribute("xformOp:rotateXYZ", Sdf.ValueTypeNames.Double3, False).Set(Gf.Vec3d(0, 0, 90)) prim.CreateAttribute("xformOpOrder", Sdf.ValueTypeNames.String, False).Set(["xformOp:translate", "xformOp:rotateXYZ", "xformOp:scale"]) # create DistantLight omni.kit.commands.execute( "CreatePrim", prim_path="/Environment/DistantLight", prim_type="DistantLight", select_new_prim=False, attributes={ UsdLux.Tokens.inputsAngle: 4.3, UsdLux.Tokens.inputsIntensity: 3000, UsdGeom.Tokens.visibility: "inherited", } if hasattr(UsdLux.Tokens, 'inputsIntensity') else \ { UsdLux.Tokens.angle: 4.3, UsdLux.Tokens.intensity: 3000, UsdGeom.Tokens.visibility: "inherited", }, create_default_xform=True, context_name=usd_context_name ) prim = stage.GetPrimAtPath("/Environment/DistantLight") prim.CreateAttribute("xformOp:scale", Sdf.ValueTypeNames.Double3, False).Set(Gf.Vec3d(1, 1, 1)) prim.CreateAttribute("xformOp:translate", Sdf.ValueTypeNames.Double3, False).Set(Gf.Vec3d(0, 0, 0)) if up_axis == "Y": prim.CreateAttribute("xformOp:rotateXYZ", Sdf.ValueTypeNames.Double3, False).Set(Gf.Vec3d(310.6366313590111, -125.93251524567805, 0.8821359067542289)) else: prim.CreateAttribute("xformOp:rotateXYZ", Sdf.ValueTypeNames.Double3, False).Set(Gf.Vec3d(41.35092544555664, 0.517652153968811, -35.92928695678711)) prim.CreateAttribute("xformOpOrder", Sdf.ValueTypeNames.String, False).Set(["xformOp:translate", "xformOp:rotateXYZ", "xformOp:scale"])
4,590
Python
48.902173
166
0.56732
DigitalBotLab/App/kit-app/source/extensions/omni.usd_explorer.setup/omni/usd_explorer/setup/menu_helper.py
import asyncio import carb.settings import omni.kit.app import omni.kit.commands import omni.kit.menu.utils import omni.renderer_capture from omni.kit.menu.utils import MenuLayout SETTINGS_APPLICATION_MODE_PATH = "/app/application_mode" class MenuHelper: def __init__(self) -> None: self._settings = carb.settings.get_settings() self._current_layout = None self._pending_layout = None self._changing_layout_task: asyncio.Task = None self._menu_layout_empty = [] self._menu_layout_modify = [] omni.kit.menu.utils.add_hook(self._menu_hook) self._app_mode_sub = self._settings.subscribe_to_node_change_events( SETTINGS_APPLICATION_MODE_PATH, self._on_application_mode_changed ) self._menu_hook() def destroy(self) -> None: omni.kit.menu.utils.remove_hook(self._menu_hook) if self._changing_layout_task and not self._changing_layout_task.done(): self._changing_layout_task.cancel() self._changing_layout_task = None if self._app_mode_sub: self._settings.unsubscribe_to_change_events(self._app_mode_sub) self._app_mode_sub = None self._app_ready_sub = None if self._current_layout: omni.kit.menu.utils.remove_layout(self._current_layout) self._current_layout = None def _menu_hook(self, *args, **kwargs) -> None: if self._settings.get_as_bool("/app/view/debug/menus"): return LAYOUT_EMPTY_ALLOWED_MENUS = set() LAYOUT_MODIFY_ALLOWED_MENUS = {"File", "Edit", "Window", "Tools", "Help"} # make NEW list object instead of clear original # the original list may be held by self._current_layout and omni.kit.menu.utils self._menu_layout_empty = [] self._menu_layout_modify = [] menu_instance = omni.kit.menu.utils.get_instance() if not menu_instance: # pragma: no cover return # Build new layouts using allowlists for key in menu_instance._menu_defs: if key.lower().endswith("widget"): continue if key not in LAYOUT_EMPTY_ALLOWED_MENUS: self._menu_layout_empty.append(MenuLayout.Menu(key, remove=True)) if key not in LAYOUT_MODIFY_ALLOWED_MENUS: self._menu_layout_modify.append(MenuLayout.Menu(key, remove=True)) # Remove 'Viewport 2' entry if key == "Window": for menu_item_1 in menu_instance._menu_defs[key]: for menu_item_2 in menu_item_1: if menu_item_2.name == "Viewport": menu_item_2.sub_menu = [mi for mi in menu_item_2.sub_menu if mi.name != "Viewport 2"] if self._changing_layout_task is None or self._changing_layout_task.done(): self._changing_layout_task = asyncio.ensure_future(self._delayed_change_layout()) def _on_application_mode_changed(self, *args) -> None: if self._changing_layout_task is None or self._changing_layout_task.done(): self._changing_layout_task = asyncio.ensure_future(self._delayed_change_layout()) async def _delayed_change_layout(self): mode = self._settings.get_as_string(SETTINGS_APPLICATION_MODE_PATH) if mode in ["present", "review"]: pending_layout = self._menu_layout_empty else: pending_layout = self._menu_layout_modify # Don't change layout inside of menu callback _on_application_mode_changed # omni.ui throws error if self._current_layout: # OMFP-2737: Do no rebuild menu (change menu layout) if layout is same # Here only check number of layout menu items and name of every of layout menu item same_layout = len(self._current_layout) == len(pending_layout) if same_layout: for index, item in enumerate(self._current_layout): if item.name != pending_layout[index].name: same_layout = False if same_layout: return omni.kit.menu.utils.remove_layout(self._current_layout) self._current_layout = None omni.kit.menu.utils.add_layout(pending_layout) # type: ignore self._current_layout = pending_layout.copy() self._changing_layout_task = None
4,434
Python
37.565217
113
0.608029
DigitalBotLab/App/kit-app/source/extensions/omni.usd_explorer.setup/omni/usd_explorer/setup/tests/test_state_manager.py
## Copyright (c) 2023, NVIDIA CORPORATION. All rights reserved. ## ## NVIDIA CORPORATION and its licensors retain all intellectual property ## and proprietary rights in and to this software, related documentation ## and any modifications thereto. Any use, reproduction, disclosure or ## distribution of this software and related documentation without an express ## license agreement from NVIDIA CORPORATION is strictly prohibited. ## import carb.settings import omni.kit.app import omni.ui as ui from omni.kit.test import AsyncTestCase from ..ui_state_manager import UIStateManager, MODAL_TOOL_ACTIVE_PATH class TestUIStateManager(AsyncTestCase): async def setUp(self): self._sm = UIStateManager() self._settings = carb.settings.get_settings() async def tearDown(self): self._sm = None async def test_destroy(self): self._sm.add_hide_on_modal('dummy', False) self._sm.add_settings_copy_dependency('a', 'b') self._sm.add_settings_dependency('c', 'd', {1: 2}) self._sm.add_window_visibility_setting('my_window', 'my_setting') self._sm.destroy() async def test_hide_on_modal(self): self._settings.set_bool(MODAL_TOOL_ACTIVE_PATH, False) self._sm.add_hide_on_modal('NO_RESTORE', False) self._sm.add_hide_on_modal(['A_RESTORE', 'B_RESTORE'], True) window_no_restore = ui.Window('NO_RESTORE') window_restore_1 = ui.Window('A_RESTORE') window_restore_2 = ui.Window('B_RESTORE') window_no_restore.visible = True window_restore_1.visible = True window_restore_2.visible = False await self._wait() self._settings.set_bool(MODAL_TOOL_ACTIVE_PATH, True) await self._wait() self.assertFalse(window_no_restore.visible) self.assertFalse(window_restore_1.visible) self.assertFalse(window_restore_2.visible) self._settings.set_bool(MODAL_TOOL_ACTIVE_PATH, False) await self._wait() self.assertFalse(window_no_restore.visible) self.assertTrue(window_restore_1.visible) self.assertFalse(window_restore_2.visible) self._sm.remove_hide_on_modal(window_restore_1.title) self._settings.set_bool(MODAL_TOOL_ACTIVE_PATH, True) await self._wait() self.assertTrue(window_restore_1.visible) self._settings.set_bool(MODAL_TOOL_ACTIVE_PATH, False) async def test_window_visibility_setting(self): window_name = 'Dummy' setting_path = '/apps/dummy' setting_path2 = '/apps/dummy2' window = ui.Window(window_name) window.visible = True await self._wait() self._sm.add_window_visibility_setting(window_name=window_name, setting_path=setting_path) self._sm.add_window_visibility_setting(window_name=window_name, setting_path=setting_path2) self.assertIsNotNone(self._settings.get(setting_path)) self.assertTrue(self._settings.get(setting_path)) self.assertTrue(self._settings.get(setting_path2)) window.visible = False self.assertFalse(self._settings.get(setting_path)) self.assertFalse(self._settings.get(setting_path2)) window.visible = True self.assertTrue(self._settings.get(setting_path)) self.assertTrue(self._settings.get(setting_path2)) self._sm.remove_window_visibility_setting(window_name=window_name, setting_path=setting_path) window.visible = False self.assertTrue(self._settings.get(setting_path)) self.assertFalse(self._settings.get(setting_path2)) self._sm.remove_all_window_visibility_settings(window_name=window_name) window.visible = True self.assertFalse(self._settings.get(setting_path2)) async def test_setting_dependency(self): setting_path_copy_from = '/app/copy_from' setting_path_copy_to = '/ext/copy_to' setting_path_map_from = '/ext/map_from' setting_path_map_to = '/something/map_to' self._sm.add_settings_copy_dependency(setting_path_copy_from, setting_path_copy_to) self._settings.set_string(setting_path_copy_from, 'hello_world') self.assertEqual(self._settings.get(setting_path_copy_from), self._settings.get(setting_path_copy_to)) # doesn't work the other way around self._settings.set_string(setting_path_copy_to, 'no_copy_back') self.assertEqual(self._settings.get(setting_path_copy_from), 'hello_world') self._sm.add_settings_dependency(setting_path_map_from, setting_path_map_to, {1: 2, 3: 4}) self._settings.set_int(setting_path_map_from, 1) self.assertEqual(self._settings.get(setting_path_map_to), 2) self._settings.set_int(setting_path_map_from, 3) self.assertEqual(self._settings.get(setting_path_map_to), 4) # not in the map self._settings.set_int(setting_path_map_from, 42) self.assertEqual(self._settings.get(setting_path_map_to), 4) self.assertEqual(self._settings.get(setting_path_copy_from), 'hello_world') self.assertEqual(self._settings.get(setting_path_copy_to), 'no_copy_back') self._sm.remove_settings_dependency(setting_path_copy_from, setting_path_copy_to) self._settings.set_string(setting_path_copy_from, 'this_is_not_copied') self.assertEqual(self._settings.get(setting_path_copy_to), 'no_copy_back') async def _wait(self, frames: int = 5): for _ in range(frames): await omni.kit.app.get_app().next_update_async()
5,552
Python
42.046511
110
0.67219
DigitalBotLab/App/kit-app/source/extensions/omni.usd_explorer.setup/omni/usd_explorer/setup/tests/__init__.py
# run startup tests first from .test_app_startup import * from .test import * from .test_state_manager import *
112
Python
21.599996
33
0.75
DigitalBotLab/App/kit-app/source/extensions/omni.usd_explorer.setup/omni/usd_explorer/setup/tests/test.py
import omni.kit.app from omni.ui.tests.test_base import OmniUiTest from omni.kit import ui_test ext_id = 'omni.usd_explorer.setup' class TestSetupToolExtension(OmniUiTest): async def test_extension(self): manager = omni.kit.app.get_app().get_extension_manager() self.assertTrue(ext_id) self.assertTrue(manager.is_extension_enabled(ext_id)) app = omni.kit.app.get_app() for _ in range(500): await app.next_update_async() manager.set_extension_enabled(ext_id, False) await ui_test.human_delay() self.assertTrue(not manager.is_extension_enabled(ext_id)) manager.set_extension_enabled(ext_id, True) await ui_test.human_delay() self.assertTrue(manager.is_extension_enabled(ext_id)) async def test_menubar_helper_camera_dependency(self): manager = omni.kit.app.get_app().get_extension_manager() manager.set_extension_enabled(ext_id, False) await ui_test.human_delay() self.assertFalse(manager.is_extension_enabled(ext_id)) manager.set_extension_enabled('omni.kit.viewport.menubar.camera', True) await ui_test.human_delay() manager.set_extension_enabled(ext_id, True) await ui_test.human_delay() self.assertTrue(manager.is_extension_enabled(ext_id)) manager.set_extension_enabled(ext_id, False) await ui_test.human_delay() self.assertFalse(manager.is_extension_enabled(ext_id)) manager.set_extension_enabled(ext_id, True) await ui_test.human_delay() self.assertTrue(manager.is_extension_enabled(ext_id)) async def test_menu_helper(self): from ..menu_helper import MenuHelper menu_helper = MenuHelper() menu_helper.destroy() async def test_menubar_helper_menu(self): from ..menubar_helper import MenubarHelper menubar_helper = MenubarHelper() menubar_helper._create_camera_speed(None, None) menubar_helper.destroy() async def test_menu_helper_debug_setting(self): SETTINGS_VIEW_DEBUG_MENUS = '/app/view/debug/menus' import carb.settings settings = carb.settings.get_settings() manager = omni.kit.app.get_app().get_extension_manager() manager.set_extension_enabled(ext_id, False) await ui_test.human_delay() self.assertFalse(manager.is_extension_enabled(ext_id)) orig_value = settings.get(SETTINGS_VIEW_DEBUG_MENUS) settings.set_bool(SETTINGS_VIEW_DEBUG_MENUS, True) manager.set_extension_enabled(ext_id, True) await ui_test.human_delay() self.assertTrue(manager.is_extension_enabled(ext_id)) manager.set_extension_enabled(ext_id, False) await ui_test.human_delay() self.assertFalse(manager.is_extension_enabled(ext_id)) settings.set_bool(SETTINGS_VIEW_DEBUG_MENUS, orig_value) manager.set_extension_enabled(ext_id, True) await ui_test.human_delay() self.assertTrue(manager.is_extension_enabled(ext_id)) async def test_menu_helper_application_mode_change(self): from ..menu_helper import SETTINGS_APPLICATION_MODE_PATH import carb.settings settings = carb.settings.get_settings() settings.set_string(SETTINGS_APPLICATION_MODE_PATH, 'modify') await ui_test.human_delay() settings.set_string(SETTINGS_APPLICATION_MODE_PATH, 'welcome') await ui_test.human_delay() settings.set_string(SETTINGS_APPLICATION_MODE_PATH, 'modify') await ui_test.human_delay() settings.set_string(SETTINGS_APPLICATION_MODE_PATH, 'comment') await ui_test.human_delay() settings.set_string(SETTINGS_APPLICATION_MODE_PATH, 'modify') await ui_test.human_delay() async def test_menu_helper_widget_menu(self): import omni.kit.menu.utils omni.kit.menu.utils.add_menu_items([], name='test widget') from ..menu_helper import MenuHelper menu_helper = MenuHelper() menu_helper.destroy() async def test_startup_expand_viewport(self): from ..setup import SETTINGS_STARTUP_EXPAND_VIEWPORT import carb.settings settings = carb.settings.get_settings() orig_value = settings.get(SETTINGS_STARTUP_EXPAND_VIEWPORT) settings.set_bool(SETTINGS_STARTUP_EXPAND_VIEWPORT, True) manager = omni.kit.app.get_app().get_extension_manager() manager.set_extension_enabled(ext_id, False) await ui_test.human_delay() self.assertFalse(manager.is_extension_enabled(ext_id)) manager.set_extension_enabled(ext_id, True) await ui_test.human_delay() self.assertTrue(manager.is_extension_enabled(ext_id)) settings.set_bool(SETTINGS_STARTUP_EXPAND_VIEWPORT, orig_value) manager.set_extension_enabled(ext_id, False) await ui_test.human_delay() self.assertFalse(manager.is_extension_enabled(ext_id)) manager.set_extension_enabled(ext_id, True) await ui_test.human_delay() self.assertTrue(manager.is_extension_enabled(ext_id)) async def test_navigation_invalid_dict(self): from ..navigation import Navigation navigation = Navigation() navigation._show_tooltips = False navigation._dict = 42 navigation._on_application_mode_changed(None, None) navigation._on_showtips_click() async def test_navigation_current_tool_mode_change(self): from ..navigation import CURRENT_TOOL_PATH, APPLICATION_MODE_PATH import carb.settings settings = carb.settings.get_settings() settings.set_string(APPLICATION_MODE_PATH, 'modify') await ui_test.human_delay() settings.set_string(CURRENT_TOOL_PATH, 'markup') await ui_test.human_delay() settings.set_string(CURRENT_TOOL_PATH, 'navigation') await ui_test.human_delay() settings.set_string(CURRENT_TOOL_PATH, 'markup') await ui_test.human_delay() settings.set_string(CURRENT_TOOL_PATH, 'welcome') await ui_test.human_delay() settings.set_string(CURRENT_TOOL_PATH, 'navigation') await ui_test.human_delay() settings.set_string(CURRENT_TOOL_PATH, 'markup') await ui_test.human_delay() settings.set_string(CURRENT_TOOL_PATH, 'navigation') await ui_test.human_delay() async def test_setup_clear_startup_scene_edits(self): from ..setup import _clear_startup_scene_edits await _clear_startup_scene_edits() import omni.usd self.assertFalse(omni.usd.get_context().has_pending_edit()) async def test_stage_template(self): import omni.kit.stage_templates omni.kit.stage_templates.new_stage(template='SunnySky')
6,826
Python
34.190721
79
0.665397
DigitalBotLab/App/kit-app/source/extensions/omni.usd_explorer.setup/omni/usd_explorer/setup/tests/test_app_startup.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 omni.kit.app from omni.kit.test import AsyncTestCase class TestAppStartup(AsyncTestCase): async def test_l1_app_startup_time(self): """Get startup time - send to nvdf""" for _ in range(60): await omni.kit.app.get_app().next_update_async() try: from omni.kit.core.tests import app_startup_time app_startup_time(self.id()) except: # noqa pass self.assertTrue(True) async def test_l1_app_startup_warning_count(self): """Get the count of warnings during startup - send to nvdf""" for _ in range(60): await omni.kit.app.get_app().next_update_async() try: from omni.kit.core.tests import app_startup_warning_count app_startup_warning_count(self.id()) except: # noqa pass self.assertTrue(True)
1,323
Python
32.948717
77
0.657596
DigitalBotLab/App/kit-app/source/extensions/omni.usd_explorer.setup/docs/CHANGELOG.md
# Changelog The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/). ## [1.0.0] - 2021-04-26 - Initial version of extension.
151
Markdown
20.714283
80
0.688742
DigitalBotLab/App/kit-app/source/extensions/omni.usd_explorer.setup/docs/README.md
# omni.usd_explorer.setup
25
Markdown
24.999975
25
0.8
DigitalBotLab/App/kit-app/source/extensions/omni.hello.world/config/extension.toml
[package] # Semantic Versionning is used: https://semver.org/ version = "1.0.0" # The title and description fields are primarily for displaying extension info in UI title = "Simple UI Extension Template" description = "The simplest python extension example. Use it as a starting point for your extensions." # Path (relative to the root) or content of readme markdown file for UI. readme = "docs/README.md" # Path (relative to the root) of changelog changelog = "docs/CHANGELOG.md" # URL of the extension source repository. repository = "https://github.com/NVIDIA-Omniverse/kit-app-template" # One of categories for UI. category = "Example" # Keywords for the extension keywords = ["kit", "example"] # Icon to show in the extension manager icon = "data/icon.png" # Preview to show in the extension manager preview_image = "data/preview.png" # Use omni.ui to build simple UI [dependencies] "omni.kit.uiapp" = {} # Main python module this extension provides, it will be publicly available as "import omni.hello.world". [[python.module]] name = "omni.hello.world" [[test]] # Extra dependencies only to be used during test run dependencies = [ "omni.kit.ui_test" # UI testing extension ]
1,200
TOML
26.295454
105
0.738333
DigitalBotLab/App/kit-app/source/extensions/omni.hello.world/omni/hello/world/extension.py
# Copyright 2019-2023 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 omni.ext import omni.ui as ui # Functions and vars are available to other extension as usual in python: `example.python_ext.some_public_function(x)` def some_public_function(x: int): print(f"[omni.hello.world] some_public_function was called with {x}") return x ** x # Any class derived from `omni.ext.IExt` in top level module (defined in `python.modules` of `extension.toml`) will be # instantiated when extension gets enabled and `on_startup(ext_id)` will be called. Later when extension gets disabled # on_shutdown() is called. class MyExtension(omni.ext.IExt): # ext_id is current extension id. It can be used with extension manager to query additional information, like where # this extension is located on filesystem. def on_startup(self, ext_id): print("[omni.hello.world] MyExtension startup") self._count = 0 self._window = ui.Window("My Window", width=300, height=300) with self._window.frame: with ui.VStack(): label = ui.Label("") def on_click(): self._count += 1 label.text = f"count: {self._count}" def on_reset(): self._count = 0 label.text = "empty" on_reset() with ui.HStack(): ui.Button("Add", clicked_fn=on_click) ui.Button("Reset", clicked_fn=on_reset) def on_shutdown(self): print("[omni.hello.world] MyExtension shutdown")
2,141
Python
36.578947
119
0.64269
DigitalBotLab/App/kit-app/source/extensions/omni.hello.world/omni/hello/world/__init__.py
# Copyright 2019-2023 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. from .extension import *
609
Python
39.666664
74
0.770115