file_path
stringlengths
21
202
content
stringlengths
13
1.02M
size
int64
13
1.02M
lang
stringclasses
9 values
avg_line_length
float64
5.43
98.5
max_line_length
int64
12
993
alphanum_fraction
float64
0.27
0.91
matthias-research/omni.fun/exts/omni.fun/docs/README.md
# Play [omni.ten] A simple plugin from ten minute physics. ## Documentation None ## Source Code None
109
Markdown
6.333333
40
0.688073
qcr/benchbot_sim_omni/pip_package_fix.py
import subprocess import sys print("HACK FIX FOR BROKEN PACKAGES") def install(package): subprocess.check_call([sys.executable, "-m", "pip", "install", package]) def uninstall(package): subprocess.check_call([sys.executable, "-m", "pip", "uninstall", "--yes", package]) uninstall("click") install("click") uninstall("typing-extensions") install("typing-extensions")
375
Python
27.923075
87
0.717333
qcr/benchbot_sim_omni/run.py
import flask import numpy as np import os import signal from builtins import print as bprint from gevent import event, pywsgi, signal from pathlib import Path from spatialmath import SE3, UnitQuaternion print("STARTING RUN.PY IN BENCHBOT_SIM_OMNI") DEFAULT_POSE = np.array([1, 0, 0, 0, 0, 0, 0]) DIRTY_EPSILON_DIST = 1 DIRTY_EPSILON_YAW = 2 DIRTY_FILE = '/tmp/benchbot_dirty' MAP_PRIM_PATH = '/env' ROBOT_NAME = 'robot' ROBOT_PRIM_PATH = '/%s' % ROBOT_NAME ROBOT_COMPONENTS = { 'clock': '/ROS_Clock', 'diff_base': '%s/ROS_DifferentialBase' % ROBOT_PRIM_PATH, 'lidar': '%s/ROS_Lidar' % ROBOT_PRIM_PATH, 'rgbd': '%s/ROS_Camera_Stereo_Left' % ROBOT_PRIM_PATH, 'tf_sensors': '%s/ROS_Carter_Sensors_Broadcaster' % ROBOT_PRIM_PATH, 'tf': '%s/ROS_Carter_Broadcaster' % ROBOT_PRIM_PATH } UPDATE_DELAY_SECS = 3.0 def _dc_tf_to_SE3(tf): r = np.array(tf.r) return SE3(np.array(tf.p)) * UnitQuaternion(r[3], r[0:3]).SE3() def _to_SE3(pose): return SE3(pose[4::]) * UnitQuaternion(pose[0], pose[1:4]).SE3() def disable_component(prop_path): from omni.kit.commands import execute from pxr import Sdf print("DISABLING '%s.enabled'" % prop_path) execute("ChangeProperty", prop_path=Sdf.Path("%s.enabled" % prop_path), value=False, prev=None) def print(*args, **kwargs): bprint(*args, **kwargs, flush=True) class SimulatorDaemon: def __init__(self, port): self.address = 'localhost:%s' % port self.inst = None self.sim = None self.sim_i = 0 self.sim_collided = False self.sim_dirty = False self.map_usd = None self.robot_usd = None self.start_pose = None self._map_usd = None self._robot_usd = None self._start_pose = None self._dc = None self._robot = None self._robot_dc = None def check_dirty(self): delta = (_to_SE3(self.start_pose).inv() * _dc_tf_to_SE3(self._dc.get_rigid_body_pose(self._robot_dc))) return (np.linalg.norm(delta.t[0:2]) > DIRTY_EPSILON_DIST or np.abs(delta.rpy(unit='deg')[2]) > DIRTY_EPSILON_YAW) def check_collided(self): return False def open_usd(self): # Bail early if we can't act if self.inst is None: print("No simulator running. " "Stored environment USD, but not opening.") return if self.map_usd is None: print("No environment USD selected. Returning.") return # Imports must go after bail early checks pass as they throw errors # when called in an "inappropriate state" (no idea what that # corresponds to...) from omni.isaac.core.utils.stage import open_stage, update_stage # Stop simulation if running self.stop_simulation() # Update the map if self.map_usd != self._map_usd: self._dc = None self._start_pose = None self._robot = None self._robot_dc = None self._robot_usd = None open_stage(usd_path=self.map_usd) update_stage() self._map_usd = self.map_usd else: print("Skipping map load; already loaded.") # Attempt to replace the robot self.place_robot() def place_robot(self): # Bail early if we can't act if self.inst is None: print("No simulator running. " "Stored robot USD & pose, but not opening.") return if self.robot_usd is None: print("No robot USD selected. Returning.") return # Imports must go after bail early checks pass as they throw errors # when called in an "inappropriate state" (no idea what that # corresponds to...) from omni.isaac.core.robots import Robot from omni.isaac.core.utils.stage import (add_reference_to_stage, update_stage) # Stop simulation if running self.stop_simulation() # Add robot to the environment at the requested pose p = DEFAULT_POSE if self.start_pose is None else self.start_pose if self.robot_usd != self._robot_usd: add_reference_to_stage(usd_path=self.robot_usd, prim_path=ROBOT_PRIM_PATH) self._robot = Robot(prim_path=ROBOT_PRIM_PATH, name=ROBOT_NAME) update_stage() self._robot_usd = self.robot_usd else: print("Skipping robot load; already loaded.") if (p != self._start_pose).any(): self._robot.set_world_pose(position=p[4::], orientation=p[:4]) update_stage() self._start_pose = p else: print("Skipping robot move; already at requested pose.") # Disable auto-publishing of all robot components (we'll manually # publish at varying frequencies instead) for p in ROBOT_COMPONENTS.values(): disable_component(p) # Attempt to start the simulation self.start_simulation() def run(self): f = flask.Flask('benchbot_sim_omni') @f.route('/', methods=['GET']) def __hello(): return flask.jsonify("Hello, I am the Omniverse Sim Daemon") @f.route('/open_environment', methods=['POST']) def __open_env(): r = flask.request.json if 'environment' in r: self.map_usd = r['environment'] self.open_usd() return flask.jsonify({}) @f.route('/place_robot', methods=['POST']) def __place_robot(): r = flask.request.json if 'robot' in r: self.robot_usd = r['robot'] if 'start_pose' in r: # Probably should be regexing... self.start_pose = np.array([ float(x.strip()) for x in r['start_pose'].replace( '[', '').replace(']', '').split(',') ]) self.place_robot() return flask.jsonify({}) @f.route('/restart_sim', methods=['POST']) def __restart_sim(): self.stop_simulation() self.start_simulation() return flask.jsonify({}) @f.route('/start', methods=['POST']) def __start_inst(): self.start_instance() return flask.jsonify({}) @f.route('/start_sim', methods=['POST']) def __start_sim(): self.start_simulation() return flask.jsonify({}) @f.route('/started', methods=['GET']) def __started(): # TODO note there is a race condition (returns true before a /start # job finishes) return flask.jsonify({'started': self.inst is not None}) @f.route('/stop_sim', methods=['POST']) def __stop_sim(): self.stop_simulation() return flask.jsonify({}) # Start long-running server server = pywsgi.WSGIServer(self.address, f) evt = event.Event() for s in [signal.SIGINT, signal.SIGQUIT, signal.SIGTERM]: signal.signal(s, lambda n, frame: evt.set()) server.start() while not evt.is_set(): evt.wait(0.001) self.tick_simulator() # Cleanup self.stop_instance() def start_instance(self): print("STARTING INSTANCE!!") if not self.inst is None: print("Instance already running. Please /stop first.") return env = {} if self.map_usd is None else {"open_usd": self.map_usd} from omni.isaac.kit import SimulationApp # Start the simulator self.inst = SimulationApp({ "renderer": "RayTracedLighting", "headless": False, **env }) # Import all required modules, and configure application from omni.isaac.core.utils.extensions import enable_extension enable_extension("omni.isaac.ros_bridge") # Attempt to place the robot if we had a map if env: self.place_robot() def start_simulation(self): if self.sim is not None: self.stop_simulation() if self.inst is None or self.map_usd is None or self.robot_usd is None: print("Can't start simulation. Missing some required state.") return from omni.isaac.core import SimulationContext self.sim_i = 0 self.sim_collided = False self.sim_dirty = False self.sim = SimulationContext() self.sim.play() from omni.isaac.dynamic_control import _dynamic_control self._dc = _dynamic_control.acquire_dynamic_control_interface() self._robot_dc = self._dc.get_articulation_root_body( self._dc.get_object(ROBOT_PRIM_PATH)) def stop_instance(self): if self.inst is None: print("No instance is running to stop.") return self.stop_simulation() self.inst.close() self.inst = None def stop_simulation(self): if self.sim is None: print("Skipping. No running simulation to stop") return if self.inst is None: print("Skipping. No running simulator found.") return self.sim.stop() self.sim = None # TODO maybe could reuse with more guarding logic? def tick_simulator(self): # Tick simulator steps. Does less now than in 2021.2.1 due to new action graph if self.inst is None: return if self.sim is None: self.inst.update() return self.sim.step() # Tick at 10Hz CHECK DIRTY if self.sim_i % 6 == 0: if not self.sim_dirty: self.sim_dirty = self.check_dirty() if self.sim_dirty: Path(DIRTY_FILE).touch() # Tick at 1Hz CHECK COLLIDED if self.sim_i % 60 == 0: self.sim_collided = self.check_collided() self.sim_i += 1 if __name__ == '__main__': print("inside run.py __main__") sd = SimulatorDaemon(port=os.environ.get('PORT')) sd.run()
10,394
Python
30.122754
86
0.554166
qcr/benchbot_sim_omni/README.md
**NOTE: this software is part of the BenchBot software stack. For a complete working BenchBot system, please install the BenchBot software stack by following the instructions [here](https://github.com/qcr/benchbot).** # BenchBot Simulator for Omniverse-powered Isaac Sim [![BenchBot project](https://img.shields.io/badge/collection-BenchBot-%231a2857)](http://benchbot.org) [![QUT Centre for Robotics Open Source](https://github.com/qcr/qcr.github.io/raw/master/misc/badge.svg)](https://qcr.github.io) ![Primary language](https://img.shields.io/github/languages/top/qcr/benchbot_sim_omni) [![License](https://img.shields.io/github/license/qcr/benchbot_sim_omni)](./LICENSE.txt) ![BenchBot Simulator interaction with the Omniverse-powered Isaac Sim](./docs/benchbot_sim_omni.jpg) The BenchBot Simulator bindings for Omniverse-powered Isaac Sim provide a simple `run` script that makes powerful photorealistic simulations available in ROS, and controllable through a basic HTTP API. Through a single script, this package provides: - creation of, and management of, a running [Omniverse-powered Isaac Sim](https://developer.nvidia.com/isaac-sim) instance - a simple HTTP API for programmatically loading environments, placing robots, and controlling simulations - ROS topics for common mobile robot topics: transforms, odometry, command velocity, RGB images, depth images, laser scans The configuration is currently Carter specific, but could easily be extended in the future to target other robots. Also all simulator interactions come from a simple Python script that could be used as a starting point for more complex projects. ## Installation **Please see the note at the top of the page; the BenchBot ecosystem contains much more than just these bindings** There is no physical installation step for these bindings, simply install Isaac Sim, clone this repository, and install Python dependencies: 1. Follow the instructions on the [NVIDIA Isaac Sim documentation site](https://docs.omniverse.nvidia.com/app_isaacsim/app_isaacsim/overview.html) for [installing Isaac Sim](https://docs.omniverse.nvidia.com/app_isaacsim/app_isaacsim/install_basic.html) 2. Clone this repository: ``` git clone https://github.com/qcr/benchbot_sim_omni ``` 3. Install declared Python dependencies: ``` pip install -r ./.custom_deps ``` ## Running and using the simulator bindings Simulator bindings are run through the `run` script, which will start a blank instance of the simulator with the HTTP API bound on port 10001 by default: ``` ./run ``` A simulation in environment `my_env.usd`, with robot `my_robot.usd` at position `(0,0,0)` and quaternion (w,x,y,z) `(1,0,0,0)` can then be started by the following two CURL commands: ``` curl localhost:10001/open_environment \ -H "Content-Type: application/json" \ -d '{"environment": "my_env.usd"}' curl localhost:10001/place_robot \ -H "Content-Type: application/json" \ -d '{"robot": "my_robot.usd", "start_pose": "1,0,0,0,0,0,0"}' ``` Full documentation of configuration options and HTTP API routes is available through the script's `--help` flag: ``` user@pc:~/benchbot_sim_omni/$ ./run --help run -- BenchBot simulator daemon for Omniverse-powered Isaac Sim USAGE: Start the daemon: run run -p /path/to/python.sh -P 8080 Print this help information: run [-h|--help] OPTION DETAILS: -h, --help Show this help menu. -P,--port Port the daemon will bind to. Default port of 10001 will be used if not provided. -p,--python-sh-path Path to the 'python.sh' environment script included with your Isaac Sim installation. Will recursively search for the script in the current directory if this flag is not provided. INTERACTING WITH THE DAEMON: The daemon responds to HTTP requests. Following routes are supported: / Returns a greeting message /open_environment Opens a new environment, with USD path specified via 'environment' data field /place_robot Places a robot at a specified pose. Robot USD is specified via 'robot' data field, and start pose via a comma-separated 7-tuple in the 'pose' field. Format for pose is: quat_w,quat_x,quat_y,quat_z,pos_x,pos_y,pos_z /start Starts a simulator instance (happens by default when first opened) /stop Stops a currently running simulator instance if it exists /restart Restarts the entire simulator (generally not needed) FURTHER DETAILS: Please contact the authors of BenchBot for support or to report bugs: b.talbot@qut.edu.au ``` ## Using this simulator with the BenchBot Robot Controller The [BenchBot Robot Controller](https://github.com/qcr/benchbot_robot_controller) is a wrapping ROS / HTTP hybrid script that manages running robots and their required subprocesses. It is ultimately fed configurations from [BenchBot add-ons](https://github.com/qcr/benchbot_addons) through our [BenchBot supervisor](https://github.com/qcr/benchbot_supervisor) service. These details are superfluous to these BenchBot simulator bindings, but are provided here for context. This context may be helpful if looking for examples of more complex interactions with the simulator bindings. For example, the `carter_sim_omni.yaml` file in the [robots_sim_omni](https://github.com/benchbot-addons/robots_sim_omni) BenchBot add-on may be of interest.
5,559
Markdown
41.442748
370
0.729808
AndrePatri/OmniRoboGym/pyproject.toml
[build-system] requires = ["flit_core >=2,<4"] build-backend = "flit_core.buildapi" [project] name = "omni_robo_gym" version = "0.1.0" description = "" authors = [{name = "AndrePatri", email = "andreapatrizi1b6e6@gmail.com"}] readme = "README.md" license = {file = "LICENSE"}
276
TOML
24.181816
73
0.666667
AndrePatri/OmniRoboGym/omnirobogym_mamba_env.yml
name: omni_robo_gym_isaac2023.1.1 channels: - defaults - pytorch - nvidia - conda-forge - omnia - robostack-staging - AndrePatri dependencies: - python=3.10 - pip - pytorch == 2.0.1 - torchvision - torchaudio - cuda-toolkit=11.7 - compilers - cmake - make - quaternion - anaconda-client - yaml-cpp - pybind11 - gtest - eigen3 - posix_ipc=1.0.4 - rospkg=1.5.0 - ros-humble-xacro - empy - python-devtools - perf_sleep - pyqt - pyqtgraph - pip: - flit - nvidia-cublas-cu11==11.11.3.6 - gym==0.26.2 - gymnasium==0.28.1 - stable_baselines3[extra]==2.0.0a10 - box2d-py - tensorboard - tensorboard-plugin-wit - protobuf - matplotlib - scipy - urdf-parser-py - multiprocess
789
YAML
15.122449
40
0.593156
AndrePatri/OmniRoboGym/meta.yaml
package: name: omni_robo_gym version: 0.1.0 source: path: . # Path to the directory containing your built distribution artifacts requirements: build: - python=3.7 - flit run: - python=3.7 about: home: https://github.com/AndrePatri/CoClusterBridge license: MIT summary: Some custom implementations of Tasks and Gyms for Omniverse Isaac Sim based on Gymnasium. Easy URDF and SRDF import/cloning and simulation configuration exploiting Omniverse API extra: recipe-maintainers: - AndrePatri
537
YAML
20.519999
189
0.722533
AndrePatri/OmniRoboGym/README.md
# OmniRoboGym Wrapper on top of [Omniverse Isaac Sim](https://developer.nvidia.com/isaac-sim), a photo-realistic GPU accelerated simulator from NVIDIA. The aim of the package is to a easy interface for loading floating-base robots and their configuration from URDF and SRDF into IsaacSim, cloning them with Isaac Sim API and, in general, simplify simulation setup for RL-based robotics applications.
402
Markdown
79.599984
248
0.80597
AndrePatri/OmniRoboGym/LICENSE.md
GNU GENERAL PUBLIC LICENSE Version 2, June 1991 Copyright (C) 1989, 1991 Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. Preamble The licenses for most software are designed to take away your freedom to share and change it. By contrast, the GNU General Public License is intended to guarantee your freedom to share and change free software--to make sure the software is free for all its users. This General Public License applies to most of the Free Software Foundation's software and to any other program whose authors commit to using it. (Some other Free Software Foundation software is covered by the GNU Lesser General Public License instead.) You can apply it to your programs, too. When we speak of free software, we are referring to freedom, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for this service if you wish), that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs; and that you know you can do these things. To protect your rights, we need to make restrictions that forbid anyone to deny you these rights or to ask you to surrender the rights. These restrictions translate to certain responsibilities for you if you distribute copies of the software, or if you modify it. For example, if you distribute copies of such a program, whether gratis or for a fee, you must give the recipients all the rights that you have. You must make sure that they, too, receive or can get the source code. And you must show them these terms so they know their rights. We protect your rights with two steps: (1) copyright the software, and (2) offer you this license which gives you legal permission to copy, distribute and/or modify the software. Also, for each author's protection and ours, we want to make certain that everyone understands that there is no warranty for this free software. If the software is modified by someone else and passed on, we want its recipients to know that what they have is not the original, so that any problems introduced by others will not reflect on the original authors' reputations. Finally, any free program is threatened constantly by software patents. We wish to avoid the danger that redistributors of a free program will individually obtain patent licenses, in effect making the program proprietary. To prevent this, we have made it clear that any patent must be licensed for everyone's free use or not licensed at all. The precise terms and conditions for copying, distribution and modification follow. GNU GENERAL PUBLIC LICENSE TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION 0. This License applies to any program or other work which contains a notice placed by the copyright holder saying it may be distributed under the terms of this General Public License. The "Program", below, refers to any such program or work, and a "work based on the Program" means either the Program or any derivative work under copyright law: that is to say, a work containing the Program or a portion of it, either verbatim or with modifications and/or translated into another language. (Hereinafter, translation is included without limitation in the term "modification".) Each licensee is addressed as "you". Activities other than copying, distribution and modification are not covered by this License; they are outside its scope. The act of running the Program is not restricted, and the output from the Program is covered only if its contents constitute a work based on the Program (independent of having been made by running the Program). Whether that is true depends on what the Program does. 1. You may copy and distribute verbatim copies of the Program's source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice and disclaimer of warranty; keep intact all the notices that refer to this License and to the absence of any warranty; and give any other recipients of the Program a copy of this License along with the Program. You may charge a fee for the physical act of transferring a copy, and you may at your option offer warranty protection in exchange for a fee. 2. You may modify your copy or copies of the Program or any portion of it, thus forming a work based on the Program, and copy and distribute such modifications or work under the terms of Section 1 above, provided that you also meet all of these conditions: a) You must cause the modified files to carry prominent notices stating that you changed the files and the date of any change. b) You must cause any work that you distribute or publish, that in whole or in part contains or is derived from the Program or any part thereof, to be licensed as a whole at no charge to all third parties under the terms of this License. c) If the modified program normally reads commands interactively when run, you must cause it, when started running for such interactive use in the most ordinary way, to print or display an announcement including an appropriate copyright notice and a notice that there is no warranty (or else, saying that you provide a warranty) and that users may redistribute the program under these conditions, and telling the user how to view a copy of this License. (Exception: if the Program itself is interactive but does not normally print such an announcement, your work based on the Program is not required to print an announcement.) These requirements apply to the modified work as a whole. If identifiable sections of that work are not derived from the Program, and can be reasonably considered independent and separate works in themselves, then this License, and its terms, do not apply to those sections when you distribute them as separate works. But when you distribute the same sections as part of a whole which is a work based on the Program, the distribution of the whole must be on the terms of this License, whose permissions for other licensees extend to the entire whole, and thus to each and every part regardless of who wrote it. Thus, it is not the intent of this section to claim rights or contest your rights to work written entirely by you; rather, the intent is to exercise the right to control the distribution of derivative or collective works based on the Program. In addition, mere aggregation of another work not based on the Program with the Program (or with a work based on the Program) on a volume of a storage or distribution medium does not bring the other work under the scope of this License. 3. You may copy and distribute the Program (or a work based on it, under Section 2) in object code or executable form under the terms of Sections 1 and 2 above provided that you also do one of the following: a) Accompany it with the complete corresponding machine-readable source code, which must be distributed under the terms of Sections 1 and 2 above on a medium customarily used for software interchange; or, b) Accompany it with a written offer, valid for at least three years, to give any third party, for a charge no more than your cost of physically performing source distribution, a complete machine-readable copy of the corresponding source code, to be distributed under the terms of Sections 1 and 2 above on a medium customarily used for software interchange; or, c) Accompany it with the information you received as to the offer to distribute corresponding source code. (This alternative is allowed only for noncommercial distribution and only if you received the program in object code or executable form with such an offer, in accord with Subsection b above.) The source code for a work means the preferred form of the work for making modifications to it. For an executable work, complete source code means all the source code for all modules it contains, plus any associated interface definition files, plus the scripts used to control compilation and installation of the executable. However, as a special exception, the source code distributed need not include anything that is normally distributed (in either source or binary form) with the major components (compiler, kernel, and so on) of the operating system on which the executable runs, unless that component itself accompanies the executable. If distribution of executable or object code is made by offering access to copy from a designated place, then offering equivalent access to copy the source code from the same place counts as distribution of the source code, even though third parties are not compelled to copy the source along with the object code. 4. You may not copy, modify, sublicense, or distribute the Program except as expressly provided under this License. Any attempt otherwise to copy, modify, sublicense or distribute the Program is void, and will automatically terminate your rights under this License. However, parties who have received copies, or rights, from you under this License will not have their licenses terminated so long as such parties remain in full compliance. 5. You are not required to accept this License, since you have not signed it. However, nothing else grants you permission to modify or distribute the Program or its derivative works. These actions are prohibited by law if you do not accept this License. Therefore, by modifying or distributing the Program (or any work based on the Program), you indicate your acceptance of this License to do so, and all its terms and conditions for copying, distributing or modifying the Program or works based on it. 6. Each time you redistribute the Program (or any work based on the Program), the recipient automatically receives a license from the original licensor to copy, distribute or modify the Program subject to these terms and conditions. You may not impose any further restrictions on the recipients' exercise of the rights granted herein. You are not responsible for enforcing compliance by third parties to this License. 7. If, as a consequence of a court judgment or allegation of patent infringement or for any other reason (not limited to patent issues), conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot distribute so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not distribute the Program at all. For example, if a patent license would not permit royalty-free redistribution of the Program by all those who receive copies directly or indirectly through you, then the only way you could satisfy both it and this License would be to refrain entirely from distribution of the Program. If any portion of this section is held invalid or unenforceable under any particular circumstance, the balance of the section is intended to apply and the section as a whole is intended to apply in other circumstances. It is not the purpose of this section to induce you to infringe any patents or other property right claims or to contest validity of any such claims; this section has the sole purpose of protecting the integrity of the free software distribution system, which is implemented by public license practices. Many people have made generous contributions to the wide range of software distributed through that system in reliance on consistent application of that system; it is up to the author/donor to decide if he or she is willing to distribute software through any other system and a licensee cannot impose that choice. This section is intended to make thoroughly clear what is believed to be a consequence of the rest of this License. 8. If the distribution and/or use of the Program is restricted in certain countries either by patents or by copyrighted interfaces, the original copyright holder who places the Program under this License may add an explicit geographical distribution limitation excluding those countries, so that distribution is permitted only in or among countries not thus excluded. In such case, this License incorporates the limitation as if written in the body of this License. 9. The Free Software Foundation may publish revised and/or new versions of the General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. Each version is given a distinguishing version number. If the Program specifies a version number of this License which applies to it and "any later version", you have the option of following the terms and conditions either of that version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of this License, you may choose any version ever published by the Free Software Foundation. 10. If you wish to incorporate parts of the Program into other free programs whose distribution conditions are different, write to the author to ask for permission. For software which is copyrighted by the Free Software Foundation, write to the Free Software Foundation; we sometimes make exceptions for this. Our decision will be guided by the two goals of preserving the free status of all derivatives of our free software and of promoting the sharing and reuse of software generally. NO WARRANTY 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. END OF TERMS AND CONDITIONS How to Apply These Terms to Your New Programs If you develop a new program, and you want it to be of the greatest possible use to the public, the best way to achieve this is to make it free software which everyone can redistribute and change under these terms. To do so, attach the following notices to the program. It is safest to attach them to the start of each source file to most effectively convey the exclusion of warranty; and each file should have at least the "copyright" line and a pointer to where the full notice is found. <one line to give the program's name and a brief idea of what it does.> Copyright (C) <year> <name of author> This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. Also add information on how to contact you by electronic and paper mail. If the program is interactive, make it output a short notice like this when it starts in an interactive mode: Gnomovision version 69, Copyright (C) year name of author Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'. This is free software, and you are welcome to redistribute it under certain conditions; type `show c' for details. The hypothetical commands `show w' and `show c' should show the appropriate parts of the General Public License. Of course, the commands you use may be called something other than `show w' and `show c'; they could even be mouse-clicks or menu items--whatever suits your program. You should also get your employer (if you work as a programmer) or your school, if any, to sign a "copyright disclaimer" for the program, if necessary. Here is a sample; alter the names: Yoyodyne, Inc., hereby disclaims all copyright interest in the program `Gnomovision' (which makes passes at compilers) written by James Hacker. <signature of Ty Coon>, 1 April 1989 Ty Coon, President of Vice This General Public License does not permit incorporating your program into proprietary programs. If your program is a subroutine library, you may consider it more useful to permit linking proprietary applications with the library. If this is what you want to do, use the GNU Lesser General Public License instead of this License.
18,092
Markdown
52.214706
77
0.785541
AndrePatri/OmniRoboGym/omni_robo_gym/envs/isaac_env.py
# Copyright (C) 2023 Andrea Patrizi (AndrePatri, andreapatrizi1b6e6@gmail.com) # # This file is part of OmniRoboGym and distributed under the General Public License version 2 license. # # OmniRoboGym is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 2 of the License, or # (at your option) any later version. # # OmniRoboGym is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with OmniRoboGym. If not, see <http://www.gnu.org/licenses/>. # from omni.isaac.kit import SimulationApp import os import signal import carb import torch from abc import ABC, abstractmethod from typing import Union, Tuple, Dict from SharsorIPCpp.PySharsorIPC import VLevel from SharsorIPCpp.PySharsorIPC import LogType from SharsorIPCpp.PySharsorIPC import Journal import numpy as np # import gymnasium as gym # class IsaacSimEnv(gym.Env): class IsaacSimEnv(): def __init__( self, headless: bool, sim_device: int = 0, enable_livestream: bool = False, enable_viewport: bool = False, debug = False ) -> None: """ Initializes RL and task parameters. Args: headless (bool): Whether to run training headless. sim_device (int): GPU device ID for running physics simulation. Defaults to 0. enable_livestream (bool): Whether to enable running with livestream. enable_viewport (bool): Whether to enable rendering in headless mode. """ self.debug = debug experience = f'{os.environ["EXP_PATH"]}/omni.isaac.sim.python.omnirobogym.kit' # experience = "" if headless: info = f"Will run in headless mode." Journal.log(self.__class__.__name__, "__init__", info, LogType.STAT, throw_when_excep = True) if enable_livestream: experience = "" elif enable_viewport: exception = f"Using viewport is not supported yet." Journal.log(self.__class__.__name__, "__init__", exception, LogType.EXCEP, throw_when_excep = True) else: experience = f'{os.environ["EXP_PATH"]}/omni.isaac.sim.python.omnirobogym.headless.kit' # experience = f'{os.environ["EXP_PATH"]}/omni.isaac.sim.python.gym.headless.kit' self._simulation_app = SimulationApp({"headless": headless, "physics_gpu": sim_device}, experience=experience) info = "Using IsaacSim experience file @ " + experience Journal.log(self.__class__.__name__, "__init__", info, LogType.STAT, throw_when_excep = True) # carb.settings.get_settings().set("/persistent/omnihydra/useSceneGraphInstancing", True) if enable_livestream: info = "Livestream enabled" Journal.log(self.__class__.__name__, "__init__", info, LogType.STAT, throw_when_excep = True) from omni.isaac.core.utils.extensions import enable_extension self._simulation_app.set_setting("/app/livestream/enabled", True) self._simulation_app.set_setting("/app/window/drawMouse", True) self._simulation_app.set_setting("/app/livestream/proto", "ws") self._simulation_app.set_setting("/app/livestream/websocket/framerate_limit", 120) self._simulation_app.set_setting("/ngx/enabled", False) enable_extension("omni.kit.livestream.native") enable_extension("omni.services.streaming.manager") # handle ctrl+c event signal.signal(signal.SIGINT, self.signal_handler) self._render = not headless or enable_livestream or enable_viewport self._record = False self.step_counter = 0 # step counter self._world = None self.metadata = None self.gpu_pipeline_enabled = False def signal_handler(self, sig, frame): self.close() def set_task(self, task, backend="torch", sim_params=None, init_sim=True) -> None: """ Creates a World object and adds Task to World. Initializes and registers task to the environment interface. Triggers task start-up. Args: task (RLTask): The task to register to the env. backend (str): Backend to use for task. Can be "numpy" or "torch". Defaults to "numpy". sim_params (dict): Simulation parameters for physics settings. Defaults to None. init_sim (Optional[bool]): Automatically starts simulation. Defaults to True. """ from omni.isaac.core.world import World # parse device based on sim_param settings if sim_params and "sim_device" in sim_params: device = sim_params["sim_device"] else: device = "cpu" physics_device_id = carb.settings.get_settings().get_as_int("/physics/cudaDevice") gpu_id = 0 if physics_device_id < 0 else physics_device_id if sim_params and "use_gpu_pipeline" in sim_params: # GPU pipeline must use GPU simulation if sim_params["use_gpu_pipeline"]: device = "cuda:" + str(gpu_id) elif sim_params and "use_gpu" in sim_params: if sim_params["use_gpu"]: device = "cuda:" + str(gpu_id) self.gpu_pipeline_enabled = sim_params["use_gpu_pipeline"] info = "Using device: " + str(device) Journal.log(self.__class__.__name__, "__init__", info, LogType.STAT, throw_when_excep = True) if (sim_params is None): info = f"No sim params provided -> defaults will be used." Journal.log(self.__class__.__name__, "set_task", info, LogType.STAT, throw_when_excep = True) sim_params = {} # defaults for integration and rendering dt if not("physics_dt" in sim_params): sim_params["physics_dt"] = 1.0/60.0 dt = sim_params["physics_dt"] info = f"Using default integration_dt of {dt} s." Journal.log(self.__class__.__name__, "set_task", info, LogType.STAT, throw_when_excep = True) if not("rendering_dt" in sim_params): sim_params["rendering_dt"] = sim_params["physics_dt"] dt = sim_params["rendering_dt"] info = f"Using default rendering_dt of {dt} s." Journal.log(self.__class__.__name__, "set_task", info, LogType.STAT, throw_when_excep = True) self._world = World( stage_units_in_meters=1.0, physics_dt=sim_params["physics_dt"], rendering_dt=sim_params["rendering_dt"], # dt between rendering steps. Note: rendering means rendering a frame of # the current application and not only rendering a frame to the viewports/ cameras. # So UI elements of Isaac Sim will be refereshed with this dt as well if running non-headless backend=backend, device=str(device), physics_prim_path="/physicsScene", set_defaults = False, # set to True to use the defaults settings [physics_dt = 1.0/ 60.0, # stage units in meters = 0.01 (i.e in cms), rendering_dt = 1.0 / 60.0, gravity = -9.81 m / s # ccd_enabled, stabilization_enabled, gpu dynamics turned off, # broadcast type is MBP, solver type is TGS] sim_params=sim_params ) self._sim_params = sim_params big_info = "[World] Creating task " + task.name + "\n" + \ "use_gpu_pipeline: " + str(sim_params["use_gpu_pipeline"]) + "\n" + \ "device: " + str(device) + "\n" +\ "backend: " + str(backend) + "\n" +\ "integration_dt: " + str(sim_params["physics_dt"]) + "\n" + \ "rendering_dt: " + str(sim_params["rendering_dt"]) + "\n" \ Journal.log(self.__class__.__name__, "set_task", big_info, LogType.STAT, throw_when_excep = True) ## we get the physics context to expose additional low-level ## # settings of the simulation self._physics_context = self._world.get_physics_context() self._physics_scene_path = self._physics_context.prim_path self._physics_context.enable_gpu_dynamics(True) self._physics_context.enable_stablization(True) self._physics_scene_prim = self._physics_context.get_current_physics_scene_prim() self._solver_type = self._physics_context.get_solver_type() # we set parameters, depending on sim_params dict if "gpu_max_rigid_contact_count" in sim_params: self._physics_context.set_gpu_max_rigid_contact_count(sim_params["gpu_max_rigid_contact_count"]) if "gpu_max_rigid_patch_count" in sim_params: self._physics_context.set_gpu_max_rigid_patch_count(sim_params["gpu_max_rigid_patch_count"]) if "gpu_found_lost_pairs_capacity" in sim_params: self._physics_context.set_gpu_found_lost_pairs_capacity(sim_params["gpu_found_lost_pairs_capacity"]) if "gpu_found_lost_aggregate_pairs_capacity" in sim_params: self._physics_context.set_gpu_found_lost_aggregate_pairs_capacity(sim_params["gpu_found_lost_aggregate_pairs_capacity"]) if "gpu_total_aggregate_pairs_capacity" in sim_params: self._physics_context.set_gpu_total_aggregate_pairs_capacity(sim_params["gpu_total_aggregate_pairs_capacity"]) if "gpu_max_soft_body_contacts" in sim_params: self._physics_context.set_gpu_max_soft_body_contacts(sim_params["gpu_max_soft_body_contacts"]) if "gpu_max_particle_contacts" in sim_params: self._physics_context.set_gpu_max_particle_contacts(sim_params["gpu_max_particle_contacts"]) if "gpu_heap_capacity" in sim_params: self._physics_context.set_gpu_heap_capacity(sim_params["gpu_heap_capacity"]) if "gpu_temp_buffer_capacity" in sim_params: self._physics_context.set_gpu_temp_buffer_capacity(sim_params["gpu_temp_buffer_capacity"]) if "gpu_max_num_partitions" in sim_params: self._physics_context.set_gpu_max_num_partitions(sim_params["gpu_max_num_partitions"]) # overwriting defaults # self._physics_context.set_gpu_max_rigid_contact_count(2 * self._physics_context.get_gpu_max_rigid_contact_count()) # self._physics_context.set_gpu_max_rigid_patch_count(2 * self._physics_context.get_gpu_max_rigid_patch_count()) # self._physics_context.set_gpu_found_lost_pairs_capacity(2 * self._physics_context.get_gpu_found_lost_pairs_capacity()) # self._physics_context.set_gpu_found_lost_aggregate_pairs_capacity(20 * self._physics_context.get_gpu_found_lost_aggregate_pairs_capacity()) # self._physics_context.set_gpu_total_aggregate_pairs_capacity(20 * self._physics_context.get_gpu_total_aggregate_pairs_capacity()) # self._physics_context.set_gpu_heap_capacity(2 * self._physics_context.get_gpu_heap_capacity()) # self._physics_context.set_gpu_temp_buffer_capacity(20 * self._physics_context.get_gpu_heap_capacity()) # self._physics_context.set_gpu_max_num_partitions(20 * self._physics_context.get_gpu_temp_buffer_capacity()) # GPU buffers self._gpu_max_rigid_contact_count = self._physics_context.get_gpu_max_rigid_contact_count() self._gpu_max_rigid_patch_count = self._physics_context.get_gpu_max_rigid_patch_count() self._gpu_found_lost_pairs_capacity = self._physics_context.get_gpu_found_lost_pairs_capacity() self._gpu_found_lost_aggregate_pairs_capacity = self._physics_context.get_gpu_found_lost_aggregate_pairs_capacity() self._gpu_total_aggregate_pairs_capacity = self._physics_context.get_gpu_total_aggregate_pairs_capacity() self._gpu_max_soft_body_contacts = self._physics_context.get_gpu_max_soft_body_contacts() self._gpu_max_particle_contacts = self._physics_context.get_gpu_max_particle_contacts() self._gpu_heap_capacity = self._physics_context.get_gpu_heap_capacity() self._gpu_temp_buffer_capacity = self._physics_context.get_gpu_temp_buffer_capacity() # self._gpu_max_num_partitions = physics_context.get_gpu_max_num_partitions() # BROKEN->method does not exist big_info2 = "[physics context]:" + "\n" + \ "gpu_max_rigid_contact_count: " + str(self._gpu_max_rigid_contact_count) + "\n" + \ "gpu_max_rigid_patch_count: " + str(self._gpu_max_rigid_patch_count) + "\n" + \ "gpu_found_lost_pairs_capacity: " + str(self._gpu_found_lost_pairs_capacity) + "\n" + \ "gpu_found_lost_aggregate_pairs_capacity: " + str(self._gpu_found_lost_aggregate_pairs_capacity) + "\n" + \ "gpu_total_aggregate_pairs_capacity: " + str(self._gpu_total_aggregate_pairs_capacity) + "\n" + \ "gpu_max_soft_body_contacts: " + str(self._gpu_max_soft_body_contacts) + "\n" + \ "gpu_max_particle_contacts: " + str(self._gpu_max_particle_contacts) + "\n" + \ "gpu_heap_capacity: " + str(self._gpu_heap_capacity) + "\n" + \ "gpu_temp_buffer_capacity: " + str(self._gpu_temp_buffer_capacity) Journal.log(self.__class__.__name__, "set_task", big_info2, LogType.STAT, throw_when_excep = True) self._scene = self._world.scene from omni.usd import get_context self._stage = get_context().get_stage() from pxr import UsdLux, Sdf, Gf, UsdPhysics, PhysicsSchemaTools # add lighting distantLight = UsdLux.DistantLight.Define(self._stage, Sdf.Path("/World/DistantLight")) distantLight.CreateIntensityAttr(500) self._world._current_tasks = dict() # resets registered tasks self._task = task self._task.set_world(self._world) self._task.configure_scene() self._world.add_task(self._task) self._num_envs = self._task.num_envs if sim_params and "enable_viewport" in sim_params: self._render = sim_params["enable_viewport"] Journal.log(self.__class__.__name__, "set_task", "[render]: " + str(self._render), LogType.STAT, throw_when_excep = True) # if init_sim: # self._world.reset() # after the first reset we get get all quantities # # from the scene # self._task.post_initialization_steps() # performs initializations # # steps after the fisrt world reset was called def render(self, mode="human") -> None: """ Step the renderer. Args: mode (str): Select mode of rendering based on OpenAI environments. """ if mode == "human": self._world.render() return None elif mode == "rgb_array": # check if viewport is enabled -- if not, then complain because we won't get any data if not self._render or not self._record: exception = f"Cannot render '{mode}' when rendering is not enabled. Please check the provided" + \ "arguments to the environment class at initialization." Journal.log(self.__class__.__name__, "__init__", exception, LogType.EXCEP, throw_when_excep = True) # obtain the rgb data rgb_data = self._rgb_annotator.get_data() # convert to numpy array rgb_data = np.frombuffer(rgb_data, dtype=np.uint8).reshape(*rgb_data.shape) # return the rgb data return rgb_data[:, :, :3] else: # gym.Env.render(self, mode=mode) return None def create_viewport_render_product(self, resolution=(1280, 720)): """Create a render product of the viewport for rendering.""" try: import omni.replicator.core as rep # create render product self._render_product = rep.create.render_product("/OmniverseKit_Persp", resolution) # create rgb annotator -- used to read data from the render product self._rgb_annotator = rep.AnnotatorRegistry.get_annotator("rgb", device="cpu") self._rgb_annotator.attach([self._render_product]) self._record = True except Exception as e: carb.log_info("omni.replicator.core could not be imported. Skipping creation of render product.") carb.log_info(str(e)) def close(self) -> None: """ Closes simulation. """ if self._simulation_app.is_running(): self._simulation_app.close() return @abstractmethod def step(self, actions = None): """ Basic implementation for stepping simulation""" pass @abstractmethod def reset(self): """ Usually resets the task and updates observations + # other custom operations. """ pass @property def num_envs(self): """ Retrieves number of environments. Returns: num_envs(int): Number of environments. """ return self._num_envs @property def simulation_app(self): """Retrieves the SimulationApp object. Returns: simulation_app(SimulationApp): SimulationApp. """ return self._simulation_app @property def get_world(self): """Retrieves the World object for simulation. Returns: world(World): Simulation World. """ return self._world @property def task(self): """Retrieves the task. Returns: task(BaseTask): Task. """ return self._task @property def render_enabled(self): """Whether rendering is enabled. Returns: render(bool): is render enabled. """ return self._render
19,383
Python
39.299376
149
0.579735
AndrePatri/OmniRoboGym/omni_robo_gym/tasks/isaac_task.py
# Copyright (C) 2023 Andrea Patrizi (AndrePatri, andreapatrizi1b6e6@gmail.com) # # This file is part of OmniRoboGym and distributed under the General Public License version 2 license. # # OmniRoboGym is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 2 of the License, or # (at your option) any later version. # # OmniRoboGym is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with OmniRoboGym. If not, see <http://www.gnu.org/licenses/>. # from omni.isaac.core.tasks.base_task import BaseTask from omni.isaac.core.articulations import ArticulationView from omni.isaac.core.utils.viewports import set_camera_view from omni.isaac.core.world import World import omni.kit import numpy as np import torch from omni.importer.urdf import _urdf from omni.isaac.core.utils.prims import move_prim from omni.isaac.cloner import GridCloner import omni.isaac.core.utils.prims as prim_utils # from omni.isaac.sensor import ContactSensor from omni.isaac.core.utils.stage import get_current_stage from omni.isaac.core.scenes.scene import Scene from omni_robo_gym.utils.jnt_imp_cntrl import OmniJntImpCntrl from omni_robo_gym.utils.homing import OmniRobotHomer from omni_robo_gym.utils.contact_sensor import OmniContactSensors from omni_robo_gym.utils.terrains import RlTerrains from omni_robo_gym.utils.math_utils import quat_to_omega, quaternion_difference, rel_vel from abc import abstractmethod from typing import List, Dict from SharsorIPCpp.PySharsorIPC import LogType from SharsorIPCpp.PySharsorIPC import Journal class IsaacTask(BaseTask): def __init__(self, name: str, integration_dt: float, robot_names: List[str], robot_pkg_names: List[str] = None, contact_prims: Dict[str, List] = None, contact_offsets: Dict[str, Dict[str, np.ndarray]] = None, sensor_radii: Dict[str, Dict[str, np.ndarray]] = None, num_envs = 1, device = "cuda", cloning_offset: np.array = None, fix_base: List[bool] = None, self_collide: List[bool] = None, merge_fixed: List[bool] = None, replicate_physics: bool = True, solver_position_iteration_count: int = 4, solver_velocity_iteration_count: int = 1, solver_stabilization_thresh: float = 1e-5, offset=None, env_spacing = 5.0, spawning_radius = 1.0, use_flat_ground = True, default_jnt_stiffness = 300.0, default_jnt_damping = 20.0, default_wheel_stiffness = 0.0, default_wheel_damping = 10.0, override_art_controller = False, dtype = torch.float64, debug_enabled: bool = False, verbose = False, use_diff_velocities = False) -> None: self.torch_dtype = dtype self._debug_enabled = debug_enabled self._verbose = verbose self.use_diff_velocities = use_diff_velocities self.num_envs = num_envs self._override_art_controller = override_art_controller self._integration_dt = integration_dt # just used for contact reporting self.torch_device = torch.device(device) # defaults to "cuda" ("cpu" also valid) self.using_gpu = False if self.torch_device == torch.device("cuda"): self.using_gpu = True self.robot_names = robot_names # these are (potentially) custom names to self.robot_pkg_names = robot_pkg_names # will be used to search for URDF and SRDF packages self.scene_setup_completed = False if self.robot_pkg_names is None: self.robot_pkg_names = self.robot_names # if not provided, robot_names are the same as robot_pkg_names else: # check dimension consistency if len(robot_names) != len(robot_pkg_names): exception = "The provided robot names list must match the length " + \ "of the provided robot package names" raise Exception(exception) if fix_base is None: self._fix_base = [False] * len(self.robot_names) else: # check dimension consistency if len(fix_base) != len(robot_pkg_names): exception = "The provided fix_base list of boolean must match the length " + \ "of the provided robot package names" raise Exception(exception) self._fix_base = fix_base if self_collide is None: self._self_collide = [False] * len(self.robot_names) else: # check dimension consistency if len(self_collide) != len(robot_pkg_names): exception = "The provided self_collide list of boolean must match the length " + \ "of the provided robot package names" raise Exception(exception) self._self_collide = self_collide if merge_fixed is None: self._merge_fixed = [False] * len(self.robot_names) else: # check dimension consistency if len(merge_fixed) != len(robot_pkg_names): exception = "The provided merge_fixed list of boolean must match the length " + \ "of the provided robot package names" raise Exception(exception) self._merge_fixed = merge_fixed self._urdf_paths = {} self._srdf_paths = {} self._robots_art_views = {} self._robots_articulations = {} self._robots_geom_prim_views = {} self._solver_position_iteration_count = solver_position_iteration_count # solver position iteration count # -> higher number makes simulation more accurate self._solver_velocity_iteration_count = solver_velocity_iteration_count self._solver_stabilization_thresh = solver_stabilization_thresh # threshold for kin. energy below which an articulatiion # "goes to sleep", i.e. it's not simulated anymore until some action wakes him up # potentially, each robot could have its own setting for the solver (not supported yet) self._solver_position_iteration_counts = {} self._solver_velocity_iteration_counts = {} self._solver_stabilization_threshs = {} self.robot_bodynames = {} self.robot_n_links = {} self.robot_n_dofs = {} self.robot_dof_names = {} self._root_p = {} self._root_q = {} self._jnts_q = {} self._root_p_prev = {} # used for num differentiation self._root_q_prev = {} # used for num differentiation self._jnts_q_prev = {} # used for num differentiation self._root_p_default = {} self._root_q_default = {} self._jnts_q_default = {} self._root_v = {} self._root_v_default = {} self._root_omega = {} self._root_omega_default = {} self._jnts_v = {} self._jnts_v_default = {} self._jnts_eff_default = {} self._root_pos_offsets = {} self._root_q_offsets = {} self.distr_offset = {} # decribed how robots within each env are distributed self.jnt_imp_controllers = {} self.homers = {} # default jnt impedance settings self.default_jnt_stiffness = default_jnt_stiffness self.default_jnt_damping = default_jnt_damping self.default_wheel_stiffness = default_wheel_stiffness self.default_wheel_damping = default_wheel_damping self.use_flat_ground = use_flat_ground self.spawning_radius = spawning_radius # [m] -> default distance between roots of robots in a single # environment self._calc_robot_distrib() # computes the offsets of robots withing each env. self._env_ns = "/World/envs" self._env_spacing = env_spacing # [m] self._template_env_ns = self._env_ns + "/env_0" self._cloner = GridCloner(spacing=self._env_spacing) self._cloner.define_base_env(self._env_ns) prim_utils.define_prim(self._template_env_ns) self._envs_prim_paths = self._cloner.generate_paths(self._env_ns + "/env", self.num_envs) self._cloning_offset = cloning_offset if self._cloning_offset is None: self._cloning_offset = np.array([[0, 0, 0]] * self.num_envs) self._replicate_physics = replicate_physics self._world_initialized = False self._ground_plane_prim_path = "/World/terrain" self._world = None self._world_scene = None self._world_physics_context = None self.omni_contact_sensors = {} self.contact_prims = contact_prims for robot_name in contact_prims: self.omni_contact_sensors[robot_name] = OmniContactSensors( name = robot_name, n_envs = self.num_envs, contact_prims = contact_prims, contact_offsets = contact_offsets, sensor_radii = sensor_radii, device = self.torch_device, dtype = self.torch_dtype, enable_debug=self._debug_enabled) # trigger __init__ of parent class BaseTask.__init__(self, name=name, offset=offset) self.xrdf_cmd_vals = [] # by default empty, needs to be overriden by # child class def update_jnt_imp_control_gains(self, robot_name: str, jnt_stiffness: float, jnt_damping: float, wheel_stiffness: float, wheel_damping: float, env_indxs: torch.Tensor = None): # updates joint imp. controller with new impedance values if self._debug_enabled: for_robots = "" if env_indxs is not None: if not isinstance(env_indxs, torch.Tensor): msg = "Provided env_indxs should be a torch tensor of indexes!" Journal.log(self.__class__.__name__, "update_jnt_imp_control_gains", msg, LogType.EXCEP, throw_when_excep = True) if self.using_gpu: if not env_indxs.device.type == "cuda": error = "Provided env_indxs should be on GPU!" Journal.log(self.__class__.__name__, "_step_jnt_imp_control", error, LogType.EXCEP, True) else: if not env_indxs.device.type == "cpu": error = "Provided env_indxs should be on CPU!" Journal.log(self.__class__.__name__, "_step_jnt_imp_control", error, LogType.EXCEP, True) for_robots = f"for robot {robot_name}, indexes: " + str(env_indxs.tolist()) if self._verbose: Journal.log(self.__class__.__name__, "update_jnt_imp_control_gains", f"updating joint impedances " + for_robots, LogType.STAT, throw_when_excep = True) # set jnt imp gains for the whole robot if env_indxs is None: gains_pos = torch.full((self.num_envs, \ self.jnt_imp_controllers[robot_name].n_dofs), jnt_stiffness, device = self.torch_device, dtype=self.torch_dtype) gains_vel = torch.full((self.num_envs, \ self.jnt_imp_controllers[robot_name].n_dofs), jnt_damping, device = self.torch_device, dtype=self.torch_dtype) else: gains_pos = torch.full((env_indxs.shape[0], \ self.jnt_imp_controllers[robot_name].n_dofs), jnt_stiffness, device = self.torch_device, dtype=self.torch_dtype) gains_vel = torch.full((env_indxs.shape[0], \ self.jnt_imp_controllers[robot_name].n_dofs), jnt_damping, device = self.torch_device, dtype=self.torch_dtype) self.jnt_imp_controllers[robot_name].set_gains( pos_gains = gains_pos, vel_gains = gains_vel, robot_indxs = env_indxs) # in case of wheels wheels_indxs = self.jnt_imp_controllers[robot_name].get_jnt_idxs_matching( name_pattern="wheel") if wheels_indxs is not None: if env_indxs is None: # wheels are velocity-controlled wheels_pos_gains = torch.full((self.num_envs, len(wheels_indxs)), wheel_stiffness, device = self.torch_device, dtype=self.torch_dtype) wheels_vel_gains = torch.full((self.num_envs, len(wheels_indxs)), wheel_damping, device = self.torch_device, dtype=self.torch_dtype) else: # wheels are velocity-controlled wheels_pos_gains = torch.full((env_indxs.shape[0], len(wheels_indxs)), wheel_stiffness, device = self.torch_device, dtype=self.torch_dtype) wheels_vel_gains = torch.full((env_indxs.shape[0], len(wheels_indxs)), wheel_damping, device = self.torch_device, dtype=self.torch_dtype) self.jnt_imp_controllers[robot_name].set_gains( pos_gains = wheels_pos_gains, vel_gains = wheels_vel_gains, jnt_indxs=wheels_indxs, robot_indxs = env_indxs) def update_root_offsets(self, robot_name: str, env_indxs: torch.Tensor = None): if self._debug_enabled: for_robots = "" if env_indxs is not None: if not isinstance(env_indxs, torch.Tensor): msg = "Provided env_indxs should be a torch tensor of indexes!" Journal.log(self.__class__.__name__, "update_root_offsets", msg, LogType.EXCEP, throw_when_excep = True) if self.using_gpu: if not env_indxs.device.type == "cuda": error = "Provided env_indxs should be on GPU!" Journal.log(self.__class__.__name__, "_step_jnt_imp_control", error, LogType.EXCEP, True) else: if not env_indxs.device.type == "cpu": error = "Provided env_indxs should be on CPU!" Journal.log(self.__class__.__name__, "_step_jnt_imp_control", error, LogType.EXCEP, True) for_robots = f"for robot {robot_name}, indexes: " + str(env_indxs.tolist()) if self._verbose: Journal.log(self.__class__.__name__, "update_root_offsets", f"updating root offsets " + for_robots, LogType.STAT, throw_when_excep = True) # only planar position used if env_indxs is None: self._root_pos_offsets[robot_name][:, 0:2] = self._root_p[robot_name][:, 0:2] self._root_q_offsets[robot_name][:, :] = self._root_q[robot_name] else: self._root_pos_offsets[robot_name][env_indxs, 0:2] = self._root_p[robot_name][env_indxs, 0:2] self._root_q_offsets[robot_name][env_indxs, :] = self._root_q[robot_name][env_indxs, :] def synch_default_root_states(self, robot_name: str = None, env_indxs: torch.Tensor = None): if self._debug_enabled: for_robots = "" if env_indxs is not None: if not isinstance(env_indxs, torch.Tensor): msg = "Provided env_indxs should be a torch tensor of indexes!" Journal.log(self.__class__.__name__, "synch_default_root_states", msg, LogType.EXCEP, throw_when_excep = True) if self.using_gpu: if not env_indxs.device.type == "cuda": error = "Provided env_indxs should be on GPU!" Journal.log(self.__class__.__name__, "_step_jnt_imp_control", error, LogType.EXCEP, True) else: if not env_indxs.device.type == "cpu": error = "Provided env_indxs should be on CPU!" Journal.log(self.__class__.__name__, "_step_jnt_imp_control", error, LogType.EXCEP, True) for_robots = f"for robot {robot_name}, indexes: " + str(env_indxs.tolist()) if self._verbose: Journal.log(self.__class__.__name__, "synch_default_root_states", f"updating default root states " + for_robots, LogType.STAT, throw_when_excep = True) if env_indxs is None: self._root_p_default[robot_name][:, :] = self._root_p[robot_name] self._root_q_default[robot_name][:, :] = self._root_q[robot_name] else: self._root_p_default[robot_name][env_indxs, :] = self._root_p[robot_name][env_indxs, :] self._root_q_default[robot_name][env_indxs, :] = self._root_q[robot_name][env_indxs, :] def post_initialization_steps(self): print("Performing post-initialization steps") self._world_initialized = True # used by other methods which nees to run # only when the world was initialized # populates robot info fields self._fill_robot_info_from_world() # initializes homing managers self._init_homing_managers() # initializes robot state data self._init_robots_state() # default robot state self._set_robots_default_jnt_config() self._set_robots_root_default_config() # initializes joint impedance controllers self._init_jnt_imp_control() # update solver options self._update_art_solver_options() self.reset() self._custom_post_init() self._get_solver_info() # get again solver option before printing everything self._print_envs_info() # debug prints def apply_collision_filters(self, physicscene_path: str, coll_root_path: str): self._cloner.filter_collisions(physicsscene_path = physicscene_path, collision_root_path = coll_root_path, prim_paths=self._envs_prim_paths, global_paths=[self._ground_plane_prim_path] # can collide with these prims ) def reset_jnt_imp_control(self, robot_name: str, env_indxs: torch.Tensor = None): if self._debug_enabled: for_robots = "" if env_indxs is not None: if not isinstance(env_indxs, torch.Tensor): Journal.log(self.__class__.__name__, "reset_jnt_imp_control", "Provided env_indxs should be a torch tensor of indexes!", LogType.EXCEP, throw_when_excep = True) if self.using_gpu: if not env_indxs.device.type == "cuda": error = "Provided env_indxs should be on GPU!" Journal.log(self.__class__.__name__, "_step_jnt_imp_control", error, LogType.EXCEP, True) else: if not env_indxs.device.type == "cpu": error = "Provided env_indxs should be on CPU!" Journal.log(self.__class__.__name__, "_step_jnt_imp_control", error, LogType.EXCEP, True) for_robots = f"for robot {robot_name}, indexes: " + str(env_indxs) if self._verbose: Journal.log(self.__class__.__name__, "reset_jnt_imp_control", f"resetting joint impedances " + for_robots, LogType.STAT, throw_when_excep = True) # resets all internal data, refs to defaults self.jnt_imp_controllers[robot_name].reset(robot_indxs = env_indxs) # restore current state if env_indxs is None: self.jnt_imp_controllers[robot_name].update_state(pos = self._jnts_q[robot_name][:, :], vel = self._jnts_v[robot_name][:, :], eff = None, robot_indxs = None) else: self.jnt_imp_controllers[robot_name].update_state(pos = self._jnts_q[robot_name][env_indxs, :], vel = self._jnts_v[robot_name][env_indxs, :], eff = None, robot_indxs = env_indxs) # restore default gains self.update_jnt_imp_control_gains(robot_name = robot_name, jnt_stiffness = self.default_jnt_stiffness, jnt_damping = self.default_jnt_damping, wheel_stiffness = self.default_wheel_stiffness, wheel_damping = self.default_wheel_damping, env_indxs = env_indxs) #restore jnt imp refs to homing if env_indxs is None: self.jnt_imp_controllers[robot_name].set_refs(pos_ref=self.homers[robot_name].get_homing()[:, :], robot_indxs = None) else: self.jnt_imp_controllers[robot_name].set_refs(pos_ref=self.homers[robot_name].get_homing()[env_indxs, :], robot_indxs = env_indxs) # actually applies reset commands to the articulation # self.jnt_imp_controllers[robot_name].apply_cmds() def set_world(self, world: World): if not isinstance(world, World): Journal.log(self.__class__.__name__, "configure_scene", "world should be an instance of omni.isaac.core.world.World!", LogType.EXCEP, throw_when_excep = True) self._world = world self._world_scene = self._world.scene self._world_physics_context = self._world.get_physics_context() def set_up_scene(self, scene: Scene): super().set_up_scene(scene) def configure_scene(self) -> None: # this is called automatically by the environment BEFORE # initializing the simulation if self._world is None: Journal.log(self.__class__.__name__, "configure_scene", "Did you call the set_world() method??", LogType.EXCEP, throw_when_excep = True) if not self.scene_setup_completed: for i in range(len(self.robot_names)): robot_name = self.robot_names[i] robot_pkg_name = self.robot_pkg_names[i] fix_base = self._fix_base[i] self_collide = self._self_collide[i] merge_fixed = self._merge_fixed[i] self._generate_rob_descriptions(robot_name=robot_name, robot_pkg_name=robot_pkg_name) self._import_urdf(robot_name, fix_base=fix_base, self_collide=self_collide, merge_fixed=merge_fixed) Journal.log(self.__class__.__name__, "set_up_scene", "cloning environments...", LogType.STAT, throw_when_excep = True) self._cloner.clone( source_prim_path=self._template_env_ns, prim_paths=self._envs_prim_paths, replicate_physics=self._replicate_physics, position_offsets = self._cloning_offset ) # we can clone the environment in which all the robos are Journal.log(self.__class__.__name__, "set_up_scene", "finishing scene setup...", LogType.STAT, throw_when_excep = True) for i in range(len(self.robot_names)): robot_name = self.robot_names[i] self._robots_art_views[robot_name] = ArticulationView(name = robot_name + "ArtView", prim_paths_expr = self._env_ns + "/env_.*"+ "/" + robot_name + "/base_link", reset_xform_properties=False) self._robots_articulations[robot_name] = self._world_scene.add(self._robots_art_views[robot_name]) # self._robots_geom_prim_views[robot_name] = GeometryPrimView(name = robot_name + "GeomView", # prim_paths_expr = self._env_ns + "/env*"+ "/" + robot_name, # # prepare_contact_sensors = True # ) # self._robots_geom_prim_views[robot_name].apply_collision_apis() # to be able to apply contact sensors if self.use_flat_ground: self._world_scene.add_default_ground_plane(z_position=0, name="terrain", prim_path= self._ground_plane_prim_path, static_friction=1.0, dynamic_friction=1.0, restitution=0.2) else: self.terrains = RlTerrains(get_current_stage()) self.terrains.get_obstacles_terrain(terrain_size=40, num_obs=100, max_height=0.4, min_size=0.5, max_size=5.0) # delete_prim(self._ground_plane_prim_path + "/SphereLight") # we remove the default spherical light # set default camera viewport position and target self._set_initial_camera_params() self.apply_collision_filters(self._world_physics_context.prim_path, "/World/collisions") # init contact sensors self._init_contact_sensors() # IMPORTANT: this has to be called # after calling the clone() method and initializing articulation views!!! self._world.reset() # reset world to make art views available self.post_initialization_steps() self.scene_setup_completed = True def post_reset(self): pass def reset(self, env_indxs: torch.Tensor = None, robot_names: List[str] =None): # we first reset all target articulations to their default state rob_names = robot_names if (robot_names is not None) else self.robot_names # resets the state of target robot and env to the defaults self.reset_state(env_indxs=env_indxs, robot_names=rob_names) # and jnt imp. controllers for i in range(len(rob_names)): self.reset_jnt_imp_control(robot_name=rob_names[i], env_indxs=env_indxs) def reset_state(self, env_indxs: torch.Tensor = None, robot_names: List[str] =None): rob_names = robot_names if (robot_names is not None) else self.robot_names if env_indxs is not None: if self._debug_enabled: if self.using_gpu: if not env_indxs.device.type == "cuda": error = "Provided env_indxs should be on GPU!" Journal.log(self.__class__.__name__, "_step_jnt_imp_control", error, LogType.EXCEP, True) else: if not env_indxs.device.type == "cpu": error = "Provided env_indxs should be on CPU!" Journal.log(self.__class__.__name__, "_step_jnt_imp_control", error, LogType.EXCEP, True) for i in range(len(rob_names)): robot_name = rob_names[i] # root q self._robots_art_views[robot_name].set_world_poses(positions = self._root_p_default[robot_name][env_indxs, :], orientations=self._root_q_default[robot_name][env_indxs, :], indices = env_indxs) # jnts q self._robots_art_views[robot_name].set_joint_positions(positions = self._jnts_q_default[robot_name][env_indxs, :], indices = env_indxs) # root v and omega self._robots_art_views[robot_name].set_joint_velocities(velocities = self._jnts_v_default[robot_name][env_indxs, :], indices = env_indxs) # jnts v concatenated_vel = torch.cat((self._root_v_default[robot_name][env_indxs, :], self._root_omega_default[robot_name][env_indxs, :]), dim=1) self._robots_art_views[robot_name].set_velocities(velocities = concatenated_vel, indices = env_indxs) # jnts eff self._robots_art_views[robot_name].set_joint_efforts(efforts = self._jnts_eff_default[robot_name][env_indxs, :], indices = env_indxs) else: for i in range(len(rob_names)): robot_name = rob_names[i] # root q self._robots_art_views[robot_name].set_world_poses(positions = self._root_p_default[robot_name][:, :], orientations=self._root_q_default[robot_name][:, :], indices = None) # jnts q self._robots_art_views[robot_name].set_joint_positions(positions = self._jnts_q_default[robot_name][:, :], indices = None) # root v and omega self._robots_art_views[robot_name].set_joint_velocities(velocities = self._jnts_v_default[robot_name][:, :], indices = None) # jnts v concatenated_vel = torch.cat((self._root_v_default[robot_name][:, :], self._root_omega_default[robot_name][:, :]), dim=1) self._robots_art_views[robot_name].set_velocities(velocities = concatenated_vel, indices = None) # jnts eff self._robots_art_views[robot_name].set_joint_efforts(efforts = self._jnts_eff_default[robot_name][:, :], indices = None) # we update the robots state self.get_states(env_indxs=env_indxs, robot_names=rob_names) def close(self): pass def root_pos_offsets(self, robot_name: str, env_idxs: torch.Tensor = None): if env_idxs is None: return self._root_pos_offsets[robot_name] else: return self._root_pos_offsets[robot_name][env_idxs, :] def root_q_offsets(self, robot_name: str, env_idxs: torch.Tensor = None): if env_idxs is None: return self._root_q_offsets[robot_name] else: return self._root_q_offsets[robot_name][env_idxs, :] def root_p(self, robot_name: str, env_idxs: torch.Tensor = None): if env_idxs is None: return self._root_p[robot_name] else: return self._root_p[robot_name][env_idxs, :] def root_p_rel(self, robot_name: str, env_idxs: torch.Tensor = None): rel_pos = torch.sub(self.root_p(robot_name=robot_name, env_idxs=env_idxs), self.root_pos_offsets(robot_name=robot_name, env_idxs=env_idxs)) return rel_pos def root_q(self, robot_name: str, env_idxs: torch.Tensor = None): if env_idxs is None: return self._root_q[robot_name] else: return self._root_q[robot_name][env_idxs, :] def root_q_rel(self, robot_name: str, env_idxs: torch.Tensor = None): rel_q = quaternion_difference(self.root_q_offsets(robot_name=robot_name, env_idxs=env_idxs), self.root_q(robot_name=robot_name, env_idxs=env_idxs)) return rel_q def root_v(self, robot_name: str, env_idxs: torch.Tensor = None): if env_idxs is None: return self._root_v[robot_name] else: return self._root_v[robot_name][env_idxs, :] def root_v_rel(self, robot_name: str, env_idxs: torch.Tensor = None): v_rel = rel_vel(offset_q0_q1=self.root_q_offsets(robot_name=robot_name, env_idxs=env_idxs), v0=self.root_v(robot_name=robot_name, env_idxs=env_idxs)) return v_rel def root_omega(self, robot_name: str, env_idxs: torch.Tensor = None): if env_idxs is None: return self._root_omega[robot_name] else: return self._root_omega[robot_name][env_idxs, :] def root_omega_rel(self, robot_name: str, env_idxs: torch.Tensor = None): omega_rel = rel_vel(offset_q0_q1=self.root_q_offsets(robot_name=robot_name, env_idxs=env_idxs), v0=self.root_omega(robot_name=robot_name, env_idxs=env_idxs)) return omega_rel def jnts_q(self, robot_name: str, env_idxs: torch.Tensor = None): if env_idxs is None: return self._jnts_q[robot_name] else: return self._jnts_q[robot_name][env_idxs, :] def jnts_v(self, robot_name: str, env_idxs: torch.Tensor = None): if env_idxs is None: return self._jnts_v[robot_name] else: return self._jnts_v[robot_name][env_idxs, :] def integration_dt(self): return self._integration_dt @abstractmethod def _xrdf_cmds(self) -> Dict: # this has to be implemented by the user depending on the arguments # the xacro description of the robot takes. The output is a list # of xacro commands. # Example implementation: # def _xrdf_cmds(): # cmds = {} # cmds{self.robot_names[0]} = [] # xrdf_cmd_vals = [True, True, True, False, False, True] # legs = "true" if xrdf_cmd_vals[0] else "false" # big_wheel = "true" if xrdf_cmd_vals[1] else "false" # upper_body ="true" if xrdf_cmd_vals[2] else "false" # velodyne = "true" if xrdf_cmd_vals[3] else "false" # realsense = "true" if xrdf_cmd_vals[4] else "false" # floating_joint = "true" if xrdf_cmd_vals[5] else "false" # horizon needs a floating joint # cmds.append("legs:=" + legs) # cmds.append("big_wheel:=" + big_wheel) # cmds.append("upper_body:=" + upper_body) # cmds.append("velodyne:=" + velodyne) # cmds.append("realsense:=" + realsense) # cmds.append("floating_joint:=" + floating_joint) # return cmds pass @abstractmethod def pre_physics_step(self, actions, robot_name: str) -> None: # apply actions to simulated robot # to be overriden by child class depending # on specific needs pass def _generate_srdf(self, robot_name: str, robot_pkg_name: str): # we generate the URDF where the description package is located import rospkg rospackage = rospkg.RosPack() descr_path = rospackage.get_path(robot_pkg_name + "_srdf") srdf_path = descr_path + "/srdf" xacro_name = robot_pkg_name xacro_path = srdf_path + "/" + xacro_name + ".srdf.xacro" self._srdf_paths[robot_name] = self._descr_dump_path + "/" + robot_name + ".srdf" if self._xrdf_cmds() is not None: cmds = self._xrdf_cmds()[robot_name] if cmds is None: xacro_cmd = ["xacro"] + [xacro_path] + ["-o"] + [self._srdf_paths[robot_name]] else: xacro_cmd = ["xacro"] + [xacro_path] + cmds + ["-o"] + [self._srdf_paths[robot_name]] if self._xrdf_cmds() is None: xacro_cmd = ["xacro"] + [xacro_path] + ["-o"] + [self._srdf_paths[robot_name]] import subprocess try: xacro_gen = subprocess.check_call(xacro_cmd) except: Journal.log(self.__class__.__name__, "_generate_urdf", "failed to generate " + robot_name + "\'S SRDF!!!", LogType.EXCEP, throw_when_excep = True) def _generate_urdf(self, robot_name: str, robot_pkg_name: str): # we generate the URDF where the description package is located import rospkg rospackage = rospkg.RosPack() descr_path = rospackage.get_path(robot_pkg_name + "_urdf") urdf_path = descr_path + "/urdf" xacro_name = robot_pkg_name xacro_path = urdf_path + "/" + xacro_name + ".urdf.xacro" self._urdf_paths[robot_name] = self._descr_dump_path + "/" + robot_name + ".urdf" if self._xrdf_cmds() is not None: cmds = self._xrdf_cmds()[robot_name] if cmds is None: xacro_cmd = ["xacro"] + [xacro_path] + ["-o"] + [self._urdf_paths[robot_name]] else: xacro_cmd = ["xacro"] + [xacro_path] + cmds + ["-o"] + [self._urdf_paths[robot_name]] if self._xrdf_cmds() is None: xacro_cmd = ["xacro"] + [xacro_path] + ["-o"] + [self._urdf_paths[robot_name]] import subprocess try: xacro_gen = subprocess.check_call(xacro_cmd) # we also generate an updated SRDF except: Journal.log(self.__class__.__name__, "_generate_urdf", "Failed to generate " + robot_name + "\'s URDF!!!", LogType.EXCEP, throw_when_excep = True) def _generate_rob_descriptions(self, robot_name: str, robot_pkg_name: str): self._descr_dump_path = "/tmp/" + f"{self.__class__.__name__}" Journal.log(self.__class__.__name__, "update_root_offsets", "generating URDF for robot "+ f"{robot_name}, of type {robot_pkg_name}...", LogType.STAT, throw_when_excep = True) self._generate_urdf(robot_name=robot_name, robot_pkg_name=robot_pkg_name) Journal.log(self.__class__.__name__, "update_root_offsets", "generating SRDF for robot "+ f"{robot_name}, of type {robot_pkg_name}...", LogType.STAT, throw_when_excep = True) # we also generate SRDF files, which are useful for control self._generate_srdf(robot_name=robot_name, robot_pkg_name=robot_pkg_name) def _import_urdf(self, robot_name: str, import_config: omni.importer.urdf._urdf.ImportConfig = _urdf.ImportConfig(), fix_base = False, self_collide = False, merge_fixed = True): Journal.log(self.__class__.__name__, "update_root_offsets", "importing robot URDF", LogType.STAT, throw_when_excep = True) _urdf.acquire_urdf_interface() # we overwrite some settings which are bound to be fixed import_config.merge_fixed_joints = merge_fixed # makes sim more stable # in case of fixed joints with light objects import_config.import_inertia_tensor = True # import_config.convex_decomp = False import_config.fix_base = fix_base import_config.self_collision = self_collide # import_config.distance_scale = 1 # import_config.make_default_prim = True # import_config.create_physics_scene = True # import_config.default_drive_strength = 1047.19751 # import_config.default_position_drive_damping = 52.35988 # import_config.default_drive_type = _urdf.UrdfJointTargetType.JOINT_DRIVE_POSITION # import URDF success, robot_prim_path_default = omni.kit.commands.execute( "URDFParseAndImportFile", urdf_path=self._urdf_paths[robot_name], import_config=import_config, ) robot_base_prim_path = self._template_env_ns + "/" + robot_name # moving default prim to base prim path for cloning move_prim(robot_prim_path_default, # from robot_base_prim_path) # to return success def _init_contact_sensors(self): for i in range(0, len(self.robot_names)): robot_name = self.robot_names[i] # creates base contact sensor (which is then cloned) self.omni_contact_sensors[robot_name].create_contact_sensors( self._world, self._env_ns ) def _init_robots_state(self): for i in range(0, len(self.robot_names)): robot_name = self.robot_names[i] pose = self._robots_art_views[robot_name].get_world_poses( clone = True) # tuple: (pos, quat) # root p (measured, previous, default) self._root_p[robot_name] = pose[0] self._root_p_prev[robot_name] = torch.clone(pose[0]) self._root_p_default[robot_name] = torch.clone(pose[0]) + self.distr_offset[robot_name] # root q (measured, previous, default) self._root_q[robot_name] = pose[1] # root orientation self._root_q_prev[robot_name] = torch.clone(pose[1]) self._root_q_default[robot_name] = torch.clone(pose[1]) # jnt q (measured, previous, default) self._jnts_q[robot_name] = self._robots_art_views[robot_name].get_joint_positions( clone = True) # joint positions self._jnts_q_prev[robot_name] = self._robots_art_views[robot_name].get_joint_positions( clone = True) self._jnts_q_default[robot_name] = self.homers[robot_name].get_homing(clone=True) # root v (measured, default) self._root_v[robot_name] = self._robots_art_views[robot_name].get_linear_velocities( clone = True) # root lin. velocity self._root_v_default[robot_name] = torch.full((self._root_v[robot_name].shape[0], self._root_v[robot_name].shape[1]), 0.0, dtype=self.torch_dtype, device=self.torch_device) # root omega (measured, default) self._root_omega[robot_name] = self._robots_art_views[robot_name].get_angular_velocities( clone = True) # root ang. velocity self._root_omega_default[robot_name] = torch.full((self._root_omega[robot_name].shape[0], self._root_omega[robot_name].shape[1]), 0.0, dtype=self.torch_dtype, device=self.torch_device) # joints v (measured, default) self._jnts_v[robot_name] = self._robots_art_views[robot_name].get_joint_velocities( clone = True) # joint velocities self._jnts_v_default[robot_name] = torch.full((self._jnts_v[robot_name].shape[0], self._jnts_v[robot_name].shape[1]), 0.0, dtype=self.torch_dtype, device=self.torch_device) self._jnts_eff_default[robot_name] = torch.full((self._jnts_v[robot_name].shape[0], self._jnts_v[robot_name].shape[1]), 0.0, dtype=self.torch_dtype, device=self.torch_device) self._root_pos_offsets[robot_name] = torch.zeros((self.num_envs, 3), device=self.torch_device) # reference position offses self._root_q_offsets[robot_name] = torch.zeros((self.num_envs, 4), device=self.torch_device) self._root_q_offsets[robot_name][:, 0] = 1.0 # init to valid identity quaternion self.update_root_offsets(robot_name) def _calc_robot_distrib(self): import math # we distribute robots in a single env. along the # circumference of a circle of given radius n_robots = len(self.robot_names) offset_baseangle = 2 * math.pi / n_robots for i in range(n_robots): offset_angle = offset_baseangle * (i + 1) robot_offset_wrt_center = torch.tensor([self.spawning_radius * math.cos(offset_angle), self.spawning_radius * math.sin(offset_angle), 0], device=self.torch_device, dtype=self.torch_dtype) # list with n references to the original tensor tensor_list = [robot_offset_wrt_center] * self.num_envs self.distr_offset[self.robot_names[i]] = torch.stack(tensor_list, dim=0) def _get_robots_state(self, env_indxs: torch.Tensor = None, robot_names: List[str] = None, dt: float = None, reset: bool = False): rob_names = robot_names if (robot_names is not None) else self.robot_names if env_indxs is not None: for i in range(0, len(rob_names)): robot_name = rob_names[i] pose = self._robots_art_views[robot_name].get_world_poses( clone = True, indices=env_indxs) # tuple: (pos, quat) self._root_p[robot_name][env_indxs, :] = pose[0] self._root_q[robot_name][env_indxs, :] = pose[1] # root orientation self._jnts_q[robot_name][env_indxs, :] = self._robots_art_views[robot_name].get_joint_positions( clone = True, indices=env_indxs) # joint positions if dt is None: # we get velocities from the simulation. This is not good since # these can actually represent artifacts which do not have physical meaning. # It's better to obtain them by differentiation to avoid issues with controllers, etc... self._root_v[robot_name][env_indxs, :] = self._robots_art_views[robot_name].get_linear_velocities( clone = True, indices=env_indxs) # root lin. velocity self._root_omega[robot_name][env_indxs, :] = self._robots_art_views[robot_name].get_angular_velocities( clone = True, indices=env_indxs) # root ang. velocity self._jnts_v[robot_name][env_indxs, :] = self._robots_art_views[robot_name].get_joint_velocities( clone = True, indices=env_indxs) # joint velocities else: # differentiate numerically if not reset: self._root_v[robot_name][env_indxs, :] = (self._root_p[robot_name][env_indxs, :] - \ self._root_p_prev[robot_name][env_indxs, :]) / dt self._root_omega[robot_name][env_indxs, :] = quat_to_omega(self._root_q[robot_name][env_indxs, :], self._root_q_prev[robot_name][env_indxs, :], dt) self._jnts_v[robot_name][env_indxs, :] = (self._jnts_q[robot_name][env_indxs, :] - \ self._jnts_q_prev[robot_name][env_indxs, :]) / dt else: # to avoid issues when differentiating numerically self._root_v[robot_name][env_indxs, :].zero_() self._root_omega[robot_name][env_indxs, :].zero_() self._jnts_v[robot_name][env_indxs, :].zero_() # update "previous" data for numerical differentiation self._root_p_prev[robot_name][env_indxs, :] = self._root_p[robot_name][env_indxs, :] self._root_q_prev[robot_name][env_indxs, :] = self._root_q[robot_name][env_indxs, :] self._jnts_q_prev[robot_name][env_indxs, :] = self._jnts_q[robot_name][env_indxs, :] else: # updating data for all environments for i in range(0, len(rob_names)): robot_name = rob_names[i] pose = self._robots_art_views[robot_name].get_world_poses( clone = True) # tuple: (pos, quat) self._root_p[robot_name][:, :] = pose[0] self._root_q[robot_name][:, :] = pose[1] # root orientation self._jnts_q[robot_name][:, :] = self._robots_art_views[robot_name].get_joint_positions( clone = True) # joint positions if dt is None: # we get velocities from the simulation. This is not good since # these can actually represent artifacts which do not have physical meaning. # It's better to obtain them by differentiation to avoid issues with controllers, etc... self._root_v[robot_name][:, :] = self._robots_art_views[robot_name].get_linear_velocities( clone = True) # root lin. velocity self._root_omega[robot_name][:, :] = self._robots_art_views[robot_name].get_angular_velocities( clone = True) # root ang. velocity self._jnts_v[robot_name][:, :] = self._robots_art_views[robot_name].get_joint_velocities( clone = True) # joint velocities else: # differentiate numerically if not reset: self._root_v[robot_name][:, :] = (self._root_p[robot_name][:, :] - \ self._root_p_prev[robot_name][:, :]) / dt self._root_omega[robot_name][:, :] = quat_to_omega(self._root_q[robot_name][:, :], self._root_q_prev[robot_name][:, :], dt) self._jnts_v[robot_name][:, :] = (self._jnts_q[robot_name][:, :] - \ self._jnts_q_prev[robot_name][:, :]) / dt # self._jnts_v[robot_name][:, :].zero_() else: # to avoid issues when differentiating numerically self._root_v[robot_name][:, :].zero_() self._root_omega[robot_name][:, :].zero_() self._jnts_v[robot_name][:, :].zero_() # update "previous" data for numerical differentiation self._root_p_prev[robot_name][:, :] = self._root_p[robot_name][:, :] self._root_q_prev[robot_name][:, :] = self._root_q[robot_name][:, :] self._jnts_q_prev[robot_name][:, :] = self._jnts_q[robot_name][:, :] def get_states(self, env_indxs: torch.Tensor = None, robot_names: List[str] = None): if self.use_diff_velocities: self._get_robots_state(dt = self.integration_dt(), env_indxs = env_indxs, robot_names = robot_names) # updates robot states # but velocities are obtained via num. differentiation else: self._get_robots_state(env_indxs = env_indxs, robot_names = robot_names) # velocities directly from simulator (can # introduce relevant artifacts, making them unrealistic) def _custom_post_init(self): # can be overridden by child class pass def _set_robots_default_jnt_config(self): # setting Isaac's internal defaults. Useful is resetting # whole scenes or views, but single env reset has to be implemented # manueally # we use the homing of the robots if (self._world_initialized): for i in range(0, len(self.robot_names)): robot_name = self.robot_names[i] homing = self.homers[robot_name].get_homing() self._robots_art_views[robot_name].set_joints_default_state(positions= homing, velocities = torch.zeros((homing.shape[0], homing.shape[1]), \ dtype=self.torch_dtype, device=self.torch_device), efforts = torch.zeros((homing.shape[0], homing.shape[1]), \ dtype=self.torch_dtype, device=self.torch_device)) else: Journal.log(self.__class__.__name__, "_set_robots_default_jnt_config", "Before calling __set_robots_default_jnt_config(), you need to reset the World" + \ " at least once and call post_initialization_steps()", LogType.EXCEP, throw_when_excep = True) def _set_robots_root_default_config(self): if (self._world_initialized): for i in range(0, len(self.robot_names)): robot_name = self.robot_names[i] self._robots_art_views[robot_name].set_default_state(positions = self._root_p_default[robot_name], orientations = self._root_q_default[robot_name]) else: Journal.log(self.__class__.__name__, "_generate_urdf", "Before calling _set_robots_root_default_config(), you need to reset the World" + \ " at least once and call post_initialization_steps()", LogType.EXCEP, throw_when_excep = True) return True def _get_solver_info(self): for i in range(0, len(self.robot_names)): robot_name = self.robot_names[i] self._solver_position_iteration_counts[robot_name] = self._robots_art_views[robot_name].get_solver_position_iteration_counts() self._solver_velocity_iteration_counts[robot_name] = self._robots_art_views[robot_name].get_solver_velocity_iteration_counts() self._solver_stabilization_threshs[robot_name] = self._robots_art_views[robot_name].get_stabilization_thresholds() def _update_art_solver_options(self): # sets new solver iteration options for specifc articulations self._get_solver_info() # gets current solver info for the articulations of the # environments, so that dictionaries are filled properly if (self._world_initialized): for i in range(0, len(self.robot_names)): robot_name = self.robot_names[i] # increase by a factor self._solver_position_iteration_counts[robot_name] = torch.full((self.num_envs,), self._solver_position_iteration_count) self._solver_velocity_iteration_counts[robot_name] = torch.full((self.num_envs,), self._solver_velocity_iteration_count) self._solver_stabilization_threshs[robot_name] = torch.full((self.num_envs,), self._solver_stabilization_thresh) self._robots_art_views[robot_name].set_solver_position_iteration_counts(self._solver_position_iteration_counts[robot_name]) self._robots_art_views[robot_name].set_solver_velocity_iteration_counts(self._solver_velocity_iteration_counts[robot_name]) self._robots_art_views[robot_name].set_stabilization_thresholds(self._solver_stabilization_threshs[robot_name]) self._get_solver_info() # gets again solver info for articulation, so that it's possible to debug if # the operation was successful else: Journal.log(self.__class__.__name__, "_set_robots_default_jnt_config", "Before calling update_art_solver_options(), you need to reset the World at least once!", LogType.EXCEP, throw_when_excep = True) def _print_envs_info(self): if (self._world_initialized): print("TASK INFO:") for i in range(0, len(self.robot_names)): robot_name = self.robot_names[i] task_info = f"[{robot_name}]" + "\n" + \ "bodies: " + str(self._robots_art_views[robot_name].body_names) + "\n" + \ "n. prims: " + str(self._robots_art_views[robot_name].count) + "\n" + \ "prims names: " + str(self._robots_art_views[robot_name].prim_paths) + "\n" + \ "n. bodies: " + str(self._robots_art_views[robot_name].num_bodies) + "\n" + \ "n. dofs: " + str(self._robots_art_views[robot_name].num_dof) + "\n" + \ "dof names: " + str(self._robots_art_views[robot_name].dof_names) + "\n" + \ "solver_position_iteration_counts: " + str(self._solver_position_iteration_counts[robot_name]) + "\n" + \ "solver_velocity_iteration_counts: " + str(self._solver_velocity_iteration_counts[robot_name]) + "\n" + \ "stabiliz. thresholds: " + str(self._solver_stabilization_threshs[robot_name]) # print("dof limits: " + str(self._robots_art_views[robot_name].get_dof_limits())) # print("effort modes: " + str(self._robots_art_views[robot_name].get_effort_modes())) # print("dof gains: " + str(self._robots_art_views[robot_name].get_gains())) # print("dof max efforts: " + str(self._robots_art_views[robot_name].get_max_efforts())) # print("dof gains: " + str(self._robots_art_views[robot_name].get_gains())) # print("physics handle valid: " + str(self._robots_art_views[robot_name].is_physics_handle_valid()) Journal.log(self.__class__.__name__, "_print_envs_info", task_info, LogType.STAT, throw_when_excep = True) else: Journal.log(self.__class__.__name__, "_set_robots_default_jnt_config", "Before calling __print_envs_info(), you need to reset the World at least once!", LogType.EXCEP, throw_when_excep = True) def _fill_robot_info_from_world(self): if self._world_initialized: for i in range(0, len(self.robot_names)): robot_name = self.robot_names[i] self.robot_bodynames[robot_name] = self._robots_art_views[robot_name].body_names self.robot_n_links[robot_name] = self._robots_art_views[robot_name].num_bodies self.robot_n_dofs[robot_name] = self._robots_art_views[robot_name].num_dof self.robot_dof_names[robot_name] = self._robots_art_views[robot_name].dof_names else: Journal.log(self.__class__.__name__, "_fill_robot_info_from_world", "Before calling _fill_robot_info_from_world(), you need to reset the World at least once!", LogType.EXCEP, throw_when_excep = True) def _init_homing_managers(self): if self._world_initialized: for i in range(0, len(self.robot_names)): robot_name = self.robot_names[i] self.homers[robot_name] = OmniRobotHomer(articulation=self._robots_art_views[robot_name], srdf_path=self._srdf_paths[robot_name], device=self.torch_device, dtype=self.torch_dtype) else: exception = "you should reset the World at least once and call the " + \ "post_initialization_steps() method before initializing the " + \ "homing manager." Journal.log(self.__class__.__name__, "_init_homing_managers", exception, LogType.EXCEP, throw_when_excep = True) def _init_jnt_imp_control(self): if self._world_initialized: for i in range(0, len(self.robot_names)): robot_name = self.robot_names[i] # creates impedance controller self.jnt_imp_controllers[robot_name] = OmniJntImpCntrl(articulation=self._robots_art_views[robot_name], default_pgain = self.default_jnt_stiffness, # defaults default_vgain = self.default_jnt_damping, override_art_controller=self._override_art_controller, filter_dt = None, filter_BW = 50, device= self.torch_device, dtype=self.torch_dtype, enable_safety=True, enable_profiling=self._debug_enabled, urdf_path=self._urdf_paths[robot_name], debug_checks = self._debug_enabled) self.reset_jnt_imp_control(robot_name) else: exception = "you should reset the World at least once and call the " + \ "post_initialization_steps() method before initializing the " + \ "joint impedance controller." Journal.log(self.__class__.__name__, "_init_homing_managers", exception, LogType.EXCEP, throw_when_excep = True) def _set_initial_camera_params(self, camera_position=[10, 10, 3], camera_target=[0, 0, 0]): set_camera_view(eye=camera_position, target=camera_target, camera_prim_path="/OmniverseKit_Persp")
68,642
Python
47.995717
142
0.49324
AndrePatri/OmniRoboGym/omni_robo_gym/tests/test_lunar_lander_stable_bs3.py
# Copyright (C) 2023 Andrea Patrizi (AndrePatri, andreapatrizi1b6e6@gmail.com) # # This file is part of OmniRoboGym and distributed under the General Public License version 2 license. # # OmniRoboGym is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 2 of the License, or # (at your option) any later version. # # OmniRoboGym is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with OmniRoboGym. If not, see <http://www.gnu.org/licenses/>. # import gymnasium as gym from stable_baselines3 import DQN from stable_baselines3.common.evaluation import evaluate_policy # Create environment env = gym.make("LunarLander-v2", render_mode="rgb_array") # Instantiate the agent model = DQN("MlpPolicy", env, verbose=1) # Train the agent and display a progress bar model.learn(total_timesteps=int(2e5), progress_bar=True) # Save the agent model.save("dqn_lunar") del model # delete trained model to demonstrate loading # Load the trained agent # NOTE: if you have loading issue, you can pass `print_system_info=True` # to compare the system on which the model was trained vs the current one # model = DQN.load("dqn_lunar", env=env, print_system_info=True) model = DQN.load("dqn_lunar", env=env) # Evaluate the agent # NOTE: If you use wrappers with your environment that modify rewards, # this will be reflected here. To evaluate with original rewards, # wrap environment in a "Monitor" wrapper before other wrappers. mean_reward, std_reward = evaluate_policy(model, model.get_env(), n_eval_episodes=10) # Enjoy trained agent vec_env = model.get_env() obs = vec_env.reset() n_pred_iterations = 100000 for i in range(n_pred_iterations): action, _states = model.predict(obs, deterministic=True) obs, rewards, dones, info = vec_env.step(action) vec_env.render("human")
2,169
Python
38.454545
102
0.751498
AndrePatri/OmniRoboGym/omni_robo_gym/tests/create_terrain_demo.py
# Copyright (C) 2023 Andrea Patrizi (AndrePatri, andreapatrizi1b6e6@gmail.com) # # This file is part of OmniRoboGym and distributed under the General Public License version 2 license. # # OmniRoboGym is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 2 of the License, or # (at your option) any later version. # # OmniRoboGym is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with OmniRoboGym. If not, see <http://www.gnu.org/licenses/>. # # Copyright (c) 2018-2022, NVIDIA Corporation # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # 1. Redistributions of source code must retain the above copyright notice, this # list of conditions and the following disclaimer. # # 2. Redistributions in binary form must reproduce the above copyright notice, # this list of conditions and the following disclaimer in the documentation # and/or other materials provided with the distribution. # # 3. Neither the name of the copyright holder nor the names of its # contributors may be used to endorse or promote products derived from # this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE # DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE # FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL # DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR # SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER # CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, # OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. import os, sys SCRIPT_DIR = os.path.dirname(os.path.abspath(__file__)) sys.path.append(SCRIPT_DIR) import omni from omni.isaac.kit import SimulationApp import numpy as np simulation_app = SimulationApp({"headless": False}) from omni.isaac.core.tasks import BaseTask from omni.isaac.core import World from omni.isaac.core.objects import DynamicSphere from omni.isaac.core.utils.prims import define_prim from omni.isaac.core.utils.stage import get_current_stage from omni.isaac.core.materials import PreviewSurface from omni.isaac.cloner import GridCloner from pxr import UsdLux, UsdShade, Sdf from omni_robo_gym.utils.terrain_utils import * from omni_robo_gym.utils.terrains import RlTerrains class TerrainsTest(BaseTask): def __init__(self, name) -> None: BaseTask.__init__(self, name=name) self._device = "cpu" def set_up_scene(self, scene) -> None: self._stage = get_current_stage() distantLight = UsdLux.DistantLight.Define(self._stage, Sdf.Path("/World/DistantLight")) distantLight.CreateIntensityAttr(2000) self.terrains = RlTerrains(self._stage) self.terrains.get_obstacles_terrain( terrain_size = 40.0, num_obs = 200, max_height = 0.5, min_size = 0.5, max_size = 5.0,) super().set_up_scene(scene) return def post_reset(self): a = 1 def get_observations(self): pass def calculate_metrics(self) -> None: pass def is_done(self) -> None: pass if __name__ == "__main__": world = World( stage_units_in_meters=1.0, rendering_dt=1.0/60.0, backend="torch", device="cpu", ) terrain_creation_task = TerrainsTest(name="CustomTerrain", ) world.add_task(terrain_creation_task) world.reset() while simulation_app.is_running(): if world.is_playing(): if world.current_time_step_index == 0: world.reset(soft=True) world.step(render=True) else: world.step(render=True) simulation_app.close()
4,763
Python
33.773722
102
0.672475
AndrePatri/OmniRoboGym/omni_robo_gym/utils/contact_sensor.py
import torch import numpy as np from omni.isaac.sensor import ContactSensor from typing import List, Dict from omni.isaac.core.world import World from omni.isaac.core.prims import RigidPrimView, RigidContactView from SharsorIPCpp.PySharsorIPC import LogType from SharsorIPCpp.PySharsorIPC import Journal class OmniContactSensors: def __init__(self, name: str, # robot name for which contact sensors are to be created n_envs: int, # number of environments contact_prims: Dict[str, List] = None, contact_offsets: Dict[str, Dict[str, np.ndarray]] = None, sensor_radii: Dict[str, Dict[str, np.ndarray]] = None, device = "cuda", dtype = torch.float64, enable_debug: bool = False, filter_paths: List[str] = ["/World/terrain/GroundPlane/CollisionPlane"]): # contact sensors abstraction for a single robot # over multiple environments self._filter_paths = filter_paths self._enable_debug = enable_debug self.n_envs = n_envs self.device = device if self.device == "cuda": self.using_gpu = True else: self.using_gpu = False self.dtype = dtype self.name = name self.contact_radius_default = 0.003 # parses contact dictionaries and checks for issues self._parse_contact_dicts(self.name, contact_prims, contact_offsets, sensor_radii) self.n_sensors = len(self.contact_prims) self.in_contact = torch.full((n_envs, self.n_sensors), False, device = self.device, dtype=torch.bool) self.force_norm = torch.full((n_envs, self.n_sensors), -1.0, device = self.device, dtype=self.dtype) self.n_contacts = torch.full((n_envs, self.n_sensors), 0, device = self.device, dtype=torch.int) self.contact_sensors = [[None] * self.n_sensors] * n_envs # outer: environment, # inner: contact sensor, ordered as in contact_prims self.contact_geom_prim_views = [None] * self.n_sensors # self.contact_views = [None] * self.n_sensors def _parse_contact_dicts(self, name: str, contact_prims: Dict[str, List], contact_offsets: Dict[str, Dict[str, np.ndarray]], sensor_radii: Dict[str, Dict[str, np.ndarray]]): try: self.contact_prims = contact_prims[name] except: Journal.log(self.__class__.__name__, "_parse_contact_dicts", f"Could not find key {name} in contact_prims dictionary.", LogType.EXCEP, throw_when_excep = True) try: self.contact_offsets = contact_offsets[name] except: Journal.log(self.__class__.__name__, "_parse_contact_dicts", f"Could not find key {name} in contact_offsets dictionary.", LogType.EXCEP, throw_when_excep = True) try: self.sensor_radii = sensor_radii[name] except: Journal.log(self.__class__.__name__, "_parse_contact_dicts", f"Could not find key {name} in sensor_radii dictionary.", LogType.EXCEP, throw_when_excep = True) contact_offsets_ok = all(item in self.contact_offsets for item in self.contact_prims) sensor_radii_ok = all(item in self.sensor_radii for item in self.contact_prims) if not contact_offsets_ok: warning = f"Provided contact_offsets dictionary does not posses all the necessary keys. " + \ f"It should contain all of [{' '.join(self.contact_prims)}]. \n" + \ f"Resetting all offsets to zero..." Journal.log(self.__class__.__name__, "_parse_contact_dicts", warning, LogType.WARN, throw_when_excep = True) for i in range(0, len(self.contact_prims)): self.contact_offsets[self.contact_prims[i]] = np.array([0.0, 0.0, 0.0]) if not sensor_radii_ok: warning = f"Provided sensor_radii dictionary does not posses all the necessary keys. " + \ f"It should contain all of [{' '.join(self.contact_prims)}]. \n" + \ f"Resetting all radii to {self.contact_radius_default} ..." Journal.log(self.__class__.__name__, "_parse_contact_dicts", warning, LogType.WARN, throw_when_excep = True) for i in range(0, len(self.contact_prims)): self.sensor_radii[self.contact_prims[i]] = self.contact_radius_default def create_contact_sensors(self, world: World, envs_namespace: str): robot_name = self.name contact_link_names = self.contact_prims for sensor_idx in range(0, self.n_sensors): # we create views of the contact links for all envs if self.contact_geom_prim_views[sensor_idx] is None: self.contact_geom_prim_views[sensor_idx] = RigidPrimView(prim_paths_expr=envs_namespace + "/env_.*/" + robot_name + \ "/" + contact_link_names[sensor_idx], name= self.name + "RigidPrimView" + contact_link_names[sensor_idx], contact_filter_prim_paths_expr= self._filter_paths, prepare_contact_sensors=True, track_contact_forces = True, disable_stablization = False, reset_xform_properties=False, max_contact_count = self.n_envs ) world.scene.add(self.contact_geom_prim_views[sensor_idx]) # for env_idx in range(0, self.n_envs): # # env_idx = 0 # create contact sensors for base env only # for sensor_idx in range(0, self.n_sensors): # contact_link_prim_path = envs_namespace + f"/env_{env_idx}" + \ # "/" + robot_name + \ # "/" + contact_link_names[sensor_idx] # sensor_prim_path = contact_link_prim_path + \ # "/contact_sensor" # contact sensor prim path # print(f"[{self.__class__.__name__}]" + f"[{self.journal.status}]" + ": creating contact sensor at " + # f"{sensor_prim_path}...") # contact_sensor = ContactSensor( # prim_path=sensor_prim_path, # name=f"{robot_name}{env_idx}_{contact_link_names[sensor_idx]}_contact_sensor", # min_threshold=0, # max_threshold=10000000, # radius=self.sensor_radii[contact_link_names[sensor_idx]], # translation=self.contact_offsets[contact_link_names[sensor_idx]], # position=None # ) # self.contact_sensors[env_idx][sensor_idx] = world.scene.add(contact_sensor) # self.contact_sensors[env_idx][sensor_idx].add_raw_contact_data_to_frame() # print(f"[{self.__class__.__name__}]" + f"[{self.journal.status}]" + ": contact sensor at " + # f"{sensor_prim_path} created.") def get(self, dt: float, contact_link: str, env_indxs: torch.Tensor = None, clone = False): index = -1 try: index = self.contact_prims.index(contact_link) except: exception = f"[{self.__class__.__name__}]" + f"[{self.journal.exception}]" + \ f"could not find contact link {contact_link} in contact list {' '.join(self.contact_prims)}." Journal.log(self.__class__.__name__, "get", exception, LogType.EXCEP, throw_when_excep = True) if env_indxs is None: return self.contact_geom_prim_views[index].get_net_contact_forces(clone = clone, dt = dt).view(self.n_envs, 3) else: if self._enable_debug: if env_indxs is not None: if not isinstance(env_indxs, torch.Tensor): msg = "Provided env_indxs should be a torch tensor of indexes!" Journal.log(self.__class__.__name__, "get", msg, LogType.EXCEP, throw_when_excep = True) if not len(env_indxs.shape) == 1: msg = "Provided robot_indxs should be a 1D torch tensor!" Journal.log(self.__class__.__name__, "get", msg, LogType.EXCEP, throw_when_excep = True) if self.using_gpu: if not env_indxs.device.type == "cuda": error = "Provided env_indxs should be on GPU!" Journal.log(self.__class__.__name__, "_step_jnt_imp_control", error, LogType.EXCEP, True) else: if not env_indxs.device.type == "cpu": error = "Provided env_indxs should be on CPU!" Journal.log(self.__class__.__name__, "_step_jnt_imp_control", error, LogType.EXCEP, True) return self.contact_geom_prim_views[index].get_net_contact_forces(clone = clone, dt = dt).view(self.n_envs, 3)[env_indxs, :]
10,792
Python
43.415638
133
0.47424
AndrePatri/OmniRoboGym/omni_robo_gym/utils/math_utils.py
import torch import time import torch.nn.functional as F def normalize_quaternion(q): # Normalizes the quaternion return q / torch.norm(q, dim=-1, keepdim=True) def quaternion_difference(q1, q2): """ Compute the quaternion difference needed to rotate from q1 to q2 """ def quat_conjugate(q): # Computes the conjugate of a quaternion w, x, y, z = q.unbind(-1) return torch.stack([w, -x, -y, -z], dim=-1) q1_conj = quat_conjugate(q1) return quaternion_multiply(q2, q1_conj) def quaternion_multiply(q1, q2): """ Multiply two quaternions. """ w1, x1, y1, z1 = q1.unbind(-1) w2, x2, y2, z2 = q2.unbind(-1) return torch.stack([ w1*w2 - x1*x2 - y1*y2 - z1*z2, w1*x2 + x1*w2 + y1*z2 - z1*y2, w1*y2 - x1*z2 + y1*w2 + z1*x2, w1*z2 + x1*y2 - y1*x2 + z1*w2 ], dim=-1) def quaternion_to_angular_velocity(q_diff, dt): """ Convert a quaternion difference to an angular velocity vector. """ angle = 2 * torch.arccos(q_diff[..., 0].clamp(-1.0, 1.0)) # Clamping for numerical stability axis = q_diff[..., 1:] norm = axis.norm(dim=-1, keepdim=True) norm = torch.where(norm > 0, norm, torch.ones_like(norm)) axis = axis / norm angle = angle.unsqueeze(-1) # Add an extra dimension for broadcasting return (angle / dt) * axis def quat_to_omega(q0, q1, dt): """ Convert quaternion pairs to angular velocities """ if q0.shape != q1.shape: raise ValueError("Tensor shapes do not match in quat_to_omega.") # Normalize quaternions and compute differences q0_normalized = normalize_quaternion(q0) q1_normalized = normalize_quaternion(q1) q_diff = quaternion_difference(q0_normalized, q1_normalized) return quaternion_to_angular_velocity(q_diff, dt) def rel_vel(offset_q0_q1, v0): # Calculate relative linear velocity in frame q1 from linear velocity in frame q0 using quaternions. # Ensure the quaternion is normalized offset_q0_q1 = F.normalize(offset_q0_q1, p=2, dim=0) # Convert the linear velocity vector to a quaternion v0_q = torch.cat([torch.tensor([0]), v0]) # Rotate the linear velocity quaternion using the orientation offset quaternion rotated_velocity_quaternion = quaternion_multiply(offset_q0_q1, v0_q) offset_q0_q1_inverse = torch.cat([offset_q0_q1[0:1], -offset_q0_q1[1:]]) # Multiply by the conjugate of the orientation offset quaternion to obtain the result in frame f1 v1_q = quaternion_multiply(rotated_velocity_quaternion, offset_q0_q1_inverse) # Extract the linear velocity vector from the quaternion result v1 = v1_q[1:] return v1 # Example usage n_envs = 100 # Number of environments dt = 0.1 # Time step # Random example tensors for initial and final orientations q_initial = torch.randn(n_envs, 4) q_final = torch.randn(n_envs, 4) start_time = time.perf_counter() # Convert to angular velocities omega = quat_to_omega(q_initial, q_final, dt) end_time = time.perf_counter() elapsed_time = end_time - start_time print(f"Time taken to compute angular velocities: {elapsed_time:.6f} seconds")
3,149
Python
32.870967
104
0.668466
AndrePatri/OmniRoboGym/omni_robo_gym/utils/rt_factor.py
import time class RtFactor(): def __init__(self, dt_nom: float, window_size: int): self._it_counter = 0 self._dt_nom = dt_nom self._start_time = time.perf_counter() self._current_rt_factor = 0.0 self._window_size = window_size self._real_time = 0 self._nom_time = 0 def update(self): self._real_time = time.perf_counter() - self._start_time self._it_counter += 1 self._nom_time += self._dt_nom self._current_rt_factor = self._nom_time / self._real_time def reset_due(self): return (self._it_counter+1) % self._window_size == 0 def get_avrg_step_time(self): return self._real_time / self._window_size def get_dt_nom(self): return self._dt_nom def get_nom_time(self): return self._now_time def get(self): return self._current_rt_factor def reset(self): self._it_counter = 0 self._nom_time = 0 self._start_time = time.perf_counter()
1,096
Python
17.913793
66
0.530109
AndrePatri/OmniRoboGym/omni_robo_gym/utils/urdf_helpers.py
import xml.etree.ElementTree as ET class UrdfLimitsParser: def __init__(self, urdf_path, joint_names, backend = "numpy", device = "cpu"): self.urdf_path = urdf_path self.joint_names = joint_names self.limits_matrix = None self.backend = backend self.device = device if self.backend == "numpy" and \ self.device != "cpu": raise Exception("When using numpy backend, only cpu device is supported!") self.parse_urdf() def parse_urdf(self): tree = ET.parse(self.urdf_path) root = tree.getroot() num_joints = len(self.joint_names) self.limits_matrix = None self.inf = None if self.backend == "numpy": import numpy as np self.limits_matrix = np.full((num_joints, 6), np.nan) self.inf = np.inf elif self.backend == "torch": import torch self.limits_matrix = torch.full((num_joints, 6), torch.nan, device=self.device) self.inf = torch.inf else: raise Exception("Backend not supported") for joint_name in self.joint_names: joint_element = root.find(".//joint[@name='{}']".format(joint_name)) if joint_element is not None: limit_element = joint_element.find('limit') jnt_index = self.joint_names.index(joint_name) # position limits q_lower = float(limit_element.get('lower', - self.inf)) q_upper = float(limit_element.get('upper', self.inf)) # effort limits effort_limit = float(limit_element.get('effort', self.inf)) # vel limits velocity_limit = float(limit_element.get('velocity', self.inf)) self.limits_matrix[jnt_index, 0] = q_lower self.limits_matrix[jnt_index, 3] = q_upper self.limits_matrix[jnt_index, 1] = - abs(velocity_limit) self.limits_matrix[jnt_index, 4] = abs(velocity_limit) self.limits_matrix[jnt_index, 2] = - abs(effort_limit) self.limits_matrix[jnt_index, 5] = abs(effort_limit) def get_limits_matrix(self): return self.limits_matrix
2,425
Python
28.228915
91
0.524536
AndrePatri/OmniRoboGym/omni_robo_gym/utils/homing.py
# Copyright (C) 2023 Andrea Patrizi (AndrePatri, andreapatrizi1b6e6@gmail.com) # # This file is part of OmniRoboGym and distributed under the General Public License version 2 license. # # OmniRoboGym is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 2 of the License, or # (at your option) any later version. # # OmniRoboGym is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with OmniRoboGym. If not, see <http://www.gnu.org/licenses/>. # from omni.isaac.core.articulations.articulation_view import ArticulationView import torch import xml.etree.ElementTree as ET from SharsorIPCpp.PySharsorIPC import LogType from SharsorIPCpp.PySharsorIPC import Journal class OmniRobotHomer: def __init__(self, articulation: ArticulationView, srdf_path: str, backend = "torch", device: torch.device = torch.device("cpu"), dtype = torch.float64): self.torch_dtype = dtype if not articulation.initialized: exception = f"the provided articulation is not initialized properly!" Journal.log(self.__class__.__name__, "__init__", exception, LogType.EXCEP, throw_when_excep = True) self._articulation = articulation self.srdf_path = srdf_path self._device = device self.num_robots = self._articulation.count self.n_dofs = self._articulation.num_dof self.jnts_names = self._articulation.dof_names self.joint_idx_map = {} for joint in range(0, self.n_dofs): self.joint_idx_map[self.jnts_names[joint]] = joint if (backend != "torch"): print(f"[{self.__class__.__name__}]" + f"[{self.journal.info}]" + ": forcing torch backend. Other backends are not yet supported.") self._backend = "torch" self._homing = torch.full((self.num_robots, self.n_dofs), 0.0, device = self._device, dtype=self.torch_dtype) # homing configuration # open srdf and parse the homing field with open(srdf_path, 'r') as file: self._srdf_content = file.read() try: self._srdf_root = ET.fromstring(self._srdf_content) # Now 'root' holds the root element of the XML tree. # You can navigate through the XML tree to extract the tags and their values. # Example: To find all elements with a specific tag, you can use: # elements = root.findall('.//your_tag_name') # Example: If you know the specific structure of your .SRDF file, you can extract # the data accordingly, for instance: # for child in root: # if child.tag == 'some_tag_name': # tag_value = child.text # # Do something with the tag value. # elif child.tag == 'another_tag_name': # # Handle another tag. except ET.ParseError as e: print(f"[{self.__class__.__name__}]" + f"[{self.journal.warning}]" + ": could not read SRDF properly!!") # Find all the 'joint' elements within 'group_state' with the name attribute and their values joints = self._srdf_root.findall(".//group_state[@name='home']/joint") self._homing_map = {} for joint in joints: joint_name = joint.attrib['name'] joint_value = joint.attrib['value'] self._homing_map[joint_name] = float(joint_value) self._assign2homing() def _assign2homing(self): for joint in list(self._homing_map.keys()): if joint in self.joint_idx_map: self._homing[:, self.joint_idx_map[joint]] = torch.full((self.num_robots, 1), self._homing_map[joint], device = self._device, dtype=self.torch_dtype).flatten() else: print(f"[{self.__class__.__name__}]" + f"[{self.journal.warning}]" + f"[{self._assign2homing.__name__}]" \ + ": joint " + f"{joint}" + " is not present in the articulation. It will be ignored.") def get_homing(self, clone: bool = False): if not clone: return self._homing else: return self._homing.clone()
5,070
Python
36.286764
144
0.554438
AndrePatri/OmniRoboGym/omni_robo_gym/utils/jnt_imp_cntrl.py
# Copyright (C) 2023 Andrea Patrizi (AndrePatri, andreapatrizi1b6e6@gmail.com) # # This file is part of OmniRoboGym and distributed under the General Public License version 2 license. # # OmniRoboGym is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 2 of the License, or # (at your option) any later version. # # OmniRoboGym is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with OmniRoboGym. If not, see <http://www.gnu.org/licenses/>. # import torch from typing import List from enum import Enum from omni.isaac.core.articulations.articulation_view import ArticulationView from omni_robo_gym.utils.urdf_helpers import UrdfLimitsParser import time from SharsorIPCpp.PySharsorIPC import LogType from SharsorIPCpp.PySharsorIPC import Journal class FirstOrderFilter: # a class implementing a simple first order filter def __init__(self, dt: float, filter_BW: float = 0.1, rows: int = 1, cols: int = 1, device: torch.device = torch.device("cpu"), dtype = torch.double): self._torch_dtype = dtype self._torch_device = device self._dt = dt self._rows = rows self._cols = cols self._filter_BW = filter_BW import math self._gain = 2 * math.pi * self._filter_BW self.yk = torch.zeros((self._rows, self._cols), device = self._torch_device, dtype=self._torch_dtype) self.ykm1 = torch.zeros((self._rows, self._cols), device = self._torch_device, dtype=self._torch_dtype) self.refk = torch.zeros((self._rows, self._cols), device = self._torch_device, dtype=self._torch_dtype) self.refkm1 = torch.zeros((self._rows, self._cols), device = self._torch_device, dtype=self._torch_dtype) self._kh2 = self._gain * self._dt / 2.0 self._coeff_ref = self._kh2 * 1/ (1 + self._kh2) self._coeff_km1 = (1 - self._kh2) / (1 + self._kh2) def update(self, refk: torch.Tensor = None): if refk is not None: self.refk[:, :] = refk self.yk[:, :] = torch.add(torch.mul(self.ykm1, self._coeff_km1), torch.mul(torch.add(self.refk, self.refkm1), self._coeff_ref)) self.refkm1[:, :] = self.refk self.ykm1[:, :] = self.yk def reset(self, idxs: torch.Tensor = None): if idxs is not None: self.yk[:, :] = torch.zeros((self._rows, self._cols), device = self._torch_device, dtype=self._torch_dtype) self.ykm1[:, :] = torch.zeros((self._rows, self._cols), device = self._torch_device, dtype=self._torch_dtype) self.refk[:, :] = torch.zeros((self._rows, self._cols), device = self._torch_device, dtype=self._torch_dtype) self.refkm1[:, :] = torch.zeros((self._rows, self._cols), device = self._torch_device, dtype=self._torch_dtype) else: self.yk[idxs, :] = torch.zeros((idxs.shape[0], self._cols), device = self._torch_device, dtype=self._torch_dtype) self.ykm1[idxs, :] = torch.zeros((idxs.shape[0], self._cols), device = self._torch_device, dtype=self._torch_dtype) self.refk[idxs, :] = torch.zeros((idxs.shape[0], self._cols), device = self._torch_device, dtype=self._torch_dtype) self.refkm1[idxs, :] = torch.zeros((idxs.shape[0], self._cols), device = self._torch_device, dtype=self._torch_dtype) def get(self): return self.yk class JntSafety: def __init__(self, urdf_parser: UrdfLimitsParser): self.limits_parser = urdf_parser self.limit_matrix = self.limits_parser.get_limits_matrix() def apply(self, q_cmd=None, v_cmd=None, eff_cmd=None): if q_cmd is not None: self.saturate_tensor(q_cmd, position=True) if v_cmd is not None: self.saturate_tensor(v_cmd, velocity=True) if eff_cmd is not None: self.saturate_tensor(eff_cmd, effort=True) def has_nan(self, tensor): return torch.any(torch.isnan(tensor)) def saturate_tensor(self, tensor, position=False, velocity=False, effort=False): if self.has_nan(tensor): exception = f"Found nan elements in provided tensor!!" Journal.log(self.__class__.__name__, "saturate_tensor", exception, LogType.EXCEP, throw_when_excep = False) # Replace NaN values with infinity, so that we can clamp it tensor[:, :] = torch.nan_to_num(tensor, nan=torch.inf) if position: tensor[:, :] = torch.clamp(tensor[:, :], min=self.limit_matrix[:, 0], max=self.limit_matrix[:, 3]) elif velocity: tensor[:, :] = torch.clamp(tensor[:, :], min=self.limit_matrix[:, 1], max=self.limit_matrix[:, 4]) elif effort: tensor[:, :] = torch.clamp(tensor[:, :], min=self.limit_matrix[:, 2], max=self.limit_matrix[:, 5]) class OmniJntImpCntrl: class IndxState(Enum): NONE = -1 VALID = 1 INVALID = 0 def __init__(self, articulation: ArticulationView, default_pgain = 300.0, default_vgain = 30.0, backend = "torch", device: torch.device = torch.device("cpu"), filter_BW = 50.0, # [Hz] filter_dt = None, # should correspond to the dt between samples override_art_controller = False, init_on_creation = False, dtype = torch.double, enable_safety = True, urdf_path: str = None, enable_profiling: bool = False, debug_checks: bool = False): # [s] self._torch_dtype = dtype self._torch_device = device self.enable_profiling = enable_profiling self._debug_checks = debug_checks # debug data self.profiling_data = {} self.profiling_data["time_to_update_state"] = -1.0 self.profiling_data["time_to_set_refs"] = -1.0 self.profiling_data["time_to_apply_cmds"] = -1.0 self.start_time = None if self.enable_profiling: self.start_time = time.perf_counter() self.enable_safety = enable_safety self.limiter = None self.robot_limits = None self.urdf_path = urdf_path self.override_art_controller = override_art_controller # whether to override Isaac's internal joint # articulation PD controller or not self.init_art_on_creation = init_on_creation # init. articulation's gains and refs as soon as the controller # is created self.gains_initialized = False self.refs_initialized = False self._default_pgain = default_pgain self._default_vgain = default_vgain self._filter_BW = filter_BW self._filter_dt = filter_dt self._articulation_view = articulation # used to actually apply control # signals to the robot if not self._articulation_view.initialized: exception = f"the provided articulation_view is not initialized properly!" Journal.log(self.__class__.__name__, "__init__", exception, LogType.EXCEP, throw_when_excep = True) self._valid_signal_types = ["pos_ref", "vel_ref", "eff_ref", # references "pos", "vel", "eff", # measurements (necessary if overriding Isaac's art. controller) "pgain", "vgain"] self.num_robots = self._articulation_view.count self.n_dofs = self._articulation_view.num_dof self.jnts_names = self._articulation_view.dof_names if (backend != "torch"): warning = f"Only supported backend is torch!!!" Journal.log(self.__class__.__name__, "__init__", warning, LogType.WARN, throw_when_excep = True) self._backend = "torch" if self.enable_safety: if self.urdf_path is None: exception = "If enable_safety is set to True, a urdf_path should be provided too!" Journal.log(self.__class__.__name__, "__init__", exception, LogType.EXCEP, throw_when_excep = True) self.robot_limits = UrdfLimitsParser(urdf_path=self.urdf_path, joint_names=self.jnts_names, backend=self._backend, device=self._torch_device) self.limiter = JntSafety(urdf_parser=self.robot_limits) self._pos_err = None self._vel_err = None self._pos = None self._vel = None self._eff = None self._imp_eff = None self._filter_available = False if filter_dt is not None: self._filter_BW = filter_BW self._filter_dt = filter_dt self._pos_ref_filter = FirstOrderFilter(dt=self._filter_dt, filter_BW=self._filter_BW, rows=self.num_robots, cols=self.n_dofs, device=self._torch_device, dtype=self._torch_dtype) self._vel_ref_filter = FirstOrderFilter(dt=self._filter_dt, filter_BW=self._filter_BW, rows=self.num_robots, cols=self.n_dofs, device=self._torch_device, dtype=self._torch_dtype) self._eff_ref_filter = FirstOrderFilter(dt=self._filter_dt, filter_BW=self._filter_BW, rows=self.num_robots, cols=self.n_dofs, device=self._torch_device, dtype=self._torch_dtype) self._filter_available = True else: warning = f"No filter dt provided -> reference filter will not be used!" Journal.log(self.__class__.__name__, "__init__", warning, LogType.WARN, throw_when_excep = True) self.reset() # initialize data def update_state(self, pos: torch.Tensor = None, vel: torch.Tensor = None, eff: torch.Tensor = None, robot_indxs: torch.Tensor = None, jnt_indxs: torch.Tensor = None): if self.enable_profiling: self.start_time = time.perf_counter() selector = self._gen_selector(robot_indxs=robot_indxs, jnt_indxs=jnt_indxs) # only checks and throws # if debug_checks if pos is not None: self._validate_signal(signal = pos, selector = selector, name="pos") # does nothing if not debug_checks self._pos[selector] = pos if vel is not None: self._validate_signal(signal = vel, selector = selector, name="vel") self._vel[selector] = vel if eff is not None: self._validate_signal(signal = eff, selector = selector, name="eff") self._eff[selector] = eff if self.enable_profiling: self.profiling_data["time_to_update_state"] = \ time.perf_counter() - self.start_time def set_gains(self, pos_gains: torch.Tensor = None, vel_gains: torch.Tensor = None, robot_indxs: torch.Tensor = None, jnt_indxs: torch.Tensor = None): selector = self._gen_selector(robot_indxs=robot_indxs, jnt_indxs=jnt_indxs) # only checks and throws # if debug_checks if pos_gains is not None: self._validate_signal(signal = pos_gains, selector = selector, name="pos_gains") self._pos_gains[selector] = pos_gains if not self.override_art_controller: self._articulation_view.set_gains(kps = self._pos_gains) if vel_gains is not None: self._validate_signal(signal = vel_gains, selector = selector, name="vel_gains") self._vel_gains[selector] = vel_gains if not self.override_art_controller: self._articulation_view.set_gains(kds = self._vel_gains) def set_refs(self, eff_ref: torch.Tensor = None, pos_ref: torch.Tensor = None, vel_ref: torch.Tensor = None, robot_indxs: torch.Tensor = None, jnt_indxs: torch.Tensor = None): if self.enable_profiling: self.start_time = time.perf_counter() selector = self._gen_selector(robot_indxs=robot_indxs, jnt_indxs=jnt_indxs) # only checks and throws # if debug_checks if eff_ref is not None: self._validate_signal(signal = eff_ref, selector = selector, name="eff_ref") self._eff_ref[selector] = eff_ref if pos_ref is not None: self._validate_signal(signal = pos_ref, selector = selector, name="pos_ref") self._pos_ref[selector] = pos_ref if vel_ref is not None: self._validate_signal(signal = vel_ref, selector = selector, name="vel_ref") self._vel_ref[selector] = vel_ref if self.enable_profiling: self.profiling_data["time_to_set_refs"] = time.perf_counter() - self.start_time def apply_cmds(self, filter = False): # initialize gains and refs if not done previously if self.enable_profiling: self.start_time = time.perf_counter() if not self.gains_initialized: self._apply_init_gains_to_art() if not self.refs_initialized: self._apply_init_refs_to_art() if filter and self._filter_available: self._pos_ref_filter.update(self._pos_ref) self._vel_ref_filter.update(self._vel_ref) self._eff_ref_filter.update(self._eff_ref) # we first filter, then apply safety eff_ref_filt = self._eff_ref_filter.get() pos_ref_filt = self._pos_ref_filter.get() vel_ref_filt = self._vel_ref_filter.get() if self.limiter is not None: # saturating ref cmds self.limiter.apply(q_cmd=pos_ref_filt, v_cmd=vel_ref_filt, eff_cmd=eff_ref_filt) if not self.override_art_controller: # using omniverse's articulation PD controller self._articulation_view.set_joint_efforts(eff_ref_filt) self._articulation_view.set_joint_position_targets(pos_ref_filt) self._articulation_view.set_joint_velocity_targets(vel_ref_filt) else: # impedance torque computed explicitly self._pos_err = torch.sub(self._pos_ref_filter.get(), self._pos) self._vel_err = torch.sub(self._vel_ref_filter.get(), self._vel) self._imp_eff = torch.add(self._eff_ref_filter.get(), torch.add( torch.mul(self._pos_gains, self._pos_err), torch.mul(self._vel_gains, self._vel_err))) # torch.cuda.synchronize() # we also make the resulting imp eff safe if self.limiter is not None: self.limiter.apply(eff_cmd=eff_ref_filt) # apply only effort (comprehensive of all imp. terms) self._articulation_view.set_joint_efforts(self._imp_eff) else: # we first apply safety to reference joint cmds if self.limiter is not None: self.limiter.apply(q_cmd=self._pos_ref, v_cmd=self._vel_ref, eff_cmd=self._eff_ref) if not self.override_art_controller: # using omniverse's articulation PD controller self._articulation_view.set_joint_efforts(self._eff_ref) self._articulation_view.set_joint_position_targets(self._pos_ref) self._articulation_view.set_joint_velocity_targets(self._vel_ref) else: # impedance torque computed explicitly self._pos_err = torch.sub(self._pos_ref, self._pos) self._vel_err = torch.sub(self._vel_ref, self._vel) self._imp_eff = torch.add(self._eff_ref, torch.add( torch.mul(self._pos_gains, self._pos_err), torch.mul(self._vel_gains, self._vel_err))) # torch.cuda.synchronize() # we also make the resulting imp eff safe if self.limiter is not None: self.limiter.apply(eff_cmd=self._imp_eff) # apply only effort (comprehensive of all imp. terms) self._articulation_view.set_joint_efforts(self._imp_eff) if self.enable_profiling: self.profiling_data["time_to_apply_cmds"] = \ time.perf_counter() - self.start_time def get_jnt_names_matching(self, name_pattern: str): return [jnt for jnt in self.jnts_names if name_pattern in jnt] def get_jnt_idxs_matching(self, name_pattern: str): jnts_names = self.get_jnt_names_matching(name_pattern) jnt_idxs = [self.jnts_names.index(jnt) for jnt in jnts_names] if not len(jnt_idxs) == 0: return torch.tensor(jnt_idxs, dtype=torch.int64, device=self._torch_device) else: return None def pos_gains(self): return self._pos_gains def vel_gains(self): return self._vel_gains def eff_ref(self): return self._eff_ref def pos_ref(self): return self._pos_ref def vel_ref(self): return self._vel_ref def pos_err(self): return self._pos_err def vel_err(self): return self._vel_err def pos(self): return self._pos def vel(self): return self._vel def eff(self): return self._eff def imp_eff(self): return self._imp_eff def reset(self, robot_indxs: torch.Tensor = None): self.gains_initialized = False self.refs_initialized = False self._all_dofs_idxs = torch.tensor([i for i in range(0, self.n_dofs)], dtype=torch.int64, device=self._torch_device) self._all_robots_idxs = torch.tensor([i for i in range(0, self.num_robots)], dtype=torch.int64, device=self._torch_device) if robot_indxs is None: # reset all data # we assume diagonal joint impedance gain matrices, so we can save on memory and only store the diagonal self._pos_gains = torch.full((self.num_robots, self.n_dofs), self._default_pgain, device = self._torch_device, dtype=self._torch_dtype) self._vel_gains = torch.full((self.num_robots, self.n_dofs), self._default_vgain, device = self._torch_device, dtype=self._torch_dtype) self._eff_ref = torch.zeros((self.num_robots, self.n_dofs), device = self._torch_device, dtype=self._torch_dtype) self._pos_ref = torch.zeros((self.num_robots, self.n_dofs), device = self._torch_device, dtype=self._torch_dtype) self._vel_ref = torch.zeros((self.num_robots, self.n_dofs), device = self._torch_device, dtype=self._torch_dtype) self._pos_err = torch.zeros((self.num_robots, self.n_dofs), device = self._torch_device, dtype=self._torch_dtype) self._vel_err = torch.zeros((self.num_robots, self.n_dofs), device = self._torch_device, dtype=self._torch_dtype) self._pos = torch.zeros((self.num_robots, self.n_dofs), device = self._torch_device, dtype=self._torch_dtype) self._vel = torch.zeros((self.num_robots, self.n_dofs), device = self._torch_device, dtype=self._torch_dtype) self._eff = torch.zeros((self.num_robots, self.n_dofs), device = self._torch_device, dtype=self._torch_dtype) self._imp_eff = torch.zeros((self.num_robots, self.n_dofs), device = self._torch_device, dtype=self._torch_dtype) if self._filter_available: self._pos_ref_filter.reset() self._vel_ref_filter.reset() self._eff_ref_filter.reset() else: # only reset some robots if self._debug_checks: self._validate_selectors(robot_indxs=robot_indxs) # throws if checks not satisfied n_envs = robot_indxs.shape[0] # we assume diagonal joint impedance gain matrices, so we can save on memory and only store the diagonal self._pos_gains[robot_indxs, :] = torch.full((n_envs, self.n_dofs), self._default_pgain, device = self._torch_device, dtype=self._torch_dtype) self._vel_gains[robot_indxs, :] = torch.full((n_envs, self.n_dofs), self._default_vgain, device = self._torch_device, dtype=self._torch_dtype) self._eff_ref[robot_indxs, :] = 0 self._pos_ref[robot_indxs, :] = 0 self._vel_ref[robot_indxs, :] = 0 # if self.override_art_controller: # saving memory (these are not necessary if not overriding Isaac's art. controller) self._pos_err[robot_indxs, :] = torch.zeros((n_envs, self.n_dofs), device = self._torch_device, dtype=self._torch_dtype) self._vel_err[robot_indxs, :] = torch.zeros((n_envs, self.n_dofs), device = self._torch_device, dtype=self._torch_dtype) self._pos[robot_indxs, :] = torch.zeros((n_envs, self.n_dofs), device = self._torch_device, dtype=self._torch_dtype) self._vel[robot_indxs, :] = torch.zeros((n_envs, self.n_dofs), device = self._torch_device, dtype=self._torch_dtype) self._eff[robot_indxs, :] = torch.zeros((n_envs, self.n_dofs), device = self._torch_device, dtype=self._torch_dtype) self._imp_eff[robot_indxs, :] = torch.zeros((n_envs, self.n_dofs), device = self._torch_device, dtype=self._torch_dtype) if self._filter_available: self._pos_ref_filter.reset(idxs = robot_indxs) self._vel_ref_filter.reset(idxs = robot_indxs) self._eff_ref_filter.reset(idxs = robot_indxs) if self.init_art_on_creation: # will use updated gains/refs based on reset (non updated gains/refs will be the same) self._apply_init_gains_to_art() self._apply_init_refs_to_art() def _apply_init_gains_to_art(self): if not self.gains_initialized: if not self.override_art_controller: self._articulation_view.set_gains(kps = self._pos_gains, kds = self._vel_gains) else: # settings Isaac's PD controller gains to 0 no_gains = torch.zeros((self.num_robots, self.n_dofs), device = self._torch_device, dtype=self._torch_dtype) self._articulation_view.set_gains(kps = no_gains, kds = no_gains) self.gains_initialized = True def _apply_init_refs_to_art(self): if not self.refs_initialized: if not self.override_art_controller: self._articulation_view.set_joint_efforts(self._eff_ref) self._articulation_view.set_joint_position_targets(self._pos_ref) self._articulation_view.set_joint_velocity_targets(self._vel_ref) else: self._articulation_view.set_joint_efforts(self._eff_ref) self.refs_initialized = True def _validate_selectors(self, robot_indxs: torch.Tensor = None, jnt_indxs: torch.Tensor = None): if robot_indxs is not None: robot_indxs_shape = robot_indxs.shape if (not (len(robot_indxs_shape) == 1 and \ robot_indxs.dtype == torch.int64 and \ bool(torch.min(robot_indxs) >= 0) and \ bool(torch.max(robot_indxs) < self.num_robots)) and \ robot_indxs.device.type == self._torch_device.type): # sanity checks error = "Mismatch in provided selector \n" + \ "robot_indxs_shape -> " + f"{len(robot_indxs_shape)}" + " VS" + " expected -> " + f"{1}" + "\n" + \ "robot_indxs.dtype -> " + f"{robot_indxs.dtype}" + " VS" + " expected -> " + f"{torch.int64}" + "\n" + \ "torch.min(robot_indxs) >= 0) -> " + f"{bool(torch.min(robot_indxs) >= 0)}" + " VS" + f" {True}" + "\n" + \ "torch.max(robot_indxs) < self.n_dofs -> " + f"{torch.max(robot_indxs)}" + " VS" + f" {self.num_robots}\n" + \ "robot_indxs.device -> " + f"{robot_indxs.device.type}" + " VS" + " expected -> " + f"{self._torch_device.type}" + "\n" Journal.log(self.__class__.__name__, "_validate_selectors", error, LogType.EXCEP, throw_when_excep = True) if jnt_indxs is not None: jnt_indxs_shape = jnt_indxs.shape if (not (len(jnt_indxs_shape) == 1 and \ jnt_indxs.dtype == torch.int64 and \ bool(torch.min(jnt_indxs) >= 0) and \ bool(torch.max(jnt_indxs) < self.n_dofs)) and \ jnt_indxs.device.type == self._torch_device.type): # sanity checks error = "Mismatch in provided selector \n" + \ "jnt_indxs_shape -> " + f"{len(jnt_indxs_shape)}" + " VS" + " expected -> " + f"{1}" + "\n" + \ "jnt_indxs.dtype -> " + f"{jnt_indxs.dtype}" + " VS" + " expected -> " + f"{torch.int64}" + "\n" + \ "torch.min(jnt_indxs) >= 0) -> " + f"{bool(torch.min(jnt_indxs) >= 0)}" + " VS" + f" {True}" + "\n" + \ "torch.max(jnt_indxs) < self.n_dofs -> " + f"{torch.max(jnt_indxs)}" + " VS" + f" {self.num_robots}" + \ "robot_indxs.device -> " + f"{jnt_indxs.device.type}" + " VS" + " expected -> " + f"{self._torch_device.type}" + "\n" Journal.log(self.__class__.__name__, "_validate_selectors", error, LogType.EXCEP, throw_when_excep = True) def _validate_signal(self, signal: torch.Tensor, selector: torch.Tensor = None, name: str = "signal"): if self._debug_checks: signal_shape = signal.shape selector_shape = selector[0].shape if not (signal_shape[0] == selector_shape[0] and \ signal_shape[1] == selector_shape[1] and \ signal.device.type == self._torch_device.type and \ signal.dtype == self._torch_dtype): big_error = f"Mismatch in provided signal [{name}" + "] and/or selector \n" + \ "signal rows -> " + f"{signal_shape[0]}" + " VS" + " expected rows -> " + f"{selector_shape[0]}" + "\n" + \ "signal cols -> " + f"{signal_shape[1]}" + " VS" + " expected cols -> " + f"{selector_shape[1]}" + "\n" + \ "signal dtype -> " + f"{signal.dtype}" + " VS" + " expected -> " + f"{self._torch_dtype}" + "\n" + \ "signal device -> " + f"{signal.device.type}" + " VS" + " expected type -> " + f"{self._torch_device.type}" Journal.log(self.__class__.__name__, "_validate_signal", big_error, LogType.EXCEP, throw_when_excep = True) def _gen_selector(self, robot_indxs: torch.Tensor = None, jnt_indxs: torch.Tensor = None): if self._debug_checks: self._validate_selectors(robot_indxs=robot_indxs, jnt_indxs=jnt_indxs) # throws if not valid if robot_indxs is None: robot_indxs = self._all_robots_idxs if jnt_indxs is None: jnt_indxs = self._all_dofs_idxs return torch.meshgrid((robot_indxs, jnt_indxs), indexing="ij")
32,884
Python
40.157697
139
0.485282
AndrePatri/OmniRoboGym/omni_robo_gym/utils/terrains.py
# Copyright (C) 2023 Andrea Patrizi (AndrePatri, andreapatrizi1b6e6@gmail.com) # # This file is part of OmniRoboGym and distributed under the General Public License version 2 license. # # OmniRoboGym is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 2 of the License, or # (at your option) any later version. # # OmniRoboGym is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with OmniRoboGym. If not, see <http://www.gnu.org/licenses/>. # import os, sys SCRIPT_DIR = os.path.dirname(os.path.abspath(__file__)) sys.path.append(SCRIPT_DIR) import numpy as np from omni_robo_gym.utils.terrain_utils import * from pxr import Usd class RlTerrains(): def __init__(self, stage: Usd.Stage): self._stage = stage def get_wave_terrain(self, terrain_size = 40, num_waves = 10, amplitude = 1, position = np.array([0.0, 0.0, 0.0])): # creates a terrain num_terrains = 1 terrain_width = terrain_size terrain_length = terrain_size horizontal_scale = 0.25 # [m] vertical_scale = 0.005 # [m] num_rows = int(terrain_width/horizontal_scale) num_cols = int(terrain_length/horizontal_scale) heightfield = np.zeros((num_terrains * num_rows, num_cols), dtype=np.int16) def new_sub_terrain(): return SubTerrain(width=num_rows, length=num_cols, vertical_scale=vertical_scale, horizontal_scale=horizontal_scale) heightfield[0:num_rows, :] = wave_terrain(new_sub_terrain(), num_waves=num_waves, amplitude=amplitude).height_field_raw vertices, triangles = convert_heightfield_to_trimesh(heightfield, horizontal_scale=horizontal_scale, vertical_scale=vertical_scale, slope_threshold=1.5) position = np.array([-terrain_width/2.0, terrain_length/2.0, 0]) + position orientation = np.array([0.70711, 0.0, 0.0, -0.70711]) add_terrain_to_stage(stage=self._stage, vertices=vertices, triangles=triangles, position=position, orientation=orientation) def get_sloped_terrain(self, terrain_size = 40, slope = -0.5, position = np.array([0.0, 0.0, 0.0])): # creates a terrain num_terrains = 1 terrain_width = terrain_size terrain_length = terrain_size horizontal_scale = 0.25 # [m] vertical_scale = 0.005 # [m] num_rows = int(terrain_width/horizontal_scale) num_cols = int(terrain_length/horizontal_scale) heightfield = np.zeros((num_terrains * num_rows, num_cols), dtype=np.int16) def new_sub_terrain(): return SubTerrain(width=num_rows, length=num_cols, vertical_scale=vertical_scale, horizontal_scale=horizontal_scale) heightfield[0:num_rows, :] = pyramid_sloped_terrain(new_sub_terrain(), slope=slope).height_field_raw vertices, triangles = convert_heightfield_to_trimesh(heightfield, horizontal_scale=horizontal_scale, vertical_scale=vertical_scale, slope_threshold=1.5) position = np.array([-terrain_width/2.0, terrain_length/2.0, 0]) + position orientation = np.array([0.70711, 0.0, 0.0, -0.70711]) add_terrain_to_stage(stage=self._stage, vertices=vertices, triangles=triangles, position=position, orientation=orientation) def get_stairs_terrain(self, terrain_size = 40, step_width = 0.75, step_height = -0.5, position = np.array([0.0, 0.0, 0.0])): # creates a terrain num_terrains = 1 terrain_width = terrain_size terrain_length = terrain_size horizontal_scale = 0.25 # [m] vertical_scale = 0.005 # [m] num_rows = int(terrain_width/horizontal_scale) num_cols = int(terrain_length/horizontal_scale) heightfield = np.zeros((num_terrains * num_rows, num_cols), dtype=np.int16) def new_sub_terrain(): return SubTerrain(width=num_rows, length=num_cols, vertical_scale=vertical_scale, horizontal_scale=horizontal_scale) heightfield[0:num_rows, :] = stairs_terrain(new_sub_terrain(), step_width=step_width, step_height=step_height).height_field_raw vertices, triangles = convert_heightfield_to_trimesh(heightfield, horizontal_scale=horizontal_scale, vertical_scale=vertical_scale, slope_threshold=1.5) position = np.array([-terrain_width/2.0, terrain_length/2.0, 0]) + position orientation = np.array([0.70711, 0.0, 0.0, -0.70711]) add_terrain_to_stage(stage=self._stage, vertices=vertices, triangles=triangles, position=position, orientation=orientation) def get_random_terrain(self, terrain_size = 40, min_height = -0.2, max_height = 0.2, step = 0.2, downsampled_scale=0.5, position = np.array([0.0, 0.0, 0.0])): # creates a terrain num_terrains = 1 terrain_width = terrain_size terrain_length = terrain_size horizontal_scale = 0.25 # [m] vertical_scale = 0.005 # [m] num_rows = int(terrain_width/horizontal_scale) num_cols = int(terrain_length/horizontal_scale) heightfield = np.zeros((num_terrains * num_rows, num_cols), dtype=np.int16) def new_sub_terrain(): return SubTerrain(width=num_rows, length=num_cols, vertical_scale=vertical_scale, horizontal_scale=horizontal_scale) heightfield[0:num_rows, :] = random_uniform_terrain(new_sub_terrain(), min_height=min_height, max_height=max_height, step=step, downsampled_scale=downsampled_scale).height_field_raw vertices, triangles = convert_heightfield_to_trimesh(heightfield, horizontal_scale=horizontal_scale, vertical_scale=vertical_scale, slope_threshold=1.5) position = np.array([-terrain_width/2.0, terrain_length/2.0, 0]) + position orientation = np.array([0.70711, 0.0, 0.0, -0.70711]) add_terrain_to_stage(stage=self._stage, vertices=vertices, triangles=triangles, position=position, orientation=orientation) def get_obstacles_terrain(self, terrain_size = 40.0, num_obs = 50, max_height = 0.5, min_size = 0.5, max_size = 5.0, position = np.array([0.0, 0.0, 0.0])): # create all available terrain types num_terains = 1 terrain_width = terrain_size terrain_length = terrain_size horizontal_scale = 0.25 # [m] vertical_scale = 0.005 # [m] num_rows = int(terrain_width/horizontal_scale) num_cols = int(terrain_length/horizontal_scale) heightfield = np.zeros((num_terains*num_rows, num_cols), dtype=np.int16) def new_sub_terrain(): return SubTerrain(width=num_rows, length=num_cols, vertical_scale=vertical_scale, horizontal_scale=horizontal_scale) heightfield[0:num_rows, :] = discrete_obstacles_terrain(new_sub_terrain(), max_height=max_height, min_size=min_size, max_size=max_size, num_rects=num_obs).height_field_raw vertices, triangles = convert_heightfield_to_trimesh(heightfield, horizontal_scale=horizontal_scale, vertical_scale=vertical_scale, slope_threshold=1.5) position = np.array([-terrain_width/2.0, terrain_length/2.0, 0]) + position orientation = np.array([0.70711, 0.0, 0.0, -0.70711]) add_terrain_to_stage(stage=self._stage, vertices=vertices, triangles=triangles, position=position, orientation=orientation) def post_reset(self): a = 1 def get_observations(self): pass def calculate_metrics(self) -> None: pass def is_done(self) -> None: pass
9,922
Python
36.730038
160
0.528926
AndrePatri/OmniRoboGym/docs/isaac2023.1.0_issues.md
### Some bugs of Isaac2023.1.0 which can be easily fixed #### 1.0 Nucleus blocking function makes startup super slow Easy temporary fix: modify /home/username/.local/share/ov/pkg/isaac_sim-2023.1.0/exts/omni.isaac.core/omni/isaac/core/utils/nucleus.py . Change lines 178 to 198 which is the check server function to below: ```python def check_server(server: str, path: str, timeout: float = 10.0) -> bool: """Check a specific server for a path Args: server (str): Name of Nucleus server path (str): Path to search Returns: bool: True if folder is found """ carb.log_info("Checking path: {}{}".format(server, path)) # Increase hang detection timeout if "localhost" not in server: omni.client.set_hang_detection_time_ms(10000) result, _ = omni.client.stat("{}{}".format(server, path)) if result == Result.OK: carb.log_info("Success: {}{}".format(server, path)) return True carb.log_info("Failure: {}{} not accessible".format(server, path)) return False ``` #### 2.0 Grid Cloner bug See `docs/grid_cloner_bugfix.py` for more details #### 3.0 Contact sensor bug When cloning environments, it's not possible to create contact sensors on the cloned environments because of a failed collision_API enabled flag option. Removing the check seems to recolve the problem without any major or noticeable issues.
1,413
Markdown
39.399999
240
0.683652
AndrePatri/OmniRoboGym/docs/grid_cloner_bugfix/grid_cloner.py
# Copyright (c) 2022-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, Union import numpy as np import omni.usd import torch from omni.isaac.cloner import Cloner from pxr import Gf, UsdGeom class GridCloner(Cloner): """ This is a specialized Cloner class that will automatically generate clones in a grid fashion. """ def __init__(self, spacing: float, num_per_row: int = -1): """ Args: spacing (float): Spacing between clones. num_per_row (int): Number of clones to place in a row. Defaults to sqrt(num_clones). """ self._spacing = spacing self._num_per_row = num_per_row Cloner.__init__(self) def clone( self, source_prim_path: str, prim_paths: List[str], position_offsets: np.ndarray = None, orientation_offsets: np.ndarray = None, replicate_physics: bool = False, base_env_path: str = None, root_path: str = None, copy_from_source: bool = False ): """ Creates clones in a grid fashion. Positions of clones are computed automatically. Args: source_prim_path (str): Path of source object. prim_paths (List[str]): List of destination paths. position_offsets (np.ndarray): Positions to be applied as local translations on top of computed clone position. Defaults to None, no offset will be applied. orientation_offsets (np.ndarray): Orientations to be applied as local rotations for each clone. Defaults to None, no offset will be applied. replicate_physics (bool): Uses omni.physics replication. This will replicate physics properties directly for paths beginning with root_path and skip physics parsing for anything under the base_env_path. base_env_path (str): Path to namespace for all environments. Required if replicate_physics=True and define_base_env() not called. root_path (str): Prefix path for each environment. Required if replicate_physics=True and generate_paths() not called. copy_from_source: (bool): Setting this to False will inherit all clones from the source prim; any changes made to the source prim will be reflected in the clones. Setting this to True will make copies of the source prim when creating new clones; changes to the source prim will not be reflected in clones. Defaults to False. Note that setting this to True will take longer to execute. Returns: positions (List): Computed positions of all clones. """ num_clones = len(prim_paths) self._num_per_row = int(np.sqrt(num_clones)) if self._num_per_row == -1 else self._num_per_row num_rows = np.ceil(num_clones / self._num_per_row) num_cols = np.ceil(num_clones / num_rows) row_offset = 0.5 * self._spacing * (num_rows - 1) col_offset = 0.5 * self._spacing * (num_cols - 1) stage = omni.usd.get_context().get_stage() positions = [] orientations = [] for i in range(num_clones): # compute transform row = i // num_cols col = i % num_cols x = row_offset - row * self._spacing y = col * self._spacing - col_offset up_axis = UsdGeom.GetStageUpAxis(stage) position = [x, y, 0] if up_axis == UsdGeom.Tokens.z else [x, 0, y] orientation = Gf.Quatd.GetIdentity() if position_offsets is not None: translation = position_offsets[i] + position else: translation = position if orientation_offsets is not None: orientation = ( Gf.Quatd(orientation_offsets[i][0].item(), Gf.Vec3d(orientation_offsets[i][1:].tolist())) * orientation ) else: orientation = [ orientation.GetReal(), orientation.GetImaginary()[0], orientation.GetImaginary()[1], orientation.GetImaginary()[2], ] positions.append(translation) orientations.append(orientation) super().clone( source_prim_path=source_prim_path, prim_paths=prim_paths, positions=positions, orientations=orientations, replicate_physics=replicate_physics, base_env_path=base_env_path, root_path=root_path, copy_from_source=copy_from_source, ) return positions
5,073
Python
40.590164
246
0.606742
AndrePatri/OmniRoboGym/docs/contact_sensor_bugfix/contact_sensor.py
# Copyright (c) 2021-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 omni.isaac.kit import SimulationApp simulation_app = SimulationApp({"headless": False}) import argparse import sys import carb import numpy as np from omni.isaac.core import World from omni.isaac.core.articulations import Articulation from omni.isaac.core.utils.nucleus import get_assets_root_path from omni.isaac.core.utils.stage import add_reference_to_stage from omni.isaac.sensor import ContactSensor from omni.isaac.cloner import GridCloner import omni.isaac.core.utils.prims as prim_utils parser = argparse.ArgumentParser() parser.add_argument("--test", default=False, action="store_true", help="Run in test mode") args, unknown = parser.parse_known_args() assets_root_path = get_assets_root_path() if assets_root_path is None: carb.log_error("Could not find Isaac Sim assets folder") simulation_app.close() sys.exit() my_world = World(stage_units_in_meters=1.0) my_world.scene.add_default_ground_plane() asset_path = assets_root_path + "/Isaac/Robots/Ant/ant.usd" add_reference_to_stage(usd_path=asset_path, prim_path="/World/envs/env_0/Ant") ant = my_world.scene.add(Articulation(prim_path="/World/envs/env_0/Ant/torso", name="ant", translation=np.array([0, 0, 1.5]))) ant_foot_prim_names = ["right_back_foot", "left_back_foot", "front_right_foot", "front_left_foot"] translations = np.array( [[0.38202, -0.40354, -0.0887], [-0.4, -0.40354, -0.0887], [-0.4, 0.4, -0.0887], [0.4, 0.4, -0.0887]] ) # moving def prim # move_prim(robot_prim_path_default, # from # robot_base_prim_path) # to num_envs = 3 env_ns = "/World/envs" env_spacing = 15 # [m] template_env_ns = env_ns + "/env_0" cloner = GridCloner(spacing=env_spacing) cloner.define_base_env(env_ns) envs_prim_paths = cloner.generate_paths(env_ns + "/env", num_envs) cloner.clone( source_prim_path=template_env_ns, prim_paths=envs_prim_paths, replicate_physics=True, position_offsets = None ) ant_sensors = [] for i in range(4): ant_sensors.append( my_world.scene.add( ContactSensor( prim_path="/World/envs/env_0/Ant/" + ant_foot_prim_names[i] + "/contact_sensor", name="ant_contact_sensor_{}".format(i), min_threshold=0, max_threshold=10000000, radius=0.1, translation=translations[i], ) ) ) ant_sensors[0].add_raw_contact_data_to_frame() ant_sensors2 = [] for i in range(4): ant_sensors2.append( my_world.scene.add( ContactSensor( prim_path="/World/envs/env_1/Ant/" + ant_foot_prim_names[i] + "/contact_sensor", name="ant_contact_sensor2_{}".format(i), min_threshold=0, max_threshold=10000000, radius=0.1, translation=translations[i], ) ) ) ant_sensors2[0].add_raw_contact_data_to_frame() my_world.reset() while simulation_app.is_running(): my_world.step(render=True) if my_world.is_playing(): print(ant_sensors2[0].get_current_frame()) if my_world.current_time_step_index == 0: my_world.reset() simulation_app.close()
3,638
Python
30.370689
126
0.657779
AndrePatri/OmniRoboGym/docs/sim_substepping_reset_issue/test_substepping_when_reset.py
# Copyright (c) 2021-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 numpy as np import torch def get_device(sim_params): if "sim_device" in sim_params: device = sim_params["sim_device"] else: device = "cpu" physics_device_id = carb.settings.get_settings().get_as_int("/physics/cudaDevice") gpu_id = 0 if physics_device_id < 0 else physics_device_id if sim_params and "use_gpu_pipeline" in sim_params: # GPU pipeline must use GPU simulation if sim_params["use_gpu_pipeline"]: device = "cuda:" + str(gpu_id) elif sim_params and "use_gpu" in sim_params: if sim_params["use_gpu"]: device = "cuda:" + str(gpu_id) return device def sim_parameters(): # simulation parameters sim_params = {} # device settings sim_params["use_gpu_pipeline"] = True # disabling gpu pipeline is necessary to be able # to retrieve some quantities from the simulator which, otherwise, would have random values sim_params["use_gpu"] = True # does this actually do anything? if sim_params["use_gpu_pipeline"]: sim_params["device"] = "cuda" else: sim_params["device"] = "cpu" device = sim_params["device"] # sim_params["dt"] = 1.0/100.0 # physics_dt? sim_params["physics_dt"] = 1.0/400.0 # physics_dt? sim_params["rendering_dt"] = sim_params["physics_dt"] sim_params["substeps"] = 1 # number of physics steps to be taken for for each rendering step sim_params["gravity"] = np.array([0.0, 0.0, -9.81]) sim_params["enable_scene_query_support"] = False sim_params["use_fabric"] = True # Enable/disable reading of physics buffers directly. Default is True. sim_params["replicate_physics"] = True # sim_params["worker_thread_count"] = 4 sim_params["solver_type"] = 1 # 0: PGS, 1:TGS, defaults to TGS. PGS faster but TGS more stable sim_params["enable_stabilization"] = True # sim_params["bounce_threshold_velocity"] = 0.2 # sim_params["friction_offset_threshold"] = 0.04 # sim_params["friction_correlation_distance"] = 0.025 # sim_params["enable_sleeping"] = True # Per-actor settings ( can override in actor_options ) sim_params["solver_position_iteration_count"] = 4 # defaults to 4 sim_params["solver_velocity_iteration_count"] = 1 # defaults to 1 sim_params["sleep_threshold"] = 0.0 # Mass-normalized kinetic energy threshold below which an actor may go to sleep. # Allowed range [0, max_float). sim_params["stabilization_threshold"] = 1e-5 # Per-body settings ( can override in actor_options ) # sim_params["enable_gyroscopic_forces"] = True # sim_params["density"] = 1000 # density to be used for bodies that do not specify mass or density # sim_params["max_depenetration_velocity"] = 100.0 # sim_params["solver_velocity_iteration_count"] = 1 # GPU buffers settings # sim_params["gpu_max_rigid_contact_count"] = 512 * 1024 # sim_params["gpu_max_rigid_patch_count"] = 80 * 1024 # sim_params["gpu_found_lost_pairs_capacity"] = 1024 # sim_params["gpu_found_lost_aggregate_pairs_capacity"] = 1024 # sim_params["gpu_total_aggregate_pairs_capacity"] = 1024 # sim_params["gpu_max_soft_body_contacts"] = 1024 * 1024 # sim_params["gpu_max_particle_contacts"] = 1024 * 1024 # sim_params["gpu_heap_capacity"] = 64 * 1024 * 1024 # sim_params["gpu_temp_buffer_capacity"] = 16 * 1024 * 1024 # sim_params["gpu_max_num_partitions"] = 8 return sim_params def reset_state(art_view, idxs: torch.Tensor): # root q art_view.set_world_poses(positions = root_p_default[idxs, :], orientations=root_q_default[idxs, :], indices = idxs) # jnts q art_view.set_joint_positions(positions = jnts_q_default[idxs, :], indices = idxs) # root v and omega art_view.set_joint_velocities(velocities = jnts_v_default[idxs, :], indices = idxs) # jnts v concatenated_vel = torch.cat((root_v_default[idxs, :], root_omega_default[idxs, :]), dim=1) art_view.set_velocities(velocities = concatenated_vel, indices = idxs) # jnts eff art_view.set_joint_efforts(efforts = jnts_eff_default[idxs, :], indices = idxs) def get_robot_state( art_view): pose = art_view.get_world_poses( clone = True) # tuple: (pos, quat) # root p (measured, previous, default) root_p = pose[0] # root q (measured, previous, default) root_q = pose[1] # root orientation # jnt q (measured, previous, default) jnts_q = art_view.get_joint_positions( clone = True) # joint positions # root v (measured, default) root_v= art_view.get_linear_velocities( clone = True) # root lin. velocity # root omega (measured, default) root_omega = art_view.get_angular_velocities( clone = True) # root ang. velocity # joints v (measured, default) jnts_v = art_view.get_joint_velocities( clone = True) # joint velocities jnts_eff = art_view.get_measured_joint_efforts(clone = True) return root_p, root_q, jnts_q, root_v, root_omega, jnts_v, jnts_eff from omni.isaac.kit import SimulationApp import carb import os experience = f'{os.environ["EXP_PATH"]}/omni.isaac.sim.python.omnirobogym.headless.kit' sim_params = sim_parameters() num_envs = 2 headless = True simulation_app = SimulationApp({"headless": headless, "physics_gpu": 0}, experience=experience) from omni.isaac.core import World from omni.isaac.core.articulations import ArticulationView from omni.importer.urdf import _urdf # urdf import config import_config = _urdf.ImportConfig() import_config.merge_fixed_joints = True import_config.import_inertia_tensor = True import_config.fix_base = False import_config.self_collision = False my_world = World(stage_units_in_meters=1.0, physics_dt=sim_params["physics_dt"], rendering_dt=sim_params["rendering_dt"], backend="torch", device=str(get_device(sim_params=sim_params)), physics_prim_path="/physicsScene", set_defaults = False, sim_params=sim_params) # create initial robot import omni.isaac.core.utils.prims as prim_utils # create GridCloner instance env_ns = "/World/envs" template_env_ns = env_ns + "/env" # a single env. may contain multiple robots base_env = template_env_ns + "_0" base_robot_path = base_env + "/panda" # get path to resource from omni.isaac.core.utils.extensions import get_extension_path_from_name extension_path = get_extension_path_from_name("omni.importer.urdf") # import URDF at default prim path import omni.kit success, robot_prim_path_default = omni.kit.commands.execute( "URDFParseAndImportFile", urdf_path=extension_path + "/data/urdf/robots/franka_description/robots/panda_arm.urdf", import_config=import_config, ) # moving default prim to base prim path (for potential cloning) from omni.isaac.core.utils.prims import move_prim prim_utils.define_prim(base_env) move_prim(robot_prim_path_default, # from base_robot_path) # to # cloning from omni.isaac.cloner import GridCloner cloner = GridCloner(spacing=6) _envs_prim_paths = cloner.generate_paths(template_env_ns, num_envs) position_offsets = np.array([[0.0, 0.0, 0.6]] * num_envs) cloner.clone( source_prim_path=base_env, prim_paths=_envs_prim_paths, base_env_path=base_env, position_offsets=position_offsets, replicate_physics=True ) # Prim paths structure: # World/envs/env_0/panda/panda_link0/... # this only in 2023.1.0 art_view = ArticulationView(name = "Panda" + "ArtView", prim_paths_expr = env_ns + "/env_.*"+ "/panda/panda_link0", reset_xform_properties=False # required as per doc. when cloning ) # moreover, robots are not cloned at different locations my_world.scene.add(art_view) ground_plane_prim_path = "/World/terrain" my_world.scene.add_default_ground_plane(z_position=0, name="terrain", prim_path= ground_plane_prim_path, static_friction=0.5, dynamic_friction=0.5, restitution=0.8) cloner.filter_collisions(physicsscene_path = my_world.get_physics_context().prim_path, collision_root_path = "/World/collisions", prim_paths=_envs_prim_paths, global_paths=[ground_plane_prim_path] # can collide with these prims ) my_world.reset() # init default state from measurements root_p, root_q, jnts_q, root_v, \ root_omega, jnts_v, jnts_eff = get_robot_state(art_view) root_p_default = torch.clone(root_p) root_q_default = torch.clone(root_q) jnts_q_default = torch.clone(jnts_q) jnts_v_default = torch.clone(jnts_v) root_omega_default = torch.clone(root_omega) root_v_default = torch.clone(root_v) jnts_eff_default = torch.clone(jnts_eff).zero_() # default values root_p_default[:, 0] = 0 root_p_default[:, 1] = 0 root_p_default[:, 2] = 0.5 root_q_default[:, 0] = 0.0 root_q_default[:, 1] = 0.0 root_q_default[:, 2] = 0.0 root_q_default[:, 3] = 1.0 jnts_q_default[:, :] = 1.0 jnts_v_default[:, :] = 0.0 root_omega_default[:, :] = 0.0 root_v_default[:, :] = 0.0 no_gains = torch.zeros((num_envs, jnts_eff_default.shape[1]), device = get_device(sim_params), dtype=torch.float32) art_view.set_gains(kps = no_gains, kds = no_gains) print("Extension path: " + str(extension_path)) print("Prim paths: " + str(art_view.prim_paths)) reset_ever_n_steps = 100 just_reset = False for i in range(0, 1000): if ((i + 1) % reset_ever_n_steps) == 0: print("resetting to default") reset_state(art_view, torch.tensor([0], dtype=torch.int)) just_reset = True my_world.step() # retrieve state root_p, root_q, jnts_q, root_v, \ root_omega, jnts_v, jnts_eff = get_robot_state(art_view) # if just_reset: # check we hace reset correcty print("measured") print(jnts_q) print("default") print(jnts_q_default) simulation_app.close()
11,081
Python
34.06962
120
0.624222
abizovnuralem/go2_omniverse/terrain_cfg.py
# Copyright (c) 2024, RoboVerse community # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # 1. Redistributions of source code must retain the above copyright notice, this # list of conditions and the following disclaimer. # # 2. Redistributions in binary form must reproduce the above copyright notice, # this list of conditions and the following disclaimer in the documentation # and/or other materials provided with the distribution. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE # DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE # FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL # DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR # SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER # CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, # OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. from terrain_generator_cfg import TerrainGeneratorCfg import omni.isaac.orbit.terrains as terrain_gen ROUGH_TERRAINS_CFG = TerrainGeneratorCfg( size=(8.0, 8.0), border_width=0.0, num_rows=1, num_cols=2, horizontal_scale=0.1, vertical_scale=0.005, slope_threshold=0.75, use_cache=False, sub_terrains={ "pyramid_stairs": terrain_gen.MeshPyramidStairsTerrainCfg( proportion=0.2, step_height_range=(0.05, 0.23), step_width=0.3, platform_width=3.0, border_width=1.0, holes=False, ), "pyramid_stairs_inv": terrain_gen.MeshInvertedPyramidStairsTerrainCfg( proportion=0.2, step_height_range=(0.05, 0.23), step_width=0.3, platform_width=3.0, border_width=1.0, holes=False, ), }, )
2,217
Python
38.607142
80
0.700947
abizovnuralem/go2_omniverse/agent_cfg.py
# Copyright (c) 2024, RoboVerse community # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # 1. Redistributions of source code must retain the above copyright notice, this # list of conditions and the following disclaimer. # # 2. Redistributions in binary form must reproduce the above copyright notice, # this list of conditions and the following disclaimer in the documentation # and/or other materials provided with the distribution. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE # DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE # FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL # DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR # SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER # CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, # OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. unitree_go2_agent_cfg = { 'seed': 42, 'device': 'cuda', 'num_steps_per_env': 24, 'max_iterations': 15000, 'empirical_normalization': False, 'policy': { 'class_name': 'ActorCritic', 'init_noise_std': 1.0, 'actor_hidden_dims': [512, 256, 128], 'critic_hidden_dims': [512, 256, 128], 'activation': 'elu' }, 'algorithm': { 'class_name': 'PPO', 'value_loss_coef': 1.0, 'use_clipped_value_loss': True, 'clip_param': 0.2, 'entropy_coef': 0.01, 'num_learning_epochs': 5, 'num_mini_batches': 4, 'learning_rate': 0.001, 'schedule': 'adaptive', 'gamma': 0.99, 'lam': 0.95, 'desired_kl': 0.01, 'max_grad_norm': 1.0 }, 'save_interval': 50, 'experiment_name': 'unitree_go2_rough', 'run_name': '', 'logger': 'tensorboard', 'neptune_project': 'orbit', 'wandb_project': 'orbit', 'resume': False, 'load_run': '.*', 'load_checkpoint': 'model_.*.pt' }
2,562
Python
40.338709
80
0.613193
abizovnuralem/go2_omniverse/main.py
# Copyright (c) 2024, RoboVerse community # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # 1. Redistributions of source code must retain the above copyright notice, this # list of conditions and the following disclaimer. # # 2. Redistributions in binary form must reproduce the above copyright notice, # this list of conditions and the following disclaimer in the documentation # and/or other materials provided with the distribution. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE # DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE # FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL # DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR # SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER # CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, # OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. """Script to play a checkpoint if an RL agent from RSL-RL.""" from __future__ import annotations """Launch Isaac Sim Simulator first.""" import argparse from omni.isaac.orbit.app import AppLauncher # local imports import cli_args # isort: skip # add argparse arguments parser = argparse.ArgumentParser(description="Train an RL agent with RSL-RL.") parser.add_argument("--cpu", action="store_true", default=False, help="Use CPU pipeline.") parser.add_argument( "--disable_fabric", action="store_true", default=False, help="Disable fabric and use USD I/O operations." ) parser.add_argument("--num_envs", type=int, default=1, help="Number of environments to simulate.") parser.add_argument("--task", type=str, default="Isaac-Velocity-Rough-Unitree-Go2-v0", help="Name of the task.") parser.add_argument("--seed", type=int, default=None, help="Seed used for the environment") # append RSL-RL cli arguments cli_args.add_rsl_rl_args(parser) # append AppLauncher cli args AppLauncher.add_app_launcher_args(parser) args_cli = parser.parse_args() # launch omniverse app app_launcher = AppLauncher(args_cli) simulation_app = app_launcher.app import omni ext_manager = omni.kit.app.get_app().get_extension_manager() ext_manager.set_extension_enabled_immediate("omni.isaac.ros2_bridge", True) """Rest everything follows.""" import os import math import gymnasium as gym import torch import carb import usdrt.Sdf from omni.isaac.orbit_tasks.utils import get_checkpoint_path from omni.isaac.orbit_tasks.utils.wrappers.rsl_rl import ( RslRlOnPolicyRunnerCfg, RslRlVecEnvWrapper ) from omni.isaac.orbit.utils import configclass from omni.isaac.orbit_assets.unitree import UNITREE_GO2_CFG from omni.isaac.orbit.envs import RLTaskEnvCfg import omni.isaac.orbit.sim as sim_utils from omni.isaac.orbit.assets import ArticulationCfg, AssetBaseCfg from omni.isaac.orbit.managers import CurriculumTermCfg as CurrTerm from omni.isaac.orbit.managers import EventTermCfg as EventTerm from omni.isaac.orbit.managers import ObservationGroupCfg as ObsGroup from omni.isaac.orbit.managers import ObservationTermCfg as ObsTerm from omni.isaac.orbit.managers import RewardTermCfg as RewTerm from omni.isaac.orbit.managers import SceneEntityCfg from omni.isaac.orbit.managers import TerminationTermCfg as DoneTerm from omni.isaac.orbit.scene import InteractiveSceneCfg from omni.isaac.orbit.sensors import ContactSensorCfg, RayCasterCfg, patterns, CameraCfg from omni.isaac.orbit.terrains import TerrainImporterCfg from omni.isaac.orbit.utils import configclass from omni.isaac.orbit.utils.noise import AdditiveUniformNoiseCfg as Unoise import omni.isaac.orbit_tasks.locomotion.velocity.mdp as mdp import omni.appwindow # Contains handle to keyboard from rsl_rl.runners import OnPolicyRunner from typing import Literal from dataclasses import MISSING from omnigraph import create_front_cam_omnigraph from agent_cfg import unitree_go2_agent_cfg from terrain_cfg import ROUGH_TERRAINS_CFG base_command = [0, 0, 0] @configclass class MySceneCfg(InteractiveSceneCfg): """Configuration for the terrain scene with a legged robot.""" # ground terrain terrain = TerrainImporterCfg( prim_path="/World/ground", terrain_type="generator", terrain_generator=ROUGH_TERRAINS_CFG, max_init_terrain_level=5, collision_group=-1, physics_material=sim_utils.RigidBodyMaterialCfg( friction_combine_mode="multiply", restitution_combine_mode="multiply", static_friction=1.0, dynamic_friction=1.0, ), visual_material=sim_utils.MdlFileCfg( mdl_path="{NVIDIA_NUCLEUS_DIR}/Materials/Base/Architecture/Shingles_01.mdl", project_uvw=True, ), debug_vis=False, ) # robots robot: ArticulationCfg = MISSING # sensors camera = CameraCfg( prim_path="{ENV_REGEX_NS}/Robot/base/front_cam", update_period=0.1, height=480, width=640, data_types=["rgb", "distance_to_image_plane"], spawn=sim_utils.PinholeCameraCfg( focal_length=24.0, focus_distance=400.0, horizontal_aperture=20.955, clipping_range=(0.1, 1.0e5) ), offset=CameraCfg.OffsetCfg(pos=(0.510, 0.0, 0.015), rot=(0.5, -0.5, 0.5, -0.5), convention="ros"), ) height_scanner = RayCasterCfg( prim_path="{ENV_REGEX_NS}/Robot/base", offset=RayCasterCfg.OffsetCfg(pos=(0.0, 0.0, 20.0)), attach_yaw_only=True, pattern_cfg=patterns.GridPatternCfg(resolution=0.1, size=[1.6, 1.0]), debug_vis=False, mesh_prim_paths=["/World/ground"], ) contact_forces = ContactSensorCfg(prim_path="{ENV_REGEX_NS}/Robot/.*", history_length=3, track_air_time=True) # lights light = AssetBaseCfg( prim_path="/World/light", spawn=sim_utils.DistantLightCfg(color=(0.75, 0.75, 0.75), intensity=3000.0), ) sky_light = AssetBaseCfg( prim_path="/World/skyLight", spawn=sim_utils.DomeLightCfg(color=(0.13, 0.13, 0.13), intensity=1000.0), ) def constant_commands(env: RLTaskEnvCfg) -> torch.Tensor: global base_command """The generated command from the command generator.""" return torch.tensor([base_command], device=env.device).repeat(env.num_envs, 1) @configclass class ObservationsCfg: """Observation specifications for the MDP.""" @configclass class PolicyCfg(ObsGroup): """Observations for policy group.""" # observation terms (order preserved) base_lin_vel = ObsTerm(func=mdp.base_lin_vel) base_ang_vel = ObsTerm(func=mdp.base_ang_vel) projected_gravity = ObsTerm( func=mdp.projected_gravity, noise=Unoise(n_min=-0.05, n_max=0.05), ) velocity_commands = ObsTerm(func=constant_commands) joint_pos = ObsTerm(func=mdp.joint_pos_rel) joint_vel = ObsTerm(func=mdp.joint_vel_rel) actions = ObsTerm(func=mdp.last_action) height_scan = ObsTerm( func=mdp.height_scan, params={"sensor_cfg": SceneEntityCfg("height_scanner")}, clip=(-1.0, 1.0), ) def __post_init__(self): self.enable_corruption = True self.concatenate_terms = True # observation groups policy: PolicyCfg = PolicyCfg() @configclass class ActionsCfg: """Action specifications for the MDP.""" joint_pos = mdp.JointPositionActionCfg(asset_name="robot", joint_names=[".*"], scale=0.5, use_default_offset=True) @configclass class CommandsCfg: """Command specifications for the MDP.""" base_velocity = mdp.UniformVelocityCommandCfg( asset_name="robot", resampling_time_range=(0.0, 0.0), rel_standing_envs=0.02, rel_heading_envs=1.0, heading_command=True, heading_control_stiffness=0.5, debug_vis=True, ranges=mdp.UniformVelocityCommandCfg.Ranges( lin_vel_x=(0.0, 0.0), lin_vel_y=(0.0, 0.0), ang_vel_z=(0.0, 0.0), heading=(0, 0) ), ) @configclass class RewardsCfg: """Reward terms for the MDP.""" # -- task track_lin_vel_xy_exp = RewTerm( func=mdp.track_lin_vel_xy_exp, weight=1.0, params={"command_name": "base_velocity", "std": math.sqrt(0.25)} ) track_ang_vel_z_exp = RewTerm( func=mdp.track_ang_vel_z_exp, weight=0.5, params={"command_name": "base_velocity", "std": math.sqrt(0.25)} ) # -- penalties lin_vel_z_l2 = RewTerm(func=mdp.lin_vel_z_l2, weight=-2.0) ang_vel_xy_l2 = RewTerm(func=mdp.ang_vel_xy_l2, weight=-0.05) dof_torques_l2 = RewTerm(func=mdp.joint_torques_l2, weight=-1.0e-5) dof_acc_l2 = RewTerm(func=mdp.joint_acc_l2, weight=-2.5e-7) action_rate_l2 = RewTerm(func=mdp.action_rate_l2, weight=-0.01) feet_air_time = RewTerm( func=mdp.feet_air_time, weight=0.125, params={ "sensor_cfg": SceneEntityCfg("contact_forces", body_names=".*FOOT"), "command_name": "base_velocity", "threshold": 0.5, }, ) undesired_contacts = RewTerm( func=mdp.undesired_contacts, weight=-1.0, params={"sensor_cfg": SceneEntityCfg("contact_forces", body_names=".*THIGH"), "threshold": 1.0}, ) # -- optional penalties flat_orientation_l2 = RewTerm(func=mdp.flat_orientation_l2, weight=0.0) dof_pos_limits = RewTerm(func=mdp.joint_pos_limits, weight=0.0) @configclass class TerminationsCfg: """Termination terms for the MDP.""" time_out = DoneTerm(func=mdp.time_out, time_out=True) base_contact = DoneTerm( func=mdp.illegal_contact, params={"sensor_cfg": SceneEntityCfg("contact_forces", body_names="base"), "threshold": 1.0}, ) @configclass class EventCfg: """Configuration for events.""" # startup physics_material = EventTerm( func=mdp.randomize_rigid_body_material, mode="startup", params={ "asset_cfg": SceneEntityCfg("robot", body_names=".*"), "static_friction_range": (0.8, 0.8), "dynamic_friction_range": (0.6, 0.6), "restitution_range": (0.0, 0.0), "num_buckets": 64, }, ) @configclass class CurriculumCfg: """Curriculum terms for the MDP.""" terrain_levels = CurrTerm(func=mdp.terrain_levels_vel) @configclass class ViewerCfg: """Configuration of the scene viewport camera.""" eye: tuple[float, float, float] = (7.5, 7.5, 7.5) lookat: tuple[float, float, float] = (0.0, 0.0, 0.0) cam_prim_path: str = "/OmniverseKit_Persp" resolution: tuple[int, int] = (1920, 1080) origin_type: Literal["world", "env", "asset_root"] = "world" env_index: int = 0 asset_name: str | None = None @configclass class LocomotionVelocityRoughEnvCfg(RLTaskEnvCfg): """Configuration for the locomotion velocity-tracking environment.""" # Scene settings scene: MySceneCfg = MySceneCfg(num_envs=4096, env_spacing=2.5) viewer: ViewerCfg = ViewerCfg() # Basic settings observations: ObservationsCfg = ObservationsCfg() actions: ActionsCfg = ActionsCfg() commands: CommandsCfg = CommandsCfg() # MDP settings rewards: RewardsCfg = RewardsCfg() terminations: TerminationsCfg = TerminationsCfg() events: EventCfg = EventCfg() curriculum: CurriculumCfg = CurriculumCfg() def __post_init__(self): """Post initialization.""" # general settings self.decimation = 4 self.episode_length_s = 20.0 # simulation settings self.sim.dt = 0.005 self.sim.disable_contact_processing = True self.sim.physics_material = self.scene.terrain.physics_material # update sensor update periods # we tick all the sensors based on the smallest update period (physics update period) if self.scene.height_scanner is not None: self.scene.height_scanner.update_period = self.decimation * self.sim.dt if self.scene.contact_forces is not None: self.scene.contact_forces.update_period = self.sim.dt # check if terrain levels curriculum is enabled - if so, enable curriculum for terrain generator # this generates terrains with increasing difficulty and is useful for training if getattr(self.curriculum, "terrain_levels", None) is not None: if self.scene.terrain.terrain_generator is not None: self.scene.terrain.terrain_generator.curriculum = True else: if self.scene.terrain.terrain_generator is not None: self.scene.terrain.terrain_generator.curriculum = False @configclass class UnitreeGo2RoughEnvCfg(LocomotionVelocityRoughEnvCfg): def __post_init__(self): # post init of parent super().__post_init__() self.scene.robot = UNITREE_GO2_CFG.replace(prim_path="{ENV_REGEX_NS}/Robot") self.scene.height_scanner.prim_path = "{ENV_REGEX_NS}/Robot/base" # reduce action scale self.actions.joint_pos.scale = 0.25 # rewards self.rewards.feet_air_time.params["sensor_cfg"].body_names = ".*_foot" self.rewards.feet_air_time.weight = 0.01 self.rewards.undesired_contacts = None self.rewards.dof_torques_l2.weight = -0.0002 self.rewards.track_lin_vel_xy_exp.weight = 1.5 self.rewards.track_ang_vel_z_exp.weight = 0.75 self.rewards.dof_acc_l2.weight = -2.5e-7 # terminations self.terminations.base_contact.params["sensor_cfg"].body_names = "base" #create ros2 camera stream omnigraph create_front_cam_omnigraph() def sub_keyboard_event(event, *args, **kwargs) -> bool: global base_command if event.type == carb.input.KeyboardEventType.KEY_PRESS: if event.input.name == 'W': base_command = [1, 0, 0] if event.input.name == 'S': base_command = [-1, 0, 0] if event.input.name == 'A': base_command = [0, 1, 0] if event.input.name == 'D': base_command = [0, -1, 0] if event.input.name == 'Q': base_command = [0, 0, 1] if event.input.name == 'E': base_command = [0, 0, -1] elif event.type == carb.input.KeyboardEventType.KEY_RELEASE: base_command = [0, 0, 0] return True def main(): # acquire input interface _input = carb.input.acquire_input_interface() _appwindow = omni.appwindow.get_default_app_window() _keyboard = _appwindow.get_keyboard() _sub_keyboard = _input.subscribe_to_keyboard_events(_keyboard, sub_keyboard_event) """Play with RSL-RL agent.""" # parse configuration env_cfg = UnitreeGo2RoughEnvCfg() env_cfg.scene.num_envs = 1 agent_cfg: RslRlOnPolicyRunnerCfg = unitree_go2_agent_cfg # create isaac environment env = gym.make(args_cli.task, cfg=env_cfg) # wrap around environment for rsl-rl env = RslRlVecEnvWrapper(env) # specify directory for logging experiments log_root_path = os.path.join("logs", "rsl_rl", agent_cfg["experiment_name"]) log_root_path = os.path.abspath(log_root_path) print(f"[INFO] Loading experiment from directory: {log_root_path}") resume_path = get_checkpoint_path(log_root_path, agent_cfg["load_run"], agent_cfg["load_checkpoint"]) print(f"[INFO]: Loading model checkpoint from: {resume_path}") # load previously trained model ppo_runner = OnPolicyRunner(env, agent_cfg, log_dir=None, device=agent_cfg["device"]) ppo_runner.load(resume_path) print(f"[INFO]: Loading model checkpoint from: {resume_path}") # obtain the trained policy for inference policy = ppo_runner.get_inference_policy(device=env.unwrapped.device) # reset environment obs, _ = env.get_observations() # simulate environment while simulation_app.is_running(): # run everything in inference mode with torch.inference_mode(): # agent stepping actions = policy(obs) # env stepping obs, _, _, _ = env.step(actions) # close the simulator env.close() if __name__ == "__main__": # run the main function main() # close sim app simulation_app.close()
16,627
Python
34.529914
118
0.669333
abizovnuralem/go2_omniverse/omnigraph.py
# Copyright (c) 2024, RoboVerse community # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # 1. Redistributions of source code must retain the above copyright notice, this # list of conditions and the following disclaimer. # # 2. Redistributions in binary form must reproduce the above copyright notice, # this list of conditions and the following disclaimer in the documentation # and/or other materials provided with the distribution. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE # DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE # FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL # DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR # SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER # CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, # OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. import omni import omni.graph.core as og def create_front_cam_omnigraph(): """Define the OmniGraph for the Isaac Sim environment.""" keys = og.Controller.Keys graph_path = "/ROS_" + "front_cam" (camera_graph, _, _, _) = og.Controller.edit( { "graph_path": graph_path, "evaluator_name": "execution", "pipeline_stage": og.GraphPipelineStage.GRAPH_PIPELINE_STAGE_SIMULATION, }, { keys.CREATE_NODES: [ ("OnPlaybackTick", "omni.graph.action.OnPlaybackTick"), ("IsaacCreateRenderProduct", "omni.isaac.core_nodes.IsaacCreateRenderProduct"), ("ROS2CameraHelper", "omni.isaac.ros2_bridge.ROS2CameraHelper"), ], keys.SET_VALUES: [ ("IsaacCreateRenderProduct.inputs:cameraPrim", "/World/envs/env_0/Robot/base/front_cam"), ("IsaacCreateRenderProduct.inputs:enabled", True), ("ROS2CameraHelper.inputs:type", "rgb"), ("ROS2CameraHelper.inputs:topicName", "unitree_go2/front_cam/rgb"), ("ROS2CameraHelper.inputs:frameId", "unitree_go2"), ], keys.CONNECT: [ ("OnPlaybackTick.outputs:tick", "IsaacCreateRenderProduct.inputs:execIn"), ("IsaacCreateRenderProduct.outputs:execOut", "ROS2CameraHelper.inputs:execIn"), ("IsaacCreateRenderProduct.outputs:renderProductPath", "ROS2CameraHelper.inputs:renderProductPath"), ], }, )
2,912
Python
45.238095
116
0.67239
abizovnuralem/go2_omniverse/README.md
# Welcome to the Unitree Go2 Omniverse Project! I am thrilled to announce that the Unitree Go2 robot has now been integrated with the Nvidia Isaac Sim (Orbit), marking a major step forward in robotics research and development. The combination of these two cutting-edge technologies opens up a world of possibilities for creating and testing algorithms in a variety of simulated environments. Get ready to take your research to the next level with this powerful new resource at your fingertips! Real time Go2 Balancing: <p align="center"> <img width="1280" height="600" src="https://github.com/abizovnuralem/go2_omniverse/assets/33475993/60c2233a-7586-49b6-a134-a7bddc4dd9ae" alt='Go2'> </p> Go2 Ros2 Camera stream: <p align="center"> <img width="1200" height="440" src="https://github.com/abizovnuralem/go2_omniverse/assets/33475993/c740147b-ce00-4d7c-94de-0140be135e3e" alt='Go2'> </p> ## Project RoadMap: 1. PPO balancing algorithm :white_check_mark: 2. Keyboard real time control :white_check_mark: 3. Camera stream to ROS2 :white_check_mark: 4. Lidar stream to ROS2 5. IMU data stream to ROS2 6. URDF real-time joints sync ## Your feedback and support mean the world to us. If you're as enthusiastic about this project as we are, please consider giving it a :star: star on our GitHub repository. Your encouragement fuels our passion and helps us develop our RoadMap further. We welcome any help or suggestions you can offer! Together, let's push the boundaries of what's possible with the Unitree Go2 and ROS2! ## System requirements You need to install Ubuntu 20.04 with Nvidia Isaac Sim and Nvidia Orbit. The full instruction: ``` https://isaac-orbit.github.io/orbit/source/setup/installation.html ``` Also, you need to install ROS2 on your system and configure it: ``` https://docs.omniverse.nvidia.com/isaacsim/latest/installation/install_ros.html#isaac-sim-app-install-ros ``` ## Usage Go inside the repo folder, then ``` conda activate orbit python main.py ``` ## Development To contribute or modify the project, refer to these resources for implementing additional features or improving the existing codebase. PRs are welcome! ## License This project is licensed under the BSD 2-clause License - see the [LICENSE](https://github.com/abizovnuralem/go2_omniverse/blob/master/LICENSE) file for details.
2,341
Markdown
33.441176
343
0.773601
abizovnuralem/go2_omniverse/logs/rsl_rl/unitree_go2_rough/2024-04-06_02-37-07/params/agent.yaml
seed: 42 device: cuda num_steps_per_env: 24 max_iterations: 15000 empirical_normalization: false policy: class_name: ActorCritic init_noise_std: 1.0 actor_hidden_dims: - 512 - 256 - 128 critic_hidden_dims: - 512 - 256 - 128 activation: elu algorithm: class_name: PPO value_loss_coef: 1.0 use_clipped_value_loss: true clip_param: 0.2 entropy_coef: 0.01 num_learning_epochs: 5 num_mini_batches: 4 learning_rate: 0.001 schedule: adaptive gamma: 0.99 lam: 0.95 desired_kl: 0.01 max_grad_norm: 1.0 save_interval: 50 experiment_name: unitree_go2_rough run_name: '' logger: tensorboard neptune_project: orbit wandb_project: orbit resume: false load_run: .* load_checkpoint: model_.*.pt
727
YAML
16.756097
34
0.700138
PatrickPalmer/Omniverse-Connect-cmake/README.md
# Omniverse Connector Sample using CMake Build generator NVidia had provided [instructions](https://forums.developer.nvidia.com/t/creating-an-omniverse-usd-app-from-the-connect-sample/189557) to hand wire in the Omniverse Connector Sample into a Visual Studio project. For more structured C++ projects, cmake is common. This repo codifies the steps in the NVidia document into a cmake project. This should be considered a lightweight simple integration though and not the level you'd expect if NVidia USD was packaged for distribution. Proper USD Cmake module should use modern CMake with optional loading of USD components and using target properties. But this is enough to get started. Currently hardwired to Connect Sample v 200.0.0. ## Setup * Windows 10. * Visual Studio 2019. * cmake v3.21 or greater. * NVidia Omniverse with Connector Sample installed locally. * Hardwired to version 200.0.0. * Installed in the default local users home directory in %LOCALAPPDATA%/ov/pkg. * Run build.bat in the Connector Sample directory to download the required header and library files for OmniVerse Client and USD. ## Build ``` mkdir build cd build cmake -G "Visual Studio 16 2019" -A x64 .. ``` NVidia suggests copying the NVidia USD and Omniverse Client libraries locally. By default, this isn't done. To do it, add the option COPY_CONNECT_LOCALLY to cmake to copy the libraries into the build deps directory. ``` cmake -G "Visual Studio 16 2019" -A x64 -DCOPY_CONNECT_LOCALLY=ON .. ``` If the Omniverse Client libraries are not installed in the default location of %LOCALAPPDATA%\ov\pkg, set the OmniverseConnectSample_ROOT variable. ``` cmake -G "Visual Studio 16 2019" -A x64 -DOmniverseConnectSample_ROOT=D:/Omniverse/Library/connectsample-200.0.0 .. ``` ## Reference * https://forums.developer.nvidia.com/t/creating-an-omniverse-usd-app-from-the-connect-sample/189557
1,907
Markdown
45.536584
686
0.769795
PatrickPalmer/Omniverse-Connect-cmake/SimpleApp/Main.cpp
#include <string> #include <vector> #include <iostream> #include <iomanip> #include "OmniClient.h" #include "pxr/usd/usd/stage.h" #include "pxr/usd/usd/prim.h" #include "pxr/usd/usd/primRange.h" #include "pxr/usd/usdGeom/metrics.h" using namespace pxr; static void OmniClientConnectionStatusCallbackImpl(void* userData, const char* url, OmniClientConnectionStatus status) noexcept { std::cout << "Connection Status: " << omniClientGetConnectionStatusString(status) << " [" << url << "]" << std::endl; if (status == eOmniClientConnectionStatus_ConnectError) { // We shouldn't just exit here - we should clean up a bit, but we're going to do it anyway std::cout << "[ERROR] Failed connection, exiting." << std::endl; exit(-1); } } // Startup Omniverse static bool startOmniverse() { // Register a function to be called whenever the library wants to print something to a log omniClientSetLogCallback( [](char const* threadName, char const* component, OmniClientLogLevel level, char const* message) { std::cout << "[" << omniClientGetLogLevelString(level) << "] " << message << std::endl; }); // The default log level is "Info", set it to "Debug" to see all messages omniClientSetLogLevel(eOmniClientLogLevel_Info); // Initialize the library and pass it the version constant defined in OmniClient.h // This allows the library to verify it was built with a compatible version. It will // return false if there is a version mismatch. if (!omniClientInitialize(kOmniClientVersion)) { return false; } omniClientRegisterConnectionStatusCallback(nullptr, OmniClientConnectionStatusCallbackImpl); return true; } int main(int argc, char* argv[]) { if (argc != 2) { std::cout << "Please provide an Omniverse stage URL to read." << std::endl; return -1; } startOmniverse(); UsdStageRefPtr stage = UsdStage::Open(argv[1]); if (!stage) { std::cout << "Failure to open stage. Exiting." << std::endl; return -2; } // Print the up-axis std::cout << "Stage up-axis: " << UsdGeomGetStageUpAxis(stage) << std::endl; // Print the stage's linear units, or "meters per unit" std::cout << "Meters per unit: " << std::setprecision(5) << UsdGeomGetStageMetersPerUnit(stage) << std::endl; auto range = stage->Traverse(); for (const auto& node : range) { std::cout << "Node: " << node.GetPath() << std::endl; } // The stage is a sophisticated object that needs to be destroyed properly. // Since stage is a smart pointer we can just reset it stage.Reset(); omniClientShutdown(); }
2,538
C++
26.597826
127
0.702522
An-u-rag/synthetic-visual-dataset-generation/main.py
import numpy as np import os import json import os # class_name_to_id_mapping = {"Cow": 0, # "Chicken": 1, # "Sheep": 2, # "Goat": 3, # "Pig": 4} class_name_to_id_mapping = {"cow_1": 0, "cow_2": 1, "cow_3": 2, "cow_4": 3, "cow_5": 4, "pig_clean": 5, "pig_dirty": 6 } # Convert the info dict to the required yolo format and write it to disk def convert_to_yolov5(info_dict, image_file, name_file): print_buffer = [] print(info_dict) data = np.load(info_dict) # image_file = Image.open(image_file) image_w, image_h = image_file.size class_id = {} with open(name_file, 'r') as info_name: data_name = json.load(info_name) # print(data_name) for k, v in data_name.items(): class_id[k] = class_name_to_id_mapping[v["class"]] # for values in data_name.values(): # # print(values) # class_id[values["class"]] = class_name_to_id_mapping[values["class"]] # class_id[class_name_to_id_mapping[values["class"]]] = values["class"] # class_id.append(class_name_to_id_mapping[values["class"]]) # class_id = class_name_to_id_mapping[values["name"]] # print(class_id) # counter = 0 # For each bounding box for b in data: # Transform the bbox co-ordinates as per the format required by YOLO v5 b_center_x = (b[1] + b[3]) / 2 b_center_y = (b[2] + b[4]) / 2 b_width = (b[3] - b[1]) b_height = (b[4] - b[2]) # Normalise the co-ordinates by the dimensions of the image b_center_x /= image_w b_center_y /= image_h b_width /= image_w b_height /= image_h # print(counter) print(class_id) # Write the bbox details to the file print(class_id.get(str(b[0]))) print_buffer.append( "{} {:.3f} {:.3f} {:.3f} {:.3f}".format(class_id.get(str(b[0])), b_center_x, b_center_y, b_width, b_height)) # counter += 1 # print(print_buffer) # Name of the file which we have to save path_pic = "C:/Users/xyche/Downloads/dataset" save_file_name = os.path.join(path_pic, info_dict.replace("bounding_box_2d_tight_", "rgb_").replace("npy", "txt")) # Save the annotation to disk print("\n".join(print_buffer), file=open(save_file_name, "w")) import os from PIL import Image # Convert and save the annotations # path_label = "/content/RenderProduct_Replicator/bounding_box_2d_loose" path_pic = "C:/Users/xyche/Downloads/dataset" datanames = os.listdir(path_pic) for i in datanames: if os.path.splitext(i)[1] == '.npy': # np.load("../"+info_dict) # info_dict = open(os.path.join(path_pic,i), "rb") info_dict = os.path.join(path_pic, i) image_file = i.replace("bounding_box_2d_tight_", "rgb_").replace("npy", "png") # os.listdir(path_pic) image_file = Image.open(os.path.join(path_pic, image_file)) info_name = i.replace("bounding_box_2d_tight_", "bounding_box_2d_tight_labels_").replace("npy", "json") name_file = os.path.join(path_pic, info_name) convert_to_yolov5(info_dict, image_file, name_file) # print(os.listdir(path_pic)) annotations = [os.path.join(path_pic, x) for x in os.listdir(path_pic) if x[-3:] == "txt" and x != 'metadata.txt'] # print(len(annotations)) from sklearn.model_selection import train_test_split # Read images and annotations images = [os.path.join(path_pic, x) for x in os.listdir(path_pic) if x[-3:] == "png"] # print(len(images)) # datanames = os.listdir(path_pic) annotations = [os.path.join(path_pic, x) for x in os.listdir(path_pic) if x[-3:] == "txt" and x != 'metadata.txt'] # print(len(annotations)) images.sort() annotations.sort() # for i in annotations: # update_annotations = i.replace("bounding_box_2d_loose_", "rgb_").replace("txt", "png") # if update_annotations not in images: # print(update_annotations) # Split the dataset into train-valid-test splits train_images, val_images, train_annotations, val_annotations = train_test_split(images, annotations, test_size=0.2, random_state=1) val_images, test_images, val_annotations, test_annotations = train_test_split(val_images, val_annotations, test_size=0.5, random_state=1) path1 = 'C:/Users/xyche/Downloads/dataset' os.mkdir(path1 + '/images') os.mkdir(path1 + '/labels') file_name = ['/train', '/val', '/test'] path2 = 'C:/Users/xyche/Downloads/dataset/images' for name in file_name: os.mkdir(path2 + name) path3 = 'C:/Users/xyche/Downloads/dataset/labels' for name in file_name: os.mkdir(path3 + name) import shutil # Utility function to move images def move_files_to_folder(list_of_files, destination_folder): for f in list_of_files: shutil.copy(f, destination_folder) # Move the splits into their folders move_files_to_folder(train_images, 'C:/Users/xyche/Downloads/dataset/images/train/') move_files_to_folder(val_images, 'C:/Users/xyche/Downloads/dataset/images/val/') move_files_to_folder(test_images, 'C:/Users/xyche/Downloads/dataset/images/test/') move_files_to_folder(train_annotations, 'C:/Users/xyche/Downloads/dataset/labels/train/') move_files_to_folder(val_annotations, 'C:/Users/xyche/Downloads/dataset/labels/val/') move_files_to_folder(test_annotations, 'C:/Users/xyche/Downloads/dataset/labels/test/') import yaml desired_caps = { 'train': 'C:/Users/xyche/Downloads/dataset/images/train/', 'val': 'C:/Users/xyche/Downloads/dataset/images/val/', 'test': 'C:/Users/xyche/Downloads/dataset/images/test/', # number of classes 'nc': 7, # class names #'names': ['Sam', 'Lucy', 'Ross', 'Mary', 'Elon', 'Alex', 'Max'] 'names': ['0', '1', '2', '3', '4', '5', '6'] } curpath = 'C:/Users/xyche/Downloads/dataset' yamlpath = os.path.join(curpath, "./dataset.yaml") with open(yamlpath, "w", encoding="utf-8") as f: yaml.dump(desired_caps, f)
6,421
Python
37.22619
120
0.583242
An-u-rag/synthetic-visual-dataset-generation/fiftyone.py
import fiftyone as fo name = "my-dataset" dataset_dir = "C:/Users/xyche/Downloads/dataset" # Create the dataset dataset = fo.Dataset.from_dir( dataset_dir=dataset_dir, dataset_type=fo.types.YOLOv5Dataset, name=name, ) # View summary info about the dataset print(dataset) # Print the first few samples in the dataset print(dataset.head()) session = fo.launch_app(dataset)
387
Python
19.421052
48
0.73385
An-u-rag/synthetic-visual-dataset-generation/README.md
# synthetic-visual-dataset-generation Generation of synthetic visual datasets using NVIDIA Omniverse for training Deep Learning Models.
136
Markdown
44.666652
97
0.852941
An-u-rag/synthetic-visual-dataset-generation/Yolov5TrainingOutputs/yolov5m_35ep_syntheticAndReal/opt.yaml
weights: yolov5m.pt cfg: models/yolov5m.yaml data: data/cocow_less.yaml hyp: lr0: 0.01 lrf: 0.01 momentum: 0.937 weight_decay: 0.0005 warmup_epochs: 3.0 warmup_momentum: 0.8 warmup_bias_lr: 0.1 box: 0.05 cls: 0.5 cls_pw: 1.0 obj: 1.0 obj_pw: 1.0 iou_t: 0.2 anchor_t: 4.0 fl_gamma: 0.0 hsv_h: 0.015 hsv_s: 0.7 hsv_v: 0.4 degrees: 0.0 translate: 0.1 scale: 0.5 shear: 0.0 perspective: 0.0 flipud: 0.0 fliplr: 0.5 mosaic: 1.0 mixup: 0.0 copy_paste: 0.0 epochs: 100 batch_size: 16 imgsz: 640 rect: false resume: false nosave: false noval: false noautoanchor: false noplots: false evolve: null bucket: '' cache: disk image_weights: false device: '' multi_scale: false single_cls: false optimizer: SGD sync_bn: false workers: 8 project: runs\train name: realaugmented exist_ok: false quad: false cos_lr: false label_smoothing: 0.0 patience: 100 freeze: - 0 save_period: 5 seed: 0 local_rank: -1 entity: null upload_dataset: false bbox_interval: -1 artifact_alias: latest save_dir: runs\train\realaugmented
1,056
YAML
14.31884
34
0.6875
An-u-rag/synthetic-visual-dataset-generation/Yolov5TrainingOutputs/yolov5m_35ep_syntheticAndReal/hyp.yaml
lr0: 0.01 lrf: 0.01 momentum: 0.937 weight_decay: 0.0005 warmup_epochs: 3.0 warmup_momentum: 0.8 warmup_bias_lr: 0.1 box: 0.05 cls: 0.5 cls_pw: 1.0 obj: 1.0 obj_pw: 1.0 iou_t: 0.2 anchor_t: 4.0 fl_gamma: 0.0 hsv_h: 0.015 hsv_s: 0.7 hsv_v: 0.4 degrees: 0.0 translate: 0.1 scale: 0.5 shear: 0.0 perspective: 0.0 flipud: 0.0 fliplr: 0.5 mosaic: 1.0 mixup: 0.0 copy_paste: 0.0
373
YAML
11.896551
20
0.662198
An-u-rag/synthetic-visual-dataset-generation/ReplicatorScripts/Replicator_RandomizeCows_Basic.py
import io import json import time import asyncio from typing import List import omni.kit import omni.usd import omni.replicator.core as rep import numpy as np from omni.replicator.core import AnnotatorRegistry, BackendDispatch, Writer, WriterRegistry, orchestrator from omni.syntheticdata.scripts.SyntheticData import SyntheticData camera_positions = [(1720, -1220, 200), (3300, -1220, 200), (3300, -3500, 200), (1720, -3500, 200)] # Attach Render Product with rep.new_layer(): camera = rep.create.camera() render_product = rep.create.render_product(camera, (1280, 1280)) # Randomizer Function def randomize_cows(): cows = rep.get.prims(semantics=[('class', 'cow')]) with cows: rep.modify.visibility(rep.distribution.choice([True, False])) return cows.node rep.randomizer.register(randomize_cows) # Trigger to call randomizer with rep.trigger.on_frame(num_frames=10): with camera: rep.modify.pose(position=rep.distribution.choice( camera_positions), look_at=(2500, -2300, 0)) rep.randomizer.randomize_cows() # Initialize and attach Writer to store result writer = rep.WriterRegistry.get('CowWriter') writer.initialize(output_dir='C:/Users/anura/Desktop/IndoorRanch_ReplicatorOutputs/Run4', rgb=True, bounding_box_2d_tight=True) writer.attach([render_product])
1,376
Python
22.741379
105
0.713663
An-u-rag/synthetic-visual-dataset-generation/ReplicatorScripts/Replicator_RandomizeSimple.py
import io import json import time import asyncio from typing import List import omni.kit import omni.usd import omni.replicator.core as rep import csv import numpy as np from omni.replicator.core import AnnotatorRegistry, BackendDispatch, Writer, WriterRegistry, orchestrator from omni.syntheticdata.scripts.SyntheticData import SyntheticData class CowWriter(Writer): def __init__( self, output_dir: str, semantic_types: List[str] = None, rgb: bool = True, bounding_box_2d_loose: bool = False, image_output_format: str = "png", ): self._output_dir = output_dir self._backend = BackendDispatch({"paths": {"out_dir": output_dir}}) self._frame_id = 0 self._sequence_id = 0 self._image_output_format = image_output_format self._output_data_format = {} self.annotators = [] if semantic_types is None: semantic_types = ["class"] # RGB if rgb: self.annotators.append(AnnotatorRegistry.get_annotator("rgb")) if bounding_box_2d_loose: self.annotators.append( AnnotatorRegistry.get_annotator("bounding_box_2d_loose", init_params={ "semanticTypes": semantic_types}) ) def write(self, data: dict): sequence_id = "" for trigger_name, call_count in data["trigger_outputs"].items(): if "on_time" in trigger_name: sequence_id = f"{call_count}_{sequence_id}" if sequence_id != self._sequence_id: self._frame_id = 0 self._sequence_id = sequence_id for annotator in data.keys(): annotator_split = annotator.split("-") render_product_path = "" multi_render_prod = 0 if len(annotator_split) > 1: multi_render_prod = 1 render_product_name = annotator_split[-1] render_product_path = f"{render_product_name}/" if annotator.startswith("rgb"): if multi_render_prod: render_product_path += "rgb/" self._write_rgb(data, render_product_path, annotator) if annotator.startswith("bounding_box_2d_loose"): if multi_render_prod: render_product_path += "bounding_box_2d_loose/" self._write_bounding_box_data( data, "2d_loose", render_product_path, annotator) self._frame_id += 1 def _write_rgb(self, data: dict, render_product_path: str, annotator: str): file_path = f"{render_product_path}rgb_{self._sequence_id}{self._frame_id:0}.{self._image_output_format}" self._backend.write_image(file_path, data[annotator]) def _write_bounding_box_data(self, data: dict, bbox_type: str, render_product_path: str, annotator: str): bbox_data_all = data[annotator]["data"] id_to_labels = data[annotator]["info"]["idToLabels"] prim_paths = data[annotator]["info"]["primPaths"] target_coco_bbox_data = [] count = 0 print(bbox_data_all) labels_file_path = f"{render_product_path}rgb_{self._sequence_id}{self._frame_id:0}.txt" for bbox_data in bbox_data_all: target_bbox_data = {'x_min': bbox_data['x_min'], 'y_min': bbox_data['y_min'], 'x_max': bbox_data['x_max'], 'y_max': bbox_data['y_max']} width = int( abs(target_bbox_data["x_max"] - target_bbox_data["x_min"])) height = int( abs(target_bbox_data["y_max"] - target_bbox_data["y_min"])) semantic_label = data[annotator]["info"]["idToLabels"].get(bbox_data["semanticId"]) coco_bbox_data = [] coco_bbox_data.append(semantic_label) coco_bbox_data.append(str((float(target_bbox_data["x_min"]) + float(target_bbox_data["x_max"]))/2)) coco_bbox_data.append(str((float(target_bbox_data["y_min"]) + float(target_bbox_data["y_max"]))/2)) coco_bbox_data.append(str(width)) coco_bbox_data.append(str(height)) target_coco_bbox_data.append(coco_bbox_data) count += 1 buf = io.StringIO() writer = csv.writer(buf, delimiter = " ") writer.writerows(target_coco_bbox_data) self._backend.write_blob(labels_file_path, bytes(buf.getvalue(), "utf-8")) rep.WriterRegistry.register(CowWriter) camera_positions = [(-1100, 1480, -900), (-1100, 3355, -900), (2815, 3410, -800), (2815, 1380, -800)] # Attach Render Product with rep.new_layer(): camera = rep.create.camera() render_product = rep.create.render_product(camera, (1280, 1280)) # Randomizer Function def randomize_pigsdirty(): pigs = rep.get.prims(semantics=[('class', 'pig_dirty')]) with pigs: rep.modify.visibility(rep.distribution.choice([True, False])) return pigs.node rep.randomizer.register(randomize_pigsdirty) def randomize_pigsclean(): pigs = rep.get.prims(semantics=[('class', 'pig_clean')]) with pigs: rep.modify.visibility(rep.distribution.choice([True, False])) return pigs.node rep.randomizer.register(randomize_pigsclean) def randomize_cows2(): cows = rep.get.prims(semantics=[('class', 'cow_2')]) with cows: rep.modify.visibility(rep.distribution.choice([True, False])) return cows.node rep.randomizer.register(randomize_cows2) def randomize_cows3(): cows = rep.get.prims(semantics=[('class', 'cow_3')]) with cows: rep.modify.visibility(rep.distribution.choice([True, False])) return cows.node rep.randomizer.register(randomize_cows3) def randomize_cows4(): cows = rep.get.prims(semantics=[('class', 'cow_4')]) with cows: rep.modify.visibility(rep.distribution.choice([True, False])) return cows.node rep.randomizer.register(randomize_cows4) def randomize_environment(): envs = ["omniverse://localhost/NVIDIA/Assets/Skies/Clear/noon_grass_4k.hdr", "omniverse://localhost/NVIDIA/Assets/Skies/Night/moonlit_golf_4k.hdr", "omniverse://localhost/NVIDIA/Assets/Skies/Storm/approaching_storm_4k.hdr"] lights = rep.create.light( light_type = "Dome", position = (2500, -2300, 0), intensity = rep.distribution.choice([1., 10., 100., 1000.]), texture = rep.distribution.choice(envs) ) return lights.node rep.randomizer.register(randomize_environment) # Trigger to call randomizer with rep.trigger.on_frame(num_frames=3000): with camera: rep.modify.pose(position=rep.distribution.choice( camera_positions), look_at=(790, 2475, -1178)) rep.randomizer.randomize_environment() rep.randomizer.randomize_pigsdirty() rep.randomizer.randomize_pigsclean() rep.randomizer.randomize_cows2() rep.randomizer.randomize_cows3() rep.randomizer.randomize_cows4() writer = rep.WriterRegistry.get('BasicWriter') writer.initialize(output_dir='C:/Users/anura/Desktop/IndoorRanch_ReplicatorOutputs/SanjRun1', rgb=True, bounding_box_2d_tight=True, bounding_box_2d_loose=True, semantic_segmentation=True, bounding_box_3d=True) writer.attach([render_product])
7,338
Python
34.8
134
0.615018
An-u-rag/synthetic-visual-dataset-generation/ReplicatorScripts/Replicator_RandomizeCows.py
import io import json import time import asyncio from typing import List import omni.kit import omni.usd import omni.replicator.core as rep import numpy as np from omni.replicator.core import AnnotatorRegistry, BackendDispatch, Writer, WriterRegistry, orchestrator from omni.syntheticdata.scripts.SyntheticData import SyntheticData class CowWriter(Writer): def __init__( self, output_dir: str, semantic_types: List[str] = None, rgb: bool = True, bounding_box_2d_tight: bool = False, bounding_box_2d_loose: bool = False, semantic_segmentation: bool = False, instance_id_segmentation: bool = False, instance_segmentation: bool = False, distance_to_camera: bool = False, bounding_box_3d: bool = False, image_output_format: str = "png", ): self._output_dir = output_dir self._backend = BackendDispatch({"paths": {"out_dir": output_dir}}) self._frame_id = 0 self._sequence_id = 0 self._image_output_format = image_output_format self._output_data_format = {} self.annotators = [] if semantic_types is None: semantic_types = ["class"] # RGB if rgb: self.annotators.append(AnnotatorRegistry.get_annotator("rgb")) # Bounding Box 2D if bounding_box_2d_tight: self.annotators.append( AnnotatorRegistry.get_annotator("bounding_box_2d_tight", init_params={ "semanticTypes": semantic_types}) ) if bounding_box_2d_loose: self.annotators.append( AnnotatorRegistry.get_annotator("bounding_box_2d_loose", init_params={ "semanticTypes": semantic_types}) ) # Semantic Segmentation if semantic_segmentation: self.annotators.append( AnnotatorRegistry.get_annotator( "semantic_segmentation", init_params={"semanticTypes": semantic_types}, ) ) # Instance Segmentation if instance_id_segmentation: self.annotators.append( AnnotatorRegistry.get_annotator( "instance_id_segmentation", init_params={} ) ) # Instance Segmentation if instance_segmentation: self.annotators.append( AnnotatorRegistry.get_annotator( "instance_segmentation", init_params={"semanticTypes": semantic_types}, ) ) # Depth if distance_to_camera: self.annotators.append( AnnotatorRegistry.get_annotator("distance_to_camera")) # Bounding Box 3D if bounding_box_3d: self.annotators.append( AnnotatorRegistry.get_annotator("bounding_box_3d", init_params={ "semanticTypes": semantic_types}) ) def write(self, data: dict): sequence_id = "" for trigger_name, call_count in data["trigger_outputs"].items(): if "on_time" in trigger_name: sequence_id = f"{call_count}_{sequence_id}" if sequence_id != self._sequence_id: self._frame_id = 0 self._sequence_id = sequence_id for annotator in data.keys(): annotator_split = annotator.split("-") render_product_path = "" multi_render_prod = 0 if len(annotator_split) > 1: multi_render_prod = 1 render_product_name = annotator_split[-1] render_product_path = f"{render_product_name}/" if annotator.startswith("rgb"): if multi_render_prod: render_product_path += "rgb/" self._write_rgb(data, render_product_path, annotator) if annotator.startswith("distance_to_camera"): if multi_render_prod: render_product_path += "distance_to_camera/" self._write_distance_to_camera( data, render_product_path, annotator) if annotator.startswith("semantic_segmentation"): if multi_render_prod: render_product_path += "semantic_segmentation/" self._write_semantic_segmentation( data, render_product_path, annotator) if annotator.startswith("instance_id_segmentation"): if multi_render_prod: render_product_path += "instance_id_segmentation/" self._write_instance_id_segmentation( data, render_product_path, annotator) if annotator.startswith("instance_segmentation"): if multi_render_prod: render_product_path += "instance_segmentation/" self._write_instance_segmentation( data, render_product_path, annotator) if annotator.startswith("bounding_box_3d"): if multi_render_prod: render_product_path += "bounding_box_3d/" self._write_bounding_box_data( data, "3d", render_product_path, annotator) if annotator.startswith("bounding_box_2d_loose"): if multi_render_prod: render_product_path += "bounding_box_2d_loose/" self._write_bounding_box_data( data, "2d_loose", render_product_path, annotator) if annotator.startswith("bounding_box_2d_tight"): if multi_render_prod: render_product_path += "bounding_box_2d_tight/" self._write_bounding_box_data( data, "2d_tight", render_product_path, annotator) self._frame_id += 1 def _write_rgb(self, data: dict, render_product_path: str, annotator: str): file_path = f"{render_product_path}rgb_{self._sequence_id}{self._frame_id:0}.{self._image_output_format}" self._backend.write_image(file_path, data[annotator]) def _write_distance_to_camera(self, data: dict, render_product_path: str, annotator: str): dist_to_cam_data = data[annotator] file_path = ( f"{render_product_path}distance_to_camera_{self._sequence_id}{self._frame_id:0}.npy" ) buf = io.BytesIO() np.save(buf, dist_to_cam_data) self._backend.write_blob(file_path, buf.getvalue()) def _write_semantic_segmentation(self, data: dict, render_product_path: str, annotator: str): semantic_seg_data = data[annotator]["data"] height, width = semantic_seg_data.shape[:2] file_path = ( f"{render_product_path}semantic_segmentation_{self._sequence_id}{self._frame_id:0}.png" ) if self.colorize_semantic_segmentation: semantic_seg_data = semantic_seg_data.view( np.uint8).reshape(height, width, -1) self._backend.write_image(file_path, semantic_seg_data) else: semantic_seg_data = semantic_seg_data.view( np.uint32).reshape(height, width) self._backend.write_image(file_path, semantic_seg_data) id_to_labels = data[annotator]["info"]["idToLabels"] file_path = f"{render_product_path}semantic_segmentation_labels_{self._sequence_id}{self._frame_id:0}.json" buf = io.BytesIO() buf.write(json.dumps( {str(k): v for k, v in id_to_labels.items()}).encode()) self._backend.write_blob(file_path, buf.getvalue()) def _write_instance_id_segmentation(self, data: dict, render_product_path: str, annotator: str): instance_seg_data = data[annotator]["data"] height, width = instance_seg_data.shape[:2] file_path = f"{render_product_path}instance_id_segmentation_{self._sequence_id}{self._frame_id:0}.png" if self.colorize_instance_id_segmentation: instance_seg_data = instance_seg_data.view( np.uint8).reshape(height, width, -1) self._backend.write_image(file_path, instance_seg_data) else: instance_seg_data = instance_seg_data.view( np.uint32).reshape(height, width) self._backend.write_image(file_path, instance_seg_data) id_to_labels = data[annotator]["info"]["idToLabels"] file_path = f"{render_product_path}instance_id_segmentation_mapping_{self._sequence_id}{self._frame_id:0}.json" buf = io.BytesIO() buf.write(json.dumps( {str(k): v for k, v in id_to_labels.items()}).encode()) self._backend.write_blob(file_path, buf.getvalue()) def _write_instance_segmentation(self, data: dict, render_product_path: str, annotator: str): instance_seg_data = data[annotator]["data"] height, width = instance_seg_data.shape[:2] file_path = ( f"{render_product_path}instance_segmentation_{self._sequence_id}{self._frame_id:0}.png" ) if self.colorize_instance_segmentation: instance_seg_data = instance_seg_data.view( np.uint8).reshape(height, width, -1) self._backend.write_image(file_path, instance_seg_data) else: instance_seg_data = instance_seg_data.view( np.uint32).reshape(height, width) self._backend.write_image(file_path, instance_seg_data) id_to_labels = data[annotator]["info"]["idToLabels"] file_path = f"{render_product_path}instance_segmentation_mapping_{self._sequence_id}{self._frame_id:0}.json" buf = io.BytesIO() buf.write(json.dumps( {str(k): v for k, v in id_to_labels.items()}).encode()) self._backend.write_blob(file_path, buf.getvalue()) id_to_semantics = data[annotator]["info"]["idToSemantics"] file_path = f"{render_product_path}instance_segmentation_semantics_mapping_{self._sequence_id}{self._frame_id:0}.json" buf = io.BytesIO() buf.write(json.dumps( {str(k): v for k, v in id_to_semantics.items()}).encode()) self._backend.write_blob(file_path, buf.getvalue()) def _write_bounding_box_data(self, data: dict, bbox_type: str, render_product_path: str, annotator: str): bbox_data_all = data[annotator]["data"] print(bbox_data_all) id_to_labels = data[annotator]["info"]["idToLabels"] prim_paths = data[annotator]["info"]["primPaths"] file_path = f"{render_product_path}bounding_box_{bbox_type}_{self._sequence_id}{self._frame_id:0}.npy" buf = io.BytesIO() np.save(buf, bbox_data_all) self._backend.write_blob(file_path, buf.getvalue()) labels_file_path = f"{render_product_path}bounding_box_{bbox_type}_labels_{self._sequence_id}{self._frame_id:0}.json" buf = io.BytesIO() buf.write(json.dumps(id_to_labels).encode()) self._backend.write_blob(labels_file_path, buf.getvalue()) labels_file_path = f"{render_product_path}bounding_box_{bbox_type}_prim_paths_{self._sequence_id}{self._frame_id:0}.json" buf = io.BytesIO() buf.write(json.dumps(prim_paths).encode()) self._backend.write_blob(labels_file_path, buf.getvalue()) target_coco_bbox_data = [] count = 0 for bbox_data in bbox_data_all: target_bbox_data = {'x_min': bbox_data['x_min'], 'y_min': bbox_data['y_min'], 'x_max': bbox_data['x_max'], 'y_max': bbox_data['y_max']} width = int( abs(target_bbox_data["x_max"] - target_bbox_data["x_min"])) height = int( abs(target_bbox_data["y_max"] - target_bbox_data["y_min"])) if width != 2147483647 and height != 2147483647: # filepath = f"rgb_{self._frame_id}.{self._image_output_format}" # self._backend.write_image(filepath, data["rgb"]) bbox_filepath = f"bbox_{self._frame_id}.txt" coco_bbox_data = { "name": prim_paths[count], "x_min": int(target_bbox_data["x_min"]), "y_min": int(target_bbox_data["y_min"]), "x_max": int(target_bbox_data["x_max"]), "y_max": int(target_bbox_data["y_max"]), "width": width, "height": height} target_coco_bbox_data.append(coco_bbox_data) count += 1 buf = io.BytesIO() buf.write(json.dumps(target_coco_bbox_data).encode()) self._backend.write_blob(bbox_filepath, buf.getvalue()) rep.WriterRegistry.register(CowWriter) camera_positions = [(1720, -1220, 200), (3300, -1220, 200), (3300, -3500, 200), (1720, -3500, 200)] # Attach Render Product with rep.new_layer(): camera = rep.create.camera() render_product = rep.create.render_product(camera, (1280, 1280)) # Randomizer Function def randomize_cows1(): cows = rep.get.prims(semantics=[('class', 'cow_1')]) with cows: rep.modify.visibility(rep.distribution.choice([True, False])) return cows.node rep.randomizer.register(randomize_cows1) def randomize_cows2(): cows = rep.get.prims(semantics=[('class', 'cow_2')]) with cows: rep.modify.visibility(rep.distribution.choice([True, False])) return cows.node rep.randomizer.register(randomize_cows2) def randomize_cows3(): cows = rep.get.prims(semantics=[('class', 'cow_3')]) with cows: rep.modify.visibility(rep.distribution.choice([True, False])) return cows.node rep.randomizer.register(randomize_cows3) def randomize_cows4(): cows = rep.get.prims(semantics=[('class', 'cow_4')]) with cows: rep.modify.visibility(rep.distribution.choice([True, False])) return cows.node rep.randomizer.register(randomize_cows4) def randomize_environment(): envs = ["omniverse://localhost/NVIDIA/Assets/Skies/Clear/noon_grass_4k.hdr", "omniverse://localhost/NVIDIA/Assets/Skies/Night/moonlit_golf_4k.hdr", "omniverse://localhost/NVIDIA/Assets/Skies/Storm/approaching_storm_4k.hdr"] lights = rep.create.light( light_type = "Dome", position = (2500, -2300, 0), intensity = rep.distribution.choice([1., 10., 100., 1000.]), texture = rep.distribution.choice(envs) ) return lights.node rep.randomizer.register(randomize_environment) # Trigger to call randomizer with rep.trigger.on_frame(num_frames=10): with camera: rep.modify.pose(position=rep.distribution.choice( camera_positions), look_at=(2500, -2300, 0)) rep.randomizer.randomize_environment() rep.randomizer.randomize_cows1() rep.randomizer.randomize_cows2() rep.randomizer.randomize_cows3() rep.randomizer.randomize_cows4() writer = rep.WriterRegistry.get('BasicWriter') writer.initialize(output_dir='C:/Users/anura/Desktop/IndoorRanch_ReplicatorOutputs/NewRun1', rgb=True, bounding_box_2d_tight=True) writer.attach([render_product])
15,455
Python
35.8
129
0.581171
An-u-rag/synthetic-visual-dataset-generation/ReplicatorScripts/CowWriter_COCO.py
import io import json import time import asyncio from typing import List import omni.kit import omni.usd import omni.replicator.core as rep import numpy as np from omni.replicator.core import AnnotatorRegistry, BackendDispatch, Writer, WriterRegistry, orchestrator from omni.syntheticdata.scripts.SyntheticData import SyntheticData class CowWriter(Writer): def __init__( self, output_dir: str, semantic_types: List[str] = None, rgb: bool = True, bounding_box_2d_tight: bool = False, bounding_box_2d_loose: bool = False, semantic_segmentation: bool = False, instance_id_segmentation: bool = False, instance_segmentation: bool = False, distance_to_camera: bool = False, bounding_box_3d: bool = False, image_output_format: str = "png", ): self._output_dir = output_dir self._backend = BackendDispatch({"paths": {"out_dir": output_dir}}) self._frame_id = 0 self._sequence_id = 0 self._image_output_format = image_output_format self._output_data_format = {} self.annotators = [] if semantic_types is None: semantic_types = ["class"] # RGB if rgb: self.annotators.append(AnnotatorRegistry.get_annotator("rgb")) # Bounding Box 2D if bounding_box_2d_tight: self.annotators.append( AnnotatorRegistry.get_annotator("bounding_box_2d_tight", init_params={ "semanticTypes": semantic_types}) ) if bounding_box_2d_loose: self.annotators.append( AnnotatorRegistry.get_annotator("bounding_box_2d_loose", init_params={ "semanticTypes": semantic_types}) ) # Semantic Segmentation if semantic_segmentation: self.annotators.append( AnnotatorRegistry.get_annotator( "semantic_segmentation", init_params={"semanticTypes": semantic_types}, ) ) # Instance Segmentation if instance_id_segmentation: self.annotators.append( AnnotatorRegistry.get_annotator( "instance_id_segmentation", init_params={} ) ) # Instance Segmentation if instance_segmentation: self.annotators.append( AnnotatorRegistry.get_annotator( "instance_segmentation", init_params={"semanticTypes": semantic_types}, ) ) # Depth if distance_to_camera: self.annotators.append( AnnotatorRegistry.get_annotator("distance_to_camera")) # Bounding Box 3D if bounding_box_3d: self.annotators.append( AnnotatorRegistry.get_annotator("bounding_box_3d", init_params={ "semanticTypes": semantic_types}) ) def write(self, data: dict): sequence_id = "" for trigger_name, call_count in data["trigger_outputs"].items(): if "on_time" in trigger_name: sequence_id = f"{call_count}_{sequence_id}" if sequence_id != self._sequence_id: self._frame_id = 0 self._sequence_id = sequence_id for annotator in data.keys(): annotator_split = annotator.split("-") render_product_path = "" multi_render_prod = 0 if len(annotator_split) > 1: multi_render_prod = 1 render_product_name = annotator_split[-1] render_product_path = f"{render_product_name}/" if annotator.startswith("rgb"): if multi_render_prod: render_product_path += "rgb/" self._write_rgb(data, render_product_path, annotator) if annotator.startswith("distance_to_camera"): if multi_render_prod: render_product_path += "distance_to_camera/" self._write_distance_to_camera( data, render_product_path, annotator) if annotator.startswith("semantic_segmentation"): if multi_render_prod: render_product_path += "semantic_segmentation/" self._write_semantic_segmentation( data, render_product_path, annotator) if annotator.startswith("instance_id_segmentation"): if multi_render_prod: render_product_path += "instance_id_segmentation/" self._write_instance_id_segmentation( data, render_product_path, annotator) if annotator.startswith("instance_segmentation"): if multi_render_prod: render_product_path += "instance_segmentation/" self._write_instance_segmentation( data, render_product_path, annotator) if annotator.startswith("bounding_box_3d"): if multi_render_prod: render_product_path += "bounding_box_3d/" self._write_bounding_box_data( data, "3d", render_product_path, annotator) if annotator.startswith("bounding_box_2d_loose"): if multi_render_prod: render_product_path += "bounding_box_2d_loose/" self._write_bounding_box_data( data, "2d_loose", render_product_path, annotator) if annotator.startswith("bounding_box_2d_tight"): if multi_render_prod: render_product_path += "bounding_box_2d_tight/" self._write_bounding_box_data( data, "2d_tight", render_product_path, annotator) self._frame_id += 1 def _write_rgb(self, data: dict, render_product_path: str, annotator: str): file_path = f"{render_product_path}rgb_{self._sequence_id}{self._frame_id:0}.{self._image_output_format}" self._backend.write_image(file_path, data[annotator]) def _write_distance_to_camera(self, data: dict, render_product_path: str, annotator: str): dist_to_cam_data = data[annotator] file_path = ( f"{render_product_path}distance_to_camera_{self._sequence_id}{self._frame_id:0}.npy" ) buf = io.BytesIO() np.save(buf, dist_to_cam_data) self._backend.write_blob(file_path, buf.getvalue()) def _write_semantic_segmentation(self, data: dict, render_product_path: str, annotator: str): semantic_seg_data = data[annotator]["data"] height, width = semantic_seg_data.shape[:2] file_path = ( f"{render_product_path}semantic_segmentation_{self._sequence_id}{self._frame_id:0}.png" ) if self.colorize_semantic_segmentation: semantic_seg_data = semantic_seg_data.view( np.uint8).reshape(height, width, -1) self._backend.write_image(file_path, semantic_seg_data) else: semantic_seg_data = semantic_seg_data.view( np.uint32).reshape(height, width) self._backend.write_image(file_path, semantic_seg_data) id_to_labels = data[annotator]["info"]["idToLabels"] file_path = f"{render_product_path}semantic_segmentation_labels_{self._sequence_id}{self._frame_id:0}.json" buf = io.BytesIO() buf.write(json.dumps( {str(k): v for k, v in id_to_labels.items()}).encode()) self._backend.write_blob(file_path, buf.getvalue()) def _write_instance_id_segmentation(self, data: dict, render_product_path: str, annotator: str): instance_seg_data = data[annotator]["data"] height, width = instance_seg_data.shape[:2] file_path = f"{render_product_path}instance_id_segmentation_{self._sequence_id}{self._frame_id:0}.png" if self.colorize_instance_id_segmentation: instance_seg_data = instance_seg_data.view( np.uint8).reshape(height, width, -1) self._backend.write_image(file_path, instance_seg_data) else: instance_seg_data = instance_seg_data.view( np.uint32).reshape(height, width) self._backend.write_image(file_path, instance_seg_data) id_to_labels = data[annotator]["info"]["idToLabels"] file_path = f"{render_product_path}instance_id_segmentation_mapping_{self._sequence_id}{self._frame_id:0}.json" buf = io.BytesIO() buf.write(json.dumps( {str(k): v for k, v in id_to_labels.items()}).encode()) self._backend.write_blob(file_path, buf.getvalue()) def _write_instance_segmentation(self, data: dict, render_product_path: str, annotator: str): instance_seg_data = data[annotator]["data"] height, width = instance_seg_data.shape[:2] file_path = ( f"{render_product_path}instance_segmentation_{self._sequence_id}{self._frame_id:0}.png" ) if self.colorize_instance_segmentation: instance_seg_data = instance_seg_data.view( np.uint8).reshape(height, width, -1) self._backend.write_image(file_path, instance_seg_data) else: instance_seg_data = instance_seg_data.view( np.uint32).reshape(height, width) self._backend.write_image(file_path, instance_seg_data) id_to_labels = data[annotator]["info"]["idToLabels"] file_path = f"{render_product_path}instance_segmentation_mapping_{self._sequence_id}{self._frame_id:0}.json" buf = io.BytesIO() buf.write(json.dumps( {str(k): v for k, v in id_to_labels.items()}).encode()) self._backend.write_blob(file_path, buf.getvalue()) id_to_semantics = data[annotator]["info"]["idToSemantics"] file_path = f"{render_product_path}instance_segmentation_semantics_mapping_{self._sequence_id}{self._frame_id:0}.json" buf = io.BytesIO() buf.write(json.dumps( {str(k): v for k, v in id_to_semantics.items()}).encode()) self._backend.write_blob(file_path, buf.getvalue()) def _write_bounding_box_data(self, data: dict, bbox_type: str, render_product_path: str, annotator: str): bbox_data_all = data[annotator]["data"] print(bbox_data_all) id_to_labels = data[annotator]["info"]["idToLabels"] prim_paths = data[annotator]["info"]["primPaths"] file_path = f"{render_product_path}bounding_box_{bbox_type}_{self._sequence_id}{self._frame_id:0}.npy" buf = io.BytesIO() np.save(buf, bbox_data_all) self._backend.write_blob(file_path, buf.getvalue()) labels_file_path = f"{render_product_path}bounding_box_{bbox_type}_labels_{self._sequence_id}{self._frame_id:0}.json" buf = io.BytesIO() buf.write(json.dumps(id_to_labels).encode()) self._backend.write_blob(labels_file_path, buf.getvalue()) labels_file_path = f"{render_product_path}bounding_box_{bbox_type}_prim_paths_{self._sequence_id}{self._frame_id:0}.json" buf = io.BytesIO() buf.write(json.dumps(prim_paths).encode()) self._backend.write_blob(labels_file_path, buf.getvalue()) target_coco_bbox_data = [] count = 0 for bbox_data in bbox_data_all: target_bbox_data = {'x_min': bbox_data['x_min'], 'y_min': bbox_data['y_min'], 'x_max': bbox_data['x_max'], 'y_max': bbox_data['y_max']} width = int( abs(target_bbox_data["x_max"] - target_bbox_data["x_min"])) height = int( abs(target_bbox_data["y_max"] - target_bbox_data["y_min"])) if width != 2147483647 and height != 2147483647: bbox_filepath = f"bbox_{self._frame_id}.json" coco_bbox_data = { "name": prim_paths[count], "x_min": int(target_bbox_data["x_min"]), "y_min": int(target_bbox_data["y_min"]), "x_max": int(target_bbox_data["x_max"]), "y_max": int(target_bbox_data["y_max"]), "width": width, "height": height} target_coco_bbox_data.append(coco_bbox_data) count += 1 buf = io.BytesIO() buf.write(json.dumps(target_coco_bbox_data).encode()) self._backend.write_blob(bbox_filepath, buf.getvalue()) rep.WriterRegistry.register(CowWriter)
12,859
Python
41.442244
129
0.565674
CesiumGS/cesium-omniverse/copy-python-path-for-vs.py
from os import getcwd from os.path import exists import json from textwrap import indent from jsmin import jsmin # # Note: This requires JSMin to be installed since the vscode workspace files have Comments in them. # You can install JSMin by just installing it globally via pip. # # Also Note: You may need to run Visual Studio and open a Python file before running this script. # cwd_path = getcwd() root_path = f"{cwd_path}/extern/nvidia/app" vs_code_workspace_file_path = f"{cwd_path}/.vscode/cesium-omniverse-windows.code-workspace" vs_python_settings_file_path = f"{cwd_path}/.vs/PythonSettings.json" if not exists(root_path): print(f"Could not find {root_path}") exit(1) if not exists(vs_code_workspace_file_path): print(f"Could not find {vs_code_workspace_file_path}") exit(1) if not exists(vs_python_settings_file_path): print(f"Could not find {vs_python_settings_file_path}") exit(1) print(f"Using root path: {root_path}") print(f"Using vs code workspace file: {vs_code_workspace_file_path}") print(f"Using vs PythonSettings file: {vs_python_settings_file_path}") with open(vs_code_workspace_file_path) as fh: m = jsmin(fh.read()) vs_code_workspace_file = json.loads(m) def process_paths(path): return path.replace("${workspaceFolder}", cwd_path).replace("/", "\\") extra_paths = list(map(process_paths, vs_code_workspace_file["settings"]["python.analysis.extraPaths"])) with open(vs_python_settings_file_path, 'r') as fh: vs_python_settings = json.load(fh) vs_python_settings["SearchPaths"] = extra_paths # The read and write handles are split because we want to truncate the old file. with open(vs_python_settings_file_path, 'w') as fh: json.dump(vs_python_settings, fh, indent=2) print(f"Wrote to {vs_python_settings_file_path}")
1,800
Python
32.981131
104
0.725556
CesiumGS/cesium-omniverse/CHANGES.md
# Change Log ### v0.19.0 - 2024-04-01 * Added scrollbar to main window UI. * Fixed issue when loading tilesets with Cesium ion Self-Hosted in developer mode. ### v0.18.0 - 2024-03-01 * **Breaking change:** removed deprecated properties `projectDefaultIonAccessToken` and `projectDefaultIonAccessToken` from `CesiumDataPrim`. `CesiumIonServerPrim` should be used instead. * Improved tile streaming performance by 35% by switching to UrlAssetAccessor from vsgCs. * Added support for disk tile caching which improves streaming performance by 50% when reloading the same scene. * Added support for Web Map Service (WMS) raster overlays. * Added support for Tile Map Service (TMS) raster overlays. * Added support for Web Map Tile Service (WMTS) raster overlays. * Added raster overlay options: `maximumScreenSpaceError`, `maximumTextureSize`, `maximumSimultaneousTileLoads`, `subTileCacheBytes`. * Added ability to bypass downloading of tiles clipped by a cartographic polygon raster overlay. * Added support for globe anchors on non-georeferenced tilesets. * Fixed crash when disabling and re-enabling the extension. * Fixed crash when setting certain `/Cesium` debug options at runtime. * Fixed crash when updating tilesets shader inputs. * Fixed crash when removing USD prims in certain order. * Fixed issue where Cesium ion session would not resume on reload. * Fixed issue where save stage dialog would appear when reloading Fabric stage at startup. * Fixed issue where zooming to tileset extents would not work correctly with non-identity transformation. * Fixed issue where globe anchors didn't work with `xformOp:orient`. * The movie capture tool now waits for tilesets to complete loading before it captures a frame. ### v0.17.0 - 2024-02-01 * **Breaking changes for globe anchors:** * Removed `anchor_xform_at_path`. Globe anchors can now be created directly in USD. * Split `cesium:anchor:geographicCoordinates` into separate properties: `cesium:anchor:latitude`, `cesium:anchor:longitude`, `cesium:anchor:height`. * Globe anchors no longer add a `transform:cesium` op to the attached prim. Instead the `translate`, `rotateXYZ`, and `scale` ops are modified directly. * Removed `cesium:anchor:rotation` and `cesium:anchor:scale`. Instead, use `UsdGeom.XformCommonAPI` to modify the globe anchor's local rotation and scale. * Globe anchors now use the scene's default georeference if `cesium:georeferenceBinding` is empty. * For migrating existing USD files, see https://github.com/CesiumGS/cesium-omniverse-samples/pull/13 * **Breaking changes for imagery layers:** * `CesiumImagery` was renamed to `CesiumRasterOverlay` and is now an abstract class. To create ion raster overlays, use `CesiumIonRasterOverlay`. * MDL changes: `cesium_imagery_layer_float4` was renamed to `cesium_raster_overlay_float4` and `imagery_layer_index` was renamed to `raster_overlay_index`. * ion raster overlays now use the scene's default ion server if `cesium:ionServerBinding` is empty. * **Breaking change for tilesets:** * Tilesets must now reference raster overlays with `cesium:rasterOverlayBinding`. * Tilesets now use the scene's default georeference if `cesium:georeferenceBinding` is empty. * Tilesets now uses the scene's default ion server if `cesium:ionServerBinding` is empty. * Added support for polygon-based clipping with `CesiumPolygonRasterOverlay`. * Added ability for multiple tilesets referencing the same raster overlay. * Added ability to reorder raster overlays in UI. * Added context menu options for adding raster overlays to tilesets. * Fixed multiple globe anchor related issues. * Fixed excessive property warnings when using custom materials. * Fixed adding raster overlays to selected tileset in the Add Assets UI. * Fixed loading 3D Tiles 1.1 implicit tilesets. ### v0.16.0 - 2024-01-02 * Fixed issue where the current ion session would be signed out on reload. * Fixed crash in Cesium Debugging window. ### v0.15.0 - 2023-12-14 * Added support for multiple Cesium ion servers by creating `CesiumIonServerPrim` prims. ### v0.14.0 - 2023-12-01 * Added support for `EXT_structural_metadata`. Property values can be accessed in material graph with the `cesium_property` nodes. * Added support for `EXT_mesh_features`. Feature ID values can be accessed in material graph with the `cesium_feature_id_int` node. * Added support for custom glTF vertex attributes. Attribute values can be accessed in material graph with the `data_lookup` nodes. * Added support for changing a tileset's imagery layer dynamically in material graph. ### v0.13.0 - 2023-11-01 * Changing certain tileset properties no longer triggers a tileset reload. * Added support for `displayColor` and `displayOpacity` for tileset prims. * Fixed rendering point clouds with alpha values. ### v0.12.1 - 2023-10-26 * Fixed version numbers. ### v0.12.0 - 2023-10-25 * Added a quick add button for Google Photorealistic 3D Tiles through ion. * Added support for globe anchors. * Added support for multiple imagery layers. * Added alpha property to imagery layers. * Added support for reading textures and imagery layers in MDL. * Added Cesium for Omniverse Python API, see the `cesium.omniverse.api` module. * Fixed debug colors not working for tiles with vertex colors. * Fixed hangs when loading tilesets by setting `omnihydra.parallelHydraSprimSync` to `false`. * Basis Universal textures are now decoded to the native BCn texture format instead of RGBA8 in Kit 105.1 and above. ### v0.11.0 - 2023-10-02 * **Breaking change:** Cesium for Omniverse now requires Kit 105.1 or above (USD Composer 2023.2.0 or above). * Reduced the number of materials created when loading un-textured tilesets. * Added debug option `cesium:debug:disableGeoreferencing` to `CesiumDataPrim` to disable georeferencing and view tilesets in ECEF coordinates. * Improvements to C++ testing infrastructure. ### v0.10.0 - 2023-09-01 * Improved error message if fetching tileset fails. * Added basic point cloud support. * Fixed loading extension in Omniverse Code 2023.1.1. * Fixed crashes when reloading tileset. * Fixed memory leak when removing tileset mid-load. * Fixed several other bugs related to removing tilesets mid-load. * Upgraded to cesium-native v0.26.0. ### v0.9.0 - 2023-08-01 * **Breaking change:** `CesiumTilesetPrim` now inherits from `UsdGeomGprim` instead of `UsdGeomBoundable`. * Improved texture loading performance by moving texture loading to a worker thread. * Improved performance when refining with parent tile's imagery by sharing the same texture instead of duplicating it. * Added support for assigning materials to a tileset. * Improved styling of credits. * Visually enable/disable top bar buttons based on sign-in status. * Fixed bug where not all Cesium windows would not appear in Windows menu. ### v0.8.0 - 2023-07-03 * **Breaking change:** Cesium for Omniverse now requires Kit 105 or above (USD Composer 2023.1.0 or above). * **Breaking change:** broke out georeference attributes from `CesiumDataPrim` into dedicated `CesiumGeoreferencePrim` class. * **Breaking change:** `CesiumTilesetPrim` is now a concrete type that inherits from `UsdGeomBoundable`. * **Breaking change:** `CesiumTilesetPrim` now has an explicit binding to a `CesiumGeoreferencePrim`. * **Breaking change:** default values for attributes are no longer written out when saved as `.usd` files. * Added ability to zoom to extents on tilesets. * Added vertex color support. * Added `cesium.omniverse.TILESET_LOADED` Carbonite event. * Added more statistics to the Cesium Debugging window. * Fixed holes when camera is moving. * Fixed orphaned tiles. * Fixed credit parsing issue. * Improved performance when refining with parent tile's imagery. * Improved performance when creating Fabric geometry. * Switched base material to `gltf/pbr.mdl`. ### v0.7.0 - 2023-06-01 * Set better default values when loading glTFs with the `KHR_materials_unlit` extension. This improves the visual quality of Google 3D Tiles. * Improved installation process by forcing application reload when Cesium for Omniverse is first enabled. * Changed material loading color from red to black. * Added `/CesiumSession` prim for storing ephemeral state in the Session Layer, including `ecefToUsdTransform`. * Fixed credits not appearing on all viewports. * Improved readability of debug statistics. * Integrated Cesium Native's performance tracing utility. * Updated to Cesium Native 0.24.0 which adds support for 3D Tiles 1.1 implicit tiling. ### v0.6.2 - 2023-05-19 * Added more rendering statistics to the Cesium Debugging window. * Added debug options to the top-level `Cesium` prim. * Fixed issue where `cesium:enableFrustumCulling` wasn't appearing in the USD schema UI. * Fixed issue where some Fabric shader node prims were not being deleted. ### v0.6.1 - 2023-05-11 * Added `premake5.lua` to `cesium.omniverse` and `cesium.usd.plugins` to better support Kit templates. * Fixed crash in the Cesium Debugging window when reloading a stage. ### v0.6.0 - 2023-05-04 * Added option to show credits on screen. * Fixed issue where tileset traversal was happening on hidden tilesets. * Fixed issue where tile render resources were not being released back into the Fabric mesh pool in certain cases. * Fixed regression where the texture wrap mode was no longer clamping to edge. ### v0.5.0 - 2023-05-01 * Added material pool for better performance and to reduce texture/material loading artifacts. * Added support for multiple viewports. * Fixed red flashes when materials are loading. * Fixed cyan flashes when textures are loading. * Fixed adding imagery as base layer for existing tileset. * Fixed Fabric types for `tilesetId` and `tileId`. * Upgraded to cesium-native v0.23.0. ### v0.4.0 - 2023-04-03 * Fixed a crash when removing the last available access token for a tileset. * Added search field to the asset window. * Added placeholder token name in the create field of the token window. * No longer printing "Error adding tileset and imagery to stage" when adding a tileset. * Better handling of long names in the asset details panel. * Upgraded to cesium-native v0.22.1. ### v0.3.0 - 2023-03-20 * Split the Cesium USD plugins into their own Kit extension. * Added on-screen credits. * Added modal dialog prompting the user to enable Fabric Scene Delegate. * General cleanup before public release. ### v0.2.0 - 2023-03-16 * Fixed raster overlay refinement. * Fixed a crash when removing tileset and imagery using the stage window. * Fixed issues around loading pre-existing USD files. * Now generating flat normals by default. * Added property window widgets for the Cesium USD Schema attributes. * Updated documentation. * General cleanup. ### v0.1.0 - 2023-03-01 * The initial preview build of Cesium for Omniverse!
10,825
Markdown
51.299517
187
0.774503
CesiumGS/cesium-omniverse/pyproject.toml
[tool.black] line-length = 118 target-version = ['py310'] include = '^/exts/cesium\.omniverse/cesium/.*\.pyi?$'
112
TOML
21.599996
53
0.669643
CesiumGS/cesium-omniverse/README.md
[![Cesium for Omniverse Logo](./docs/resources/Cesium_for_Omniverse_dark_color_white_bgnd.jpg)](https://cesium.com/) Cesium for Omniverse enables building 3D geospatial applications and experiences with 3D Tiles and open standards in NVIDIA Omniverse, a real-time 3D graphics collaboration development platform. Cesium for Omniverse is an extension for Omniverse's Kit-based applications such as USD Composer, a reference application for large-scale world building and advanced 3D scene composition of Universal Scene Description (USD)-based workflows, and Omniverse Code, an integrated development environment (IDE) for developers. Cesium for Omniverse enables developers to create geospatial and enterprise metaverse, simulations, digital twins, and other real-world applications in precise geospatial context and stream massive real-word 3D content. By combining a high-accuracy full-scale WGS84 globe, open APIs and open standards for spatial indexing such as 3D Tiles, and cloud-based real-world content from [Cesium ion](https://cesium.com/cesium-ion) with Omniverse, this extension enables rich 3D geospatial workflows and applications in Omniverse, which adds real-time ray tracing and AI-powered analytics. [Cesium for Omniverse Homepage](https://cesium.com/platform/cesium-for-omniverse?utm_source=github&utm_medium=github&utm_campaign=omniverse) ### :rocket: Get Started **[Download Cesium for Omniverse](https://github.com/CesiumGS/cesium-omniverse/releases/latest)** **[Follow the Quickstart](https://cesium.com/learn/omniverse/omniverse-quickstart/)** Have questions? Ask them on the [community forum](https://community.cesium.com/c/cesium-for-omniverse). ### :clap: Featured Demos ### :house_with_garden: Cesium for Omniverse and the 3D Geospatial Ecosystem Cesium for Omniverse streams real-world 3D content such as high-resolution photogrammetry, terrain, imagery, and 3D buildings from [Cesium ion](https://cesium.com/cesium-ion) and other sources, available as optional commercial subscriptions. The extension includes Cesium ion integration for instant access to global high-resolution 3D content ready for runtime streaming. Cesium ion users can also leverage cloud-based 3D tiling pipelines to create end-to-end workflows to transform massive heterogenous content into semantically-rich 3D Tiles, ready for streaming to Omniverse. ![Cesium for Ecosystem Diagram](./docs/resources/integration-ecosystem-diagram.png) Cesium for Omniverse supports cloud and private network content and services based on open standards and APIs. You are free to use any combination of supported content sources, standards, APIs with Cesium for Omniverse. ![Cesium for Omniverse Architecture](./docs/resources/integration-workflow_omniverse.png) Using Cesium ion helps support Cesium for Omniverse development. :heart: ### :green_book: License [Apache 2.0](http://www.apache.org/licenses/LICENSE-2.0.html). Cesium for Omniverse is free for both commercial and non-commercial use. ### :computer: Developing Cesium for Omniverse See the [Developer Setup Guide](docs/developer-setup/README.md) to learn how to set up a development environment for Cesium for Omniverse, allowing you to compile it, customize it, and contribute to its development.
3,262
Markdown
84.868419
735
0.806867
CesiumGS/cesium-omniverse/src/core/src/UrlAssetAccessor.cpp
/* <editor-fold desc="MIT License"> Copyright(c) 2023 Timothy Moore Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. </editor-fold> */ // Copyright 2024 CesiumGS, Inc. and Contributors #include "cesium/omniverse/UrlAssetAccessor.h" #include <CesiumAsync/IAssetResponse.h> #include <CesiumUtility/Tracing.h> #include <omni/kit/IApp.h> #include <algorithm> #include <cstring> namespace cesium::omniverse { const auto CURL_BUFFERSIZE = 3145728L; // 3 MiB class UrlAssetResponse final : public CesiumAsync::IAssetResponse { public: uint16_t statusCode() const override { return _statusCode; } std::string contentType() const override { return _contentType; } const CesiumAsync::HttpHeaders& headers() const override { return _headers; } gsl::span<const std::byte> data() const override { return {const_cast<const std::byte*>(_result.data()), _result.size()}; } static size_t headerCallback(char* buffer, size_t size, size_t nitems, void* userData); static size_t dataCallback(char* buffer, size_t size, size_t nitems, void* userData); void setCallbacks(CURL* curl); uint16_t _statusCode = 0; std::string _contentType; CesiumAsync::HttpHeaders _headers; std::vector<std::byte> _result; }; class UrlAssetRequest final : public CesiumAsync::IAssetRequest { public: UrlAssetRequest(std::string method, std::string url, CesiumAsync::HttpHeaders headers) : _method(std::move(method)) , _url(std::move(url)) , _headers(std::move(headers)) {} UrlAssetRequest( std::string method, std::string url, const std::vector<CesiumAsync::IAssetAccessor::THeader>& headers) : _method(std::move(method)) , _url(std::move(url)) { _headers.insert(headers.begin(), headers.end()); const auto app = carb::getCachedInterface<omni::kit::IApp>(); const auto& buildInfo = app->getBuildInfo(); const auto platformInfo = app->getPlatformInfo(); _headers.insert({"X-Cesium-Client", "Cesium for Omniverse"}); _headers.insert( {"X-Cesium-Client-Version", fmt::format("v{} {}", CESIUM_OMNI_VERSION, CESIUM_OMNI_GIT_HASH_ABBREVIATED)}); _headers.insert({"X-Cesium-Client-Engine", fmt::format("Kit SDK {}", buildInfo.kitVersion)}); _headers.insert({"X-Cesium-Client-OS", platformInfo.platform}); } const std::string& method() const override { return _method; } const std::string& url() const override { return _url; } const CesiumAsync::HttpHeaders& headers() const override { return _headers; } const CesiumAsync::IAssetResponse* response() const override { return _response.get(); } void setResponse(std::unique_ptr<UrlAssetResponse> response) { _response = std::move(response); } private: std::string _method; std::string _url; CesiumAsync::HttpHeaders _headers; std::unique_ptr<UrlAssetResponse> _response; }; size_t UrlAssetResponse::headerCallback(char* buffer, size_t size, size_t nitems, void* userData) { // size is supposed to always be 1, but who knows const size_t cnt = size * nitems; auto* response = static_cast<UrlAssetResponse*>(userData); if (!response) { return cnt; } auto* colon = static_cast<char*>(std::memchr(buffer, ':', nitems)); if (colon) { char* value = colon + 1; auto* end = std::find(value, buffer + cnt, '\r'); while (value < end && *value == ' ') { ++value; } response->_headers.insert({std::string(buffer, colon), std::string(value, end)}); auto contentTypeItr = response->_headers.find("content-type"); if (contentTypeItr != response->_headers.end()) { response->_contentType = contentTypeItr->second; } } return cnt; } size_t UrlAssetResponse::dataCallback(char* buffer, size_t size, size_t nitems, void* userData) { const size_t cnt = size * nitems; auto* response = static_cast<UrlAssetResponse*>(userData); if (!response) { return cnt; } std::transform(buffer, buffer + cnt, std::back_inserter(response->_result), [](char c) { return std::byte{static_cast<unsigned char>(c)}; }); return cnt; } } //namespace cesium::omniverse extern "C" size_t headerCallback(char* buffer, size_t size, size_t nitems, void* userData) { return cesium::omniverse::UrlAssetResponse::headerCallback(buffer, size, nitems, userData); } extern "C" size_t dataCallback(char* buffer, size_t size, size_t nitems, void* userData) { return cesium::omniverse::UrlAssetResponse::dataCallback(buffer, size, nitems, userData); } namespace cesium::omniverse { void UrlAssetResponse::setCallbacks(CURL* curl) { curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, ::dataCallback); curl_easy_setopt(curl, CURLOPT_WRITEDATA, this); curl_easy_setopt(curl, CURLOPT_HEADERFUNCTION, ::headerCallback); curl_easy_setopt(curl, CURLOPT_HEADERDATA, this); } UrlAssetAccessor::UrlAssetAccessor(const std::filesystem::path& certificatePath) : userAgent("Mozilla/5.0 Cesium for Omniverse") , _certificatePath(certificatePath.generic_string()) { // XXX Do we need to worry about the thread safety problems with this? curl_global_init(CURL_GLOBAL_ALL); } UrlAssetAccessor::~UrlAssetAccessor() { curl_global_cleanup(); } curl_slist* UrlAssetAccessor::setCommonOptions(CURL* curl, const std::string& url, const CesiumAsync::HttpHeaders& headers) { curl_easy_setopt(curl, CURLOPT_USERAGENT, userAgent.c_str()); curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 1L); if (!_certificatePath.empty()) { curl_easy_setopt(curl, CURLOPT_CAINFO, _certificatePath.c_str()); } else { curl_easy_setopt(curl, CURLOPT_SSL_OPTIONS, CURLSSLOPT_NATIVE_CA); } curl_easy_setopt(curl, CURLOPT_ACCEPT_ENCODING, ""); curl_easy_setopt(curl, CURLOPT_BUFFERSIZE, CURL_BUFFERSIZE); curl_easy_setopt(curl, CURLOPT_MAXCONNECTS, 20L); curl_easy_setopt(curl, CURLOPT_DNS_CACHE_TIMEOUT, 300L); // curl_easy_setopt(curl, CURLOPT_SSL_VERIFYPEER, 0L); curl_slist* list = nullptr; for (const auto& header : headers) { std::string fullHeader = header.first + ":" + header.second; list = curl_slist_append(list, fullHeader.c_str()); } if (list) { curl_easy_setopt(curl, CURLOPT_HTTPHEADER, list); } curl_easy_setopt(curl, CURLOPT_URL, url.c_str()); return list; } // RAII wrapper for the CurlCache. class CurlHandle { public: CurlHandle(UrlAssetAccessor* accessor_) : _accessor(accessor_) { _curl = _accessor->curlCache.get(); } ~CurlHandle() { _accessor->curlCache.release(_curl); } CURL* operator()() const { return _curl; } private: UrlAssetAccessor* _accessor; CURL* _curl; }; CesiumAsync::Future<std::shared_ptr<CesiumAsync::IAssetRequest>> UrlAssetAccessor::get( const CesiumAsync::AsyncSystem& asyncSystem, const std::string& url, const std::vector<CesiumAsync::IAssetAccessor::THeader>& headers) { return asyncSystem.createFuture<std::shared_ptr<CesiumAsync::IAssetRequest>>([&](const auto& promise) { std::shared_ptr<UrlAssetRequest> request = std::make_shared<UrlAssetRequest>("GET", url, headers); asyncSystem.runInWorkerThread([promise, request, this]() { CESIUM_TRACE("UrlAssetAccessor::get"); CurlHandle curl(this); curl_slist* list = setCommonOptions(curl(), request->url(), request->headers()); std::unique_ptr<UrlAssetResponse> response = std::make_unique<UrlAssetResponse>(); response->setCallbacks(curl()); CURLcode responseCode = curl_easy_perform(curl()); curl_slist_free_all(list); if (responseCode == 0) { long httpResponseCode = 0; curl_easy_getinfo(curl(), CURLINFO_RESPONSE_CODE, &httpResponseCode); response->_statusCode = static_cast<uint16_t>(httpResponseCode); // The response header callback also sets _contentType, so not sure that this is // necessary... char* ct = nullptr; curl_easy_getinfo(curl(), CURLINFO_CONTENT_TYPE, &ct); if (ct) { response->_contentType = ct; } request->setResponse(std::move(response)); promise.resolve(request); } else { std::string curlMsg("curl: "); curlMsg += curl_easy_strerror(responseCode); promise.reject(std::runtime_error(curlMsg)); } }); }); } // request() with a verb and argument is essentially a POST CesiumAsync::Future<std::shared_ptr<CesiumAsync::IAssetRequest>> UrlAssetAccessor::request( const CesiumAsync::AsyncSystem& asyncSystem, const std::string& verb, const std::string& url, const std::vector<CesiumAsync::IAssetAccessor::THeader>& headers, const gsl::span<const std::byte>& contentPayload) { return asyncSystem.createFuture<std::shared_ptr<CesiumAsync::IAssetRequest>>([&](const auto& promise) { auto request = std::make_shared<UrlAssetRequest>(verb, url, headers); auto payloadCopy = std::make_shared<std::vector<std::byte>>(contentPayload.begin(), contentPayload.end()); asyncSystem.runInWorkerThread([promise, request, payloadCopy, this]() { CESIUM_TRACE("UrlAssetAccessor::request"); CurlHandle curl(this); curl_slist* list = setCommonOptions(curl(), request->url(), request->headers()); if (payloadCopy->size() > 1UL << 31) { curl_easy_setopt(curl(), CURLOPT_POSTFIELDSIZE_LARGE, payloadCopy->size()); } else { curl_easy_setopt(curl(), CURLOPT_POSTFIELDSIZE, payloadCopy->size()); } curl_easy_setopt(curl(), CURLOPT_COPYPOSTFIELDS, reinterpret_cast<const char*>(payloadCopy->data())); curl_easy_setopt(curl(), CURLOPT_CUSTOMREQUEST, request->method().c_str()); std::unique_ptr<UrlAssetResponse> response = std::make_unique<UrlAssetResponse>(); response->setCallbacks(curl()); CURLcode responseCode = curl_easy_perform(curl()); curl_slist_free_all(list); if (responseCode == 0) { long httpResponseCode = 0; curl_easy_getinfo(curl(), CURLINFO_RESPONSE_CODE, &httpResponseCode); response->_statusCode = static_cast<uint16_t>(httpResponseCode); char* ct = nullptr; curl_easy_getinfo(curl(), CURLINFO_CONTENT_TYPE, &ct); if (ct) { response->_contentType = ct; } request->setResponse(std::move(response)); promise.resolve(request); } else { std::string curlMsg("curl: "); curlMsg += curl_easy_strerror(responseCode); promise.reject(std::runtime_error(curlMsg)); } }); }); } void UrlAssetAccessor::tick() noexcept {} } //namespace cesium::omniverse
12,288
C++
37.88924
119
0.645182
CesiumGS/cesium-omniverse/src/core/src/FabricPrepareRenderResources.cpp
#include "cesium/omniverse/FabricPrepareRenderResources.h" #include "cesium/omniverse/AssetRegistry.h" #include "cesium/omniverse/Context.h" #include "cesium/omniverse/CppUtil.h" #include "cesium/omniverse/FabricFeaturesInfo.h" #include "cesium/omniverse/FabricFeaturesUtil.h" #include "cesium/omniverse/FabricGeometry.h" #include "cesium/omniverse/FabricMaterial.h" #include "cesium/omniverse/FabricMesh.h" #include "cesium/omniverse/FabricRasterOverlaysInfo.h" #include "cesium/omniverse/FabricRenderResources.h" #include "cesium/omniverse/FabricResourceManager.h" #include "cesium/omniverse/FabricTexture.h" #include "cesium/omniverse/FabricTextureData.h" #include "cesium/omniverse/FabricUtil.h" #include "cesium/omniverse/GltfUtil.h" #include "cesium/omniverse/MetadataUtil.h" #include "cesium/omniverse/OmniRasterOverlay.h" #include "cesium/omniverse/OmniTileset.h" #include "cesium/omniverse/UsdUtil.h" #ifdef CESIUM_OMNI_MSVC #pragma push_macro("OPAQUE") #undef OPAQUE #endif #include <Cesium3DTilesSelection/Tile.h> #include <Cesium3DTilesSelection/Tileset.h> #include <CesiumAsync/AsyncSystem.h> #include <CesiumGltfContent/GltfUtilities.h> #include <omni/fabric/FabricUSD.h> #include <omni/ui/ImageProvider/DynamicTextureProvider.h> namespace cesium::omniverse { namespace { struct RasterOverlayLoadThreadResult { std::shared_ptr<FabricTexture> pTexture; }; struct RasterOverlayRenderResources { std::shared_ptr<FabricTexture> pTexture; }; struct LoadingMesh { const glm::dmat4 gltfLocalToEcefTransform; const uint64_t gltfMeshIndex; const uint64_t gltfPrimitiveIndex; }; struct TileLoadThreadResult { std::vector<LoadingMesh> loadingMeshes; std::vector<FabricMesh> fabricMeshes; }; uint64_t getFeatureIdTextureCount(const FabricFeaturesInfo& fabricFeaturesInfo) { return CppUtil::countIf(fabricFeaturesInfo.featureIds, [](const auto& featureId) { return std::holds_alternative<FabricTextureInfo>(featureId.featureIdStorage); }); } std::vector<LoadingMesh> getLoadingMeshes(const glm::dmat4& tileToEcefTransform, const CesiumGltf::Model& model) { CESIUM_TRACE("FabricPrepareRenderResources::getLoadingMeshes"); auto gltfWorldToTileTransform = glm::dmat4(1.0); gltfWorldToTileTransform = CesiumGltfContent::GltfUtilities::applyRtcCenter(model, gltfWorldToTileTransform); gltfWorldToTileTransform = CesiumGltfContent::GltfUtilities::applyGltfUpAxisTransform(model, gltfWorldToTileTransform); std::vector<LoadingMesh> loadingMeshes; model.forEachPrimitiveInScene( -1, [&tileToEcefTransform, &gltfWorldToTileTransform, &loadingMeshes]( const CesiumGltf::Model& gltf, [[maybe_unused]] const CesiumGltf::Node& node, const CesiumGltf::Mesh& mesh, const CesiumGltf::MeshPrimitive& primitive, const glm::dmat4& gltfLocalToWorldTransform) { const auto gltfMeshIndex = CppUtil::getIndexFromRef(gltf.meshes, mesh); const auto gltfPrimitiveIndex = CppUtil::getIndexFromRef(mesh.primitives, primitive); const auto gltfLocalToEcefTransform = tileToEcefTransform * gltfWorldToTileTransform * gltfLocalToWorldTransform; // In C++ 20 this can be emplace_back without the {} loadingMeshes.push_back({ gltfLocalToEcefTransform, gltfMeshIndex, gltfPrimitiveIndex, }); }); return loadingMeshes; } std::vector<FabricMesh> acquireFabricMeshes( Context& context, const CesiumGltf::Model& model, const std::vector<LoadingMesh>& loadingMeshes, const FabricRasterOverlaysInfo& rasterOverlaysInfo, const OmniTileset& tileset) { CESIUM_TRACE("FabricPrepareRenderResources::acquireFabricMeshes"); std::vector<FabricMesh> fabricMeshes; fabricMeshes.reserve(loadingMeshes.size()); auto& fabricResourceManager = context.getFabricResourceManager(); const auto tilesetMaterialPath = tileset.getMaterialPath(); for (const auto& loadingMesh : loadingMeshes) { auto& fabricMesh = fabricMeshes.emplace_back(); const auto& primitive = model.meshes[loadingMesh.gltfMeshIndex].primitives[loadingMesh.gltfPrimitiveIndex]; const auto materialInfo = GltfUtil::getMaterialInfo(model, primitive); const auto featuresInfo = GltfUtil::getFeaturesInfo(model, primitive); const auto shouldAcquireMaterial = fabricResourceManager.shouldAcquireMaterial( primitive, rasterOverlaysInfo.overlayRenderMethods.size() > 0, tilesetMaterialPath); fabricMesh.materialInfo = materialInfo; fabricMesh.featuresInfo = featuresInfo; fabricMesh.pGeometry = fabricResourceManager.acquireGeometry(model, primitive, featuresInfo, tileset.getSmoothNormals()); if (shouldAcquireMaterial) { fabricMesh.pMaterial = fabricResourceManager.acquireMaterial( model, primitive, materialInfo, featuresInfo, rasterOverlaysInfo, tileset.getTilesetId(), tilesetMaterialPath); } if (materialInfo.baseColorTexture.has_value()) { fabricMesh.pBaseColorTexture = fabricResourceManager.acquireTexture(); } const auto featureIdTextureCount = getFeatureIdTextureCount(featuresInfo); fabricMesh.featureIdTextures.reserve(featureIdTextureCount); for (uint64_t i = 0; i < featureIdTextureCount; ++i) { fabricMesh.featureIdTextures.push_back(fabricResourceManager.acquireTexture()); } const auto propertyTextureCount = MetadataUtil::getPropertyTextureImages(context, model, primitive).size(); fabricMesh.propertyTextures.reserve(propertyTextureCount); for (uint64_t i = 0; i < propertyTextureCount; ++i) { fabricMesh.propertyTextures.push_back(fabricResourceManager.acquireTexture()); } const auto propertyTableTextureCount = MetadataUtil::getPropertyTableTextureCount(context, model, primitive); fabricMesh.propertyTableTextures.reserve(propertyTableTextureCount); for (uint64_t i = 0; i < propertyTableTextureCount; ++i) { fabricMesh.propertyTableTextures.push_back(fabricResourceManager.acquireTexture()); } // Map glTF texcoord set index to primvar st index const auto texcoordSetIndexes = GltfUtil::getTexcoordSetIndexes(model, primitive); const auto rasterOverlayTexcoordSetIndexes = GltfUtil::getRasterOverlayTexcoordSetIndexes(model, primitive); uint64_t primvarStIndex = 0; for (const auto gltfSetIndex : texcoordSetIndexes) { fabricMesh.texcoordIndexMapping[gltfSetIndex] = primvarStIndex++; } for (const auto gltfSetIndex : rasterOverlayTexcoordSetIndexes) { fabricMesh.rasterOverlayTexcoordIndexMapping[gltfSetIndex] = primvarStIndex++; } // Map feature id types to set indexes fabricMesh.featureIdIndexSetIndexMapping = FabricFeaturesUtil::getSetIndexMapping(featuresInfo, FabricFeatureIdType::INDEX); fabricMesh.featureIdAttributeSetIndexMapping = FabricFeaturesUtil::getSetIndexMapping(featuresInfo, FabricFeatureIdType::ATTRIBUTE); fabricMesh.featureIdTextureSetIndexMapping = FabricFeaturesUtil::getSetIndexMapping(featuresInfo, FabricFeatureIdType::TEXTURE); // Map glTF texture index to property texture (FabricTexture) index fabricMesh.propertyTextureIndexMapping = MetadataUtil::getPropertyTextureIndexMapping(context, model, primitive); } return fabricMeshes; } void setFabricTextures( const Context& context, const CesiumGltf::Model& model, const std::vector<LoadingMesh>& loadingMeshes, std::vector<FabricMesh>& fabricMeshes) { CESIUM_TRACE("FabricPrepareRenderResources::setFabricTextures"); for (uint64_t i = 0; i < loadingMeshes.size(); ++i) { const auto& loadingMesh = loadingMeshes[i]; const auto& primitive = model.meshes[loadingMesh.gltfMeshIndex].primitives[loadingMesh.gltfPrimitiveIndex]; auto& fabricMesh = fabricMeshes[i]; if (fabricMesh.pBaseColorTexture) { const auto pBaseColorTextureImage = GltfUtil::getBaseColorTextureImage(model, primitive); if (!pBaseColorTextureImage || context.getFabricResourceManager().getDisableTextures()) { fabricMesh.pBaseColorTexture->setBytes( {std::byte(255), std::byte(255), std::byte(255), std::byte(255)}, 1, 1, carb::Format::eRGBA8_SRGB); } else { fabricMesh.pBaseColorTexture->setImage(*pBaseColorTextureImage, TransferFunction::SRGB); } } const auto featureIdTextureCount = fabricMesh.featureIdTextures.size(); for (uint64_t j = 0; j < featureIdTextureCount; ++j) { const auto featureIdSetIndex = fabricMesh.featureIdTextureSetIndexMapping[j]; const auto pFeatureIdTextureImage = GltfUtil::getFeatureIdTextureImage(model, primitive, featureIdSetIndex); if (!pFeatureIdTextureImage) { fabricMesh.featureIdTextures[j]->setBytes( {std::byte(0), std::byte(0), std::byte(0), std::byte(0)}, 1, 1, carb::Format::eRGBA8_SRGB); } else { fabricMesh.featureIdTextures[j]->setImage(*pFeatureIdTextureImage, TransferFunction::LINEAR); } } const auto propertyTextureImages = MetadataUtil::getPropertyTextureImages(context, model, primitive); const auto propertyTextureCount = fabricMesh.propertyTextures.size(); for (uint64_t j = 0; j < propertyTextureCount; ++j) { fabricMesh.propertyTextures[j]->setImage(*propertyTextureImages[j], TransferFunction::LINEAR); } const auto propertyTableTextures = MetadataUtil::encodePropertyTables(context, model, primitive); const auto propertyTableTextureCount = fabricMesh.propertyTableTextures.size(); for (uint64_t j = 0; j < propertyTableTextureCount; ++j) { const auto& texture = propertyTableTextures[j]; fabricMesh.propertyTableTextures[j]->setBytes(texture.bytes, texture.width, texture.height, texture.format); } } } void setFabricMeshes( const Context& context, const CesiumGltf::Model& model, const std::vector<LoadingMesh>& loadingMeshes, std::vector<FabricMesh>& fabricMeshes, const OmniTileset& tileset) { CESIUM_TRACE("FabricPrepareRenderResources::setFabricMeshes"); const auto& tilesetMaterialPath = tileset.getMaterialPath(); const auto displayColor = tileset.getDisplayColor(); const auto displayOpacity = tileset.getDisplayOpacity(); const auto ecefToPrimWorldTransform = UsdUtil::computeEcefToPrimWorldTransform(context, tileset.getResolvedGeoreferencePath(), tileset.getPath()); const auto tilesetId = tileset.getTilesetId(); const auto smoothNormals = tileset.getSmoothNormals(); for (uint64_t i = 0; i < loadingMeshes.size(); ++i) { const auto& loadingMesh = loadingMeshes[i]; const auto& primitive = model.meshes[loadingMesh.gltfMeshIndex].primitives[loadingMesh.gltfPrimitiveIndex]; const auto& fabricMesh = fabricMeshes[i]; const auto pGeometry = fabricMesh.pGeometry; const auto pMaterial = fabricMesh.pMaterial; pGeometry->setGeometry( tilesetId, ecefToPrimWorldTransform, loadingMesh.gltfLocalToEcefTransform, model, primitive, fabricMesh.materialInfo, smoothNormals, fabricMesh.texcoordIndexMapping, fabricMesh.rasterOverlayTexcoordIndexMapping); if (pMaterial) { pMaterial->setMaterial( model, primitive, tilesetId, fabricMesh.materialInfo, fabricMesh.featuresInfo, fabricMesh.pBaseColorTexture.get(), fabricMesh.featureIdTextures, fabricMesh.propertyTextures, fabricMesh.propertyTableTextures, displayColor, displayOpacity, fabricMesh.texcoordIndexMapping, fabricMesh.featureIdIndexSetIndexMapping, fabricMesh.featureIdAttributeSetIndexMapping, fabricMesh.featureIdTextureSetIndexMapping, fabricMesh.propertyTextureIndexMapping); pGeometry->setMaterial(pMaterial->getPath()); } else if (!tilesetMaterialPath.IsEmpty()) { pGeometry->setMaterial(FabricUtil::toFabricPath(tilesetMaterialPath)); } } } void freeFabricMeshes(Context& context, const std::vector<FabricMesh>& fabricMeshes) { auto& fabricResourceManager = context.getFabricResourceManager(); for (const auto& fabricMesh : fabricMeshes) { if (fabricMesh.pGeometry) { fabricResourceManager.releaseGeometry(fabricMesh.pGeometry); } if (fabricMesh.pMaterial) { fabricResourceManager.releaseMaterial(fabricMesh.pMaterial); } if (fabricMesh.pBaseColorTexture) { fabricResourceManager.releaseTexture(fabricMesh.pBaseColorTexture); } for (const auto& pFeatureIdTexture : fabricMesh.featureIdTextures) { fabricResourceManager.releaseTexture(pFeatureIdTexture); } for (const auto& pPropertyTexture : fabricMesh.propertyTextures) { fabricResourceManager.releaseTexture(pPropertyTexture); } for (const auto& pPropertyTableTexture : fabricMesh.propertyTableTextures) { fabricResourceManager.releaseTexture(pPropertyTableTexture); } } } } // namespace FabricPrepareRenderResources::FabricPrepareRenderResources(Context* pContext, OmniTileset* pTileset) : _pContext(pContext) , _pTileset(pTileset) {} CesiumAsync::Future<Cesium3DTilesSelection::TileLoadResultAndRenderResources> FabricPrepareRenderResources::prepareInLoadThread( const CesiumAsync::AsyncSystem& asyncSystem, Cesium3DTilesSelection::TileLoadResult&& tileLoadResult, const glm::dmat4& tileToEcefTransform, [[maybe_unused]] const std::any& rendererOptions) { const auto pModel = std::get_if<CesiumGltf::Model>(&tileLoadResult.contentKind); if (!pModel) { return asyncSystem.createResolvedFuture( Cesium3DTilesSelection::TileLoadResultAndRenderResources{std::move(tileLoadResult), nullptr}); } if (!tilesetExists()) { return asyncSystem.createResolvedFuture( Cesium3DTilesSelection::TileLoadResultAndRenderResources{std::move(tileLoadResult), nullptr}); } // We don't know how many raster overlays actually overlap this tile until attachRasterInMainThread is called // but at least we have an upper bound. Unused texture slots are initialized with a 1x1 transparent pixel so // blending still works. const auto overlapsRasterOverlay = tileLoadResult.rasterOverlayDetails.has_value(); FabricRasterOverlaysInfo rasterOverlaysInfo; if (overlapsRasterOverlay) { for (const auto& rasterOverlayPath : _pTileset->getRasterOverlayPaths()) { const auto& pRasterOverlay = _pContext->getAssetRegistry().getRasterOverlay(rasterOverlayPath); const auto overlayRenderMethod = pRasterOverlay ? pRasterOverlay->getOverlayRenderMethod() : FabricOverlayRenderMethod::OVERLAY; rasterOverlaysInfo.overlayRenderMethods.push_back(overlayRenderMethod); } } auto loadingMeshes = getLoadingMeshes(tileToEcefTransform, *pModel); struct IntermediateLoadThreadResult { Cesium3DTilesSelection::TileLoadResult tileLoadResult; std::vector<LoadingMesh> loadingMeshes; std::vector<FabricMesh> fabricMeshes; }; return asyncSystem .runInMainThread([this, rasterOverlaysInfo = std::move(rasterOverlaysInfo), loadingMeshes = std::move(loadingMeshes), tileLoadResult = std::move(tileLoadResult)]() mutable { if (!tilesetExists()) { return IntermediateLoadThreadResult{ std::move(tileLoadResult), {}, {}, }; } const auto pModel = std::get_if<CesiumGltf::Model>(&tileLoadResult.contentKind); auto fabricMeshes = acquireFabricMeshes(*_pContext, *pModel, loadingMeshes, rasterOverlaysInfo, *_pTileset); return IntermediateLoadThreadResult{ std::move(tileLoadResult), std::move(loadingMeshes), std::move(fabricMeshes), }; }) .thenInWorkerThread([this](IntermediateLoadThreadResult&& workerResult) mutable { auto tileLoadResult = std::move(workerResult.tileLoadResult); auto loadingMeshes = std::move(workerResult.loadingMeshes); auto fabricMeshes = std::move(workerResult.fabricMeshes); const auto pModel = std::get_if<CesiumGltf::Model>(&tileLoadResult.contentKind); if (tilesetExists()) { setFabricTextures(*_pContext, *pModel, loadingMeshes, fabricMeshes); } return Cesium3DTilesSelection::TileLoadResultAndRenderResources{ std::move(tileLoadResult), new TileLoadThreadResult{ std::move(loadingMeshes), std::move(fabricMeshes), }, }; }); } void* FabricPrepareRenderResources::prepareInMainThread(Cesium3DTilesSelection::Tile& tile, void* pLoadThreadResult) { if (!pLoadThreadResult) { return nullptr; } // Wrap in a unique_ptr so that pLoadThreadResult gets freed when this function returns std::unique_ptr<TileLoadThreadResult> pTileLoadThreadResult(static_cast<TileLoadThreadResult*>(pLoadThreadResult)); const auto& loadingMeshes = pTileLoadThreadResult->loadingMeshes; auto& fabricMeshes = pTileLoadThreadResult->fabricMeshes; const auto& content = tile.getContent(); auto pRenderContent = content.getRenderContent(); if (!pRenderContent) { return nullptr; } const auto& model = pRenderContent->getModel(); if (tilesetExists()) { setFabricMeshes(*_pContext, model, loadingMeshes, fabricMeshes, *_pTileset); } return new FabricRenderResources{ std::move(fabricMeshes), }; } void FabricPrepareRenderResources::free( [[maybe_unused]] Cesium3DTilesSelection::Tile& tile, void* pLoadThreadResult, void* pMainThreadResult) noexcept { if (pLoadThreadResult) { const auto pTileLoadThreadResult = static_cast<TileLoadThreadResult*>(pLoadThreadResult); freeFabricMeshes(*_pContext, pTileLoadThreadResult->fabricMeshes); delete pTileLoadThreadResult; } if (pMainThreadResult) { const auto pFabricRenderResources = static_cast<FabricRenderResources*>(pMainThreadResult); freeFabricMeshes(*_pContext, pFabricRenderResources->fabricMeshes); delete pFabricRenderResources; } } void* FabricPrepareRenderResources::prepareRasterInLoadThread( CesiumGltf::ImageCesium& image, [[maybe_unused]] const std::any& rendererOptions) { if (!tilesetExists()) { return nullptr; } const auto pTexture = _pContext->getFabricResourceManager().acquireTexture(); pTexture->setImage(image, TransferFunction::SRGB); return new RasterOverlayLoadThreadResult{pTexture}; } void* FabricPrepareRenderResources::prepareRasterInMainThread( [[maybe_unused]] CesiumRasterOverlays::RasterOverlayTile& rasterTile, void* pLoadThreadResult) { if (!pLoadThreadResult) { return nullptr; } // Wrap in a unique_ptr so that pLoadThreadResult gets freed when this function returns std::unique_ptr<RasterOverlayLoadThreadResult> pRasterOverlayLoadThreadResult( static_cast<RasterOverlayLoadThreadResult*>(pLoadThreadResult)); if (!tilesetExists()) { return nullptr; } return new RasterOverlayRenderResources{pRasterOverlayLoadThreadResult->pTexture}; } void FabricPrepareRenderResources::freeRaster( [[maybe_unused]] const CesiumRasterOverlays::RasterOverlayTile& rasterTile, void* pLoadThreadResult, void* pMainThreadResult) noexcept { if (pLoadThreadResult) { const auto pRasterOverlayLoadThreadResult = static_cast<RasterOverlayLoadThreadResult*>(pLoadThreadResult); _pContext->getFabricResourceManager().releaseTexture(pRasterOverlayLoadThreadResult->pTexture); delete pRasterOverlayLoadThreadResult; } if (pMainThreadResult) { const auto pRasterOverlayRenderResources = static_cast<RasterOverlayRenderResources*>(pMainThreadResult); _pContext->getFabricResourceManager().releaseTexture(pRasterOverlayRenderResources->pTexture); delete pRasterOverlayRenderResources; } } void FabricPrepareRenderResources::attachRasterInMainThread( const Cesium3DTilesSelection::Tile& tile, int32_t overlayTextureCoordinateID, [[maybe_unused]] const CesiumRasterOverlays::RasterOverlayTile& rasterTile, void* pMainThreadRendererResources, const glm::dvec2& translation, const glm::dvec2& scale) { auto pRasterOverlayRenderResources = static_cast<RasterOverlayRenderResources*>(pMainThreadRendererResources); if (!pRasterOverlayRenderResources) { return; } if (!tilesetExists()) { return; } const auto pTexture = pRasterOverlayRenderResources->pTexture.get(); const auto& content = tile.getContent(); const auto pRenderContent = content.getRenderContent(); if (!pRenderContent) { return; } const auto pFabricRenderResources = static_cast<FabricRenderResources*>(pRenderContent->getRenderResources()); if (!pFabricRenderResources) { return; } const auto rasterOverlayPath = _pTileset->getRasterOverlayPathIfExists(rasterTile.getOverlay()); if (rasterOverlayPath.IsEmpty()) { return; } const auto rasterOverlayPaths = _pTileset->getRasterOverlayPaths(); const auto rasterOverlayIndex = CppUtil::indexOf(_pTileset->getRasterOverlayPaths(), rasterOverlayPath); if (rasterOverlayIndex == rasterOverlayPaths.size()) { return; } const auto pRasterOverlay = _pContext->getAssetRegistry().getRasterOverlay(rasterOverlayPath); if (!pRasterOverlay) { return; } const auto alpha = glm::clamp(pRasterOverlay->getAlpha(), 0.0, 1.0); for (const auto& fabricMesh : pFabricRenderResources->fabricMeshes) { const auto pMaterial = fabricMesh.pMaterial; if (pMaterial) { const auto gltfSetIndex = static_cast<uint64_t>(overlayTextureCoordinateID); const auto textureInfo = FabricTextureInfo{ translation, 0.0, scale, gltfSetIndex, CesiumGltf::Sampler::WrapS::CLAMP_TO_EDGE, CesiumGltf::Sampler::WrapT::CLAMP_TO_EDGE, false, {}, }; pMaterial->setRasterOverlay( pTexture, textureInfo, rasterOverlayIndex, alpha, fabricMesh.rasterOverlayTexcoordIndexMapping); } } } void FabricPrepareRenderResources::detachRasterInMainThread( const Cesium3DTilesSelection::Tile& tile, [[maybe_unused]] int32_t overlayTextureCoordinateID, const CesiumRasterOverlays::RasterOverlayTile& rasterTile, [[maybe_unused]] void* pMainThreadRendererResources) noexcept { const auto& content = tile.getContent(); const auto pRenderContent = content.getRenderContent(); if (!pRenderContent) { return; } const auto pFabricRenderResources = static_cast<FabricRenderResources*>(pRenderContent->getRenderResources()); if (!pFabricRenderResources) { return; } if (!tilesetExists()) { return; } const auto rasterOverlayPath = _pTileset->getRasterOverlayPathIfExists(rasterTile.getOverlay()); if (rasterOverlayPath.IsEmpty()) { return; } const auto rasterOverlayPaths = _pTileset->getRasterOverlayPaths(); const auto rasterOverlayIndex = CppUtil::indexOf(rasterOverlayPaths, rasterOverlayPath); if (rasterOverlayIndex == rasterOverlayPaths.size()) { return; } for (const auto& fabricMesh : pFabricRenderResources->fabricMeshes) { const auto pMaterial = fabricMesh.pMaterial; if (pMaterial) { pMaterial->clearRasterOverlay(rasterOverlayIndex); } } } bool FabricPrepareRenderResources::tilesetExists() const { // When a tileset is deleted there's a short period between the prim being deleted and TfNotice notifying us about the change. // This function helps us know whether we should proceed with loading render resources. return _pTileset && _pContext->hasUsdStage() && UsdUtil::primExists(_pContext->getUsdStage(), _pTileset->getPath()); } void FabricPrepareRenderResources::detachTileset() { _pTileset = nullptr; } } // namespace cesium::omniverse
25,459
C++
39.094488
130
0.695196
CesiumGS/cesium-omniverse/src/core/src/Context.cpp
#include "cesium/omniverse/Context.h" #include "cesium/omniverse/AssetRegistry.h" #include "cesium/omniverse/CesiumIonServerManager.h" #include "cesium/omniverse/FabricResourceManager.h" #include "cesium/omniverse/FabricStatistics.h" #include "cesium/omniverse/FabricUtil.h" #include "cesium/omniverse/FilesystemUtil.h" #include "cesium/omniverse/Logger.h" #include "cesium/omniverse/OmniData.h" #include "cesium/omniverse/OmniIonRasterOverlay.h" #include "cesium/omniverse/OmniTileset.h" #include "cesium/omniverse/RenderStatistics.h" #include "cesium/omniverse/SettingsWrapper.h" #include "cesium/omniverse/TaskProcessor.h" #include "cesium/omniverse/TilesetStatistics.h" #include "cesium/omniverse/UrlAssetAccessor.h" #include "cesium/omniverse/UsdNotificationHandler.h" #include "cesium/omniverse/UsdUtil.h" #ifdef CESIUM_OMNI_MSVC #pragma push_macro("OPAQUE") #undef OPAQUE #endif #include <Cesium3DTilesContent/registerAllTileContentTypes.h> #include <CesiumAsync/CachingAssetAccessor.h> #include <CesiumAsync/SqliteCache.h> #include <CesiumUtility/CreditSystem.h> #include <omni/fabric/SimStageWithHistory.h> #include <pxr/usd/sdf/path.h> #include <pxr/usd/usdUtils/stageCache.h> #include <chrono> namespace cesium::omniverse { namespace { std::string getCacheDatabaseName() { auto cacheDirPath = FilesystemUtil::getCesiumCacheDirectory(); if (!cacheDirPath.empty()) { auto cacheFilePath = cacheDirPath / "cesium-request-cache.sqlite"; return cacheFilePath.generic_string(); } return {}; } std::shared_ptr<CesiumAsync::ICacheDatabase> makeCacheDatabase(const std::shared_ptr<Logger>& logger) { uint64_t maxCacheItems = Settings::getMaxCacheItems(); if (maxCacheItems == 0) { logger->oneTimeWarning("maxCacheItems set to 0, so disabling accessor cache"); return {}; } else if (auto dbName = getCacheDatabaseName(); !dbName.empty()) { logger->oneTimeWarning(fmt::format("Cesium cache file: {}", dbName)); return std::make_shared<CesiumAsync::SqliteCache>(logger, dbName, maxCacheItems); } logger->oneTimeWarning("could not get name for cache database"); return {}; } } // namespace namespace { uint64_t getSecondsSinceEpoch() { const auto timePoint = std::chrono::system_clock::now(); return std::chrono::duration_cast<std::chrono::seconds>(timePoint.time_since_epoch()).count(); } } // namespace Context::Context(const std::filesystem::path& cesiumExtensionLocation) : _cesiumExtensionLocation(cesiumExtensionLocation.lexically_normal()) , _certificatePath(_cesiumExtensionLocation / "certs" / "cacert.pem") , _cesiumMdlPathToken(pxr::TfToken((_cesiumExtensionLocation / "mdl" / "cesium.mdl").generic_string())) , _pTaskProcessor(std::make_shared<TaskProcessor>()) , _pAsyncSystem(std::make_unique<CesiumAsync::AsyncSystem>(_pTaskProcessor)) , _pLogger(std::make_shared<Logger>()) , _pCacheDatabase(makeCacheDatabase(_pLogger)) , _pCreditSystem(std::make_shared<CesiumUtility::CreditSystem>()) , _pAssetRegistry(std::make_unique<AssetRegistry>(this)) , _pFabricResourceManager(std::make_unique<FabricResourceManager>(this)) , _pCesiumIonServerManager(std::make_unique<CesiumIonServerManager>(this)) , _pUsdNotificationHandler(std::make_unique<UsdNotificationHandler>(this)) , _contextId(static_cast<int64_t>(getSecondsSinceEpoch())) { if (_pCacheDatabase) { _pAssetAccessor = std::make_shared<CesiumAsync::CachingAssetAccessor>( _pLogger, std::make_shared<UrlAssetAccessor>(_certificatePath), _pCacheDatabase); } else { _pAssetAccessor = std::make_shared<UrlAssetAccessor>(_certificatePath); } Cesium3DTilesContent::registerAllTileContentTypes(); #if CESIUM_TRACING_ENABLED const auto timeNow = std::chrono::time_point_cast<std::chrono::microseconds>(std::chrono::steady_clock::now()); const auto timeSinceEpoch = timeNow.time_since_epoch().count(); const auto path = cesiumExtensionLocation / fmt::format("cesium-trace-{}.json", timeSinceEpoch); CESIUM_TRACE_INIT(path.string()); #endif } Context::~Context() { clearStage(); CESIUM_TRACE_SHUTDOWN(); } const std::filesystem::path& Context::getCesiumExtensionLocation() const { return _cesiumExtensionLocation; } const std::filesystem::path& Context::getCertificatePath() const { return _certificatePath; } const pxr::TfToken& Context::getCesiumMdlPathToken() const { return _cesiumMdlPathToken; } std::shared_ptr<TaskProcessor> Context::getTaskProcessor() const { return _pTaskProcessor; } const CesiumAsync::AsyncSystem& Context::getAsyncSystem() const { return *_pAsyncSystem.get(); } std::shared_ptr<CesiumAsync::IAssetAccessor> Context::getAssetAccessor() const { return _pAssetAccessor; } std::shared_ptr<CesiumUtility::CreditSystem> Context::getCreditSystem() const { return _pCreditSystem; } std::shared_ptr<Logger> Context::getLogger() const { return _pLogger; } const AssetRegistry& Context::getAssetRegistry() const { return *_pAssetRegistry.get(); } AssetRegistry& Context::getAssetRegistry() { return *_pAssetRegistry.get(); } const FabricResourceManager& Context::getFabricResourceManager() const { return *_pFabricResourceManager.get(); } FabricResourceManager& Context::getFabricResourceManager() { return *_pFabricResourceManager.get(); } const CesiumIonServerManager& Context::getCesiumIonServerManager() const { return *_pCesiumIonServerManager.get(); } CesiumIonServerManager& Context::getCesiumIonServerManager() { return *_pCesiumIonServerManager.get(); } void Context::clearStage() { // The order is important. Clear the asset registry first so that Fabric // resources are released back into the pool. Then clear the pools. _pAssetRegistry->clear(); _pFabricResourceManager->clear(); _pUsdNotificationHandler->clear(); } void Context::reloadStage() { clearStage(); // Populate the asset registry from prims already on the stage _pUsdNotificationHandler->onStageLoaded(); // Update FabricResourceManager settings auto pData = _pAssetRegistry->getFirstData(); if (pData) { _pFabricResourceManager->setDisableMaterials(pData->getDebugDisableMaterials()); _pFabricResourceManager->setDisableTextures(pData->getDebugDisableTextures()); _pFabricResourceManager->setDisableGeometryPool(pData->getDebugDisableGeometryPool()); _pFabricResourceManager->setDisableMaterialPool(pData->getDebugDisableMaterialPool()); _pFabricResourceManager->setDisableTexturePool(pData->getDebugDisableTexturePool()); _pFabricResourceManager->setGeometryPoolInitialCapacity(pData->getDebugGeometryPoolInitialCapacity()); _pFabricResourceManager->setMaterialPoolInitialCapacity(pData->getDebugMaterialPoolInitialCapacity()); _pFabricResourceManager->setTexturePoolInitialCapacity(pData->getDebugTexturePoolInitialCapacity()); _pFabricResourceManager->setDebugRandomColors(pData->getDebugRandomColors()); } } void Context::clearAccessorCache() { if (_pCacheDatabase) { _pCacheDatabase->clearAll(); } } void Context::onUpdateFrame(const gsl::span<const Viewport>& viewports, bool waitForLoadingTiles) { _pUsdNotificationHandler->onUpdateFrame(); _pAssetRegistry->onUpdateFrame(viewports, waitForLoadingTiles); _pCesiumIonServerManager->onUpdateFrame(); } void Context::onUsdStageChanged(int64_t usdStageId) { if (_usdStageId == usdStageId) { return; } // Remove references to the old stage _pUsdStage = nullptr; _pFabricStage = nullptr; _usdStageId = 0; // Now it's safe to clear anything else that references the old stage clearStage(); if (usdStageId > 0) { _pUsdStage = pxr::UsdUtilsStageCache::Get().Find(pxr::UsdStageCache::Id::FromLongInt(static_cast<long>(usdStageId))); const auto iFabricStage = carb::getCachedInterface<omni::fabric::IStageReaderWriter>(); const auto fabricStageId = iFabricStage->get(omni::fabric::UsdStageId(static_cast<uint64_t>(usdStageId))); _pFabricStage = std::make_unique<omni::fabric::StageReaderWriter>(fabricStageId); _usdStageId = usdStageId; reloadStage(); } } const pxr::UsdStageWeakPtr& Context::getUsdStage() const { return _pUsdStage; } pxr::UsdStageWeakPtr& Context::getUsdStage() { return _pUsdStage; } int64_t Context::getUsdStageId() const { return _usdStageId; } bool Context::hasUsdStage() const { return getUsdStageId() != 0; } omni::fabric::StageReaderWriter& Context::getFabricStage() const { return *_pFabricStage.get(); } RenderStatistics Context::getRenderStatistics() const { RenderStatistics renderStatistics; if (!hasUsdStage()) { return renderStatistics; } const auto fabricStatistics = FabricUtil::getStatistics(getFabricStage()); renderStatistics.materialsCapacity = fabricStatistics.materialsCapacity; renderStatistics.materialsLoaded = fabricStatistics.materialsLoaded; renderStatistics.geometriesCapacity = fabricStatistics.geometriesCapacity; renderStatistics.geometriesLoaded = fabricStatistics.geometriesLoaded; renderStatistics.geometriesRendered = fabricStatistics.geometriesRendered; renderStatistics.trianglesLoaded = fabricStatistics.trianglesLoaded; renderStatistics.trianglesRendered = fabricStatistics.trianglesRendered; const auto& tilesets = _pAssetRegistry->getTilesets(); for (const auto& pTileset : tilesets) { const auto tilesetStatistics = pTileset->getStatistics(); renderStatistics.tilesetCachedBytes += tilesetStatistics.tilesetCachedBytes; renderStatistics.tilesVisited += tilesetStatistics.tilesVisited; renderStatistics.culledTilesVisited += tilesetStatistics.culledTilesVisited; renderStatistics.tilesRendered += tilesetStatistics.tilesRendered; renderStatistics.tilesCulled += tilesetStatistics.tilesCulled; renderStatistics.maxDepthVisited += tilesetStatistics.maxDepthVisited; renderStatistics.tilesLoadingWorker += tilesetStatistics.tilesLoadingWorker; renderStatistics.tilesLoadingMain += tilesetStatistics.tilesLoadingMain; renderStatistics.tilesLoaded += tilesetStatistics.tilesLoaded; } return renderStatistics; } int64_t Context::getContextId() const { // Creating a Fabric prim with the same path as a previously destroyed prim causes a crash. // The contextId is randomly generated and ensures that Fabric prim paths are unique even across extension reloads. return _contextId; } } // namespace cesium::omniverse
10,723
C++
35.852234
119
0.743355
CesiumGS/cesium-omniverse/src/core/src/FabricGeometryPool.cpp
#include "cesium/omniverse/FabricGeometryPool.h" #include "cesium/omniverse/Context.h" #include "cesium/omniverse/FabricVertexAttributeDescriptor.h" #include "cesium/omniverse/GltfUtil.h" #include <spdlog/fmt/fmt.h> namespace cesium::omniverse { FabricGeometryPool::FabricGeometryPool( Context* pContext, int64_t poolId, const FabricGeometryDescriptor& geometryDescriptor, uint64_t initialCapacity) : ObjectPool<FabricGeometry>() , _pContext(pContext) , _poolId(poolId) , _geometryDescriptor(geometryDescriptor) { setCapacity(initialCapacity); } const FabricGeometryDescriptor& FabricGeometryPool::getGeometryDescriptor() const { return _geometryDescriptor; } int64_t FabricGeometryPool::getPoolId() const { return _poolId; } std::shared_ptr<FabricGeometry> FabricGeometryPool::createObject(uint64_t objectId) const { const auto contextId = _pContext->getContextId(); const auto pathStr = fmt::format("/cesium_geometry_pool_{}_object_{}_context_{}", _poolId, objectId, contextId); const auto path = omni::fabric::Path(pathStr.c_str()); return std::make_shared<FabricGeometry>(_pContext, path, _geometryDescriptor, _poolId); } void FabricGeometryPool::setActive(FabricGeometry* pGeometry, bool active) const { pGeometry->setActive(active); } }; // namespace cesium::omniverse
1,348
C++
30.372092
116
0.749258
CesiumGS/cesium-omniverse/src/core/src/MetadataUtil.cpp
#include "cesium/omniverse/MetadataUtil.h" #include "cesium/omniverse/Context.h" #include "cesium/omniverse/DataType.h" #include "cesium/omniverse/FabricPropertyDescriptor.h" #include "cesium/omniverse/FabricTextureData.h" namespace cesium::omniverse::MetadataUtil { namespace { const auto unsupportedPropertyCallbackNoop = []([[maybe_unused]] const std::string& propertyId, [[maybe_unused]] const std::string& warning) {}; } std::tuple<std::vector<FabricPropertyDescriptor>, std::map<std::string, std::string>> getStyleableProperties( const Context& context, const CesiumGltf::Model& model, const CesiumGltf::MeshPrimitive& primitive) { std::vector<FabricPropertyDescriptor> properties; std::map<std::string, std::string> unsupportedPropertyWarnings; const auto unsupportedPropertyCallback = [&unsupportedPropertyWarnings](const std::string& propertyId, const std::string& warning) { unsupportedPropertyWarnings.insert({propertyId, warning}); }; forEachStyleablePropertyAttributeProperty( context, model, primitive, [&properties]( const std::string& propertyId, [[maybe_unused]] const auto& propertyAttributePropertyView, const auto& property) { constexpr auto type = std::decay_t<decltype(property)>::Type; // In C++ 20 this can be emplace_back without the {} properties.push_back({ FabricPropertyStorageType::ATTRIBUTE, DataTypeUtil::getMdlInternalPropertyType<type>(), propertyId, 0, // featureIdSetIndex not relevant for property attributes }); }, unsupportedPropertyCallback); forEachStyleablePropertyTextureProperty( context, model, primitive, [&properties]( const std::string& propertyId, [[maybe_unused]] const auto& propertyTexturePropertyView, const auto& property) { constexpr auto type = std::decay_t<decltype(property)>::Type; // In C++ 20 this can be emplace_back without the {} properties.push_back({ FabricPropertyStorageType::TEXTURE, DataTypeUtil::getMdlInternalPropertyType<type>(), propertyId, 0, // featureIdSetIndex not relevant for property textures }); }, unsupportedPropertyCallback); forEachStyleablePropertyTableProperty( context, model, primitive, [&properties]( const std::string& propertyId, [[maybe_unused]] const auto& propertyTablePropertyView, const auto& property) { constexpr auto type = std::decay_t<decltype(property)>::Type; // In C++ 20 this can be emplace_back without the {} properties.push_back({ FabricPropertyStorageType::TABLE, DataTypeUtil::getMdlInternalPropertyType<type>(), propertyId, property.featureIdSetIndex, }); }, unsupportedPropertyCallback); // Sorting is important for checking FabricMaterialDescriptor equality CppUtil::sort(properties, [](const auto& lhs, const auto& rhs) { return lhs.propertyId > rhs.propertyId; }); return {std::move(properties), std::move(unsupportedPropertyWarnings)}; } std::vector<const CesiumGltf::ImageCesium*> getPropertyTextureImages( const Context& context, const CesiumGltf::Model& model, const CesiumGltf::MeshPrimitive& primitive) { std::vector<const CesiumGltf::ImageCesium*> images; forEachStyleablePropertyTextureProperty( context, model, primitive, [&images]( [[maybe_unused]] const std::string& propertyId, const auto& propertyTexturePropertyView, [[maybe_unused]] const auto& property) { const auto pImage = propertyTexturePropertyView.getImage(); assert(pImage); // Shouldn't have gotten this far if image is invalid const auto imageIndex = CppUtil::indexOf(images, pImage); if (imageIndex == images.size()) { images.push_back(pImage); } }, unsupportedPropertyCallbackNoop); return images; } std::unordered_map<uint64_t, uint64_t> getPropertyTextureIndexMapping( const Context& context, const CesiumGltf::Model& model, const CesiumGltf::MeshPrimitive& primitive) { std::vector<const CesiumGltf::ImageCesium*> images; std::unordered_map<uint64_t, uint64_t> propertyTextureIndexMapping; forEachStyleablePropertyTextureProperty( context, model, primitive, [&images, &propertyTextureIndexMapping]( [[maybe_unused]] const std::string& propertyId, const auto& propertyTexturePropertyView, [[maybe_unused]] const auto& property) { const auto pImage = propertyTexturePropertyView.getImage(); assert(pImage); // Shouldn't have gotten this far if image is invalid const auto imageIndex = CppUtil::indexOf(images, pImage); if (imageIndex == images.size()) { images.push_back(pImage); } const auto textureIndex = property.textureIndex; propertyTextureIndexMapping[textureIndex] = imageIndex; }, unsupportedPropertyCallbackNoop); return propertyTextureIndexMapping; } std::vector<FabricTextureData> encodePropertyTables( const Context& context, const CesiumGltf::Model& model, const CesiumGltf::MeshPrimitive& primitive) { std::vector<FabricTextureData> textures; forEachStyleablePropertyTableProperty( context, model, primitive, [&textures]( [[maybe_unused]] const std::string& propertyId, const auto& propertyTablePropertyView, const auto& property) { constexpr auto type = std::decay_t<decltype(property)>::Type; constexpr auto textureType = DataTypeUtil::getPropertyTableTextureType<type>(); constexpr auto textureFormat = DataTypeUtil::getTextureFormat<textureType>(); using TextureType = DataTypeUtil::GetNativeType<textureType>; using TextureComponentType = DataTypeUtil::GetNativeType<DataTypeUtil::getComponentType<textureType>()>; // The texture type should always be the same or larger type static_assert(DataTypeUtil::getComponentCount<type>() <= DataTypeUtil::getComponentCount<textureType>()); // Matrix packing not implemented yet static_assert(!DataTypeUtil::isMatrix<type>()); const auto size = static_cast<uint64_t>(propertyTablePropertyView.size()); assert(size > 0); constexpr uint64_t maximumTextureWidth = 4096; const auto width = glm::min(maximumTextureWidth, size); const auto height = ((size - 1) / maximumTextureWidth) + 1; constexpr auto texelByteLength = DataTypeUtil::getByteLength<textureType>(); const auto textureByteLength = width * height * texelByteLength; std::vector<std::byte> texelBytes(textureByteLength, std::byte(0)); gsl::span<TextureType> texelValues( reinterpret_cast<TextureType*>(texelBytes.data()), texelBytes.size() / texelByteLength); for (uint64_t i = 0; i < size; ++i) { auto& texelValue = texelValues[i]; const auto& rawValue = propertyTablePropertyView.getRaw(static_cast<int64_t>(i)); if constexpr (DataTypeUtil::isVector<type>()) { for (uint64_t j = 0; j < DataTypeUtil::getComponentCount<type>(); ++j) { texelValue[j] = static_cast<TextureComponentType>(rawValue[j]); } } else { texelValue = static_cast<TextureType>(rawValue); } } // In C++ 20 this can be push_back without the {} textures.push_back({ std::move(texelBytes), width, height, textureFormat, }); }, unsupportedPropertyCallbackNoop); return textures; } uint64_t getPropertyTableTextureCount( const Context& context, const CesiumGltf::Model& model, const CesiumGltf::MeshPrimitive& primitive) { uint64_t count = 0; forEachStyleablePropertyTableProperty( context, model, primitive, [&count]( [[maybe_unused]] const std::string& propertyId, [[maybe_unused]] const auto& propertyTablePropertyView, [[maybe_unused]] const auto& property) { ++count; }, unsupportedPropertyCallbackNoop); return count; } } // namespace cesium::omniverse::MetadataUtil
9,027
C++
37.092827
117
0.622244
CesiumGS/cesium-omniverse/src/core/src/FabricMaterialPool.cpp
#include "cesium/omniverse/FabricMaterialPool.h" #include "cesium/omniverse/FabricPropertyDescriptor.h" #include "cesium/omniverse/FabricUtil.h" #include "cesium/omniverse/MetadataUtil.h" #include <spdlog/fmt/fmt.h> namespace cesium::omniverse { FabricMaterialPool::FabricMaterialPool( Context* pContext, int64_t poolId, const FabricMaterialDescriptor& materialDescriptor, uint64_t initialCapacity, const pxr::TfToken& defaultWhiteTextureAssetPathToken, const pxr::TfToken& defaultTransparentTextureAssetPathToken, bool debugRandomColors) : ObjectPool<FabricMaterial>() , _pContext(pContext) , _poolId(poolId) , _materialDescriptor(materialDescriptor) , _defaultWhiteTextureAssetPathToken(defaultWhiteTextureAssetPathToken) , _defaultTransparentTextureAssetPathToken(defaultTransparentTextureAssetPathToken) , _debugRandomColors(debugRandomColors) { setCapacity(initialCapacity); } const FabricMaterialDescriptor& FabricMaterialPool::getMaterialDescriptor() const { return _materialDescriptor; } int64_t FabricMaterialPool::getPoolId() const { return _poolId; } void FabricMaterialPool::updateShaderInput(const pxr::SdfPath& shaderPath, const pxr::TfToken& attributeName) { const auto& materials = getQueue(); for (auto& pMaterial : materials) { pMaterial->updateShaderInput(FabricUtil::toFabricPath(shaderPath), FabricUtil::toFabricToken(attributeName)); } } std::shared_ptr<FabricMaterial> FabricMaterialPool::createObject(uint64_t objectId) const { const auto contextId = _pContext->getContextId(); const auto pathStr = fmt::format("/cesium_material_pool_{}_object_{}_context_{}", _poolId, objectId, contextId); const auto path = omni::fabric::Path(pathStr.c_str()); return std::make_shared<FabricMaterial>( _pContext, path, _materialDescriptor, _defaultWhiteTextureAssetPathToken, _defaultTransparentTextureAssetPathToken, _debugRandomColors, _poolId); } void FabricMaterialPool::setActive(FabricMaterial* pMaterial, bool active) const { pMaterial->setActive(active); } }; // namespace cesium::omniverse
2,181
C++
34.193548
117
0.750573
CesiumGS/cesium-omniverse/src/core/src/OmniGlobeAnchor.cpp
#include "cesium/omniverse/OmniGlobeAnchor.h" #include "cesium/omniverse/AssetRegistry.h" #include "cesium/omniverse/Context.h" #include "cesium/omniverse/CppUtil.h" #include "cesium/omniverse/Logger.h" #include "cesium/omniverse/MathUtil.h" #include "cesium/omniverse/OmniGeoreference.h" #include "cesium/omniverse/UsdTokens.h" #include "cesium/omniverse/UsdUtil.h" #include <CesiumGeospatial/Cartographic.h> #include <CesiumGeospatial/Ellipsoid.h> #include <CesiumGeospatial/GlobeAnchor.h> #include <CesiumGeospatial/LocalHorizontalCoordinateSystem.h> #include <CesiumUsdSchemas/data.h> #include <CesiumUsdSchemas/georeference.h> #include <CesiumUsdSchemas/globeAnchorAPI.h> #include <CesiumUsdSchemas/ionServer.h> #include <CesiumUsdSchemas/rasterOverlay.h> #include <CesiumUsdSchemas/session.h> #include <CesiumUsdSchemas/tileset.h> #include <CesiumUsdSchemas/tokens.h> #include <CesiumUtility/Math.h> #include <glm/ext/matrix_relational.hpp> #include <glm/ext/matrix_transform.hpp> #include <glm/gtc/quaternion.hpp> #include <glm/gtx/euler_angles.hpp> #include <pxr/usd/usdGeom/xform.h> #include <pxr/usd/usdGeom/xformCommonAPI.h> #include <tuple> #include <utility> namespace cesium::omniverse { OmniGlobeAnchor::OmniGlobeAnchor(Context* pContext, const pxr::SdfPath& path) : _pContext(pContext) , _path(path) { initialize(); } OmniGlobeAnchor::~OmniGlobeAnchor() = default; const pxr::SdfPath& OmniGlobeAnchor::getPath() const { return _path; } bool OmniGlobeAnchor::getDetectTransformChanges() const { const auto cesiumGlobeAnchor = UsdUtil::getCesiumGlobeAnchor(_pContext->getUsdStage(), _path); if (!UsdUtil::isSchemaValid(cesiumGlobeAnchor)) { return true; } bool detectTransformChanges; cesiumGlobeAnchor.GetDetectTransformChangesAttr().Get(&detectTransformChanges); return detectTransformChanges; } bool OmniGlobeAnchor::getAdjustOrientation() const { const auto cesiumGlobeAnchor = UsdUtil::getCesiumGlobeAnchor(_pContext->getUsdStage(), _path); if (!UsdUtil::isSchemaValid(cesiumGlobeAnchor)) { return true; } bool adjustOrientation; cesiumGlobeAnchor.GetAdjustOrientationForGlobeWhenMovingAttr().Get(&adjustOrientation); return adjustOrientation; } pxr::SdfPath OmniGlobeAnchor::getResolvedGeoreferencePath() const { const auto cesiumGlobeAnchor = UsdUtil::getCesiumGlobeAnchor(_pContext->getUsdStage(), _path); if (!UsdUtil::isSchemaValid(cesiumGlobeAnchor)) { return {}; } pxr::SdfPathVector targets; cesiumGlobeAnchor.GetGeoreferenceBindingRel().GetForwardedTargets(&targets); if (!targets.empty()) { return targets.front(); } // Fall back to using the first georeference if there's no explicit binding const auto pGeoreference = _pContext->getAssetRegistry().getFirstGeoreference(); if (pGeoreference) { return pGeoreference->getPath(); } return {}; } void OmniGlobeAnchor::updateByEcefPosition() { initialize(); if (!isAnchorValid()) { return; } const auto primLocalToEcefTranslation = getPrimLocalToEcefTranslation(); const auto tolerance = CesiumUtility::Math::Epsilon4; if (MathUtil::epsilonEqual(primLocalToEcefTranslation, _cachedPrimLocalToEcefTranslation, tolerance)) { // Short circuit if we don't need to do an actual update. return; } auto primLocalToEcefTransform = _pAnchor->getAnchorToFixedTransform(); primLocalToEcefTransform[3] = glm::dvec4(primLocalToEcefTranslation, 1.0); const auto pGeoreference = _pContext->getAssetRegistry().getGeoreference(getResolvedGeoreferencePath()); _pAnchor->setAnchorToFixedTransform( primLocalToEcefTransform, getAdjustOrientation(), pGeoreference->getEllipsoid()); finalize(); } void OmniGlobeAnchor::updateByGeographicCoordinates() { initialize(); if (!isAnchorValid()) { return; } const auto geographicCoordinates = getGeographicCoordinates(); const auto tolerance = CesiumUtility::Math::Epsilon7; if (MathUtil::epsilonEqual(geographicCoordinates, _cachedGeographicCoordinates, tolerance)) { // Short circuit if we don't need to do an actual update. return; } const auto pGeoreference = _pContext->getAssetRegistry().getGeoreference(getResolvedGeoreferencePath()); const auto& ellipsoid = pGeoreference->getEllipsoid(); const auto primLocalToEcefTranslation = ellipsoid.cartographicToCartesian(geographicCoordinates); auto primLocalToEcefTransform = _pAnchor->getAnchorToFixedTransform(); primLocalToEcefTransform[3] = glm::dvec4(primLocalToEcefTranslation, 1.0); _pAnchor->setAnchorToFixedTransform(primLocalToEcefTransform, getAdjustOrientation(), ellipsoid); finalize(); } void OmniGlobeAnchor::updateByPrimLocalTransform(bool resetOrientation) { initialize(); if (!isAnchorValid()) { return; } const auto primLocalTranslation = getPrimLocalTranslation(); const auto primLocalRotation = getPrimLocalRotation(); const auto primLocalOrientation = getPrimLocalOrientation(); const auto primLocalScale = getPrimLocalScale(); const auto tolerance = CesiumUtility::Math::Epsilon4; if (MathUtil::epsilonEqual(primLocalTranslation, _cachedPrimLocalTranslation, tolerance) && MathUtil::epsilonEqual(primLocalRotation, _cachedPrimLocalRotation, tolerance) && MathUtil::epsilonEqual(primLocalOrientation, _cachedPrimLocalOrientation, tolerance) && MathUtil::epsilonEqual(primLocalScale, _cachedPrimLocalScale, tolerance)) { // Short circuit if we don't need to do an actual update. return; } const auto cesiumGlobeAnchor = UsdUtil::getCesiumGlobeAnchor(_pContext->getUsdStage(), _path); const auto xformable = pxr::UsdGeomXformable(cesiumGlobeAnchor); const auto xformOps = UsdUtil::getOrCreateTranslateRotateScaleOps(xformable); const auto opType = xformOps.value().rotateOrOrientOp.GetOpType(); glm::dmat4 primLocalTransform; if (opType == pxr::UsdGeomXformOp::TypeOrient) { primLocalTransform = MathUtil::compose(primLocalTranslation, primLocalOrientation, primLocalScale); } else { // xform ops are applied right to left, so xformOp:rotateXYZ actually applies a z-axis, then y-axis, then x-axis // rotation. To compensate for that, we need to compose euler angles in the reverse order. primLocalTransform = MathUtil::composeEuler( primLocalTranslation, primLocalRotation, primLocalScale, getReversedEulerAngleOrder(xformOps->eulerAngleOrder)); } const auto pGeoreference = _pContext->getAssetRegistry().getGeoreference(getResolvedGeoreferencePath()); _pAnchor->setAnchorToLocalTransform( pGeoreference->getLocalCoordinateSystem(), primLocalTransform, !resetOrientation && getAdjustOrientation(), pGeoreference->getEllipsoid()); finalize(); } void OmniGlobeAnchor::updateByGeoreference() { initialize(); if (!isAnchorValid()) { return; } finalize(); } bool OmniGlobeAnchor::isAnchorValid() const { const auto georeferencePath = getResolvedGeoreferencePath(); if (georeferencePath.IsEmpty()) { return false; } const auto pGeoreference = _pContext->getAssetRegistry().getGeoreference(georeferencePath); if (!pGeoreference) { return false; } const auto cesiumGlobeAnchor = UsdUtil::getCesiumGlobeAnchor(_pContext->getUsdStage(), _path); const auto xformable = pxr::UsdGeomXformable(cesiumGlobeAnchor); if (!UsdUtil::isSchemaValid(xformable)) { return false; } const auto xformOps = UsdUtil::getOrCreateTranslateRotateScaleOps(xformable); if (!xformOps) { _pContext->getLogger()->oneTimeWarning( "Globe anchor xform op order must be [translate, rotate, scale] followed by any additional transforms.", _path.GetText()); return false; } return true; } void OmniGlobeAnchor::initialize() { if (!isAnchorValid()) { _pAnchor = nullptr; return; } if (_pAnchor) { return; } // This function has the effect of baking the world transform into the local transform, which is unavoidable // when using globe anchors. const auto cesiumGlobeAnchor = UsdUtil::getCesiumGlobeAnchor(_pContext->getUsdStage(), _path); const auto xformable = pxr::UsdGeomXformable(cesiumGlobeAnchor); if (!UsdUtil::isSchemaValid(xformable)) { return; } bool resetsXformStack; const auto originalXformOps = xformable.GetOrderedXformOps(&resetsXformStack); const auto translateRotateScaleXformOps = {originalXformOps[0], originalXformOps[1], originalXformOps[2]}; // Only use translate, rotate, and scale ops when computing the local to ecef transform. // Additional transforms like xformOp:rotateX:unitsResolve are not baked into this transform. xformable.SetXformOpOrder(translateRotateScaleXformOps); // Compute the local to ecef transform const auto primLocalToEcefTransform = UsdUtil::computePrimLocalToEcefTransform(*_pContext, getResolvedGeoreferencePath(), _path); // Now that the transform is computed, switch back to the original ops xformable.SetXformOpOrder(originalXformOps); // Disable inheriting parent transforms from now on xformable.SetResetXformStack(true); // Initialize the globe anchor _pAnchor = std::make_unique<CesiumGeospatial::GlobeAnchor>(primLocalToEcefTransform); // Use the ecef transform (if set) or geographic coordinates (if set) to reposition the globe anchor. updateByEcefPosition(); updateByGeographicCoordinates(); // Update ecef position, geographic coordinates, and prim local transform from the globe anchor transform finalize(); } void OmniGlobeAnchor::finalize() { savePrimLocalToEcefTranslation(); saveGeographicCoordinates(); savePrimLocalTransform(); } glm::dvec3 OmniGlobeAnchor::getPrimLocalToEcefTranslation() const { const auto cesiumGlobeAnchor = UsdUtil::getCesiumGlobeAnchor(_pContext->getUsdStage(), _path); if (!UsdUtil::isSchemaValid(cesiumGlobeAnchor)) { return {0.0, 0.0, 0.0}; } pxr::GfVec3d primLocalToEcefTranslation; cesiumGlobeAnchor.GetPositionAttr().Get(&primLocalToEcefTranslation); return UsdUtil::usdToGlmVector(primLocalToEcefTranslation); } CesiumGeospatial::Cartographic OmniGlobeAnchor::getGeographicCoordinates() const { const auto cesiumGlobeAnchor = UsdUtil::getCesiumGlobeAnchor(_pContext->getUsdStage(), _path); if (!UsdUtil::isSchemaValid(cesiumGlobeAnchor)) { return {0.0, 0.0, 0.0}; } double longitude; double latitude; double height; cesiumGlobeAnchor.GetAnchorLongitudeAttr().Get(&longitude); cesiumGlobeAnchor.GetAnchorLatitudeAttr().Get(&latitude); cesiumGlobeAnchor.GetAnchorHeightAttr().Get(&height); return {glm::radians(longitude), glm::radians(latitude), height}; } glm::dvec3 OmniGlobeAnchor::getPrimLocalTranslation() const { const auto cesiumGlobeAnchor = UsdUtil::getCesiumGlobeAnchor(_pContext->getUsdStage(), _path); const auto xformable = pxr::UsdGeomXformable(cesiumGlobeAnchor); if (!UsdUtil::isSchemaValid(xformable)) { return {0.0, 0.0, 0.0}; } const auto xformOps = UsdUtil::getOrCreateTranslateRotateScaleOps(xformable); return UsdUtil::getTranslate(xformOps.value().translateOp); } glm::dvec3 OmniGlobeAnchor::getPrimLocalRotation() const { const auto cesiumGlobeAnchor = UsdUtil::getCesiumGlobeAnchor(_pContext->getUsdStage(), _path); const auto xformable = pxr::UsdGeomXformable(cesiumGlobeAnchor); if (!UsdUtil::isSchemaValid(xformable)) { return {0.0, 0.0, 0.0}; } const auto xformOps = UsdUtil::getOrCreateTranslateRotateScaleOps(xformable); const auto& rotateOrOrientOp = xformOps.value().rotateOrOrientOp; const auto opType = rotateOrOrientOp.GetOpType(); if (opType == pxr::UsdGeomXformOp::TypeOrient) { return {0.0, 0.0, 0.0}; } return glm::radians(UsdUtil::getRotate(rotateOrOrientOp)); } glm::dquat OmniGlobeAnchor::getPrimLocalOrientation() const { const auto cesiumGlobeAnchor = UsdUtil::getCesiumGlobeAnchor(_pContext->getUsdStage(), _path); const auto xformable = pxr::UsdGeomXformable(cesiumGlobeAnchor); if (!UsdUtil::isSchemaValid(xformable)) { return {1.0, 0.0, 0.0, 0.0}; } const auto xformOps = UsdUtil::getOrCreateTranslateRotateScaleOps(xformable); const auto& rotateOrOrientOp = xformOps.value().rotateOrOrientOp; const auto opType = rotateOrOrientOp.GetOpType(); if (opType != pxr::UsdGeomXformOp::TypeOrient) { return {1.0, 0.0, 0.0, 0.0}; } return UsdUtil::getOrient(rotateOrOrientOp); } glm::dvec3 OmniGlobeAnchor::getPrimLocalScale() const { const auto cesiumGlobeAnchor = UsdUtil::getCesiumGlobeAnchor(_pContext->getUsdStage(), _path); const auto xformable = pxr::UsdGeomXformable(cesiumGlobeAnchor); if (!UsdUtil::isSchemaValid(xformable)) { return {1.0, 1.0, 1.0}; } const auto xformOps = UsdUtil::getOrCreateTranslateRotateScaleOps(xformable); return UsdUtil::getScale(xformOps.value().scaleOp); } void OmniGlobeAnchor::savePrimLocalToEcefTranslation() { const auto cesiumGlobeAnchor = UsdUtil::getCesiumGlobeAnchor(_pContext->getUsdStage(), _path); if (!UsdUtil::isSchemaValid(cesiumGlobeAnchor)) { return; } const auto& primLocalToEcefTransform = _pAnchor->getAnchorToFixedTransform(); const auto primLocalToEcefTranslation = glm::dvec3(primLocalToEcefTransform[3]); _cachedPrimLocalToEcefTranslation = primLocalToEcefTranslation; cesiumGlobeAnchor.GetPositionAttr().Set(UsdUtil::glmToUsdVector(primLocalToEcefTranslation)); } void OmniGlobeAnchor::saveGeographicCoordinates() { const auto cesiumGlobeAnchor = UsdUtil::getCesiumGlobeAnchor(_pContext->getUsdStage(), _path); if (!UsdUtil::isSchemaValid(cesiumGlobeAnchor)) { return; } const auto pGeoreference = _pContext->getAssetRegistry().getGeoreference(getResolvedGeoreferencePath()); const auto& primLocalToEcefTransform = _pAnchor->getAnchorToFixedTransform(); const auto primLocalToEcefTranslation = glm::dvec3(primLocalToEcefTransform[3]); const auto cartographic = pGeoreference->getEllipsoid().cartesianToCartographic(primLocalToEcefTranslation); if (!cartographic) { return; } _cachedGeographicCoordinates = *cartographic; cesiumGlobeAnchor.GetAnchorLongitudeAttr().Set(glm::degrees(cartographic->longitude)); cesiumGlobeAnchor.GetAnchorLatitudeAttr().Set(glm::degrees(cartographic->latitude)); cesiumGlobeAnchor.GetAnchorHeightAttr().Set(cartographic->height); } void OmniGlobeAnchor::savePrimLocalTransform() { // Ideally we would just use UsdGeomXformableAPI to set translation, rotation, scale, but this doesn't // work when rotation and scale properties are double precision, which is common in Omniverse. const auto cesiumGlobeAnchor = UsdUtil::getCesiumGlobeAnchor(_pContext->getUsdStage(), _path); const auto xformable = pxr::UsdGeomXformable(cesiumGlobeAnchor); if (!UsdUtil::isSchemaValid(xformable)) { return; } auto xformOps = UsdUtil::getOrCreateTranslateRotateScaleOps(xformable); auto& [translateOp, rotateOrOrientOp, scaleOp, eulerAngleOrder] = xformOps.value(); const auto opType = rotateOrOrientOp.GetOpType(); const auto pGeoreference = _pContext->getAssetRegistry().getGeoreference(getResolvedGeoreferencePath()); const auto primLocalToWorldTransform = _pAnchor->getAnchorToLocalTransform(pGeoreference->getLocalCoordinateSystem()); if (opType == pxr::UsdGeomXformOp::TypeOrient) { const auto decomposed = MathUtil::decompose(primLocalToWorldTransform); _cachedPrimLocalTranslation = decomposed.translation; _cachedPrimLocalOrientation = decomposed.rotation; _cachedPrimLocalScale = decomposed.scale; UsdUtil::setTranslate(translateOp, decomposed.translation); UsdUtil::setOrient(rotateOrOrientOp, decomposed.rotation); UsdUtil::setScale(scaleOp, decomposed.scale); } else { // xform ops are applied right to left, so xformOp:rotateXYZ actually applies a z-axis, then y-axis, then x-axis // rotation. To compensate for that, we need to decompose euler angles in the reverse order. const auto decomposed = MathUtil::decomposeEuler(primLocalToWorldTransform, getReversedEulerAngleOrder(eulerAngleOrder)); _cachedPrimLocalTranslation = decomposed.translation; _cachedPrimLocalRotation = decomposed.rotation; _cachedPrimLocalScale = decomposed.scale; UsdUtil::setTranslate(translateOp, decomposed.translation); UsdUtil::setRotate(rotateOrOrientOp, glm::degrees(decomposed.rotation)); UsdUtil::setScale(scaleOp, decomposed.scale); } } } // namespace cesium::omniverse
17,158
C++
35.821888
120
0.732486
CesiumGS/cesium-omniverse/src/core/src/OmniTileset.cpp
#include "cesium/omniverse/OmniTileset.h" #include "cesium/omniverse/AssetRegistry.h" #include "cesium/omniverse/Broadcast.h" #include "cesium/omniverse/CesiumIonSession.h" #include "cesium/omniverse/Context.h" #include "cesium/omniverse/FabricGeometry.h" #include "cesium/omniverse/FabricMaterial.h" #include "cesium/omniverse/FabricMesh.h" #include "cesium/omniverse/FabricPrepareRenderResources.h" #include "cesium/omniverse/FabricRenderResources.h" #include "cesium/omniverse/FabricUtil.h" #include "cesium/omniverse/GltfUtil.h" #include "cesium/omniverse/Logger.h" #include "cesium/omniverse/OmniCartographicPolygon.h" #include "cesium/omniverse/OmniGeoreference.h" #include "cesium/omniverse/OmniGlobeAnchor.h" #include "cesium/omniverse/OmniIonServer.h" #include "cesium/omniverse/OmniPolygonRasterOverlay.h" #include "cesium/omniverse/OmniRasterOverlay.h" #include "cesium/omniverse/TaskProcessor.h" #include "cesium/omniverse/TilesetStatistics.h" #include "cesium/omniverse/UsdUtil.h" #include "cesium/omniverse/Viewport.h" #ifdef CESIUM_OMNI_MSVC #pragma push_macro("OPAQUE") #undef OPAQUE #endif #include <Cesium3DTilesSelection/Tileset.h> #include <Cesium3DTilesSelection/ViewState.h> #include <Cesium3DTilesSelection/ViewUpdateResult.h> #include <CesiumUsdSchemas/rasterOverlay.h> #include <CesiumUsdSchemas/tileset.h> #include <pxr/usd/usd/prim.h> #include <pxr/usd/usd/stage.h> #include <pxr/usd/usdGeom/boundable.h> #include <pxr/usd/usdShade/materialBindingAPI.h> namespace cesium::omniverse { namespace { void forEachFabricMaterial( Cesium3DTilesSelection::Tileset* pTileset, const std::function<void(FabricMaterial& fabricMaterial)>& callback) { pTileset->forEachLoadedTile([&callback](Cesium3DTilesSelection::Tile& tile) { if (tile.getState() != Cesium3DTilesSelection::TileLoadState::Done) { return; } const auto& content = tile.getContent(); const auto pRenderContent = content.getRenderContent(); if (!pRenderContent) { return; } const auto pFabricRenderResources = static_cast<FabricRenderResources*>(pRenderContent->getRenderResources()); if (!pFabricRenderResources) { return; } for (const auto& fabricMesh : pFabricRenderResources->fabricMeshes) { if (fabricMesh.pMaterial) { callback(*fabricMesh.pMaterial.get()); } } }); } } // namespace OmniTileset::OmniTileset(Context* pContext, const pxr::SdfPath& path, int64_t tilesetId) : _pContext(pContext) , _path(path) , _tilesetId(tilesetId) { reload(); } OmniTileset::~OmniTileset() { destroyNativeTileset(); } const pxr::SdfPath& OmniTileset::getPath() const { return _path; } int64_t OmniTileset::getTilesetId() const { return _tilesetId; } TilesetStatistics OmniTileset::getStatistics() const { TilesetStatistics statistics; statistics.tilesetCachedBytes = static_cast<uint64_t>(_pTileset->getTotalDataBytes()); statistics.tilesLoaded = static_cast<uint64_t>(_pTileset->getNumberOfTilesLoaded()); if (_pViewUpdateResult) { statistics.tilesVisited = static_cast<uint64_t>(_pViewUpdateResult->tilesVisited); statistics.culledTilesVisited = static_cast<uint64_t>(_pViewUpdateResult->culledTilesVisited); statistics.tilesRendered = static_cast<uint64_t>(_pViewUpdateResult->tilesToRenderThisFrame.size()); statistics.tilesCulled = static_cast<uint64_t>(_pViewUpdateResult->tilesCulled); statistics.maxDepthVisited = static_cast<uint64_t>(_pViewUpdateResult->maxDepthVisited); statistics.tilesLoadingWorker = static_cast<uint64_t>(_pViewUpdateResult->workerThreadTileLoadQueueLength); statistics.tilesLoadingMain = static_cast<uint64_t>(_pViewUpdateResult->mainThreadTileLoadQueueLength); } return statistics; } TilesetSourceType OmniTileset::getSourceType() const { const auto cesiumTileset = UsdUtil::getCesiumTileset(_pContext->getUsdStage(), _path); if (!UsdUtil::isSchemaValid(cesiumTileset)) { return TilesetSourceType::ION; } pxr::TfToken sourceType; cesiumTileset.GetSourceTypeAttr().Get(&sourceType); if (sourceType == pxr::CesiumTokens->url) { return TilesetSourceType::URL; } return TilesetSourceType::ION; } std::string OmniTileset::getUrl() const { const auto cesiumTileset = UsdUtil::getCesiumTileset(_pContext->getUsdStage(), _path); if (!UsdUtil::isSchemaValid(cesiumTileset)) { return ""; } std::string url; cesiumTileset.GetUrlAttr().Get(&url); return url; } int64_t OmniTileset::getIonAssetId() const { const auto cesiumTileset = UsdUtil::getCesiumTileset(_pContext->getUsdStage(), _path); if (!UsdUtil::isSchemaValid(cesiumTileset)) { return 0; } int64_t ionAssetId; cesiumTileset.GetIonAssetIdAttr().Get(&ionAssetId); return ionAssetId; } CesiumIonClient::Token OmniTileset::getIonAccessToken() const { const auto cesiumTileset = UsdUtil::getCesiumTileset(_pContext->getUsdStage(), _path); if (!UsdUtil::isSchemaValid(cesiumTileset)) { return {}; } std::string ionAccessToken; cesiumTileset.GetIonAccessTokenAttr().Get(&ionAccessToken); if (!ionAccessToken.empty()) { CesiumIonClient::Token t; t.token = ionAccessToken; return t; } const auto ionServerPath = getResolvedIonServerPath(); if (ionServerPath.IsEmpty()) { return {}; } const auto pIonServer = _pContext->getAssetRegistry().getIonServer(ionServerPath); if (!pIonServer) { return {}; } return pIonServer->getToken(); } std::string OmniTileset::getIonApiUrl() const { const auto ionServerPath = getResolvedIonServerPath(); if (ionServerPath.IsEmpty()) { return {}; } const auto pIonServer = _pContext->getAssetRegistry().getIonServer(ionServerPath); if (!pIonServer) { return {}; } return pIonServer->getIonServerApiUrl(); } pxr::SdfPath OmniTileset::getResolvedIonServerPath() const { const auto cesiumTileset = UsdUtil::getCesiumTileset(_pContext->getUsdStage(), _path); if (!UsdUtil::isSchemaValid(cesiumTileset)) { return {}; } pxr::SdfPathVector targets; cesiumTileset.GetIonServerBindingRel().GetForwardedTargets(&targets); if (!targets.empty()) { return targets.front(); } // Fall back to using the first ion server if there's no explicit binding const auto pIonServer = _pContext->getAssetRegistry().getFirstIonServer(); if (pIonServer) { return pIonServer->getPath(); } return {}; } double OmniTileset::getMaximumScreenSpaceError() const { const auto cesiumTileset = UsdUtil::getCesiumTileset(_pContext->getUsdStage(), _path); if (!UsdUtil::isSchemaValid(cesiumTileset)) { return 16.0; } float maximumScreenSpaceError; cesiumTileset.GetMaximumScreenSpaceErrorAttr().Get(&maximumScreenSpaceError); return static_cast<double>(maximumScreenSpaceError); } bool OmniTileset::getPreloadAncestors() const { const auto cesiumTileset = UsdUtil::getCesiumTileset(_pContext->getUsdStage(), _path); if (!UsdUtil::isSchemaValid(cesiumTileset)) { return true; } bool preloadAncestors; cesiumTileset.GetPreloadAncestorsAttr().Get(&preloadAncestors); return preloadAncestors; } bool OmniTileset::getPreloadSiblings() const { const auto cesiumTileset = UsdUtil::getCesiumTileset(_pContext->getUsdStage(), _path); if (!UsdUtil::isSchemaValid(cesiumTileset)) { return true; } bool preloadSiblings; cesiumTileset.GetPreloadSiblingsAttr().Get(&preloadSiblings); return preloadSiblings; } bool OmniTileset::getForbidHoles() const { const auto cesiumTileset = UsdUtil::getCesiumTileset(_pContext->getUsdStage(), _path); if (!UsdUtil::isSchemaValid(cesiumTileset)) { return false; } bool forbidHoles; cesiumTileset.GetForbidHolesAttr().Get(&forbidHoles); return forbidHoles; } uint32_t OmniTileset::getMaximumSimultaneousTileLoads() const { const auto cesiumTileset = UsdUtil::getCesiumTileset(_pContext->getUsdStage(), _path); if (!UsdUtil::isSchemaValid(cesiumTileset)) { return 20; } uint32_t maximumSimultaneousTileLoads; cesiumTileset.GetMaximumSimultaneousTileLoadsAttr().Get(&maximumSimultaneousTileLoads); return maximumSimultaneousTileLoads; } uint64_t OmniTileset::getMaximumCachedBytes() const { const auto cesiumTileset = UsdUtil::getCesiumTileset(_pContext->getUsdStage(), _path); if (!UsdUtil::isSchemaValid(cesiumTileset)) { return 536870912; } uint64_t maximumCachedBytes; cesiumTileset.GetMaximumCachedBytesAttr().Get(&maximumCachedBytes); return maximumCachedBytes; } uint32_t OmniTileset::getLoadingDescendantLimit() const { const auto cesiumTileset = UsdUtil::getCesiumTileset(_pContext->getUsdStage(), _path); if (!UsdUtil::isSchemaValid(cesiumTileset)) { return 20; } uint32_t loadingDescendantLimit; cesiumTileset.GetLoadingDescendantLimitAttr().Get(&loadingDescendantLimit); return loadingDescendantLimit; } bool OmniTileset::getEnableFrustumCulling() const { const auto cesiumTileset = UsdUtil::getCesiumTileset(_pContext->getUsdStage(), _path); if (!UsdUtil::isSchemaValid(cesiumTileset)) { return true; } bool enableFrustumCulling; cesiumTileset.GetEnableFrustumCullingAttr().Get(&enableFrustumCulling); return enableFrustumCulling; } bool OmniTileset::getEnableFogCulling() const { const auto cesiumTileset = UsdUtil::getCesiumTileset(_pContext->getUsdStage(), _path); if (!UsdUtil::isSchemaValid(cesiumTileset)) { return true; } bool enableFogCulling; cesiumTileset.GetEnableFogCullingAttr().Get(&enableFogCulling); return enableFogCulling; } bool OmniTileset::getEnforceCulledScreenSpaceError() const { const auto cesiumTileset = UsdUtil::getCesiumTileset(_pContext->getUsdStage(), _path); if (!UsdUtil::isSchemaValid(cesiumTileset)) { return true; } bool enforceCulledScreenSpaceError; cesiumTileset.GetEnforceCulledScreenSpaceErrorAttr().Get(&enforceCulledScreenSpaceError); return enforceCulledScreenSpaceError; } double OmniTileset::getMainThreadLoadingTimeLimit() const { const auto cesiumTileset = UsdUtil::getCesiumTileset(_pContext->getUsdStage(), _path); if (!UsdUtil::isSchemaValid(cesiumTileset)) { return 0.0; } float mainThreadLoadingTimeLimit; cesiumTileset.GetMainThreadLoadingTimeLimitAttr().Get(&mainThreadLoadingTimeLimit); return static_cast<double>(mainThreadLoadingTimeLimit); } double OmniTileset::getCulledScreenSpaceError() const { const auto cesiumTileset = UsdUtil::getCesiumTileset(_pContext->getUsdStage(), _path); if (!UsdUtil::isSchemaValid(cesiumTileset)) { return 64.0; } float culledScreenSpaceError; cesiumTileset.GetCulledScreenSpaceErrorAttr().Get(&culledScreenSpaceError); return static_cast<double>(culledScreenSpaceError); } bool OmniTileset::getSuspendUpdate() const { const auto cesiumTileset = UsdUtil::getCesiumTileset(_pContext->getUsdStage(), _path); if (!UsdUtil::isSchemaValid(cesiumTileset)) { return false; } bool suspendUpdate; cesiumTileset.GetSuspendUpdateAttr().Get(&suspendUpdate); return suspendUpdate; } bool OmniTileset::getSmoothNormals() const { const auto cesiumTileset = UsdUtil::getCesiumTileset(_pContext->getUsdStage(), _path); if (!UsdUtil::isSchemaValid(cesiumTileset)) { return false; } bool smoothNormals; cesiumTileset.GetSmoothNormalsAttr().Get(&smoothNormals); return smoothNormals; } bool OmniTileset::getShowCreditsOnScreen() const { const auto cesiumTileset = UsdUtil::getCesiumTileset(_pContext->getUsdStage(), _path); if (!UsdUtil::isSchemaValid(cesiumTileset)) { return false; } bool showCreditsOnScreen; cesiumTileset.GetShowCreditsOnScreenAttr().Get(&showCreditsOnScreen); return showCreditsOnScreen; } pxr::SdfPath OmniTileset::getResolvedGeoreferencePath() const { const auto pGlobeAnchor = _pContext->getAssetRegistry().getGlobeAnchor(_path); if (pGlobeAnchor) { // The georeference math has already happened in OmniGlobeAnchor, so this prevents it from happening again. // By returning an empty path any ecefTo or toEcef conversions are really conversions to and from tile world // space, which for non-georeferenced tilesets is some local coordinate system. return {}; } const auto cesiumTileset = UsdUtil::getCesiumTileset(_pContext->getUsdStage(), _path); if (!UsdUtil::isSchemaValid(cesiumTileset)) { return {}; } pxr::SdfPathVector targets; cesiumTileset.GetGeoreferenceBindingRel().GetForwardedTargets(&targets); if (!targets.empty()) { return targets.front(); } // Fall back to using the first georeference if there's no explicit binding const auto pGeoreference = _pContext->getAssetRegistry().getFirstGeoreference(); if (pGeoreference) { return pGeoreference->getPath(); } return {}; } pxr::SdfPath OmniTileset::getMaterialPath() const { const auto cesiumTileset = UsdUtil::getCesiumTileset(_pContext->getUsdStage(), _path); const auto materialBindingApi = pxr::UsdShadeMaterialBindingAPI(cesiumTileset); if (!UsdUtil::isSchemaValid(materialBindingApi)) { return {}; } const auto materialBinding = materialBindingApi.GetDirectBinding(); const auto& materialPath = materialBinding.GetMaterialPath(); return materialPath; } glm::dvec3 OmniTileset::getDisplayColor() const { const auto cesiumTileset = UsdUtil::getCesiumTileset(_pContext->getUsdStage(), _path); if (!UsdUtil::isSchemaValid(cesiumTileset)) { return {1.0, 1.0, 1.0}; } pxr::VtVec3fArray displayColorArray; cesiumTileset.GetDisplayColorAttr().Get(&displayColorArray); if (displayColorArray.size() == 0) { return {1.0, 1.0, 1.0}; } const auto& displayColor = displayColorArray[0]; return { static_cast<double>(displayColor[0]), static_cast<double>(displayColor[1]), static_cast<double>(displayColor[2]), }; } double OmniTileset::getDisplayOpacity() const { const auto cesiumTileset = UsdUtil::getCesiumTileset(_pContext->getUsdStage(), _path); if (!UsdUtil::isSchemaValid(cesiumTileset)) { return 1.0; } pxr::VtFloatArray displayOpacityArray; cesiumTileset.GetDisplayOpacityAttr().Get(&displayOpacityArray); if (displayOpacityArray.size() == 0) { return 1.0; } return static_cast<double>(displayOpacityArray[0]); } std::vector<pxr::SdfPath> OmniTileset::getRasterOverlayPaths() const { const auto cesiumTileset = UsdUtil::getCesiumTileset(_pContext->getUsdStage(), _path); if (!UsdUtil::isSchemaValid(cesiumTileset)) { return {}; } pxr::SdfPathVector targets; cesiumTileset.GetRasterOverlayBindingRel().GetForwardedTargets(&targets); return targets; } void OmniTileset::updateTilesetOptions() { auto& options = _pTileset->getOptions(); options.maximumScreenSpaceError = getMaximumScreenSpaceError(); options.preloadAncestors = getPreloadAncestors(); options.preloadSiblings = getPreloadSiblings(); options.forbidHoles = getForbidHoles(); options.maximumSimultaneousTileLoads = getMaximumSimultaneousTileLoads(); options.maximumCachedBytes = static_cast<int64_t>(getMaximumCachedBytes()); options.loadingDescendantLimit = getLoadingDescendantLimit(); options.enableFrustumCulling = getEnableFrustumCulling(); options.enableFogCulling = getEnableFogCulling(); options.enforceCulledScreenSpaceError = getEnforceCulledScreenSpaceError(); options.culledScreenSpaceError = getCulledScreenSpaceError(); options.mainThreadLoadingTimeLimit = getMainThreadLoadingTimeLimit(); options.showCreditsOnScreen = getShowCreditsOnScreen(); } void OmniTileset::reload() { destroyNativeTileset(); _pRenderResourcesPreparer = std::make_shared<FabricPrepareRenderResources>(_pContext, this); const auto externals = Cesium3DTilesSelection::TilesetExternals{ _pContext->getAssetAccessor(), _pRenderResourcesPreparer, _pContext->getAsyncSystem(), _pContext->getCreditSystem(), _pContext->getLogger()}; const auto sourceType = getSourceType(); const auto url = getUrl(); const auto tilesetPath = getPath(); const auto ionAssetId = getIonAssetId(); const auto ionAccessToken = getIonAccessToken(); const auto ionApiUrl = getIonApiUrl(); const auto name = UsdUtil::getName(_pContext->getUsdStage(), _path); Cesium3DTilesSelection::TilesetOptions options; options.maximumScreenSpaceError = static_cast<double>(getMaximumScreenSpaceError()); options.preloadAncestors = getPreloadAncestors(); options.preloadSiblings = getPreloadSiblings(); options.forbidHoles = getForbidHoles(); options.maximumSimultaneousTileLoads = getMaximumSimultaneousTileLoads(); options.maximumCachedBytes = static_cast<int64_t>(getMaximumCachedBytes()); options.loadingDescendantLimit = getLoadingDescendantLimit(); options.enableFrustumCulling = getEnableFrustumCulling(); options.enableFogCulling = getEnableFogCulling(); options.enforceCulledScreenSpaceError = getEnforceCulledScreenSpaceError(); options.culledScreenSpaceError = getCulledScreenSpaceError(); options.mainThreadLoadingTimeLimit = getMainThreadLoadingTimeLimit(); options.showCreditsOnScreen = getShowCreditsOnScreen(); options.loadErrorCallback = [this, tilesetPath, ionAssetId, name](const Cesium3DTilesSelection::TilesetLoadFailureDetails& error) { // Check for a 401 connecting to Cesium ion, which means the token is invalid // (or perhaps the asset ID is). Also check for a 404, because ion returns 404 // when the token is valid but not authorized for the asset. if (error.type == Cesium3DTilesSelection::TilesetLoadType::CesiumIon && (error.statusCode == 401 || error.statusCode == 404)) { Broadcast::showTroubleshooter(tilesetPath, ionAssetId, name, 0, "", error.message); } _pContext->getLogger()->error(error.message); }; options.contentOptions.ktx2TranscodeTargets = GltfUtil::getKtx2TranscodeTargets(); const auto rasterOverlayPaths = getRasterOverlayPaths(); for (const auto& rasterOverlayPath : rasterOverlayPaths) { const auto pPolygonRasterOverlay = _pContext->getAssetRegistry().getPolygonRasterOverlay(rasterOverlayPath); if (pPolygonRasterOverlay) { const auto pExcluder = pPolygonRasterOverlay->getExcluder(); if (pExcluder) { options.excluders.push_back(pExcluder); } } } _pViewUpdateResult = nullptr; _extentSet = false; _activeLoading = false; switch (sourceType) { case TilesetSourceType::ION: if (ionAssetId <= 0 || ionApiUrl.empty()) { _pTileset = std::make_unique<Cesium3DTilesSelection::Tileset>(externals, 0, "", options); } else { _pTileset = std::make_unique<Cesium3DTilesSelection::Tileset>( externals, ionAssetId, ionAccessToken.token, options, ionApiUrl); } break; case TilesetSourceType::URL: _pTileset = std::make_unique<Cesium3DTilesSelection::Tileset>(externals, url, options); break; } const auto boundRasterOverlayPaths = getRasterOverlayPaths(); for (const auto& boundRasterOverlayPath : boundRasterOverlayPaths) { const auto pOmniRasterOverlay = _pContext->getAssetRegistry().getRasterOverlay(boundRasterOverlayPath); if (pOmniRasterOverlay) { pOmniRasterOverlay->reload(); addRasterOverlayIfExists(pOmniRasterOverlay); } } } pxr::SdfPath OmniTileset::getRasterOverlayPathIfExists(const CesiumRasterOverlays::RasterOverlay& rasterOverlay) { const auto rasterOverlayPaths = getRasterOverlayPaths(); for (const auto& rasterOverlayPath : rasterOverlayPaths) { const auto pRasterOverlay = _pContext->getAssetRegistry().getRasterOverlay(rasterOverlayPath); if (pRasterOverlay) { const auto pNativeRasterOverlay = pRasterOverlay->getRasterOverlay(); if (pNativeRasterOverlay == &rasterOverlay) { return rasterOverlayPath; } } } return {}; } void OmniTileset::updateRasterOverlayAlpha(const pxr::SdfPath& rasterOverlayPath) { const auto rasterOverlayPaths = getRasterOverlayPaths(); const auto rasterOverlayIndex = CppUtil::indexOf(rasterOverlayPaths, rasterOverlayPath); if (rasterOverlayIndex == rasterOverlayPaths.size()) { return; } const auto pRasterOverlay = _pContext->getAssetRegistry().getRasterOverlay(rasterOverlayPath); if (!pRasterOverlay) { return; } const auto alpha = glm::clamp(pRasterOverlay->getAlpha(), 0.0, 1.0); forEachFabricMaterial(_pTileset.get(), [rasterOverlayIndex, alpha](FabricMaterial& fabricMaterial) { fabricMaterial.setRasterOverlayAlpha(rasterOverlayIndex, alpha); }); } void OmniTileset::updateDisplayColorAndOpacity() { const auto displayColor = getDisplayColor(); const auto displayOpacity = getDisplayOpacity(); forEachFabricMaterial(_pTileset.get(), [&displayColor, &displayOpacity](FabricMaterial& fabricMaterial) { fabricMaterial.setDisplayColorAndOpacity(displayColor, displayOpacity); }); } void OmniTileset::updateShaderInput(const pxr::SdfPath& shaderPath, const pxr::TfToken& attributeName) { forEachFabricMaterial(_pTileset.get(), [&shaderPath, &attributeName](FabricMaterial& fabricMaterial) { fabricMaterial.updateShaderInput( FabricUtil::toFabricPath(shaderPath), FabricUtil::toFabricToken(attributeName)); }); } void OmniTileset::onUpdateFrame(const gsl::span<const Viewport>& viewports, bool waitForLoadingTiles) { if (!UsdUtil::primExists(_pContext->getUsdStage(), _path)) { // TfNotice can be slow, and sometimes we get a frame or two before we actually get a chance to react on it. // This guard prevents us from crashing if the prim no longer exists. return; } updateTransform(); updateView(viewports, waitForLoadingTiles); if (!_extentSet) { _extentSet = updateExtent(); } updateLoadStatus(); } void OmniTileset::updateTransform() { // computeEcefToPrimWorldTransform is a slightly expensive operation to do every frame but it is simple // and exhaustive; it reacts to USD scene graph changes, up-axis changes, meters-per-unit changes, and georeference // origin changes without us needing to subscribe to any events. // // The faster approach would be to subscribe to change events for _worldPosition, _worldOrientation, _worldScale. // Alternatively, we could register a listener with Tf::Notice but this has the downside of only notifying us // about changes to the current prim and not its ancestor prims. Also Tf::Notice may notify us in a thread other // than the main thread and we would have to be careful to synchronize updates to Fabric in the main thread. const auto georeferencePath = getResolvedGeoreferencePath(); const auto ecefToPrimWorldTransform = UsdUtil::computeEcefToPrimWorldTransform(*_pContext, georeferencePath, _path); // Check for transform changes and update prims accordingly if (ecefToPrimWorldTransform != _ecefToPrimWorldTransform) { _ecefToPrimWorldTransform = ecefToPrimWorldTransform; FabricUtil::setTilesetTransform(_pContext->getFabricStage(), _tilesetId, ecefToPrimWorldTransform); _extentSet = updateExtent(); } } void OmniTileset::updateView(const gsl::span<const Viewport>& viewports, bool waitForLoadingTiles) { const auto visible = UsdUtil::isPrimVisible(_pContext->getUsdStage(), _path); if (visible && !getSuspendUpdate()) { // Go ahead and select some tiles const auto georeferencePath = getResolvedGeoreferencePath(); _viewStates.clear(); for (const auto& viewport : viewports) { _viewStates.push_back(UsdUtil::computeViewState(*_pContext, georeferencePath, _path, viewport)); } if (waitForLoadingTiles) { _pViewUpdateResult = &_pTileset->updateViewOffline(_viewStates); } else { _pViewUpdateResult = &_pTileset->updateView(_viewStates); } } if (!_pViewUpdateResult) { // No tiles have ever been selected. Return early. return; } // Hide tiles that we no longer need for (const auto pTile : _pViewUpdateResult->tilesFadingOut) { if (pTile->getState() == Cesium3DTilesSelection::TileLoadState::Done) { const auto pRenderContent = pTile->getContent().getRenderContent(); if (pRenderContent) { const auto pRenderResources = static_cast<const FabricRenderResources*>(pRenderContent->getRenderResources()); if (pRenderResources) { for (const auto& fabricMesh : pRenderResources->fabricMeshes) { fabricMesh.pGeometry->setVisibility(false); } } } } } // Update visibility for selected tiles for (const auto pTile : _pViewUpdateResult->tilesToRenderThisFrame) { if (pTile->getState() == Cesium3DTilesSelection::TileLoadState::Done) { const auto pRenderContent = pTile->getContent().getRenderContent(); if (pRenderContent) { const auto pRenderResources = static_cast<const FabricRenderResources*>(pRenderContent->getRenderResources()); if (pRenderResources) { for (const auto& fabricMesh : pRenderResources->fabricMeshes) { fabricMesh.pGeometry->setVisibility(visible); } } } } } } bool OmniTileset::updateExtent() { const auto pRootTile = _pTileset->getRootTile(); if (!pRootTile) { return false; } const auto cesiumTileset = UsdUtil::getCesiumTileset(_pContext->getUsdStage(), _path); const auto boundable = pxr::UsdGeomBoundable(cesiumTileset); if (!UsdUtil::isSchemaValid(boundable)) { return false; } const auto& boundingVolume = pRootTile->getBoundingVolume(); const auto ecefObb = Cesium3DTilesSelection::getOrientedBoundingBoxFromBoundingVolume(boundingVolume); const auto georeferencePath = getResolvedGeoreferencePath(); const auto ecefToStageTransform = UsdUtil::computeEcefToStageTransform(*_pContext, georeferencePath); const auto primObb = ecefObb.transform(ecefToStageTransform); const auto primAabb = primObb.toAxisAligned(); const auto bottomLeft = glm::dvec3(primAabb.minimumX, primAabb.minimumY, primAabb.minimumZ); const auto topRight = glm::dvec3(primAabb.maximumX, primAabb.maximumY, primAabb.maximumZ); pxr::VtArray<pxr::GfVec3f> extent = { UsdUtil::glmToUsdVector(glm::fvec3(bottomLeft)), UsdUtil::glmToUsdVector(glm::fvec3(topRight)), }; boundable.GetExtentAttr().Set(extent); return true; } void OmniTileset::updateLoadStatus() { const auto loadProgress = _pTileset->computeLoadProgress(); if (loadProgress < 100.0f) { _activeLoading = true; } else if (_activeLoading) { Broadcast::tilesetLoaded(_path); _activeLoading = false; } } void OmniTileset::destroyNativeTileset() { if (_pTileset) { // Remove raster overlays before the native tileset is destroyed // See comment above _pLoadedTiles in RasterOverlayCollection.h while (_pTileset->getOverlays().size() > 0) { _pTileset->getOverlays().remove(*_pTileset->getOverlays().begin()); } } if (_pRenderResourcesPreparer) { _pRenderResourcesPreparer->detachTileset(); } _pTileset = nullptr; _pRenderResourcesPreparer = nullptr; } void OmniTileset::addRasterOverlayIfExists(const OmniRasterOverlay* pOmniRasterOverlay) { const auto pNativeRasterOverlay = pOmniRasterOverlay->getRasterOverlay(); if (pNativeRasterOverlay) { _pTileset->getOverlays().add(pNativeRasterOverlay); } } } // namespace cesium::omniverse
28,867
C++
34.639506
120
0.704438
CesiumGS/cesium-omniverse/src/core/src/OmniCartographicPolygon.cpp
#include "cesium/omniverse/OmniCartographicPolygon.h" #include "cesium/omniverse/AssetRegistry.h" #include "cesium/omniverse/Context.h" #include "cesium/omniverse/OmniGeoreference.h" #include "cesium/omniverse/OmniGlobeAnchor.h" #include "cesium/omniverse/UsdUtil.h" #include <CesiumGeospatial/Cartographic.h> #include <CesiumUsdSchemas/globeAnchorAPI.h> #include <glm/glm.hpp> #include <pxr/usd/usdGeom/basisCurves.h> namespace cesium::omniverse { OmniCartographicPolygon::OmniCartographicPolygon(Context* pContext, const pxr::SdfPath& path) : _pContext(pContext) , _path(path) {} const pxr::SdfPath& OmniCartographicPolygon::getPath() const { return _path; } std::vector<CesiumGeospatial::Cartographic> OmniCartographicPolygon::getCartographics() const { const auto pGlobeAnchor = _pContext->getAssetRegistry().getGlobeAnchor(_path); if (!pGlobeAnchor) { return {}; } const auto georeferencePath = pGlobeAnchor->getResolvedGeoreferencePath(); if (georeferencePath.IsEmpty()) { return {}; } const auto pGeoreference = _pContext->getAssetRegistry().getGeoreference(georeferencePath); if (!pGeoreference) { return {}; } const auto cesiumCartographicPolygon = UsdUtil::getCesiumCartographicPolygon(_pContext->getUsdStage(), _path); if (!UsdUtil::isSchemaValid(cesiumCartographicPolygon)) { return {}; } pxr::VtArray<pxr::GfVec3f> points; cesiumCartographicPolygon.GetPointsAttr().Get(&points); std::vector<glm::dvec3> positionsLocal; positionsLocal.reserve(points.size()); for (const auto& point : points) { positionsLocal.push_back(glm::dvec3(UsdUtil::usdToGlmVector(point))); } const auto primLocalToEcefTransform = UsdUtil::computePrimLocalToEcefTransform(*_pContext, georeferencePath, _path); std::vector<CesiumGeospatial::Cartographic> cartographics; cartographics.reserve(positionsLocal.size()); for (const auto& positionLocal : positionsLocal) { const auto positionEcef = glm::dvec3(primLocalToEcefTransform * glm::dvec4(positionLocal, 1.0)); const auto positionCartographic = pGeoreference->getEllipsoid().cartesianToCartographic(positionEcef); if (!positionCartographic.has_value()) { return {}; } cartographics.push_back(positionCartographic.value()); } return cartographics; } } // namespace cesium::omniverse
2,437
C++
31.945946
120
0.72261
CesiumGS/cesium-omniverse/src/core/src/FabricFeaturesUtil.cpp
#include "cesium/omniverse/FabricFeaturesUtil.h" #include "cesium/omniverse/FabricFeaturesInfo.h" namespace cesium::omniverse::FabricFeaturesUtil { FabricFeatureIdType getFeatureIdType(const FabricFeatureId& featureId) { if (std::holds_alternative<std::monostate>(featureId.featureIdStorage)) { return FabricFeatureIdType::INDEX; } else if (std::holds_alternative<uint64_t>(featureId.featureIdStorage)) { return FabricFeatureIdType::ATTRIBUTE; } else if (std::holds_alternative<FabricTextureInfo>(featureId.featureIdStorage)) { return FabricFeatureIdType::TEXTURE; } return FabricFeatureIdType::INDEX; } std::vector<FabricFeatureIdType> getFeatureIdTypes(const FabricFeaturesInfo& featuresInfo) { const auto& featureIds = featuresInfo.featureIds; std::vector<FabricFeatureIdType> featureIdTypes; featureIdTypes.reserve(featureIds.size()); for (const auto& featureId : featureIds) { featureIdTypes.push_back(getFeatureIdType(featureId)); } return featureIdTypes; } std::vector<uint64_t> getSetIndexMapping(const FabricFeaturesInfo& featuresInfo, FabricFeatureIdType type) { const auto& featureIds = featuresInfo.featureIds; std::vector<uint64_t> setIndexMapping; setIndexMapping.reserve(featureIds.size()); for (uint64_t i = 0; i < featureIds.size(); ++i) { if (getFeatureIdType(featureIds[i]) == type) { setIndexMapping.push_back(i); } } return setIndexMapping; } bool hasFeatureIdType(const FabricFeaturesInfo& featuresInfo, FabricFeatureIdType type) { const auto& featureIds = featuresInfo.featureIds; for (const auto& featureId : featureIds) { if (getFeatureIdType(featureId) == type) { return true; } } return false; } } // namespace cesium::omniverse::FabricFeaturesUtil
1,864
C++
30.083333
108
0.719957
CesiumGS/cesium-omniverse/src/core/src/OmniTileMapServiceRasterOverlay.cpp
#include "cesium/omniverse/OmniTileMapServiceRasterOverlay.h" #include "cesium/omniverse/AssetRegistry.h" #include "cesium/omniverse/Context.h" #include "cesium/omniverse/GltfUtil.h" #include "cesium/omniverse/Logger.h" #include "cesium/omniverse/OmniGeoreference.h" #include "cesium/omniverse/UsdUtil.h" #include <CesiumRasterOverlays/TileMapServiceRasterOverlay.h> #include <CesiumUsdSchemas/tileMapServiceRasterOverlay.h> namespace cesium::omniverse { OmniTileMapServiceRasterOverlay::OmniTileMapServiceRasterOverlay(Context* pContext, const pxr::SdfPath& path) : OmniRasterOverlay(pContext, path) { reload(); } CesiumRasterOverlays::RasterOverlay* OmniTileMapServiceRasterOverlay::getRasterOverlay() const { return _pTileMapServiceRasterOverlay.get(); } std::string OmniTileMapServiceRasterOverlay::getUrl() const { const auto cesiumTileMapServiceRasterOverlay = UsdUtil::getCesiumTileMapServiceRasterOverlay(_pContext->getUsdStage(), _path); if (!UsdUtil::isSchemaValid(cesiumTileMapServiceRasterOverlay)) { return ""; } std::string url; cesiumTileMapServiceRasterOverlay.GetUrlAttr().Get(&url); return url; } int OmniTileMapServiceRasterOverlay::getMinimumZoomLevel() const { const auto cesiumTileMapServiceRasterOverlay = UsdUtil::getCesiumTileMapServiceRasterOverlay(_pContext->getUsdStage(), _path); if (!UsdUtil::isSchemaValid(cesiumTileMapServiceRasterOverlay)) { return 0; } int minimumZoomLevel; cesiumTileMapServiceRasterOverlay.GetMinimumZoomLevelAttr().Get(&minimumZoomLevel); return minimumZoomLevel; } int OmniTileMapServiceRasterOverlay::getMaximumZoomLevel() const { const auto cesiumTileMapServiceRasterOverlay = UsdUtil::getCesiumTileMapServiceRasterOverlay(_pContext->getUsdStage(), _path); if (!UsdUtil::isSchemaValid(cesiumTileMapServiceRasterOverlay)) { return 10; } int maximumZoomLevel; cesiumTileMapServiceRasterOverlay.GetMaximumZoomLevelAttr().Get(&maximumZoomLevel); return maximumZoomLevel; } bool OmniTileMapServiceRasterOverlay::getSpecifyZoomLevels() const { const auto cesiumTileMapServiceRasterOverlay = UsdUtil::getCesiumTileMapServiceRasterOverlay(_pContext->getUsdStage(), _path); if (!UsdUtil::isSchemaValid(cesiumTileMapServiceRasterOverlay)) { return false; } bool value; cesiumTileMapServiceRasterOverlay.GetSpecifyZoomLevelsAttr().Get(&value); return value; } void OmniTileMapServiceRasterOverlay::reload() { const auto rasterOverlayName = UsdUtil::getName(_pContext->getUsdStage(), _path); auto options = createRasterOverlayOptions(); options.loadErrorCallback = [this](const CesiumRasterOverlays::RasterOverlayLoadFailureDetails& error) { _pContext->getLogger()->error(error.message); }; CesiumRasterOverlays::TileMapServiceRasterOverlayOptions tmsOptions; const auto specifyZoomLevels = getSpecifyZoomLevels(); if (specifyZoomLevels) { tmsOptions.minimumLevel = getMinimumZoomLevel(); tmsOptions.maximumLevel = getMaximumZoomLevel(); } _pTileMapServiceRasterOverlay = new CesiumRasterOverlays::TileMapServiceRasterOverlay( rasterOverlayName, getUrl(), std::vector<CesiumAsync::IAssetAccessor::THeader>(), tmsOptions, options); } } // namespace cesium::omniverse
3,371
C++
34.87234
111
0.767725
CesiumGS/cesium-omniverse/src/core/src/OmniGeoreference.cpp
#include "cesium/omniverse/OmniGeoreference.h" #include "cesium/omniverse/Context.h" #include "cesium/omniverse/UsdUtil.h" #include <CesiumGeospatial/Ellipsoid.h> #include <CesiumGeospatial/LocalHorizontalCoordinateSystem.h> #include <CesiumUsdSchemas/georeference.h> #include <glm/glm.hpp> #include <pxr/usd/usdGeom/tokens.h> namespace cesium::omniverse { OmniGeoreference::OmniGeoreference(Context* pContext, const pxr::SdfPath& path) : _pContext(pContext) , _path(path) , _ellipsoid(CesiumGeospatial::Ellipsoid::WGS84) {} const pxr::SdfPath& OmniGeoreference::getPath() const { return _path; } CesiumGeospatial::Cartographic OmniGeoreference::getOrigin() const { const auto cesiumGeoreference = UsdUtil::getCesiumGeoreference(_pContext->getUsdStage(), _path); if (!UsdUtil::isSchemaValid(cesiumGeoreference)) { return {0.0, 0.0, 0.0}; } double longitude; double latitude; double height; cesiumGeoreference.GetGeoreferenceOriginLongitudeAttr().Get(&longitude); cesiumGeoreference.GetGeoreferenceOriginLatitudeAttr().Get(&latitude); cesiumGeoreference.GetGeoreferenceOriginHeightAttr().Get(&height); return {glm::radians(longitude), glm::radians(latitude), height}; } const CesiumGeospatial::Ellipsoid& OmniGeoreference::getEllipsoid() const { return _ellipsoid; } CesiumGeospatial::LocalHorizontalCoordinateSystem OmniGeoreference::getLocalCoordinateSystem() const { const auto origin = getOrigin(); const auto upAxis = UsdUtil::getUsdUpAxis(_pContext->getUsdStage()); const auto scaleInMeters = UsdUtil::getUsdMetersPerUnit(_pContext->getUsdStage()); if (upAxis == pxr::UsdGeomTokens->z) { return { origin, CesiumGeospatial::LocalDirection::East, CesiumGeospatial::LocalDirection::North, CesiumGeospatial::LocalDirection::Up, scaleInMeters, _ellipsoid, }; } return { origin, CesiumGeospatial::LocalDirection::East, CesiumGeospatial::LocalDirection::Up, CesiumGeospatial::LocalDirection::South, scaleInMeters, _ellipsoid, }; } } // namespace cesium::omniverse
2,209
C++
29.694444
102
0.709371
CesiumGS/cesium-omniverse/src/core/src/CesiumIonSession.cpp
// Copyright 2023 CesiumGS, Inc. and Contributors #include "cesium/omniverse/CesiumIonSession.h" #include "cesium/omniverse/Broadcast.h" #include "cesium/omniverse/SettingsWrapper.h" #include <CesiumUtility/Uri.h> #include <utility> using namespace CesiumAsync; using namespace CesiumIonClient; using namespace cesium::omniverse; CesiumIonSession::CesiumIonSession( const CesiumAsync::AsyncSystem& asyncSystem, std::shared_ptr<CesiumAsync::IAssetAccessor> pAssetAccessor, std::string ionServerUrl, std::string ionApiUrl, int64_t ionApplicationId) : _asyncSystem(asyncSystem) , _pAssetAccessor(std::move(pAssetAccessor)) , _connection(std::nullopt) , _profile(std::nullopt) , _assets(std::nullopt) , _tokens(std::nullopt) , _isConnecting(false) , _isResuming(false) , _isLoadingProfile(false) , _isLoadingAssets(false) , _isLoadingTokens(false) , _loadProfileQueued(false) , _loadAssetsQueued(false) , _loadTokensQueued(false) , _authorizeUrl() , _ionServerUrl(std::move(ionServerUrl)) , _ionApiUrl(std::move(ionApiUrl)) , _ionApplicationId(ionApplicationId) {} void CesiumIonSession::connect() { if (this->isConnecting() || this->isConnected() || this->isResuming()) { return; } this->_isConnecting = true; Connection::authorize( this->_asyncSystem, this->_pAssetAccessor, "Cesium for Omniverse", _ionApplicationId, "/cesium-for-omniverse/oauth2/callback", {"assets:list", "assets:read", "profile:read", "tokens:read", "tokens:write", "geocode"}, [this](const std::string& url) { // NOTE: We open the browser in the Python code. Check in the sign in widget's on_update_frame function. this->_authorizeUrl = url; }, _ionApiUrl, CesiumUtility::Uri::resolve(_ionServerUrl, "oauth")) .thenInMainThread([this](CesiumIonClient::Connection&& connection) { this->_isConnecting = false; this->_connection = std::move(connection); Settings::AccessToken token; token.ionApiUrl = _ionApiUrl; token.accessToken = this->_connection.value().getAccessToken(); Settings::setAccessToken(token); Broadcast::connectionUpdated(); }) .catchInMainThread([this]([[maybe_unused]] std::exception&& e) { this->_isConnecting = false; this->_connection = std::nullopt; Broadcast::connectionUpdated(); }); } void CesiumIonSession::resume() { if (this->isConnecting() || this->isConnected() || this->isResuming()) { return; } auto tokens = Settings::getAccessTokens(); if (tokens.size() < 1) { // No existing session to resume. return; } std::string accessToken; for (const auto& token : tokens) { if (token.ionApiUrl == _ionApiUrl) { accessToken = token.accessToken; break; } } if (accessToken.empty()) { // No existing session to resume. return; } this->_isResuming = true; this->_connection = Connection(this->_asyncSystem, this->_pAssetAccessor, accessToken); // Verify that the connection actually works. this->_connection.value() .me() .thenInMainThread([this](Response<Profile>&& response) { if (!response.value.has_value()) { this->_connection.reset(); } this->_isResuming = false; Broadcast::connectionUpdated(); }) .catchInMainThread([this]([[maybe_unused]] std::exception&& e) { this->_isResuming = false; this->_connection.reset(); Broadcast::connectionUpdated(); }); } void CesiumIonSession::disconnect() { this->_connection.reset(); this->_profile.reset(); this->_assets.reset(); this->_tokens.reset(); Settings::removeAccessToken(_ionApiUrl); Broadcast::connectionUpdated(); Broadcast::profileUpdated(); Broadcast::assetsUpdated(); Broadcast::tokensUpdated(); } void CesiumIonSession::tick() { this->_asyncSystem.dispatchMainThreadTasks(); } void CesiumIonSession::refreshProfile() { if (!this->_connection || this->_isLoadingProfile) { this->_loadProfileQueued = true; return; } this->_isLoadingProfile = true; this->_loadProfileQueued = false; this->_connection->me() .thenInMainThread([this](Response<Profile>&& profile) { this->_isLoadingProfile = false; this->_profile = std::move(profile.value); Broadcast::profileUpdated(); this->refreshProfileIfNeeded(); }) .catchInMainThread([this]([[maybe_unused]] std::exception&& e) { this->_isLoadingProfile = false; this->_profile = std::nullopt; Broadcast::profileUpdated(); this->refreshProfileIfNeeded(); }); } void CesiumIonSession::refreshAssets() { if (!this->_connection || this->_isLoadingAssets) { return; } this->_isLoadingAssets = true; this->_loadAssetsQueued = false; this->_connection->assets() .thenInMainThread([this](Response<Assets>&& assets) { this->_isLoadingAssets = false; this->_assets = std::move(assets.value); Broadcast::assetsUpdated(); this->refreshAssetsIfNeeded(); }) .catchInMainThread([this]([[maybe_unused]] std::exception&& e) { this->_isLoadingAssets = false; this->_assets = std::nullopt; Broadcast::assetsUpdated(); this->refreshAssetsIfNeeded(); }); } void CesiumIonSession::refreshTokens() { if (!this->_connection || this->_isLoadingTokens) { return; } this->_isLoadingTokens = true; this->_loadTokensQueued = false; this->_connection->tokens() .thenInMainThread([this](Response<TokenList>&& tokens) { this->_isLoadingTokens = false; this->_tokens = tokens.value ? std::make_optional(std::move(tokens.value.value().items)) : std::nullopt; Broadcast::tokensUpdated(); this->refreshTokensIfNeeded(); }) .catchInMainThread([this]([[maybe_unused]] std::exception&& e) { this->_isLoadingTokens = false; this->_tokens = std::nullopt; Broadcast::tokensUpdated(); this->refreshTokensIfNeeded(); }); } const std::optional<CesiumIonClient::Connection>& CesiumIonSession::getConnection() const { return this->_connection; } const CesiumIonClient::Profile& CesiumIonSession::getProfile() { static const CesiumIonClient::Profile empty{}; if (this->_profile) { return *this->_profile; } else { this->refreshProfile(); return empty; } } const CesiumIonClient::Assets& CesiumIonSession::getAssets() { static const CesiumIonClient::Assets empty; if (this->_assets) { return *this->_assets; } else { this->refreshAssets(); return empty; } } const std::vector<CesiumIonClient::Token>& CesiumIonSession::getTokens() { static const std::vector<CesiumIonClient::Token> empty; if (this->_tokens) { return *this->_tokens; } else { this->refreshTokens(); return empty; } } bool CesiumIonSession::refreshProfileIfNeeded() { if (this->_loadProfileQueued || !this->_profile.has_value()) { this->refreshProfile(); } return this->isProfileLoaded(); } bool CesiumIonSession::refreshAssetsIfNeeded() { if (this->_loadAssetsQueued || !this->_assets.has_value()) { this->refreshAssets(); } return this->isAssetListLoaded(); } bool CesiumIonSession::refreshTokensIfNeeded() { if (this->_loadTokensQueued || !this->_tokens.has_value()) { this->refreshTokens(); } return this->isTokenListLoaded(); } Future<Response<Token>> CesiumIonSession::findToken(const std::string& token) const { if (!this->_connection) { return _asyncSystem.createResolvedFuture(Response<Token>(0, "NOTCONNECTED", "Not connected to Cesium ion.")); } std::optional<std::string> maybeTokenID = Connection::getIdFromToken(token); if (!maybeTokenID) { return _asyncSystem.createResolvedFuture(Response<Token>(0, "INVALIDTOKEN", "The token is not valid.")); } return this->_connection->token(*maybeTokenID); }
8,547
C++
29.204947
117
0.615304
CesiumGS/cesium-omniverse/src/core/src/Logger.cpp
#include "cesium/omniverse/Logger.h" #include "cesium/omniverse/CppUtil.h" #include "cesium/omniverse/LoggerSink.h" namespace cesium::omniverse { Logger::Logger() : spdlog::logger( std::string("cesium-omniverse"), spdlog::sinks_init_list{ std::make_shared<LoggerSink>(omni::log::Level::eVerbose), std::make_shared<LoggerSink>(omni::log::Level::eInfo), std::make_shared<LoggerSink>(omni::log::Level::eWarn), std::make_shared<LoggerSink>(omni::log::Level::eError), std::make_shared<LoggerSink>(omni::log::Level::eFatal), }) {} } // namespace cesium::omniverse
666
C++
32.349998
71
0.618619
CesiumGS/cesium-omniverse/src/core/src/GltfUtil.cpp
#include "cesium/omniverse/GltfUtil.h" #include "cesium/omniverse/DataType.h" #include "cesium/omniverse/FabricFeaturesInfo.h" #include "cesium/omniverse/FabricMaterialInfo.h" #include "cesium/omniverse/FabricTextureInfo.h" #include "cesium/omniverse/FabricVertexAttributeDescriptor.h" #include <CesiumGltf/Material.h> #ifdef CESIUM_OMNI_MSVC #pragma push_macro("OPAQUE") #undef OPAQUE #endif #include <CesiumGltf/Accessor.h> #include <CesiumGltf/AccessorView.h> #include <CesiumGltf/ExtensionExtMeshFeatures.h> #include <CesiumGltf/ExtensionKhrMaterialsUnlit.h> #include <CesiumGltf/ExtensionKhrTextureTransform.h> #include <CesiumGltf/FeatureIdTexture.h> #include <CesiumGltf/FeatureIdTextureView.h> #include <CesiumGltf/Model.h> #include <CesiumGltf/PropertyTextureProperty.h> #include <CesiumGltf/TextureInfo.h> #include <spdlog/fmt/fmt.h> #include <charconv> #include <numeric> #include <optional> namespace cesium::omniverse::GltfUtil { namespace { const CesiumGltf::Material defaultMaterial; const CesiumGltf::MaterialPBRMetallicRoughness defaultPbrMetallicRoughness; const CesiumGltf::Sampler defaultSampler; const CesiumGltf::ExtensionKhrTextureTransform defaultTextureTransform; const CesiumGltf::TextureInfo defaultTextureInfo; template <typename IndexType> IndicesAccessor getIndicesAccessor( const CesiumGltf::MeshPrimitive& primitive, const CesiumGltf::AccessorView<IndexType>& indicesAccessorView) { if (indicesAccessorView.status() != CesiumGltf::AccessorViewStatus::Valid) { return {}; } if (primitive.mode == CesiumGltf::MeshPrimitive::Mode::TRIANGLES) { if (indicesAccessorView.size() % 3 != 0) { return {}; } return IndicesAccessor(indicesAccessorView); } if (primitive.mode == CesiumGltf::MeshPrimitive::Mode::TRIANGLE_STRIP) { if (indicesAccessorView.size() <= 2) { return {}; } return IndicesAccessor::FromTriangleStrips(indicesAccessorView); } if (primitive.mode == CesiumGltf::MeshPrimitive::Mode::TRIANGLE_FAN) { if (indicesAccessorView.size() <= 2) { return {}; } return IndicesAccessor::FromTriangleFans(indicesAccessorView); } return {}; } CesiumGltf::AccessorView<glm::fvec2> getTexcoordsView( const CesiumGltf::Model& model, const CesiumGltf::MeshPrimitive& primitive, const std::string& semantic, uint64_t setIndex) { const auto it = primitive.attributes.find(fmt::format("{}_{}", semantic, setIndex)); if (it == primitive.attributes.end()) { return {}; } const auto pTexcoordAccessor = model.getSafe(&model.accessors, it->second); if (!pTexcoordAccessor) { return {}; } const auto texcoordsView = CesiumGltf::AccessorView<glm::fvec2>(model, *pTexcoordAccessor); if (texcoordsView.status() != CesiumGltf::AccessorViewStatus::Valid) { return {}; } return texcoordsView; } CesiumGltf::AccessorView<glm::fvec3> getNormalsView(const CesiumGltf::Model& model, const CesiumGltf::MeshPrimitive& primitive) { const auto it = primitive.attributes.find("NORMAL"); if (it == primitive.attributes.end()) { return {}; } const auto pNormalAccessor = model.getSafe(&model.accessors, it->second); if (!pNormalAccessor) { return {}; } const auto normalsView = CesiumGltf::AccessorView<glm::fvec3>(model, *pNormalAccessor); if (normalsView.status() != CesiumGltf::AccessorViewStatus::Valid) { return {}; } return normalsView; } CesiumGltf::AccessorView<glm::fvec3> getPositionsView(const CesiumGltf::Model& model, const CesiumGltf::MeshPrimitive& primitive) { const auto it = primitive.attributes.find("POSITION"); if (it == primitive.attributes.end()) { return {}; } const auto pPositionAccessor = model.getSafe(&model.accessors, it->second); if (!pPositionAccessor) { return {}; } const auto positionsView = CesiumGltf::AccessorView<glm::fvec3>(model, *pPositionAccessor); if (positionsView.status() != CesiumGltf::AccessorViewStatus::Valid) { return {}; } return positionsView; } TexcoordsAccessor getTexcoords( const CesiumGltf::Model& model, const CesiumGltf::MeshPrimitive& primitive, const std::string& semantic, uint64_t setIndex, bool flipVertical) { const auto texcoordsView = getTexcoordsView(model, primitive, semantic, setIndex); if (texcoordsView.status() != CesiumGltf::AccessorViewStatus::Valid) { return {}; } return {texcoordsView, flipVertical}; } template <typename VertexColorType> VertexColorsAccessor getVertexColorsAccessor(const CesiumGltf::Model& model, const CesiumGltf::Accessor& accessor) { CesiumGltf::AccessorView<VertexColorType> view(model, accessor); if (view.status() == CesiumGltf::AccessorViewStatus::Valid) { return VertexColorsAccessor(view); } return {}; } double getAlphaCutoff(const CesiumGltf::Material& material) { return material.alphaCutoff; } FabricAlphaMode getAlphaMode(const CesiumGltf::Material& material) { if (material.alphaMode == CesiumGltf::Material::AlphaMode::OPAQUE) { return FabricAlphaMode::OPAQUE; } else if (material.alphaMode == CesiumGltf::Material::AlphaMode::MASK) { return FabricAlphaMode::MASK; } else if (material.alphaMode == CesiumGltf::Material::AlphaMode::BLEND) { return FabricAlphaMode::BLEND; } return FabricAlphaMode::OPAQUE; } double getBaseAlpha(const CesiumGltf::MaterialPBRMetallicRoughness& pbrMetallicRoughness) { return pbrMetallicRoughness.baseColorFactor[3]; } glm::dvec3 getBaseColorFactor(const CesiumGltf::MaterialPBRMetallicRoughness& pbrMetallicRoughness) { return { pbrMetallicRoughness.baseColorFactor[0], pbrMetallicRoughness.baseColorFactor[1], pbrMetallicRoughness.baseColorFactor[2], }; } glm::dvec3 getEmissiveFactor(const CesiumGltf::Material& material) { return { material.emissiveFactor[0], material.emissiveFactor[1], material.emissiveFactor[2], }; } double getMetallicFactor(const CesiumGltf::MaterialPBRMetallicRoughness& pbrMetallicRoughness) { return pbrMetallicRoughness.metallicFactor; } double getRoughnessFactor(const CesiumGltf::MaterialPBRMetallicRoughness& pbrMetallicRoughness) { return pbrMetallicRoughness.roughnessFactor; } bool getDoubleSided(const CesiumGltf::Material& material) { return material.doubleSided; } int32_t getWrapS(const CesiumGltf::Sampler& sampler) { return sampler.wrapS; } int32_t getWrapT(const CesiumGltf::Sampler& sampler) { return sampler.wrapT; } glm::dvec2 getTexcoordOffset(const CesiumGltf::ExtensionKhrTextureTransform& textureTransform) { const auto& offset = textureTransform.offset; return {offset[0], offset[1]}; } double getTexcoordRotation(const CesiumGltf::ExtensionKhrTextureTransform& textureTransform) { return textureTransform.rotation; } glm::dvec2 getTexcoordScale(const CesiumGltf::ExtensionKhrTextureTransform& textureTransform) { const auto& scale = textureTransform.scale; return {scale[0], scale[1]}; } uint64_t getTexcoordSetIndex(const CesiumGltf::TextureInfo& textureInfo) { return static_cast<uint64_t>(textureInfo.index); } double getDefaultAlphaCutoff() { return getAlphaCutoff(defaultMaterial); } FabricAlphaMode getDefaultAlphaMode() { return getAlphaMode(defaultMaterial); } double getDefaultBaseAlpha() { return getBaseAlpha(defaultPbrMetallicRoughness); } glm::dvec3 getDefaultBaseColorFactor() { return getBaseColorFactor(defaultPbrMetallicRoughness); } glm::dvec3 getDefaultEmissiveFactor() { return getEmissiveFactor(defaultMaterial); } double getDefaultMetallicFactor() { return getMetallicFactor(defaultPbrMetallicRoughness); } double getDefaultRoughnessFactor() { return getRoughnessFactor(defaultPbrMetallicRoughness); } bool getDefaultDoubleSided() { return getDoubleSided(defaultMaterial); } glm::dvec2 getDefaultTexcoordOffset() { return getTexcoordOffset(defaultTextureTransform); } double getDefaultTexcoordRotation() { return getTexcoordRotation(defaultTextureTransform); } glm::dvec2 getDefaultTexcoordScale() { return getTexcoordScale(defaultTextureTransform); } uint64_t getDefaultTexcoordSetIndex() { return getTexcoordSetIndex(defaultTextureInfo); } int32_t getDefaultWrapS() { return getWrapS(defaultSampler); } int32_t getDefaultWrapT() { return getWrapT(defaultSampler); } FabricTextureInfo getTextureInfo(const CesiumGltf::Model& model, const CesiumGltf::TextureInfo& textureInfoGltf) { FabricTextureInfo textureInfo = getDefaultTextureInfo(); textureInfo.setIndex = static_cast<uint64_t>(textureInfoGltf.texCoord); const auto pTextureTransform = textureInfoGltf.getExtension<CesiumGltf::ExtensionKhrTextureTransform>(); if (pTextureTransform) { textureInfo.offset = getTexcoordOffset(*pTextureTransform); textureInfo.rotation = getTexcoordRotation(*pTextureTransform); textureInfo.scale = getTexcoordScale(*pTextureTransform); } const auto pTexture = model.getSafe(&model.textures, textureInfoGltf.index); if (pTexture) { const auto pSampler = model.getSafe(&model.samplers, pTexture->sampler); if (pSampler) { textureInfo.wrapS = getWrapS(*pSampler); textureInfo.wrapT = getWrapT(*pSampler); } } return textureInfo; } template <typename T> std::vector<uint8_t> getChannels(const T& textureInfoWithChannels) { std::vector<uint8_t> channels; channels.reserve(textureInfoWithChannels.channels.size()); for (const auto channel : textureInfoWithChannels.channels) { channels.push_back(static_cast<uint8_t>(channel)); } return channels; } FabricTextureInfo getFeatureIdTextureInfo(const CesiumGltf::Model& model, const CesiumGltf::FeatureIdTexture& featureIdTexture) { FabricTextureInfo textureInfo = getTextureInfo(model, featureIdTexture); textureInfo.channels = getChannels(featureIdTexture); return textureInfo; } const CesiumGltf::ImageCesium* getImageCesium(const CesiumGltf::Model& model, const CesiumGltf::Texture& texture) { const auto pImage = model.getSafe(&model.images, texture.source); if (pImage) { return &pImage->cesium; } return nullptr; } std::pair<std::string, uint64_t> parseAttributeName(const std::string& attributeName) { auto searchPosition = static_cast<int>(attributeName.size()) - 1; auto lastUnderscorePosition = -1; while (searchPosition > 0) { const auto character = attributeName[static_cast<uint64_t>(searchPosition)]; if (!isdigit(character)) { if (character == '_') { lastUnderscorePosition = searchPosition; } break; } --searchPosition; } std::string semantic; uint64_t setIndexU64 = 0; if (lastUnderscorePosition == -1) { semantic = attributeName; } else { semantic = attributeName.substr(0, static_cast<uint64_t>(lastUnderscorePosition)); std::from_chars( attributeName.data() + lastUnderscorePosition + 1, attributeName.data() + attributeName.size(), setIndexU64); } return std::make_pair(semantic, setIndexU64); } std::optional<DataType> getVertexAttributeTypeFromGltf(const CesiumGltf::Accessor& accessor) { const auto& type = accessor.type; const auto componentType = accessor.componentType; const auto normalized = accessor.normalized; if (type == CesiumGltf::Accessor::Type::SCALAR) { if (componentType == CesiumGltf::Accessor::ComponentType::BYTE) { return normalized ? DataType::INT8_NORM : DataType::INT8; } else if (componentType == CesiumGltf::Accessor::ComponentType::UNSIGNED_BYTE) { return normalized ? DataType::UINT8_NORM : DataType::UINT8; } else if (componentType == CesiumGltf::Accessor::ComponentType::SHORT) { return normalized ? DataType::INT16_NORM : DataType::INT16; } else if (componentType == CesiumGltf::Accessor::ComponentType::UNSIGNED_SHORT) { return normalized ? DataType::UINT16_NORM : DataType::UINT16; } else if (componentType == CesiumGltf::Accessor::ComponentType::FLOAT) { return DataType::FLOAT32; } } else if (type == CesiumGltf::Accessor::Type::VEC2) { if (componentType == CesiumGltf::Accessor::ComponentType::BYTE) { return normalized ? DataType::VEC2_INT8_NORM : DataType::VEC2_INT8; } else if (componentType == CesiumGltf::Accessor::ComponentType::UNSIGNED_BYTE) { return normalized ? DataType::VEC2_UINT8_NORM : DataType::VEC2_UINT8; } else if (componentType == CesiumGltf::Accessor::ComponentType::SHORT) { return normalized ? DataType::VEC2_INT16_NORM : DataType::VEC2_INT16; } else if (componentType == CesiumGltf::Accessor::ComponentType::UNSIGNED_SHORT) { return normalized ? DataType::VEC2_UINT16_NORM : DataType::VEC2_UINT16; } else if (componentType == CesiumGltf::Accessor::ComponentType::FLOAT) { return DataType::VEC2_FLOAT32; } } else if (type == CesiumGltf::Accessor::Type::VEC3) { if (componentType == CesiumGltf::Accessor::ComponentType::BYTE) { return normalized ? DataType::VEC3_INT8_NORM : DataType::VEC3_INT8; } else if (componentType == CesiumGltf::Accessor::ComponentType::UNSIGNED_BYTE) { return normalized ? DataType::VEC3_UINT8_NORM : DataType::VEC3_UINT8; } else if (componentType == CesiumGltf::Accessor::ComponentType::SHORT) { return normalized ? DataType::VEC3_INT16_NORM : DataType::VEC3_INT16; } else if (componentType == CesiumGltf::Accessor::ComponentType::UNSIGNED_SHORT) { return normalized ? DataType::VEC3_UINT16_NORM : DataType::VEC3_UINT16; } else if (componentType == CesiumGltf::Accessor::ComponentType::FLOAT) { return DataType::VEC3_FLOAT32; } } else if (type == CesiumGltf::Accessor::Type::VEC4) { if (componentType == CesiumGltf::Accessor::ComponentType::BYTE) { return normalized ? DataType::VEC4_INT8_NORM : DataType::VEC4_INT8; } else if (componentType == CesiumGltf::Accessor::ComponentType::UNSIGNED_BYTE) { return normalized ? DataType::VEC4_UINT8_NORM : DataType::VEC4_UINT8; } else if (componentType == CesiumGltf::Accessor::ComponentType::SHORT) { return normalized ? DataType::VEC4_INT16_NORM : DataType::VEC4_INT16; } else if (componentType == CesiumGltf::Accessor::ComponentType::UNSIGNED_SHORT) { return normalized ? DataType::VEC4_UINT16_NORM : DataType::VEC4_UINT16; } else if (componentType == CesiumGltf::Accessor::ComponentType::FLOAT) { return DataType::VEC4_FLOAT32; } } else if (type == CesiumGltf::Accessor::Type::MAT2) { if (componentType == CesiumGltf::Accessor::ComponentType::BYTE) { return normalized ? DataType::MAT2_INT8_NORM : DataType::MAT2_INT8; } else if (componentType == CesiumGltf::Accessor::ComponentType::UNSIGNED_BYTE) { return normalized ? DataType::MAT2_UINT8_NORM : DataType::MAT2_UINT8; } else if (componentType == CesiumGltf::Accessor::ComponentType::SHORT) { return normalized ? DataType::MAT2_INT16_NORM : DataType::MAT2_INT16; } else if (componentType == CesiumGltf::Accessor::ComponentType::UNSIGNED_SHORT) { return normalized ? DataType::MAT2_UINT16_NORM : DataType::MAT2_UINT16; } else if (componentType == CesiumGltf::Accessor::ComponentType::FLOAT) { return DataType::MAT2_FLOAT32; } } else if (type == CesiumGltf::Accessor::Type::MAT3) { if (componentType == CesiumGltf::Accessor::ComponentType::BYTE) { return normalized ? DataType::MAT3_INT8_NORM : DataType::MAT3_INT8; } else if (componentType == CesiumGltf::Accessor::ComponentType::UNSIGNED_BYTE) { return normalized ? DataType::MAT3_UINT8_NORM : DataType::MAT3_UINT8; } else if (componentType == CesiumGltf::Accessor::ComponentType::SHORT) { return normalized ? DataType::MAT3_INT16_NORM : DataType::MAT3_INT16; } else if (componentType == CesiumGltf::Accessor::ComponentType::UNSIGNED_SHORT) { return normalized ? DataType::MAT3_UINT16_NORM : DataType::MAT3_UINT16; } else if (componentType == CesiumGltf::Accessor::ComponentType::FLOAT) { return DataType::MAT3_FLOAT32; } } else if (type == CesiumGltf::Accessor::Type::MAT4) { if (componentType == CesiumGltf::Accessor::ComponentType::BYTE) { return normalized ? DataType::MAT4_INT8_NORM : DataType::MAT4_INT8; } else if (componentType == CesiumGltf::Accessor::ComponentType::UNSIGNED_BYTE) { return normalized ? DataType::MAT4_UINT8_NORM : DataType::MAT4_UINT8; } else if (componentType == CesiumGltf::Accessor::ComponentType::SHORT) { return normalized ? DataType::MAT4_INT16_NORM : DataType::MAT4_INT16; } else if (componentType == CesiumGltf::Accessor::ComponentType::UNSIGNED_SHORT) { return normalized ? DataType::MAT4_UINT16_NORM : DataType::MAT4_UINT16; } else if (componentType == CesiumGltf::Accessor::ComponentType::FLOAT) { return DataType::MAT4_FLOAT32; } } return std::nullopt; } } // namespace PositionsAccessor getPositions(const CesiumGltf::Model& model, const CesiumGltf::MeshPrimitive& primitive) { const auto positionsView = getPositionsView(model, primitive); if (positionsView.status() != CesiumGltf::AccessorViewStatus::Valid) { return {}; } return {positionsView}; } std::optional<std::array<glm::dvec3, 2>> getExtent(const CesiumGltf::Model& model, const CesiumGltf::MeshPrimitive& primitive) { const auto it = primitive.attributes.find("POSITION"); if (it == primitive.attributes.end()) { return std::nullopt; } auto pPositionAccessor = model.getSafe(&model.accessors, it->second); if (!pPositionAccessor) { return std::nullopt; } const auto& min = pPositionAccessor->min; const auto& max = pPositionAccessor->max; if (min.size() != 3 || max.size() != 3) { return std::nullopt; } return std::array<glm::dvec3, 2>{{glm::dvec3(min[0], min[1], min[2]), glm::dvec3(max[0], max[1], max[2])}}; } IndicesAccessor getIndices( const CesiumGltf::Model& model, const CesiumGltf::MeshPrimitive& primitive, const PositionsAccessor& positions) { const auto pIndicesAccessor = model.getSafe(&model.accessors, primitive.indices); if (!pIndicesAccessor) { return {positions.size()}; } if (pIndicesAccessor->componentType == CesiumGltf::AccessorSpec::ComponentType::UNSIGNED_BYTE) { CesiumGltf::AccessorView<uint8_t> view(model, *pIndicesAccessor); return getIndicesAccessor(primitive, view); } else if (pIndicesAccessor->componentType == CesiumGltf::AccessorSpec::ComponentType::UNSIGNED_SHORT) { CesiumGltf::AccessorView<uint16_t> view(model, *pIndicesAccessor); return getIndicesAccessor(primitive, view); } else if (pIndicesAccessor->componentType == CesiumGltf::AccessorSpec::ComponentType::UNSIGNED_INT) { CesiumGltf::AccessorView<uint32_t> view(model, *pIndicesAccessor); return getIndicesAccessor(primitive, view); } return {}; } FaceVertexCountsAccessor getFaceVertexCounts(const IndicesAccessor& indices) { return {indices.size() / 3}; } NormalsAccessor getNormals( const CesiumGltf::Model& model, const CesiumGltf::MeshPrimitive& primitive, const PositionsAccessor& positions, const IndicesAccessor& indices, bool smoothNormals) { const auto normalsView = getNormalsView(model, primitive); if (normalsView.status() == CesiumGltf::AccessorViewStatus::Valid) { return {normalsView}; } if (smoothNormals) { return NormalsAccessor::GenerateSmooth(positions, indices); } // Otherwise if normals are missing and smoothNormals is false Omniverse will generate flat normals for us automatically return {}; } TexcoordsAccessor getTexcoords(const CesiumGltf::Model& model, const CesiumGltf::MeshPrimitive& primitive, uint64_t setIndex) { return getTexcoords(model, primitive, "TEXCOORD", setIndex, true); } TexcoordsAccessor getRasterOverlayTexcoords( const CesiumGltf::Model& model, const CesiumGltf::MeshPrimitive& primitive, uint64_t setIndex) { return getTexcoords(model, primitive, "_CESIUMOVERLAY", setIndex, false); } VertexColorsAccessor getVertexColors(const CesiumGltf::Model& model, const CesiumGltf::MeshPrimitive& primitive, uint64_t setIndex) { const auto vertexColorAttribute = primitive.attributes.find(fmt::format("{}_{}", "COLOR", setIndex)); if (vertexColorAttribute == primitive.attributes.end()) { return {}; } const auto pVertexColorAccessor = model.getSafe(&model.accessors, vertexColorAttribute->second); if (!pVertexColorAccessor) { return {}; } if (pVertexColorAccessor->componentType == CesiumGltf::AccessorSpec::ComponentType::UNSIGNED_BYTE) { if (pVertexColorAccessor->type == CesiumGltf::AccessorSpec::Type::VEC3) { return getVertexColorsAccessor<glm::u8vec3>(model, *pVertexColorAccessor); } else if (pVertexColorAccessor->type == CesiumGltf::AccessorSpec::Type::VEC4) { return getVertexColorsAccessor<glm::u8vec4>(model, *pVertexColorAccessor); } } else if (pVertexColorAccessor->componentType == CesiumGltf::AccessorSpec::ComponentType::UNSIGNED_SHORT) { if (pVertexColorAccessor->type == CesiumGltf::AccessorSpec::Type::VEC3) { return getVertexColorsAccessor<glm::u16vec3>(model, *pVertexColorAccessor); } else if (pVertexColorAccessor->type == CesiumGltf::AccessorSpec::Type::VEC4) { return getVertexColorsAccessor<glm::u16vec4>(model, *pVertexColorAccessor); } } else if (pVertexColorAccessor->componentType == CesiumGltf::AccessorSpec::ComponentType::FLOAT) { if (pVertexColorAccessor->type == CesiumGltf::AccessorSpec::Type::VEC3) { return getVertexColorsAccessor<glm::fvec3>(model, *pVertexColorAccessor); } else if (pVertexColorAccessor->type == CesiumGltf::AccessorSpec::Type::VEC4) { return getVertexColorsAccessor<glm::fvec4>(model, *pVertexColorAccessor); } } return {}; } VertexIdsAccessor getVertexIds(const PositionsAccessor& positionsAccessor) { return {positionsAccessor.size()}; } const CesiumGltf::ImageCesium* getBaseColorTextureImage(const CesiumGltf::Model& model, const CesiumGltf::MeshPrimitive& primitive) { if (!hasMaterial(primitive)) { return nullptr; } const auto pMaterial = model.getSafe(&model.materials, primitive.material); if (!pMaterial) { return nullptr; } const auto& pbrMetallicRoughness = pMaterial->pbrMetallicRoughness; if (pbrMetallicRoughness.has_value() && pbrMetallicRoughness.value().baseColorTexture.has_value()) { const auto index = pbrMetallicRoughness.value().baseColorTexture.value().index; const auto pBaseColorTexture = model.getSafe(&model.textures, index); if (pBaseColorTexture) { return getImageCesium(model, *pBaseColorTexture); } } return nullptr; } const CesiumGltf::ImageCesium* getFeatureIdTextureImage( const CesiumGltf::Model& model, const CesiumGltf::MeshPrimitive& primitive, uint64_t featureIdSetIndex) { const auto pMeshFeatures = primitive.getExtension<CesiumGltf::ExtensionExtMeshFeatures>(); if (!pMeshFeatures) { return nullptr; } const auto pFeatureId = model.getSafe(&pMeshFeatures->featureIds, static_cast<int32_t>(featureIdSetIndex)); if (!pFeatureId) { return nullptr; } if (!pFeatureId->texture.has_value()) { return nullptr; } const auto featureIdTextureView = CesiumGltf::FeatureIdTextureView(model, pFeatureId->texture.value()); if (featureIdTextureView.status() != CesiumGltf::FeatureIdTextureViewStatus::Valid) { return nullptr; } return featureIdTextureView.getImage(); } FabricMaterialInfo getMaterialInfo(const CesiumGltf::Model& model, const CesiumGltf::MeshPrimitive& primitive) { if (!hasMaterial(primitive)) { return getDefaultMaterialInfo(); } const auto pMaterial = model.getSafe(&model.materials, primitive.material); if (!pMaterial) { return getDefaultMaterialInfo(); } // Ignore uninitialized member warning from gcc 11.2.0. This warning is not reported in gcc 11.4.0 #ifdef CESIUM_OMNI_GCC #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Wmaybe-uninitialized" #endif auto materialInfo = getDefaultMaterialInfo(); #ifdef CESIUM_OMNI_GCC #pragma GCC diagnostic pop #endif materialInfo.alphaCutoff = getAlphaCutoff(*pMaterial); materialInfo.alphaMode = getAlphaMode(*pMaterial); materialInfo.emissiveFactor = getEmissiveFactor(*pMaterial); materialInfo.doubleSided = getDoubleSided(*pMaterial); const auto& pbrMetallicRoughness = pMaterial->pbrMetallicRoughness; if (pbrMetallicRoughness.has_value()) { materialInfo.baseAlpha = getBaseAlpha(pbrMetallicRoughness.value()); materialInfo.baseColorFactor = getBaseColorFactor(pbrMetallicRoughness.value()); materialInfo.metallicFactor = getMetallicFactor(pbrMetallicRoughness.value()); materialInfo.roughnessFactor = getRoughnessFactor(pbrMetallicRoughness.value()); if (pbrMetallicRoughness.value().baseColorTexture.has_value() && getBaseColorTextureImage(model, primitive)) { materialInfo.baseColorTexture = getTextureInfo(model, pbrMetallicRoughness.value().baseColorTexture.value()); } } if (pMaterial->hasExtension<CesiumGltf::ExtensionKhrMaterialsUnlit>()) { // Unlit materials aren't supported in Omniverse yet but we can hard code the material values to something reasonable materialInfo.metallicFactor = 0.0; materialInfo.roughnessFactor = 1.0; } materialInfo.hasVertexColors = hasVertexColors(model, primitive, 0); return materialInfo; } FabricFeaturesInfo getFeaturesInfo(const CesiumGltf::Model& model, const CesiumGltf::MeshPrimitive& primitive) { const auto& pMeshFeatures = primitive.getExtension<CesiumGltf::ExtensionExtMeshFeatures>(); if (!pMeshFeatures) { return {}; } const auto& featureIds = pMeshFeatures->featureIds; FabricFeaturesInfo featuresInfo; featuresInfo.featureIds.reserve(featureIds.size()); for (const auto& featureId : featureIds) { const auto nullFeatureId = CppUtil::castOptional<uint64_t>(featureId.nullFeatureId); const auto featureCount = static_cast<uint64_t>(featureId.featureCount); auto featureIdStorage = std::variant<std::monostate, uint64_t, FabricTextureInfo>(); if (featureId.attribute.has_value()) { featureIdStorage = static_cast<uint64_t>(featureId.attribute.value()); } else if (featureId.texture.has_value()) { featureIdStorage = getFeatureIdTextureInfo(model, featureId.texture.value()); } else { featureIdStorage = std::monostate(); } // In C++ 20 this can be emplace_back without the {} featuresInfo.featureIds.push_back({nullFeatureId, featureCount, featureIdStorage}); } return featuresInfo; } std::set<FabricVertexAttributeDescriptor> getCustomVertexAttributes(const CesiumGltf::Model& model, const CesiumGltf::MeshPrimitive& primitive) { constexpr std::array<std::string_view, 8> knownSemantics = {{ "POSITION", "NORMAL", "TANGENT", "TEXCOORD", "COLOR", "JOINTS", "WEIGHTS", "_CESIUMOVERLAY", }}; std::set<FabricVertexAttributeDescriptor> customVertexAttributes; for (const auto& attribute : primitive.attributes) { const auto& attributeName = attribute.first; const auto [semantic, setIndex] = parseAttributeName(attributeName); if (CppUtil::contains(knownSemantics, semantic)) { continue; } auto pAccessor = model.getSafe(&model.accessors, static_cast<int32_t>(attribute.second)); if (!pAccessor) { continue; } const auto valid = createAccessorView(model, *pAccessor, [](const auto& accessorView) { return accessorView.status() == CesiumGltf::AccessorViewStatus::Valid; }); if (!valid) { continue; } const auto type = getVertexAttributeTypeFromGltf(*pAccessor); if (!type.has_value()) { continue; } const auto fabricAttributeNameStr = fmt::format("primvars:{}", attributeName); const auto fabricAttributeName = omni::fabric::Token(fabricAttributeNameStr.c_str()); // In C++ 20 this can be emplace without the {} customVertexAttributes.insert(FabricVertexAttributeDescriptor{ type.value(), fabricAttributeName, attributeName, }); } return customVertexAttributes; } const FabricMaterialInfo& getDefaultMaterialInfo() { static const auto defaultInfo = FabricMaterialInfo{ getDefaultAlphaCutoff(), getDefaultAlphaMode(), getDefaultBaseAlpha(), getDefaultBaseColorFactor(), getDefaultEmissiveFactor(), getDefaultMetallicFactor(), getDefaultRoughnessFactor(), getDefaultDoubleSided(), false, std::nullopt, }; return defaultInfo; } const FabricTextureInfo& getDefaultTextureInfo() { static const auto defaultInfo = FabricTextureInfo{ getDefaultTexcoordOffset(), getDefaultTexcoordRotation(), getDefaultTexcoordScale(), getDefaultTexcoordSetIndex(), getDefaultWrapS(), getDefaultWrapT(), true, {}, }; return defaultInfo; } FabricTextureInfo getPropertyTexturePropertyInfo( const CesiumGltf::Model& model, const CesiumGltf::PropertyTextureProperty& propertyTextureProperty) { FabricTextureInfo textureInfo = getTextureInfo(model, propertyTextureProperty); textureInfo.channels = getChannels(propertyTextureProperty); return textureInfo; } bool hasNormals(const CesiumGltf::Model& model, const CesiumGltf::MeshPrimitive& primitive, bool smoothNormals) { return smoothNormals || getNormalsView(model, primitive).status() == CesiumGltf::AccessorViewStatus::Valid; } bool hasTexcoords(const CesiumGltf::Model& model, const CesiumGltf::MeshPrimitive& primitive, uint64_t setIndex) { return getTexcoordsView(model, primitive, "TEXCOORD", setIndex).status() == CesiumGltf::AccessorViewStatus::Valid; } bool hasRasterOverlayTexcoords( const CesiumGltf::Model& model, const CesiumGltf::MeshPrimitive& primitive, uint64_t setIndex) { return getTexcoordsView(model, primitive, "_CESIUMOVERLAY", setIndex).status() == CesiumGltf::AccessorViewStatus::Valid; } bool hasVertexColors(const CesiumGltf::Model& model, const CesiumGltf::MeshPrimitive& primitive, uint64_t setIndex) { return getVertexColors(model, primitive, setIndex).size() > 0; } bool hasMaterial(const CesiumGltf::MeshPrimitive& primitive) { return primitive.material >= 0; } std::vector<uint64_t> getTexcoordSetIndexes(const CesiumGltf::Model& model, const CesiumGltf::MeshPrimitive& primitive) { auto setIndexes = std::vector<uint64_t>(); for (const auto& attribute : primitive.attributes) { const auto [semantic, setIndex] = parseAttributeName(attribute.first); if (semantic == "TEXCOORD") { if (hasTexcoords(model, primitive, setIndex)) { setIndexes.push_back(setIndex); } } } return setIndexes; } std::vector<uint64_t> getRasterOverlayTexcoordSetIndexes(const CesiumGltf::Model& model, const CesiumGltf::MeshPrimitive& primitive) { auto setIndexes = std::vector<uint64_t>(); for (const auto& attribute : primitive.attributes) { const auto [semantic, setIndex] = parseAttributeName(attribute.first); if (semantic == "_CESIUMOVERLAY") { if (hasRasterOverlayTexcoords(model, primitive, setIndex)) { setIndexes.push_back(setIndex); } } } return setIndexes; } CesiumGltf::Ktx2TranscodeTargets getKtx2TranscodeTargets() { CesiumGltf::SupportedGpuCompressedPixelFormats supportedFormats; // Only BCN compressed texture formats are supported in Omniverse supportedFormats.ETC1_RGB = false; supportedFormats.ETC2_RGBA = false; supportedFormats.BC1_RGB = true; supportedFormats.BC3_RGBA = true; supportedFormats.BC4_R = true; supportedFormats.BC5_RG = true; supportedFormats.BC7_RGBA = true; supportedFormats.PVRTC1_4_RGB = false; supportedFormats.PVRTC1_4_RGBA = false; supportedFormats.ASTC_4x4_RGBA = false; supportedFormats.PVRTC2_4_RGB = false; supportedFormats.PVRTC2_4_RGBA = false; supportedFormats.ETC2_EAC_R11 = false; supportedFormats.ETC2_EAC_RG11 = false; return {supportedFormats, false}; } } // namespace cesium::omniverse::GltfUtil
33,726
C++
35.98136
125
0.698541
CesiumGS/cesium-omniverse/src/core/src/CesiumIonServerManager.cpp
#include "cesium/omniverse/CesiumIonServerManager.h" #include "cesium/omniverse/AssetRegistry.h" #include "cesium/omniverse/Broadcast.h" #include "cesium/omniverse/CesiumIonSession.h" #include "cesium/omniverse/Context.h" #include "cesium/omniverse/CppUtil.h" #include "cesium/omniverse/OmniData.h" #include "cesium/omniverse/OmniIonRasterOverlay.h" #include "cesium/omniverse/OmniIonServer.h" #include "cesium/omniverse/OmniTileset.h" #include "cesium/omniverse/TokenTroubleshootingDetails.h" #include <CesiumIonClient/Connection.h> namespace cesium::omniverse { CesiumIonServerManager::CesiumIonServerManager(Context* pContext) : _pContext(pContext) {} void CesiumIonServerManager::onUpdateFrame() { const auto& ionServers = _pContext->getAssetRegistry().getIonServers(); for (const auto& pIonServer : ionServers) { pIonServer->getSession()->tick(); } } void CesiumIonServerManager::setProjectDefaultToken(const CesiumIonClient::Token& token) { if (token.token.empty()) { return; } const auto pCurrentIonServer = getCurrentIonServer(); if (!pCurrentIonServer) { return; } pCurrentIonServer->setToken(token); } void CesiumIonServerManager::updateTokenTroubleshootingDetails( int64_t ionAssetId, const std::string& token, uint64_t eventId, TokenTroubleshootingDetails& details) { const auto pSession = getCurrentIonSession(); if (!pSession) { // TODO: Signal an error. return; } details.showDetails = true; const auto pConnection = std::make_shared<CesiumIonClient::Connection>(pSession->getAsyncSystem(), pSession->getAssetAccessor(), token); pConnection->me() .thenInMainThread( [ionAssetId, pConnection, &details](CesiumIonClient::Response<CesiumIonClient::Profile>&& profile) { details.isValid = profile.value.has_value(); return pConnection->asset(ionAssetId); }) .thenInMainThread([this, pConnection, &details](CesiumIonClient::Response<CesiumIonClient::Asset>&& asset) { details.allowsAccessToAsset = asset.value.has_value(); const auto pIonSession = getCurrentIonSession(); pIonSession->resume(); const std::optional<CesiumIonClient::Connection>& userConnection = pIonSession->getConnection(); if (!userConnection) { CesiumIonClient::Response<CesiumIonClient::TokenList> result{}; return pIonSession->getAsyncSystem().createResolvedFuture(std::move(result)); } return userConnection.value().tokens(); }) .thenInMainThread( [pConnection, &details, eventId](CesiumIonClient::Response<CesiumIonClient::TokenList>&& tokens) { if (tokens.value.has_value()) { details.associatedWithUserAccount = CppUtil::containsByMember( tokens.value.value().items, &CesiumIonClient::Token::token, pConnection->getAccessToken()); } Broadcast::sendMessageToBus(eventId); }); } void CesiumIonServerManager::updateAssetTroubleshootingDetails( int64_t ionAssetId, uint64_t eventId, AssetTroubleshootingDetails& details) { const auto pSession = getCurrentIonSession(); if (!pSession) { return; } pSession->getConnection() ->asset(ionAssetId) .thenInMainThread([eventId, &details](CesiumIonClient::Response<CesiumIonClient::Asset>&& asset) { details.assetExistsInUserAccount = asset.value.has_value(); Broadcast::sendMessageToBus(eventId); }); } OmniIonServer* CesiumIonServerManager::getCurrentIonServer() const { const auto pData = _pContext->getAssetRegistry().getFirstData(); if (!pData) { return _pContext->getAssetRegistry().getFirstIonServer(); } const auto selectedIonServerPath = pData->getSelectedIonServerPath(); if (selectedIonServerPath.IsEmpty()) { return _pContext->getAssetRegistry().getFirstIonServer(); } const auto pIonServer = _pContext->getAssetRegistry().getIonServer(selectedIonServerPath); if (!pIonServer) { return _pContext->getAssetRegistry().getFirstIonServer(); } return pIonServer; } void CesiumIonServerManager::connectToIon() { const auto pCurrentIonServer = getCurrentIonServer(); if (!pCurrentIonServer) { return; } pCurrentIonServer->getSession()->connect(); } std::shared_ptr<CesiumIonSession> CesiumIonServerManager::getCurrentIonSession() const { // A lot of UI code will end up calling the session prior to us actually having a stage. The user won't see this // but some major segfaults will occur without this check. if (!_pContext->hasUsdStage()) { return nullptr; } const auto pCurrentIonServer = getCurrentIonServer(); if (!pCurrentIonServer) { return nullptr; } return pCurrentIonServer->getSession(); } std::optional<CesiumIonClient::Token> CesiumIonServerManager::getDefaultToken() const { const auto pCurrentIonServer = getCurrentIonServer(); if (!pCurrentIonServer) { return std::nullopt; } const auto token = pCurrentIonServer->getToken(); if (token.token.empty()) { return std::nullopt; } return token; } SetDefaultTokenResult CesiumIonServerManager::getSetDefaultTokenResult() const { return _lastSetTokenResult; } bool CesiumIonServerManager::isDefaultTokenSet() const { return getDefaultToken().has_value(); } void CesiumIonServerManager::createToken(const std::string& name) { const auto pCurrentIonServer = getCurrentIonServer(); if (!pCurrentIonServer) { return; } const auto pConnection = pCurrentIonServer->getSession()->getConnection(); if (!pConnection.has_value()) { _lastSetTokenResult = SetDefaultTokenResult{ SetDefaultTokenResultCode::NOT_CONNECTED_TO_ION, std::string(SetDefaultTokenResultMessages::NOT_CONNECTED_TO_ION_MESSAGE), }; return; } pConnection->createToken(name, {"assets:read"}, std::vector<int64_t>{1}, std::nullopt) .thenInMainThread([this](CesiumIonClient::Response<CesiumIonClient::Token>&& response) { if (response.value) { setProjectDefaultToken(response.value.value()); _lastSetTokenResult = SetDefaultTokenResult{ SetDefaultTokenResultCode::OK, std::string(SetDefaultTokenResultMessages::OK_MESSAGE), }; } else { _lastSetTokenResult = SetDefaultTokenResult{ SetDefaultTokenResultCode::CREATE_FAILED, fmt::format( SetDefaultTokenResultMessages::CREATE_FAILED_MESSAGE_BASE, response.errorMessage, response.errorCode), }; } Broadcast::setDefaultTokenComplete(); }); } void CesiumIonServerManager::selectToken(const CesiumIonClient::Token& token) { const auto pCurrentIonServer = getCurrentIonServer(); if (!pCurrentIonServer) { return; } const auto& connection = pCurrentIonServer->getSession()->getConnection(); if (!connection.has_value()) { _lastSetTokenResult = SetDefaultTokenResult{ SetDefaultTokenResultCode::NOT_CONNECTED_TO_ION, std::string(SetDefaultTokenResultMessages::NOT_CONNECTED_TO_ION_MESSAGE), }; } else { setProjectDefaultToken(token); _lastSetTokenResult = SetDefaultTokenResult{ SetDefaultTokenResultCode::OK, std::string(SetDefaultTokenResultMessages::OK_MESSAGE), }; } Broadcast::setDefaultTokenComplete(); } void CesiumIonServerManager::specifyToken(const std::string& token) { const auto pCurrentIonServer = getCurrentIonServer(); if (!pCurrentIonServer) { return; } const auto pSession = pCurrentIonServer->getSession(); pSession->findToken(token).thenInMainThread( [this, token](CesiumIonClient::Response<CesiumIonClient::Token>&& response) { if (response.value) { setProjectDefaultToken(response.value.value()); } else { CesiumIonClient::Token t; t.token = token; setProjectDefaultToken(t); } // We assume the user knows what they're doing if they specify a token not on their account. _lastSetTokenResult = SetDefaultTokenResult{ SetDefaultTokenResultCode::OK, std::string(SetDefaultTokenResultMessages::OK_MESSAGE), }; Broadcast::setDefaultTokenComplete(); }); } std::optional<AssetTroubleshootingDetails> CesiumIonServerManager::getAssetTroubleshootingDetails() const { return _assetTroubleshootingDetails; } std::optional<TokenTroubleshootingDetails> CesiumIonServerManager::getAssetTokenTroubleshootingDetails() const { return _assetTokenTroubleshootingDetails; } std::optional<TokenTroubleshootingDetails> CesiumIonServerManager::getDefaultTokenTroubleshootingDetails() const { return _defaultTokenTroubleshootingDetails; } void CesiumIonServerManager::updateTroubleshootingDetails( const pxr::SdfPath& tilesetPath, int64_t tilesetIonAssetId, uint64_t tokenEventId, uint64_t assetEventId) { const auto pTileset = _pContext->getAssetRegistry().getTileset(tilesetPath); if (!pTileset) { return; } _assetTroubleshootingDetails = AssetTroubleshootingDetails(); updateAssetTroubleshootingDetails(tilesetIonAssetId, assetEventId, _assetTroubleshootingDetails.value()); _defaultTokenTroubleshootingDetails = TokenTroubleshootingDetails(); const auto& defaultToken = getDefaultToken(); if (defaultToken.has_value()) { const auto& token = defaultToken.value().token; updateTokenTroubleshootingDetails( tilesetIonAssetId, token, tokenEventId, _defaultTokenTroubleshootingDetails.value()); } _assetTokenTroubleshootingDetails = TokenTroubleshootingDetails(); auto tilesetIonAccessToken = pTileset->getIonAccessToken(); if (!tilesetIonAccessToken.token.empty()) { updateTokenTroubleshootingDetails( tilesetIonAssetId, tilesetIonAccessToken.token, tokenEventId, _assetTokenTroubleshootingDetails.value()); } } void CesiumIonServerManager::updateTroubleshootingDetails( const pxr::SdfPath& tilesetPath, [[maybe_unused]] int64_t tilesetIonAssetId, int64_t rasterOverlayIonAssetId, uint64_t tokenEventId, uint64_t assetEventId) { const auto pTileset = _pContext->getAssetRegistry().getTileset(tilesetPath); if (!pTileset) { return; } const auto pIonRasterOverlay = _pContext->getAssetRegistry().getIonRasterOverlayByIonAssetId(rasterOverlayIonAssetId); if (!pIonRasterOverlay) { return; } _assetTroubleshootingDetails = AssetTroubleshootingDetails(); updateAssetTroubleshootingDetails(rasterOverlayIonAssetId, assetEventId, _assetTroubleshootingDetails.value()); _defaultTokenTroubleshootingDetails = TokenTroubleshootingDetails(); const auto& defaultToken = getDefaultToken(); if (defaultToken.has_value()) { const auto& token = defaultToken.value().token; updateTokenTroubleshootingDetails( rasterOverlayIonAssetId, token, tokenEventId, _defaultTokenTroubleshootingDetails.value()); } _assetTokenTroubleshootingDetails = TokenTroubleshootingDetails(); auto rasterOverlayIonAccessToken = pIonRasterOverlay->getIonAccessToken(); if (!rasterOverlayIonAccessToken.token.empty()) { updateTokenTroubleshootingDetails( rasterOverlayIonAssetId, rasterOverlayIonAccessToken.token, tokenEventId, _assetTokenTroubleshootingDetails.value()); } } } // namespace cesium::omniverse
12,101
C++
33.380682
119
0.683332
CesiumGS/cesium-omniverse/src/core/src/FabricGeometryDescriptor.cpp
#include "cesium/omniverse/FabricGeometryDescriptor.h" #include "cesium/omniverse/FabricFeaturesInfo.h" #include "cesium/omniverse/FabricFeaturesUtil.h" #include "cesium/omniverse/FabricVertexAttributeDescriptor.h" #include "cesium/omniverse/GltfUtil.h" #ifdef CESIUM_OMNI_MSVC #pragma push_macro("OPAQUE") #undef OPAQUE #endif #include <CesiumGltf/Model.h> namespace cesium::omniverse { FabricGeometryDescriptor::FabricGeometryDescriptor( const CesiumGltf::Model& model, const CesiumGltf::MeshPrimitive& primitive, const FabricFeaturesInfo& featuresInfo, bool smoothNormals) : _hasNormals(GltfUtil::hasNormals(model, primitive, smoothNormals)) , _hasVertexColors(GltfUtil::hasVertexColors(model, primitive, 0)) , _hasVertexIds(FabricFeaturesUtil::hasFeatureIdType(featuresInfo, FabricFeatureIdType::INDEX)) , _texcoordSetCount( GltfUtil::getTexcoordSetIndexes(model, primitive).size() + GltfUtil::getRasterOverlayTexcoordSetIndexes(model, primitive).size()) , _customVertexAttributes(GltfUtil::getCustomVertexAttributes(model, primitive)) {} bool FabricGeometryDescriptor::hasNormals() const { return _hasNormals; } bool FabricGeometryDescriptor::hasVertexColors() const { return _hasVertexColors; } bool FabricGeometryDescriptor::hasVertexIds() const { return _hasVertexIds; } uint64_t FabricGeometryDescriptor::getTexcoordSetCount() const { return _texcoordSetCount; } const std::set<FabricVertexAttributeDescriptor>& FabricGeometryDescriptor::getCustomVertexAttributes() const { return _customVertexAttributes; } bool FabricGeometryDescriptor::operator==(const FabricGeometryDescriptor& other) const { return _hasNormals == other._hasNormals && _hasVertexColors == other._hasVertexColors && _hasVertexIds == other._hasVertexIds && _texcoordSetCount == other._texcoordSetCount && _customVertexAttributes == other._customVertexAttributes; } } // namespace cesium::omniverse
1,990
C++
33.929824
110
0.770352
CesiumGS/cesium-omniverse/src/core/src/FabricResourceManager.cpp
#include "cesium/omniverse/FabricResourceManager.h" #include "cesium/omniverse/Context.h" #include "cesium/omniverse/FabricGeometry.h" #include "cesium/omniverse/FabricGeometryDescriptor.h" #include "cesium/omniverse/FabricGeometryPool.h" #include "cesium/omniverse/FabricMaterialDescriptor.h" #include "cesium/omniverse/FabricMaterialInfo.h" #include "cesium/omniverse/FabricMaterialPool.h" #include "cesium/omniverse/FabricPropertyDescriptor.h" #include "cesium/omniverse/FabricTexture.h" #include "cesium/omniverse/FabricTexturePool.h" #include "cesium/omniverse/FabricUtil.h" #include "cesium/omniverse/FabricVertexAttributeDescriptor.h" #include "cesium/omniverse/GltfUtil.h" #include "cesium/omniverse/MetadataUtil.h" #include "cesium/omniverse/UsdUtil.h" #include <omni/ui/ImageProvider/DynamicTextureProvider.h> #include <spdlog/fmt/fmt.h> namespace cesium::omniverse { namespace { const std::string_view DEFAULT_WHITE_TEXTURE_NAME = "cesium_default_white_texture"; const std::string_view DEFAULT_TRANSPARENT_TEXTURE_NAME = "cesium_default_transparent_texture"; std::unique_ptr<omni::ui::DynamicTextureProvider> createSinglePixelTexture(const std::string_view& name, const std::array<uint8_t, 4>& bytes) { const auto size = carb::Uint2{1, 1}; auto pTexture = std::make_unique<omni::ui::DynamicTextureProvider>(std::string(name)); pTexture->setBytesData(bytes.data(), size, omni::ui::kAutoCalculateStride, carb::Format::eRGBA8_SRGB); return pTexture; } bool shouldAcquireSharedMaterial(const FabricMaterialDescriptor& materialDescriptor) { if (materialDescriptor.hasBaseColorTexture() || materialDescriptor.getRasterOverlayRenderMethods().size() > 0 || !materialDescriptor.getFeatureIdTypes().empty() || !materialDescriptor.getStyleableProperties().empty()) { return false; } return true; } } // namespace FabricResourceManager::FabricResourceManager(Context* pContext) : _pContext(pContext) , _defaultWhiteTexture(createSinglePixelTexture(DEFAULT_WHITE_TEXTURE_NAME, {{255, 255, 255, 255}})) , _defaultTransparentTexture(createSinglePixelTexture(DEFAULT_TRANSPARENT_TEXTURE_NAME, {{0, 0, 0, 0}})) , _defaultWhiteTextureAssetPathToken(UsdUtil::getDynamicTextureProviderAssetPathToken(DEFAULT_WHITE_TEXTURE_NAME)) , _defaultTransparentTextureAssetPathToken( UsdUtil::getDynamicTextureProviderAssetPathToken(DEFAULT_TRANSPARENT_TEXTURE_NAME)) {} FabricResourceManager::~FabricResourceManager() = default; bool FabricResourceManager::shouldAcquireMaterial( const CesiumGltf::MeshPrimitive& primitive, bool hasRasterOverlay, const pxr::SdfPath& tilesetMaterialPath) const { if (_disableMaterials) { return false; } if (!tilesetMaterialPath.IsEmpty()) { return FabricUtil::materialHasCesiumNodes( _pContext->getFabricStage(), FabricUtil::toFabricPath(tilesetMaterialPath)); } return hasRasterOverlay || GltfUtil::hasMaterial(primitive); } bool FabricResourceManager::getDisableTextures() const { return _disableTextures; } std::shared_ptr<FabricGeometry> FabricResourceManager::acquireGeometry( const CesiumGltf::Model& model, const CesiumGltf::MeshPrimitive& primitive, const FabricFeaturesInfo& featuresInfo, bool smoothNormals) { FabricGeometryDescriptor geometryDescriptor(model, primitive, featuresInfo, smoothNormals); if (_disableGeometryPool) { const auto contextId = _pContext->getContextId(); const auto pathStr = fmt::format("/cesium_geometry_{}_context_{}", getNextGeometryId(), contextId); const auto path = omni::fabric::Path(pathStr.c_str()); return std::make_shared<FabricGeometry>(_pContext, path, geometryDescriptor, -1); } std::scoped_lock<std::mutex> lock(_poolMutex); return acquireGeometryFromPool(geometryDescriptor); } std::shared_ptr<FabricMaterial> FabricResourceManager::acquireMaterial( const CesiumGltf::Model& model, const CesiumGltf::MeshPrimitive& primitive, const FabricMaterialInfo& materialInfo, const FabricFeaturesInfo& featuresInfo, const FabricRasterOverlaysInfo& rasterOverlaysInfo, int64_t tilesetId, const pxr::SdfPath& tilesetMaterialPath) { FabricMaterialDescriptor materialDescriptor( *_pContext, model, primitive, materialInfo, featuresInfo, rasterOverlaysInfo, tilesetMaterialPath); if (shouldAcquireSharedMaterial(materialDescriptor)) { return acquireSharedMaterial(materialInfo, materialDescriptor, tilesetId); } if (_disableMaterialPool) { return createMaterial(materialDescriptor); } std::scoped_lock<std::mutex> lock(_poolMutex); return acquireMaterialFromPool(materialDescriptor); } std::shared_ptr<FabricTexture> FabricResourceManager::acquireTexture() { if (_disableTexturePool) { const auto contextId = _pContext->getContextId(); const auto name = fmt::format("/cesium_texture_{}_context_{}", getNextTextureId(), contextId); return std::make_shared<FabricTexture>(_pContext, name, -1); } std::scoped_lock<std::mutex> lock(_poolMutex); return acquireTextureFromPool(); } void FabricResourceManager::releaseGeometry(std::shared_ptr<FabricGeometry> pGeometry) { if (_disableGeometryPool) { return; } std::scoped_lock<std::mutex> lock(_poolMutex); const auto pGeometryPool = getGeometryPool(*pGeometry); if (pGeometryPool) { pGeometryPool->release(std::move(pGeometry)); } } void FabricResourceManager::releaseMaterial(std::shared_ptr<FabricMaterial> pMaterial) { if (isSharedMaterial(*pMaterial)) { releaseSharedMaterial(*pMaterial); return; } if (_disableMaterialPool) { return; } std::scoped_lock<std::mutex> lock(_poolMutex); const auto pMaterialPool = getMaterialPool(*pMaterial); if (pMaterialPool) { pMaterialPool->release(std::move(pMaterial)); } } void FabricResourceManager::releaseTexture(std::shared_ptr<FabricTexture> pTexture) { if (_disableTexturePool) { return; } std::scoped_lock<std::mutex> lock(_poolMutex); const auto pTexturePool = getTexturePool(*pTexture); if (pTexturePool) { pTexturePool->release(std::move(pTexture)); } } void FabricResourceManager::setDisableMaterials(bool disableMaterials) { _disableMaterials = disableMaterials; } void FabricResourceManager::setDisableTextures(bool disableTextures) { _disableTextures = disableTextures; } void FabricResourceManager::setDisableGeometryPool(bool disableGeometryPool) { assert(_geometryPools.size() == 0); _disableGeometryPool = disableGeometryPool; } void FabricResourceManager::setDisableMaterialPool(bool disableMaterialPool) { assert(_materialPools.size() == 0); _disableMaterialPool = disableMaterialPool; } void FabricResourceManager::setDisableTexturePool(bool disableTexturePool) { assert(_texturePools.size() == 0); _disableTexturePool = disableTexturePool; } void FabricResourceManager::setGeometryPoolInitialCapacity(uint64_t geometryPoolInitialCapacity) { assert(_geometryPools.size() == 0); _geometryPoolInitialCapacity = geometryPoolInitialCapacity; } void FabricResourceManager::setMaterialPoolInitialCapacity(uint64_t materialPoolInitialCapacity) { assert(_materialPools.size() == 0); _materialPoolInitialCapacity = materialPoolInitialCapacity; } void FabricResourceManager::setTexturePoolInitialCapacity(uint64_t texturePoolInitialCapacity) { assert(_texturePools.size() == 0); _texturePoolInitialCapacity = texturePoolInitialCapacity; } void FabricResourceManager::setDebugRandomColors(bool debugRandomColors) { _debugRandomColors = debugRandomColors; } void FabricResourceManager::updateShaderInput( const pxr::SdfPath& materialPath, const pxr::SdfPath& shaderPath, const pxr::TfToken& attributeName) const { for (const auto& pMaterialPool : _materialPools) { const auto& tilesetMaterialPath = pMaterialPool->getMaterialDescriptor().getTilesetMaterialPath(); if (tilesetMaterialPath == materialPath) { pMaterialPool->updateShaderInput(shaderPath, attributeName); } } } void FabricResourceManager::clear() { _geometryPools.clear(); _materialPools.clear(); _texturePools.clear(); _sharedMaterials.clear(); } std::shared_ptr<FabricMaterial> FabricResourceManager::createMaterial(const FabricMaterialDescriptor& materialDescriptor) { const auto contextId = _pContext->getContextId(); const auto pathStr = fmt::format("/cesium_material_{}_context_{}", getNextMaterialId(), contextId); const auto path = omni::fabric::Path(pathStr.c_str()); return std::make_shared<FabricMaterial>( _pContext, path, materialDescriptor, _defaultWhiteTextureAssetPathToken, _defaultTransparentTextureAssetPathToken, _debugRandomColors, -1); } std::shared_ptr<FabricMaterial> FabricResourceManager::acquireSharedMaterial( const FabricMaterialInfo& materialInfo, const FabricMaterialDescriptor& materialDescriptor, int64_t tilesetId) { for (auto& sharedMaterial : _sharedMaterials) { if (sharedMaterial.materialInfo == materialInfo && sharedMaterial.tilesetId == tilesetId) { ++sharedMaterial.referenceCount; return sharedMaterial.pMaterial; } } const auto material = createMaterial(materialDescriptor); // In C++ 20 this can be emplace_back without the {} _sharedMaterials.push_back({ material, materialInfo, tilesetId, 1, }); return _sharedMaterials.back().pMaterial; } void FabricResourceManager::releaseSharedMaterial(const FabricMaterial& material) { CppUtil::eraseIf(_sharedMaterials, [&material](auto& sharedMaterial) { if (sharedMaterial.pMaterial.get() == &material) { --sharedMaterial.referenceCount; if (sharedMaterial.referenceCount == 0) { return true; } } return false; }); } bool FabricResourceManager::isSharedMaterial(const FabricMaterial& material) const { for (auto& sharedMaterial : _sharedMaterials) { if (sharedMaterial.pMaterial.get() == &material) { return true; } } return false; } std::shared_ptr<FabricGeometry> FabricResourceManager::acquireGeometryFromPool(const FabricGeometryDescriptor& geometryDescriptor) { for (const auto& pGeometryPool : _geometryPools) { if (geometryDescriptor == pGeometryPool->getGeometryDescriptor()) { // Found a pool with the same geometry descriptor return pGeometryPool->acquire(); } } auto pGeometryPool = std::make_unique<FabricGeometryPool>( _pContext, getNextGeometryPoolId(), geometryDescriptor, _geometryPoolInitialCapacity); _geometryPools.push_back(std::move(pGeometryPool)); return _geometryPools.back()->acquire(); } std::shared_ptr<FabricMaterial> FabricResourceManager::acquireMaterialFromPool(const FabricMaterialDescriptor& materialDescriptor) { for (const auto& pMaterialPool : _materialPools) { if (materialDescriptor == pMaterialPool->getMaterialDescriptor()) { // Found a pool with the same material descriptor return pMaterialPool->acquire(); } } auto pMaterialPool = std::make_unique<FabricMaterialPool>( _pContext, getNextMaterialPoolId(), materialDescriptor, _materialPoolInitialCapacity, _defaultWhiteTextureAssetPathToken, _defaultTransparentTextureAssetPathToken, _debugRandomColors); _materialPools.push_back(std::move(pMaterialPool)); return _materialPools.back()->acquire(); } std::shared_ptr<FabricTexture> FabricResourceManager::acquireTextureFromPool() { if (!_texturePools.empty()) { return _texturePools.front()->acquire(); } auto pTexturePool = std::make_unique<FabricTexturePool>(_pContext, getNextTexturePoolId(), _texturePoolInitialCapacity); _texturePools.push_back(std::move(pTexturePool)); return _texturePools.back()->acquire(); } FabricGeometryPool* FabricResourceManager::getGeometryPool(const FabricGeometry& geometry) const { for (const auto& pGeometryPool : _geometryPools) { if (pGeometryPool->getPoolId() == geometry.getPoolId()) { return pGeometryPool.get(); } } return nullptr; } FabricMaterialPool* FabricResourceManager::getMaterialPool(const FabricMaterial& material) const { for (const auto& pMaterialPool : _materialPools) { if (pMaterialPool->getPoolId() == material.getPoolId()) { return pMaterialPool.get(); } } return nullptr; } FabricTexturePool* FabricResourceManager::getTexturePool(const FabricTexture& texture) const { for (const auto& pTexturePool : _texturePools) { if (pTexturePool->getPoolId() == texture.getPoolId()) { return pTexturePool.get(); } } return nullptr; } int64_t FabricResourceManager::getNextGeometryId() { return _geometryId++; } int64_t FabricResourceManager::getNextMaterialId() { return _materialId++; } int64_t FabricResourceManager::getNextTextureId() { return _textureId++; } int64_t FabricResourceManager::getNextGeometryPoolId() { return _geometryPoolId++; } int64_t FabricResourceManager::getNextMaterialPoolId() { return _materialPoolId++; } int64_t FabricResourceManager::getNextTexturePoolId() { return _texturePoolId++; } }; // namespace cesium::omniverse
13,698
C++
32.169491
118
0.722295
CesiumGS/cesium-omniverse/src/core/src/FabricVertexAttributeAccessors.cpp
#include "cesium/omniverse/FabricVertexAttributeAccessors.h" namespace cesium::omniverse { PositionsAccessor::PositionsAccessor() : _size(0) {} PositionsAccessor::PositionsAccessor(const CesiumGltf::AccessorView<glm::fvec3>& view) : _view(view) , _size(static_cast<uint64_t>(view.size())) {} void PositionsAccessor::fill(const gsl::span<glm::fvec3>& values) const { for (uint64_t i = 0; i < _size; ++i) { values[i] = _view[static_cast<int64_t>(i)]; } } const glm::fvec3& PositionsAccessor::get(uint64_t index) const { return _view[static_cast<int64_t>(index)]; } uint64_t PositionsAccessor::size() const { return _size; } IndicesAccessor::IndicesAccessor() : _size(0) {} IndicesAccessor::IndicesAccessor(uint64_t size) : _size(size) {} IndicesAccessor::IndicesAccessor(const CesiumGltf::AccessorView<uint8_t>& uint8View) : _uint8View(uint8View) , _size(static_cast<uint64_t>(uint8View.size())) {} IndicesAccessor::IndicesAccessor(const CesiumGltf::AccessorView<uint16_t>& uint16View) : _uint16View(uint16View) , _size(static_cast<uint64_t>(uint16View.size())) {} IndicesAccessor::IndicesAccessor(const CesiumGltf::AccessorView<uint32_t>& uint32View) : _uint32View(uint32View) , _size(static_cast<uint64_t>(uint32View.size())) {} template <typename T> IndicesAccessor IndicesAccessor::FromTriangleStrips(const CesiumGltf::AccessorView<T>& view) { auto indices = std::vector<uint32_t>(); indices.reserve(static_cast<uint64_t>(view.size() - 2) * 3); for (auto i = 0; i < view.size() - 2; ++i) { if (i % 2) { indices.push_back(static_cast<uint32_t>(view[i])); indices.push_back(static_cast<uint32_t>(view[i + 2])); indices.push_back(static_cast<uint32_t>(view[i + 1])); } else { indices.push_back(static_cast<uint32_t>(view[i])); indices.push_back(static_cast<uint32_t>(view[i + 1])); indices.push_back(static_cast<uint32_t>(view[i + 2])); } } auto accessor = IndicesAccessor(); accessor._size = indices.size(); accessor._computed = std::move(indices); return accessor; } // Explicit template instantiation template IndicesAccessor IndicesAccessor::FromTriangleStrips<uint8_t>(const CesiumGltf::AccessorView<uint8_t>& view); template IndicesAccessor IndicesAccessor::FromTriangleStrips<uint16_t>(const CesiumGltf::AccessorView<uint16_t>& view); template IndicesAccessor IndicesAccessor::FromTriangleStrips<uint32_t>(const CesiumGltf::AccessorView<uint32_t>& view); template <typename T> IndicesAccessor IndicesAccessor::FromTriangleFans(const CesiumGltf::AccessorView<T>& view) { auto indices = std::vector<uint32_t>(); indices.reserve(static_cast<uint64_t>(view.size() - 2) * 3); for (auto i = 0; i < view.size() - 2; ++i) { indices.push_back(static_cast<uint32_t>(view[0])); indices.push_back(static_cast<uint32_t>(view[i + 1])); indices.push_back(static_cast<uint32_t>(view[i + 2])); } auto accessor = IndicesAccessor(); accessor._size = indices.size(); accessor._computed = std::move(indices); return accessor; } // Explicit template instantiation template IndicesAccessor IndicesAccessor::FromTriangleFans<uint8_t>(const CesiumGltf::AccessorView<uint8_t>& view); template IndicesAccessor IndicesAccessor::FromTriangleFans<uint16_t>(const CesiumGltf::AccessorView<uint16_t>& view); template IndicesAccessor IndicesAccessor::FromTriangleFans<uint32_t>(const CesiumGltf::AccessorView<uint32_t>& view); void IndicesAccessor::fill(const gsl::span<int>& values) const { const auto size = values.size(); assert(size == _size); if (!_computed.empty()) { for (uint64_t i = 0; i < size; ++i) { values[i] = static_cast<int>(_computed[i]); } } else if (_uint8View.status() == CesiumGltf::AccessorViewStatus::Valid) { for (uint64_t i = 0; i < size; ++i) { values[i] = static_cast<int>(_uint8View[static_cast<int64_t>(i)]); } } else if (_uint16View.status() == CesiumGltf::AccessorViewStatus::Valid) { for (uint64_t i = 0; i < size; ++i) { values[i] = static_cast<int>(_uint16View[static_cast<int64_t>(i)]); } } else if (_uint32View.status() == CesiumGltf::AccessorViewStatus::Valid) { for (uint64_t i = 0; i < size; ++i) { values[i] = static_cast<int>(_uint32View[static_cast<int64_t>(i)]); } } else { for (uint64_t i = 0; i < size; ++i) { values[i] = static_cast<int>(i); } } } uint32_t IndicesAccessor::get(uint64_t index) const { if (!_computed.empty()) { return _computed[index]; } else if (_uint8View.status() == CesiumGltf::AccessorViewStatus::Valid) { return static_cast<uint32_t>(_uint8View[static_cast<int64_t>(index)]); } else if (_uint16View.status() == CesiumGltf::AccessorViewStatus::Valid) { return static_cast<uint32_t>(_uint16View[static_cast<int64_t>(index)]); } else if (_uint32View.status() == CesiumGltf::AccessorViewStatus::Valid) { return static_cast<uint32_t>(_uint32View[static_cast<int64_t>(index)]); } else { return static_cast<uint32_t>(index); } } uint64_t IndicesAccessor::size() const { return _size; } NormalsAccessor::NormalsAccessor() : _size(0) {} NormalsAccessor::NormalsAccessor(const CesiumGltf::AccessorView<glm::fvec3>& view) : _view(view) , _size(static_cast<uint64_t>(view.size())) {} NormalsAccessor NormalsAccessor::GenerateSmooth(const PositionsAccessor& positions, const IndicesAccessor& indices) { auto normals = std::vector<glm::fvec3>(positions.size(), glm::fvec3(0.0f)); for (uint64_t i = 0; i < indices.size(); i += 3) { const auto idx0 = static_cast<uint64_t>(indices.get(i)); const auto idx1 = static_cast<uint64_t>(indices.get(i + 1)); const auto idx2 = static_cast<uint64_t>(indices.get(i + 2)); const auto& p0 = positions.get(idx0); const auto& p1 = positions.get(idx1); const auto& p2 = positions.get(idx2); auto n = glm::normalize(glm::cross(p1 - p0, p2 - p0)); normals[idx0] += n; normals[idx1] += n; normals[idx2] += n; } for (auto& n : normals) { n = glm::normalize(n); } auto accessor = NormalsAccessor(); accessor._computed = std::move(normals); accessor._size = indices.size(); return accessor; } void NormalsAccessor::fill(const gsl::span<glm::fvec3>& values) const { const auto size = values.size(); assert(size == _size); if (!_computed.empty()) { for (uint64_t i = 0; i < size; ++i) { values[i] = _computed[i]; } } else { for (uint64_t i = 0; i < size; ++i) { values[i] = _view[static_cast<int64_t>(i)]; } } } uint64_t NormalsAccessor::size() const { return _size; } TexcoordsAccessor::TexcoordsAccessor() : _size(0) {} TexcoordsAccessor::TexcoordsAccessor(const CesiumGltf::AccessorView<glm::fvec2>& view, bool flipVertical) : _view(view) , _flipVertical(flipVertical) , _size(static_cast<uint64_t>(view.size())) {} void TexcoordsAccessor::fill(const gsl::span<glm::fvec2>& values) const { const auto size = values.size(); assert(size == _size); for (uint64_t i = 0; i < size; ++i) { values[i] = _view[static_cast<int64_t>(i)]; } if (_flipVertical) { for (uint64_t i = 0; i < size; ++i) { values[i][1] = 1.0f - values[i][1]; } } } uint64_t TexcoordsAccessor::size() const { return _size; } VertexColorsAccessor::VertexColorsAccessor() : _size(0) {} VertexColorsAccessor::VertexColorsAccessor(const CesiumGltf::AccessorView<glm::u8vec3>& uint8Vec3View) : _uint8Vec3View(uint8Vec3View) , _size(static_cast<uint64_t>(uint8Vec3View.size())) {} VertexColorsAccessor::VertexColorsAccessor(const CesiumGltf::AccessorView<glm::u8vec4>& uint8Vec4View) : _uint8Vec4View(uint8Vec4View) , _size(static_cast<uint64_t>(uint8Vec4View.size())) {} VertexColorsAccessor::VertexColorsAccessor(const CesiumGltf::AccessorView<glm::u16vec3>& uint16Vec3View) : _uint16Vec3View(uint16Vec3View) , _size(static_cast<uint64_t>(uint16Vec3View.size())) {} VertexColorsAccessor::VertexColorsAccessor(const CesiumGltf::AccessorView<glm::u16vec4>& uint16Vec4View) : _uint16Vec4View(uint16Vec4View) , _size(static_cast<uint64_t>(uint16Vec4View.size())) {} VertexColorsAccessor::VertexColorsAccessor(const CesiumGltf::AccessorView<glm::fvec3>& float32Vec3View) : _float32Vec3View(float32Vec3View) , _size(static_cast<uint64_t>(float32Vec3View.size())) {} VertexColorsAccessor::VertexColorsAccessor(const CesiumGltf::AccessorView<glm::fvec4>& float32Vec4View) : _float32Vec4View(float32Vec4View) , _size(static_cast<uint64_t>(float32Vec4View.size())) {} void VertexColorsAccessor::fill(const gsl::span<glm::fvec4>& values, uint64_t repeat) const { constexpr auto MAX_UINT8 = static_cast<float>(std::numeric_limits<uint8_t>::max()); constexpr auto MAX_UINT16 = static_cast<float>(std::numeric_limits<uint16_t>::max()); const auto size = values.size(); assert(size == _size * repeat); if (_uint8Vec3View.status() == CesiumGltf::AccessorViewStatus::Valid) { for (uint64_t i = 0; i < size; ++i) { values[i] = glm::fvec4( static_cast<float>(_uint8Vec3View[static_cast<int64_t>(i / repeat)].x) / MAX_UINT8, static_cast<float>(_uint8Vec3View[static_cast<int64_t>(i / repeat)].y) / MAX_UINT8, static_cast<float>(_uint8Vec3View[static_cast<int64_t>(i / repeat)].z) / MAX_UINT8, 1.0); } } else if (_uint8Vec4View.status() == CesiumGltf::AccessorViewStatus::Valid) { for (uint64_t i = 0; i < size; ++i) { values[i] = glm::fvec4( static_cast<float>(_uint8Vec4View[static_cast<int64_t>(i / repeat)].x) / MAX_UINT8, static_cast<float>(_uint8Vec4View[static_cast<int64_t>(i / repeat)].y) / MAX_UINT8, static_cast<float>(_uint8Vec4View[static_cast<int64_t>(i / repeat)].z) / MAX_UINT8, static_cast<float>(_uint8Vec4View[static_cast<int64_t>(i / repeat)].w) / MAX_UINT8); } } else if (_uint16Vec3View.status() == CesiumGltf::AccessorViewStatus::Valid) { for (uint64_t i = 0; i < size; ++i) { values[i] = glm::fvec4( static_cast<float>(_uint16Vec3View[static_cast<int64_t>(i / repeat)].x) / MAX_UINT16, static_cast<float>(_uint16Vec3View[static_cast<int64_t>(i / repeat)].y) / MAX_UINT16, static_cast<float>(_uint16Vec3View[static_cast<int64_t>(i / repeat)].z) / MAX_UINT16, 1.0); } } else if (_uint16Vec4View.status() == CesiumGltf::AccessorViewStatus::Valid) { for (uint64_t i = 0; i < size; ++i) { values[i] = glm::fvec4( static_cast<float>(_uint16Vec4View[static_cast<int64_t>(i / repeat)].x) / MAX_UINT16, static_cast<float>(_uint16Vec4View[static_cast<int64_t>(i / repeat)].y) / MAX_UINT16, static_cast<float>(_uint16Vec4View[static_cast<int64_t>(i / repeat)].z) / MAX_UINT16, static_cast<float>(_uint16Vec4View[static_cast<int64_t>(i / repeat)].w) / MAX_UINT16); } } else if (_float32Vec3View.status() == CesiumGltf::AccessorViewStatus::Valid) { for (uint64_t i = 0; i < size; ++i) { values[i] = glm::fvec4(_float32Vec3View[static_cast<int64_t>(i / repeat)], 1.0f); } } else if (_float32Vec4View.status() == CesiumGltf::AccessorViewStatus::Valid) { for (uint64_t i = 0; i < size; ++i) { values[i] = _float32Vec4View[static_cast<int64_t>(i / repeat)]; } } } uint64_t VertexColorsAccessor::size() const { return _size; } VertexIdsAccessor::VertexIdsAccessor() : _size(0) {} VertexIdsAccessor::VertexIdsAccessor(uint64_t size) : _size(size) {} void VertexIdsAccessor::fill(const gsl::span<float>& values, uint64_t repeat) const { const auto size = values.size(); assert(size == _size * repeat); for (uint64_t i = 0; i < size; ++i) { // NOLINTNEXTLINE(bugprone-integer-division) values[i] = static_cast<float>(i / repeat); } } uint64_t VertexIdsAccessor::size() const { return _size; } FaceVertexCountsAccessor::FaceVertexCountsAccessor() : _size(0) {} FaceVertexCountsAccessor::FaceVertexCountsAccessor(uint64_t size) : _size(size) {} void FaceVertexCountsAccessor::fill(const gsl::span<int>& values) const { const auto size = values.size(); assert(size == _size); for (uint64_t i = 0; i < size; ++i) { values[i] = 3; } } uint64_t FaceVertexCountsAccessor::size() const { return _size; } } // namespace cesium::omniverse
12,982
C++
37.297935
119
0.63642
CesiumGS/cesium-omniverse/src/core/src/TaskProcessor.cpp
#include "cesium/omniverse/TaskProcessor.h" namespace cesium::omniverse { void TaskProcessor::startTask(std::function<void()> f) { _dispatcher.Run(f); } } // namespace cesium::omniverse
191
C++
22.999997
56
0.732984
CesiumGS/cesium-omniverse/src/core/src/FabricAttributesBuilder.cpp
#include "cesium/omniverse/FabricAttributesBuilder.h" #include "cesium/omniverse/Context.h" #include "cesium/omniverse/UsdUtil.h" #include <omni/fabric/SimStageWithHistory.h> namespace cesium::omniverse { FabricAttributesBuilder::FabricAttributesBuilder(Context* pContext) : _pContext(pContext) {} void FabricAttributesBuilder::addAttribute(const omni::fabric::Type& type, const omni::fabric::Token& name) { assert(_size < MAX_ATTRIBUTES); _attributes[_size++] = omni::fabric::AttrNameAndType(type, name); } void FabricAttributesBuilder::createAttributes(const omni::fabric::Path& path) const { // Somewhat annoyingly, fabricStage.createAttributes takes an std::array instead of a gsl::span. This is fine if // you know exactly which set of attributes to create at compile time but we don't. For example, not all prims will // have texture coordinates or materials. This class allows attributes to be added dynamically up to a hardcoded maximum // count (MAX_ATTRIBUTES) and avoids heap allocations. The downside is that we need this ugly if/else chain below. auto& fabricStage = _pContext->getFabricStage(); // clang-format off if (_size == 0) fabricStage.createAttributes<0>(path, *reinterpret_cast<const std::array<omni::fabric::AttrNameAndType, 0>*>(_attributes.data())); else if (_size == 1) fabricStage.createAttributes<1>(path, *reinterpret_cast<const std::array<omni::fabric::AttrNameAndType, 1>*>(_attributes.data())); else if (_size == 2) fabricStage.createAttributes<2>(path, *reinterpret_cast<const std::array<omni::fabric::AttrNameAndType, 2>*>(_attributes.data())); else if (_size == 3) fabricStage.createAttributes<3>(path, *reinterpret_cast<const std::array<omni::fabric::AttrNameAndType, 3>*>(_attributes.data())); else if (_size == 4) fabricStage.createAttributes<4>(path, *reinterpret_cast<const std::array<omni::fabric::AttrNameAndType, 4>*>(_attributes.data())); else if (_size == 5) fabricStage.createAttributes<5>(path, *reinterpret_cast<const std::array<omni::fabric::AttrNameAndType, 5>*>(_attributes.data())); else if (_size == 6) fabricStage.createAttributes<6>(path, *reinterpret_cast<const std::array<omni::fabric::AttrNameAndType, 6>*>(_attributes.data())); else if (_size == 7) fabricStage.createAttributes<7>(path, *reinterpret_cast<const std::array<omni::fabric::AttrNameAndType, 7>*>(_attributes.data())); else if (_size == 8) fabricStage.createAttributes<8>(path, *reinterpret_cast<const std::array<omni::fabric::AttrNameAndType, 8>*>(_attributes.data())); else if (_size == 9) fabricStage.createAttributes<9>(path, *reinterpret_cast<const std::array<omni::fabric::AttrNameAndType, 9>*>(_attributes.data())); else if (_size == 10) fabricStage.createAttributes<10>(path, *reinterpret_cast<const std::array<omni::fabric::AttrNameAndType, 10>*>(_attributes.data())); else if (_size == 11) fabricStage.createAttributes<11>(path, *reinterpret_cast<const std::array<omni::fabric::AttrNameAndType, 11>*>(_attributes.data())); else if (_size == 12) fabricStage.createAttributes<12>(path, *reinterpret_cast<const std::array<omni::fabric::AttrNameAndType, 12>*>(_attributes.data())); else if (_size == 13) fabricStage.createAttributes<13>(path, *reinterpret_cast<const std::array<omni::fabric::AttrNameAndType, 13>*>(_attributes.data())); else if (_size == 14) fabricStage.createAttributes<14>(path, *reinterpret_cast<const std::array<omni::fabric::AttrNameAndType, 14>*>(_attributes.data())); else if (_size == 15) fabricStage.createAttributes<15>(path, *reinterpret_cast<const std::array<omni::fabric::AttrNameAndType, 15>*>(_attributes.data())); else if (_size == 16) fabricStage.createAttributes<16>(path, *reinterpret_cast<const std::array<omni::fabric::AttrNameAndType, 16>*>(_attributes.data())); else if (_size == 17) fabricStage.createAttributes<17>(path, *reinterpret_cast<const std::array<omni::fabric::AttrNameAndType, 17>*>(_attributes.data())); else if (_size == 18) fabricStage.createAttributes<18>(path, *reinterpret_cast<const std::array<omni::fabric::AttrNameAndType, 18>*>(_attributes.data())); else if (_size == 19) fabricStage.createAttributes<19>(path, *reinterpret_cast<const std::array<omni::fabric::AttrNameAndType, 19>*>(_attributes.data())); else if (_size == 20) fabricStage.createAttributes<20>(path, *reinterpret_cast<const std::array<omni::fabric::AttrNameAndType, 20>*>(_attributes.data())); else if (_size == 21) fabricStage.createAttributes<21>(path, *reinterpret_cast<const std::array<omni::fabric::AttrNameAndType, 21>*>(_attributes.data())); else if (_size == 22) fabricStage.createAttributes<22>(path, *reinterpret_cast<const std::array<omni::fabric::AttrNameAndType, 22>*>(_attributes.data())); else if (_size == 23) fabricStage.createAttributes<23>(path, *reinterpret_cast<const std::array<omni::fabric::AttrNameAndType, 23>*>(_attributes.data())); else if (_size == 24) fabricStage.createAttributes<24>(path, *reinterpret_cast<const std::array<omni::fabric::AttrNameAndType, 24>*>(_attributes.data())); else if (_size == 25) fabricStage.createAttributes<25>(path, *reinterpret_cast<const std::array<omni::fabric::AttrNameAndType, 25>*>(_attributes.data())); else if (_size == 26) fabricStage.createAttributes<26>(path, *reinterpret_cast<const std::array<omni::fabric::AttrNameAndType, 26>*>(_attributes.data())); else if (_size == 27) fabricStage.createAttributes<27>(path, *reinterpret_cast<const std::array<omni::fabric::AttrNameAndType, 27>*>(_attributes.data())); else if (_size == 28) fabricStage.createAttributes<28>(path, *reinterpret_cast<const std::array<omni::fabric::AttrNameAndType, 28>*>(_attributes.data())); else if (_size == 29) fabricStage.createAttributes<29>(path, *reinterpret_cast<const std::array<omni::fabric::AttrNameAndType, 29>*>(_attributes.data())); // clang-format on } } // namespace cesium::omniverse
5,966
C++
98.449998
158
0.722595
CesiumGS/cesium-omniverse/src/core/src/FabricMaterialDescriptor.cpp
#include "cesium/omniverse/FabricMaterialDescriptor.h" #include "cesium/omniverse/FabricFeaturesInfo.h" #include "cesium/omniverse/FabricFeaturesUtil.h" #include "cesium/omniverse/FabricMaterialInfo.h" #include "cesium/omniverse/FabricPropertyDescriptor.h" #include "cesium/omniverse/FabricRasterOverlaysInfo.h" #include "cesium/omniverse/GltfUtil.h" #include "cesium/omniverse/MetadataUtil.h" #ifdef CESIUM_OMNI_MSVC #pragma push_macro("OPAQUE") #undef OPAQUE #endif #include <CesiumGltf/Model.h> namespace cesium::omniverse { FabricMaterialDescriptor::FabricMaterialDescriptor( const Context& context, const CesiumGltf::Model& model, const CesiumGltf::MeshPrimitive& primitive, const FabricMaterialInfo& materialInfo, const FabricFeaturesInfo& featuresInfo, const FabricRasterOverlaysInfo& rasterOverlaysInfo, const pxr::SdfPath& tilesetMaterialPath) : _hasVertexColors(materialInfo.hasVertexColors) , _hasBaseColorTexture(materialInfo.baseColorTexture.has_value()) , _featureIdTypes(FabricFeaturesUtil::getFeatureIdTypes(featuresInfo)) , _rasterOverlayRenderMethods(rasterOverlaysInfo.overlayRenderMethods) , _tilesetMaterialPath(tilesetMaterialPath) { // Ignore styleable properties unless the tileset has a material if (!_tilesetMaterialPath.IsEmpty()) { std::tie(_styleableProperties, _unsupportedPropertyWarnings) = MetadataUtil::getStyleableProperties(context, model, primitive); } } bool FabricMaterialDescriptor::hasVertexColors() const { return _hasVertexColors; } bool FabricMaterialDescriptor::hasBaseColorTexture() const { return _hasBaseColorTexture; } const std::vector<FabricFeatureIdType>& FabricMaterialDescriptor::getFeatureIdTypes() const { return _featureIdTypes; } const std::vector<FabricOverlayRenderMethod>& FabricMaterialDescriptor::getRasterOverlayRenderMethods() const { return _rasterOverlayRenderMethods; } bool FabricMaterialDescriptor::hasTilesetMaterial() const { return !_tilesetMaterialPath.IsEmpty(); } const pxr::SdfPath& FabricMaterialDescriptor::getTilesetMaterialPath() const { return _tilesetMaterialPath; } const std::vector<FabricPropertyDescriptor>& FabricMaterialDescriptor::getStyleableProperties() const { return _styleableProperties; } const std::map<std::string, std::string>& FabricMaterialDescriptor::getUnsupportedPropertyWarnings() const { return _unsupportedPropertyWarnings; } // Make sure to update this function when adding new fields to the class bool FabricMaterialDescriptor::operator==(const FabricMaterialDescriptor& other) const { // clang-format off return _hasVertexColors == other._hasVertexColors && _hasBaseColorTexture == other._hasBaseColorTexture && _featureIdTypes == other._featureIdTypes && _rasterOverlayRenderMethods == other._rasterOverlayRenderMethods && _tilesetMaterialPath == other._tilesetMaterialPath && _styleableProperties == other._styleableProperties; // _unsupportedPropertyWarnings is intentionally not checked because it adds unecessary overhead // clang-format on } } // namespace cesium::omniverse
3,197
C++
35.75862
111
0.772599
CesiumGS/cesium-omniverse/src/core/src/FilesystemUtil.cpp
#include "cesium/omniverse/FilesystemUtil.h" #include <carb/Framework.h> #include <carb/tokens/ITokens.h> #include <carb/tokens/TokensUtils.h> #include <cstdlib> #include <filesystem> #if defined(__linux__) #include <pwd.h> #include <sys/types.h> #include <unistd.h> #include <cerrno> #endif namespace cesium::omniverse::FilesystemUtil { std::filesystem::path getCesiumCacheDirectory() { auto f = carb::getFramework(); auto* tokensInterface = f->tryAcquireInterface<carb::tokens::ITokens>(); std::string cacheDir; if (tokensInterface) { cacheDir = carb::tokens::resolveString(tokensInterface, "${omni_global_cache}"); } if (!cacheDir.empty()) { std::filesystem::path cacheDirPath(cacheDir); if (exists(cacheDirPath)) { return cacheDirPath; } // Should we create the directory if it doesn't exist? It's hard to believe that Omniverse // won't have already created it. } auto homeDirPath = getUserHomeDirectory(); if (!homeDirPath.empty()) { auto cacheDirPath = homeDirPath / ".nvidia-omniverse"; if (exists(cacheDirPath)) { return cacheDirPath; } } return {}; } // Quite a lot of ceremony to get the home directory. std::filesystem::path getUserHomeDirectory() { std::string homeDir; #if defined(__linux__) if (char* cString = std::getenv("HOME")) { homeDir = cString; } else { passwd pwd; long bufsize = sysconf(_SC_GETPW_R_SIZE_MAX); if (bufsize == -1) { bufsize = 16384; } char* buf = new char[static_cast<size_t>(bufsize)]; passwd* result = nullptr; int getResult = getpwuid_r(getuid(), &pwd, buf, static_cast<size_t>(bufsize), &result); if (getResult == 0) { homeDir = pwd.pw_dir; } delete[] buf; } #elif defined(_WIN32) if (char* cString = std::getenv("USERPROFILE")) { homeDir = cString; } #endif return homeDir; } } // namespace cesium::omniverse::FilesystemUtil
2,066
C++
26.932432
98
0.617135
CesiumGS/cesium-omniverse/src/core/src/UsdUtil.cpp
#include "cesium/omniverse/UsdUtil.h" #include "CesiumUsdSchemas/webMapServiceRasterOverlay.h" #include "cesium/omniverse/AssetRegistry.h" #include "cesium/omniverse/Context.h" #include "cesium/omniverse/CppUtil.h" #include "cesium/omniverse/MathUtil.h" #include "cesium/omniverse/OmniData.h" #include "cesium/omniverse/OmniGeoreference.h" #include "cesium/omniverse/UsdScopedEdit.h" #include "cesium/omniverse/UsdTokens.h" #include "cesium/omniverse/Viewport.h" #include <Cesium3DTilesSelection/ViewState.h> #include <CesiumGeometry/Transforms.h> #include <CesiumGeospatial/Cartographic.h> #include <CesiumGeospatial/Ellipsoid.h> #include <CesiumGeospatial/GlobeAnchor.h> #include <CesiumGeospatial/GlobeTransforms.h> #include <CesiumGeospatial/LocalHorizontalCoordinateSystem.h> #include <CesiumUsdSchemas/data.h> #include <CesiumUsdSchemas/georeference.h> #include <CesiumUsdSchemas/globeAnchorAPI.h> #include <CesiumUsdSchemas/ionRasterOverlay.h> #include <CesiumUsdSchemas/ionServer.h> #include <CesiumUsdSchemas/polygonRasterOverlay.h> #include <CesiumUsdSchemas/session.h> #include <CesiumUsdSchemas/tileMapServiceRasterOverlay.h> #include <CesiumUsdSchemas/tileset.h> #include <CesiumUsdSchemas/webMapServiceRasterOverlay.h> #include <CesiumUsdSchemas/webMapTileServiceRasterOverlay.h> #include <glm/gtc/matrix_access.hpp> #include <glm/gtc/matrix_inverse.hpp> #include <glm/gtc/matrix_transform.hpp> #include <glm/gtc/quaternion.hpp> #include <omni/ui/ImageProvider/DynamicTextureProvider.h> #include <pxr/base/gf/rotation.h> #include <pxr/usd/sdf/primSpec.h> #include <pxr/usd/usd/prim.h> #include <pxr/usd/usd/stage.h> #include <pxr/usd/usd/timeCode.h> #include <pxr/usd/usdGeom/metrics.h> #include <pxr/usd/usdGeom/xform.h> #include <pxr/usd/usdGeom/xformCommonAPI.h> #include <pxr/usd/usdShade/material.h> #include <pxr/usd/usdShade/shader.h> #include <spdlog/fmt/fmt.h> #include <cctype> namespace cesium::omniverse::UsdUtil { namespace { bool getDebugDisableGeoreferencing(const Context& context) { const auto pData = context.getAssetRegistry().getFirstData(); if (!pData) { return false; } return pData->getDebugDisableGeoreferencing(); } } // namespace glm::dvec3 usdToGlmVector(const pxr::GfVec3d& vector) { return {vector[0], vector[1], vector[2]}; } glm::fvec3 usdToGlmVector(const pxr::GfVec3f& vector) { return {vector[0], vector[1], vector[2]}; } glm::dmat4 usdToGlmMatrix(const pxr::GfMatrix4d& matrix) { // USD is row-major with left-to-right matrix multiplication // glm is column-major with right-to-left matrix multiplication // This means they have the same data layout return { matrix[0][0], matrix[0][1], matrix[0][2], matrix[0][3], matrix[1][0], matrix[1][1], matrix[1][2], matrix[1][3], matrix[2][0], matrix[2][1], matrix[2][2], matrix[2][3], matrix[3][0], matrix[3][1], matrix[3][2], matrix[3][3], }; } glm::dquat usdToGlmQuat(const pxr::GfQuatd& quat) { const auto real = quat.GetReal(); const auto imaginary = usdToGlmVector(quat.GetImaginary()); return {real, imaginary.x, imaginary.y, imaginary.z}; } glm::fquat usdToGlmQuat(const pxr::GfQuatf& quat) { const auto real = quat.GetReal(); const auto imaginary = usdToGlmVector(quat.GetImaginary()); return {real, imaginary.x, imaginary.y, imaginary.z}; } std::array<glm::dvec3, 2> usdToGlmExtent(const pxr::GfRange3d& extent) { return {{usdToGlmVector(extent.GetMin()), usdToGlmVector(extent.GetMax())}}; } pxr::GfVec3d glmToUsdVector(const glm::dvec3& vector) { return {vector.x, vector.y, vector.z}; } pxr::GfVec2f glmToUsdVector(const glm::fvec2& vector) { return {vector.x, vector.y}; } pxr::GfVec3f glmToUsdVector(const glm::fvec3& vector) { return {vector.x, vector.y, vector.z}; } pxr::GfVec4f glmToUsdVector(const glm::fvec4& vector) { return {vector.x, vector.y, vector.z, vector.w}; } pxr::GfRange3d glmToUsdExtent(const std::array<glm::dvec3, 2>& extent) { return {glmToUsdVector(extent[0]), glmToUsdVector(extent[1])}; } pxr::GfQuatd glmToUsdQuat(const glm::dquat& quat) { return {quat.w, quat.x, quat.y, quat.z}; } pxr::GfQuatf glmToUsdQuat(const glm::fquat& quat) { return {quat.w, quat.x, quat.y, quat.z}; } pxr::GfMatrix4d glmToUsdMatrix(const glm::dmat4& matrix) { // USD is row-major with left-to-right matrix multiplication // glm is column-major with right-to-left matrix multiplication // This means they have the same data layout return pxr::GfMatrix4d{ matrix[0][0], matrix[0][1], matrix[0][2], matrix[0][3], matrix[1][0], matrix[1][1], matrix[1][2], matrix[1][3], matrix[2][0], matrix[2][1], matrix[2][2], matrix[2][3], matrix[3][0], matrix[3][1], matrix[3][2], matrix[3][3], }; } glm::dmat4 computePrimLocalToWorldTransform(const pxr::UsdStageWeakPtr& pStage, const pxr::SdfPath& path) { const auto prim = pStage->GetPrimAtPath(path); const auto xform = pxr::UsdGeomXformable(prim); if (!isSchemaValid(xform)) { return glm::dmat4(1.0); } const auto time = pxr::UsdTimeCode::Default(); const auto transform = xform.ComputeLocalToWorldTransform(time); return usdToGlmMatrix(transform); } glm::dmat4 computePrimWorldToLocalTransform(const pxr::UsdStageWeakPtr& pStage, const pxr::SdfPath& path) { return glm::affineInverse(computePrimLocalToWorldTransform(pStage, path)); } glm::dmat4 computeEcefToStageTransform(const Context& context, const pxr::SdfPath& georeferencePath) { const auto disableGeoreferencing = getDebugDisableGeoreferencing(context); const auto pGeoreference = georeferencePath.IsEmpty() ? nullptr : context.getAssetRegistry().getGeoreference(georeferencePath); if (disableGeoreferencing || !pGeoreference) { const auto zUp = getUsdUpAxis(context.getUsdStage()) == pxr::UsdGeomTokens->z; const auto axisConversion = zUp ? glm::dmat4(1.0) : CesiumGeometry::Transforms::Z_UP_TO_Y_UP; const auto scale = glm::scale(glm::dmat4(1.0), glm::dvec3(1.0 / getUsdMetersPerUnit(context.getUsdStage()))); return scale * axisConversion; } return pGeoreference->getLocalCoordinateSystem().getEcefToLocalTransformation(); } glm::dmat4 computeEcefToPrimWorldTransform( const Context& context, const pxr::SdfPath& georeferencePath, const pxr::SdfPath& primPath) { const auto ecefToStageTransform = computeEcefToStageTransform(context, georeferencePath); const auto primLocalToWorldTransform = computePrimLocalToWorldTransform(context.getUsdStage(), primPath); return primLocalToWorldTransform * ecefToStageTransform; } glm::dmat4 computePrimWorldToEcefTransform( const Context& context, const pxr::SdfPath& georeferencePath, const pxr::SdfPath& primPath) { return glm::affineInverse(computeEcefToPrimWorldTransform(context, georeferencePath, primPath)); } glm::dmat4 computeEcefToPrimLocalTransform( const Context& context, const pxr::SdfPath& georeferencePath, const pxr::SdfPath& primPath) { const auto ecefToStageTransform = computeEcefToStageTransform(context, georeferencePath); const auto primWorldToLocalTransform = computePrimWorldToLocalTransform(context.getUsdStage(), primPath); return primWorldToLocalTransform * ecefToStageTransform; } glm::dmat4 computePrimLocalToEcefTransform( const Context& context, const pxr::SdfPath& georeferencePath, const pxr::SdfPath& primPath) { return glm::affineInverse(computeEcefToPrimLocalTransform(context, georeferencePath, primPath)); } Cesium3DTilesSelection::ViewState computeViewState( const Context& context, const pxr::SdfPath& georeferencePath, const pxr::SdfPath& primPath, const Viewport& viewport) { const auto& viewMatrix = viewport.viewMatrix; const auto& projMatrix = viewport.projMatrix; const auto width = viewport.width; const auto height = viewport.height; const auto primWorldToEcefTransform = computePrimWorldToEcefTransform(context, georeferencePath, primPath); const auto inverseView = glm::affineInverse(viewMatrix); const auto usdCameraUp = glm::dvec3(inverseView[1]); const auto usdCameraFwd = glm::dvec3(-inverseView[2]); const auto usdCameraPosition = glm::dvec3(inverseView[3]); const auto cameraUp = glm::normalize(glm::dvec3(primWorldToEcefTransform * glm::dvec4(usdCameraUp, 0.0))); const auto cameraFwd = glm::normalize(glm::dvec3(primWorldToEcefTransform * glm::dvec4(usdCameraFwd, 0.0))); const auto cameraPosition = glm::dvec3(primWorldToEcefTransform * glm::dvec4(usdCameraPosition, 1.0)); const auto aspect = width / height; const auto verticalFov = 2.0 * glm::atan(1.0 / projMatrix[1][1]); const auto horizontalFov = 2.0 * glm::atan(glm::tan(verticalFov * 0.5) * aspect); return Cesium3DTilesSelection::ViewState::create( cameraPosition, cameraFwd, cameraUp, glm::dvec2(width, height), horizontalFov, verticalFov); } bool primExists(const pxr::UsdStageWeakPtr& pStage, const pxr::SdfPath& path) { return pStage->GetPrimAtPath(path).IsValid(); } bool isSchemaValid(const pxr::UsdSchemaBase& schema) { return schema.GetPrim().IsValid() && schema.GetSchemaKind() != pxr::UsdSchemaKind::Invalid; } bool isPrimVisible(const pxr::UsdStageWeakPtr& pStage, const pxr::SdfPath& path) { // This is similar to isPrimVisible in kit-sdk/dev/include/omni/usd/UsdUtils.h const auto prim = pStage->GetPrimAtPath(path); const auto imageable = pxr::UsdGeomImageable(prim); if (!isSchemaValid(imageable)) { return false; } const auto time = pxr::UsdTimeCode::Default(); const auto visibility = imageable.ComputeVisibility(time); return visibility != pxr::UsdGeomTokens->invisible; } const std::string& getName(const pxr::UsdStageWeakPtr& pStage, const pxr::SdfPath& path) { return pStage->GetPrimAtPath(path).GetName().GetString(); } pxr::TfToken getUsdUpAxis(const pxr::UsdStageWeakPtr& pStage) { return pxr::UsdGeomGetStageUpAxis(pStage); } double getUsdMetersPerUnit(const pxr::UsdStageWeakPtr& pStage) { return pxr::UsdGeomGetStageMetersPerUnit(pStage); } pxr::SdfPath getRootPath(const pxr::UsdStageWeakPtr& pStage) { return pStage->GetPseudoRoot().GetPath(); } pxr::SdfPath makeUniquePath(const pxr::UsdStageWeakPtr& pStage, const pxr::SdfPath& parentPath, const std::string& name) { pxr::UsdPrim prim; pxr::SdfPath path; auto copy = 0; do { const auto copyName = copy > 0 ? fmt::format("{}_{}", name, copy) : name; path = parentPath.AppendChild(pxr::TfToken(copyName)); prim = pStage->GetPrimAtPath(path); ++copy; } while (prim.IsValid()); return path; } std::string getSafeName(const std::string& name) { auto safeName = name; for (auto& c : safeName) { if (!std::isalnum(c)) { c = '_'; } } return safeName; } pxr::TfToken getDynamicTextureProviderAssetPathToken(const std::string_view& name) { return pxr::TfToken(pxr::SdfAssetPath(fmt::format("dynamic://{}", name)).GetAssetPath()); } pxr::CesiumData defineCesiumData(const pxr::UsdStageWeakPtr& pStage, const pxr::SdfPath& path) { return pxr::CesiumData::Define(pStage, path); } pxr::CesiumTileset defineCesiumTileset(const pxr::UsdStageWeakPtr& pStage, const pxr::SdfPath& path) { return pxr::CesiumTileset::Define(pStage, path); } pxr::CesiumIonRasterOverlay defineCesiumIonRasterOverlay(const pxr::UsdStageWeakPtr& pStage, const pxr::SdfPath& path) { return pxr::CesiumIonRasterOverlay::Define(pStage, path); } pxr::CesiumPolygonRasterOverlay defineCesiumPolygonRasterOverlay(const pxr::UsdStageWeakPtr& pStage, const pxr::SdfPath& path) { return pxr::CesiumPolygonRasterOverlay::Define(pStage, path); } pxr::CesiumGeoreference defineCesiumGeoreference(const pxr::UsdStageWeakPtr& pStage, const pxr::SdfPath& path) { return pxr::CesiumGeoreference::Define(pStage, path); } pxr::CesiumIonServer defineCesiumIonServer(const pxr::UsdStageWeakPtr& pStage, const pxr::SdfPath& path) { return pxr::CesiumIonServer::Define(pStage, path); } pxr::CesiumGlobeAnchorAPI applyCesiumGlobeAnchor(const pxr::UsdStageWeakPtr& pStage, const pxr::SdfPath& path) { const auto prim = pStage->GetPrimAtPath(path); assert(prim.IsValid() && prim.IsA<pxr::UsdGeomXformable>()); return pxr::CesiumGlobeAnchorAPI::Apply(prim); } pxr::CesiumSession defineCesiumSession(const pxr::UsdStageWeakPtr& pStage, const pxr::SdfPath& path) { return pxr::CesiumSession::Define(pStage, path); } pxr::CesiumData getCesiumData(const pxr::UsdStageWeakPtr& pStage, const pxr::SdfPath& path) { return pxr::CesiumData::Get(pStage, path); } pxr::CesiumTileset getCesiumTileset(const pxr::UsdStageWeakPtr& pStage, const pxr::SdfPath& path) { return pxr::CesiumTileset::Get(pStage, path); } pxr::CesiumRasterOverlay getCesiumRasterOverlay(const pxr::UsdStageWeakPtr& pStage, const pxr::SdfPath& path) { return pxr::CesiumRasterOverlay::Get(pStage, path); } pxr::CesiumIonRasterOverlay getCesiumIonRasterOverlay(const pxr::UsdStageWeakPtr& pStage, const pxr::SdfPath& path) { return pxr::CesiumIonRasterOverlay::Get(pStage, path); } pxr::CesiumPolygonRasterOverlay getCesiumPolygonRasterOverlay(const pxr::UsdStageWeakPtr& pStage, const pxr::SdfPath& path) { return pxr::CesiumPolygonRasterOverlay::Get(pStage, path); } pxr::CesiumWebMapServiceRasterOverlay getCesiumWebMapServiceRasterOverlay(const pxr::UsdStageWeakPtr& pStage, const pxr::SdfPath& path) { return pxr::CesiumWebMapServiceRasterOverlay::Get(pStage, path); } pxr::CesiumTileMapServiceRasterOverlay getCesiumTileMapServiceRasterOverlay(const pxr::UsdStageWeakPtr& pStage, const pxr::SdfPath& path) { return pxr::CesiumTileMapServiceRasterOverlay::Get(pStage, path); } pxr::CesiumWebMapTileServiceRasterOverlay getCesiumWebMapTileServiceRasterOverlay(const pxr::UsdStageWeakPtr& pStage, const pxr::SdfPath& path) { return pxr::CesiumWebMapTileServiceRasterOverlay::Get(pStage, path); } pxr::CesiumGeoreference getCesiumGeoreference(const pxr::UsdStageWeakPtr& pStage, const pxr::SdfPath& path) { return pxr::CesiumGeoreference::Get(pStage, path); } pxr::CesiumGlobeAnchorAPI getCesiumGlobeAnchor(const pxr::UsdStageWeakPtr& pStage, const pxr::SdfPath& path) { return pxr::CesiumGlobeAnchorAPI::Get(pStage, path); } pxr::CesiumIonServer getCesiumIonServer(const pxr::UsdStageWeakPtr& pStage, const pxr::SdfPath& path) { return pxr::CesiumIonServer::Get(pStage, path); } // This is currently a pass-through to getUsdBasisCurves until // issue with crashes in prims that inherit from BasisCurves is resolved pxr::UsdGeomBasisCurves getCesiumCartographicPolygon(const pxr::UsdStageWeakPtr& pStage, const pxr::SdfPath& path) { return getUsdBasisCurves(pStage, path); } pxr::UsdShadeShader getUsdShader(const pxr::UsdStageWeakPtr& pStage, const pxr::SdfPath& path) { return pxr::UsdShadeShader::Get(pStage, path); } pxr::UsdGeomBasisCurves getUsdBasisCurves(const pxr::UsdStageWeakPtr& pStage, const pxr::SdfPath& path) { return pxr::UsdGeomBasisCurves::Get(pStage, path); } pxr::CesiumSession getOrCreateCesiumSession(const pxr::UsdStageWeakPtr& pStage) { static const auto CesiumSessionPath = pxr::SdfPath("/CesiumSession"); if (isCesiumSession(pStage, CesiumSessionPath)) { return pxr::CesiumSession::Get(pStage, CesiumSessionPath); } // Ensures that CesiumSession is created in the session layer const UsdScopedEdit scopedEdit(pStage); // Create the CesiumSession const auto cesiumSession = defineCesiumSession(pStage, CesiumSessionPath); // Prevent CesiumSession from being traversed and composed into the stage cesiumSession.GetPrim().SetActive(false); return cesiumSession; } bool isCesiumData(const pxr::UsdStageWeakPtr& pStage, const pxr::SdfPath& path) { const auto prim = pStage->GetPrimAtPath(path); if (!prim.IsValid()) { return false; } return prim.IsA<pxr::CesiumData>(); } bool isCesiumTileset(const pxr::UsdStageWeakPtr& pStage, const pxr::SdfPath& path) { const auto prim = pStage->GetPrimAtPath(path); if (!prim.IsValid()) { return false; } return prim.IsA<pxr::CesiumTileset>(); } bool isCesiumRasterOverlay(const pxr::UsdStageWeakPtr& pStage, const pxr::SdfPath& path) { const auto prim = pStage->GetPrimAtPath(path); if (!prim.IsValid()) { return false; } return prim.IsA<pxr::CesiumRasterOverlay>(); } bool isCesiumIonRasterOverlay(const pxr::UsdStageWeakPtr& pStage, const pxr::SdfPath& path) { const auto prim = pStage->GetPrimAtPath(path); if (!prim.IsValid()) { return false; } return prim.IsA<pxr::CesiumIonRasterOverlay>(); } bool isCesiumPolygonRasterOverlay(const pxr::UsdStageWeakPtr& pStage, const pxr::SdfPath& path) { const auto prim = pStage->GetPrimAtPath(path); if (!prim.IsValid()) { return false; } return prim.IsA<pxr::CesiumPolygonRasterOverlay>(); } bool isCesiumWebMapServiceRasterOverlay(const pxr::UsdStageWeakPtr& pStage, const pxr::SdfPath& path) { const auto prim = pStage->GetPrimAtPath(path); if (!prim.IsValid()) { return false; } return prim.IsA<pxr::CesiumWebMapServiceRasterOverlay>(); } bool isCesiumTileMapServiceRasterOverlay(const pxr::UsdStageWeakPtr& pStage, const pxr::SdfPath& path) { const auto prim = pStage->GetPrimAtPath(path); if (!prim.IsValid()) { return false; } return prim.IsA<pxr::CesiumTileMapServiceRasterOverlay>(); } bool isCesiumWebMapTileServiceRasterOverlay(const pxr::UsdStageWeakPtr& pStage, const pxr::SdfPath& path) { const auto prim = pStage->GetPrimAtPath(path); if (!prim.IsValid()) { return false; } return prim.IsA<pxr::CesiumWebMapTileServiceRasterOverlay>(); } bool isCesiumGeoreference(const pxr::UsdStageWeakPtr& pStage, const pxr::SdfPath& path) { const auto prim = pStage->GetPrimAtPath(path); if (!prim.IsValid()) { return false; } return prim.IsA<pxr::CesiumGeoreference>(); } bool isCesiumIonServer(const pxr::UsdStageWeakPtr& pStage, const pxr::SdfPath& path) { const auto prim = pStage->GetPrimAtPath(path); if (!prim.IsValid()) { return false; } return prim.IsA<pxr::CesiumIonServer>(); } bool isCesiumCartographicPolygon(const pxr::UsdStageWeakPtr& pStage, const pxr::SdfPath& path) { const auto prim = pStage->GetPrimAtPath(path); if (!prim.IsValid()) { return false; } if (!prim.IsA<pxr::UsdGeomBasisCurves>()) { return false; } return prim.HasAPI<pxr::CesiumGlobeAnchorAPI>(); } bool isCesiumSession(const pxr::UsdStageWeakPtr& pStage, const pxr::SdfPath& path) { const auto prim = pStage->GetPrimAtPath(path); if (!prim.IsValid()) { return false; } return prim.IsA<pxr::CesiumSession>(); } bool hasCesiumGlobeAnchor(const pxr::UsdStageWeakPtr& pStage, const pxr::SdfPath& path) { const auto prim = pStage->GetPrimAtPath(path); if (!prim.IsValid()) { return false; } return prim.IsA<pxr::UsdGeomXformable>() && prim.HasAPI<pxr::CesiumGlobeAnchorAPI>(); } bool isUsdShader(const pxr::UsdStageWeakPtr& pStage, const pxr::SdfPath& path) { const auto prim = pStage->GetPrimAtPath(path); if (!prim.IsValid()) { return false; } return prim.IsA<pxr::UsdShadeShader>(); } bool isUsdMaterial(const pxr::UsdStageWeakPtr& pStage, const pxr::SdfPath& path) { const auto prim = pStage->GetPrimAtPath(path); if (!prim.IsValid()) { return false; } return prim.IsA<pxr::UsdShadeMaterial>(); } glm::dvec3 getTranslate(const pxr::UsdGeomXformOp& translateOp) { if (translateOp.GetPrecision() == pxr::UsdGeomXformOp::PrecisionDouble) { pxr::GfVec3d translation; translateOp.Get(&translation); return UsdUtil::usdToGlmVector(translation); } else if (translateOp.GetPrecision() == pxr::UsdGeomXformOp::PrecisionFloat) { pxr::GfVec3f translation; translateOp.Get(&translation); return glm::dvec3(UsdUtil::usdToGlmVector(translation)); } return glm::dvec3(0.0); } glm::dvec3 getRotate(const pxr::UsdGeomXformOp& rotateOp) { if (rotateOp.GetPrecision() == pxr::UsdGeomXformOp::PrecisionDouble) { pxr::GfVec3d rotation; rotateOp.Get(&rotation); return UsdUtil::usdToGlmVector(rotation); } else if (rotateOp.GetPrecision() == pxr::UsdGeomXformOp::PrecisionFloat) { pxr::GfVec3f rotation; rotateOp.Get(&rotation); return glm::dvec3(UsdUtil::usdToGlmVector(rotation)); } return glm::dvec3(0.0); } glm::dquat getOrient(const pxr::UsdGeomXformOp& orientOp) { if (orientOp.GetPrecision() == pxr::UsdGeomXformOp::PrecisionDouble) { pxr::GfQuatd orient; orientOp.Get(&orient); return UsdUtil::usdToGlmQuat(orient); } else if (orientOp.GetPrecision() == pxr::UsdGeomXformOp::PrecisionFloat) { pxr::GfQuatf orient; orientOp.Get(&orient); return glm::dquat(UsdUtil::usdToGlmQuat(orient)); } return {1.0, 0.0, 0.0, 0.0}; } glm::dvec3 getScale(const pxr::UsdGeomXformOp& scaleOp) { if (scaleOp.GetPrecision() == pxr::UsdGeomXformOp::PrecisionDouble) { pxr::GfVec3d scale; scaleOp.Get(&scale); return UsdUtil::usdToGlmVector(scale); } else if (scaleOp.GetPrecision() == pxr::UsdGeomXformOp::PrecisionFloat) { pxr::GfVec3f scale; scaleOp.Get(&scale); return glm::dvec3(UsdUtil::usdToGlmVector(scale)); } return glm::dvec3(1.0); } void setTranslate(pxr::UsdGeomXformOp& translateOp, const glm::dvec3& translate) { if (translateOp.GetPrecision() == pxr::UsdGeomXformOp::PrecisionDouble) { translateOp.Set(UsdUtil::glmToUsdVector(translate)); } else if (translateOp.GetPrecision() == pxr::UsdGeomXformOp::PrecisionFloat) { translateOp.Set(UsdUtil::glmToUsdVector(glm::fvec3(translate))); } } void setRotate(pxr::UsdGeomXformOp& rotateOp, const glm::dvec3& rotate) { if (rotateOp.GetPrecision() == pxr::UsdGeomXformOp::PrecisionDouble) { rotateOp.Set(UsdUtil::glmToUsdVector(rotate)); } else if (rotateOp.GetPrecision() == pxr::UsdGeomXformOp::PrecisionFloat) { rotateOp.Set(UsdUtil::glmToUsdVector(glm::fvec3(rotate))); } } void setOrient(pxr::UsdGeomXformOp& orientOp, const glm::dquat& orient) { if (orientOp.GetPrecision() == pxr::UsdGeomXformOp::PrecisionDouble) { orientOp.Set(UsdUtil::glmToUsdQuat(orient)); } else if (orientOp.GetPrecision() == pxr::UsdGeomXformOp::PrecisionFloat) { orientOp.Set(UsdUtil::glmToUsdQuat(glm::fquat(orient))); } } void setScale(pxr::UsdGeomXformOp& scaleOp, const glm::dvec3& scale) { if (scaleOp.GetPrecision() == pxr::UsdGeomXformOp::PrecisionDouble) { scaleOp.Set(UsdUtil::glmToUsdVector(scale)); } else if (scaleOp.GetPrecision() == pxr::UsdGeomXformOp::PrecisionFloat) { scaleOp.Set(UsdUtil::glmToUsdVector(glm::fvec3(scale))); } } std::optional<TranslateRotateScaleOps> getOrCreateTranslateRotateScaleOps(const pxr::UsdGeomXformable& xformable) { pxr::UsdGeomXformOp translateOp; pxr::UsdGeomXformOp rotateOp; pxr::UsdGeomXformOp orientOp; pxr::UsdGeomXformOp scaleOp; int64_t translateOpIndex = -1; int64_t rotateOpIndex = -1; int64_t orientOpIndex = -1; int64_t scaleOpIndex = -1; int64_t opCount = 0; bool resetsXformStack; const auto xformOps = xformable.GetOrderedXformOps(&resetsXformStack); auto eulerAngleOrder = MathUtil::EulerAngleOrder::XYZ; for (const auto& xformOp : xformOps) { switch (xformOp.GetOpType()) { case pxr::UsdGeomXformOp::TypeTranslate: if (translateOpIndex == -1) { translateOp = xformOp; translateOpIndex = opCount; } break; case pxr::UsdGeomXformOp::TypeRotateXYZ: if (rotateOpIndex == -1) { eulerAngleOrder = MathUtil::EulerAngleOrder::XYZ; rotateOp = xformOp; rotateOpIndex = opCount; } break; case pxr::UsdGeomXformOp::TypeRotateXZY: if (rotateOpIndex == -1) { eulerAngleOrder = MathUtil::EulerAngleOrder::XZY; rotateOp = xformOp; rotateOpIndex = opCount; } break; case pxr::UsdGeomXformOp::TypeRotateYXZ: if (rotateOpIndex == -1) { eulerAngleOrder = MathUtil::EulerAngleOrder::YXZ; rotateOp = xformOp; rotateOpIndex = opCount; } break; case pxr::UsdGeomXformOp::TypeRotateYZX: if (rotateOpIndex == -1) { eulerAngleOrder = MathUtil::EulerAngleOrder::YZX; rotateOp = xformOp; rotateOpIndex = opCount; } break; case pxr::UsdGeomXformOp::TypeRotateZXY: if (rotateOpIndex == -1) { eulerAngleOrder = MathUtil::EulerAngleOrder::ZXY; rotateOp = xformOp; rotateOpIndex = opCount; } break; case pxr::UsdGeomXformOp::TypeRotateZYX: if (rotateOpIndex == -1) { eulerAngleOrder = MathUtil::EulerAngleOrder::ZYX; rotateOp = xformOp; rotateOpIndex = opCount; } break; case pxr::UsdGeomXformOp::TypeOrient: if (orientOpIndex == -1) { orientOp = xformOp; orientOpIndex = opCount; } break; case pxr::UsdGeomXformOp::TypeScale: if (scaleOpIndex == -1) { scaleOp = xformOp; scaleOpIndex = opCount; } break; default: break; } ++opCount; } const auto translateOpDefined = translateOp.IsDefined(); const auto rotateOpDefined = rotateOp.IsDefined(); const auto orientOpDefined = orientOp.IsDefined(); const auto scaleOpDefined = scaleOp.IsDefined(); if (rotateOpDefined && orientOpDefined) { return std::nullopt; } opCount = 0; if (translateOpDefined && translateOpIndex != opCount++) { return std::nullopt; } if (rotateOpDefined && rotateOpIndex != opCount++) { return std::nullopt; } if (orientOpDefined && orientOpIndex != opCount++) { return std::nullopt; } if (scaleOpDefined && scaleOpIndex != opCount++) { return std::nullopt; } const auto isPrecisionSupported = [](pxr::UsdGeomXformOp::Precision precision) { return precision == pxr::UsdGeomXformOp::PrecisionDouble || precision == pxr::UsdGeomXformOp::PrecisionFloat; }; if (translateOpDefined && !isPrecisionSupported(translateOp.GetPrecision())) { return std::nullopt; } if (rotateOpDefined && !isPrecisionSupported(rotateOp.GetPrecision())) { return std::nullopt; } if (orientOpDefined && !isPrecisionSupported(orientOp.GetPrecision())) { return std::nullopt; } if (scaleOpDefined && !isPrecisionSupported(scaleOp.GetPrecision())) { return std::nullopt; } if (!translateOpDefined) { translateOp = xformable.AddTranslateOp(pxr::UsdGeomXformOp::PrecisionDouble); translateOp.Set(UsdUtil::glmToUsdVector(glm::dvec3(0.0))); } if (!rotateOpDefined && !orientOpDefined) { rotateOp = xformable.AddRotateXYZOp(pxr::UsdGeomXformOp::PrecisionDouble); rotateOp.Set(UsdUtil::glmToUsdVector(glm::dvec3(0.0))); } if (!scaleOpDefined) { scaleOp = xformable.AddScaleOp(pxr::UsdGeomXformOp::PrecisionDouble); scaleOp.Set(UsdUtil::glmToUsdVector(glm::dvec3(1.0))); } if (!translateOpDefined || (!rotateOpDefined && !orientOpDefined) || !scaleOpDefined) { std::vector<pxr::UsdGeomXformOp> reorderedXformOps; if (orientOpDefined) { reorderedXformOps = {translateOp, orientOp, scaleOp}; } else { reorderedXformOps = {translateOp, rotateOp, scaleOp}; } // Add back additional xform ops like xformOp:rotateX:unitsResolve reorderedXformOps.insert(reorderedXformOps.end(), xformOps.begin() + opCount, xformOps.end()); xformable.SetXformOpOrder(reorderedXformOps); } if (orientOpDefined) { return TranslateRotateScaleOps{translateOp, orientOp, scaleOp, eulerAngleOrder}; } return TranslateRotateScaleOps{translateOp, rotateOp, scaleOp, eulerAngleOrder}; } } // namespace cesium::omniverse::UsdUtil
29,345
C++
33.935714
120
0.684376
CesiumGS/cesium-omniverse/src/core/src/Broadcast.cpp
#include "cesium/omniverse/Broadcast.h" #include <omni/kit/IApp.h> #include <pxr/usd/sdf/path.h> namespace cesium::omniverse::Broadcast { namespace { const std::string_view ASSETS_UPDATED_EVENT_KEY = "cesium.omniverse.ASSETS_UPDATED"; const std::string_view CONNECTION_UPDATED_EVENT_KEY = "cesium.omniverse.CONNECTION_UPDATED"; const std::string_view PROFILE_UPDATED_EVENT_KEY = "cesium.omniverse.PROFILE_UPDATED"; const std::string_view TOKENS_UPDATED_EVENT_KEY = "cesium.omniverse.TOKENS_UPDATED"; const std::string_view SHOW_TROUBLESHOOTER_EVENT_KEY = "cesium.omniverse.SHOW_TROUBLESHOOTER"; const std::string_view SET_DEFAULT_PROJECT_TOKEN_COMPLETE_KEY = "cesium.omniverse.SET_DEFAULT_PROJECT_TOKEN_COMPLETE"; const std::string_view TILESET_LOADED_KEY = "cesium.omniverse.TILESET_LOADED"; template <typename... ValuesT> void sendMessageToBusWithPayload(carb::events::EventType eventType, ValuesT&&... payload) { const auto iApp = carb::getCachedInterface<omni::kit::IApp>(); const auto bus = iApp->getMessageBusEventStream(); bus->push(eventType, std::forward<ValuesT>(payload)...); } template <typename... ValuesT> void sendMessageToBusWithPayload(const std::string_view& eventKey, ValuesT&&... payload) { const auto eventType = carb::events::typeFromString(eventKey.data()); sendMessageToBusWithPayload(eventType, std::forward<ValuesT>(payload)...); } } // namespace void assetsUpdated() { sendMessageToBus(ASSETS_UPDATED_EVENT_KEY); } void connectionUpdated() { sendMessageToBus(CONNECTION_UPDATED_EVENT_KEY); } void profileUpdated() { sendMessageToBus(PROFILE_UPDATED_EVENT_KEY); } void tokensUpdated() { sendMessageToBus(TOKENS_UPDATED_EVENT_KEY); } void showTroubleshooter( const pxr::SdfPath& tilesetPath, int64_t tilesetIonAssetId, const std::string& tilesetName, int64_t rasterOverlayIonAssetId, const std::string& rasterOverlayName, const std::string& message) { sendMessageToBusWithPayload( SHOW_TROUBLESHOOTER_EVENT_KEY, std::make_pair("tilesetPath", tilesetPath.GetText()), std::make_pair("tilesetIonAssetId", tilesetIonAssetId), std::make_pair("tilesetName", tilesetName.c_str()), std::make_pair("rasterOverlayIonAssetId", rasterOverlayIonAssetId), std::make_pair("rasterOverlayName", rasterOverlayName.c_str()), std::make_pair("message", message.c_str())); } void setDefaultTokenComplete() { sendMessageToBus(SET_DEFAULT_PROJECT_TOKEN_COMPLETE_KEY); } void tilesetLoaded(const pxr::SdfPath& tilesetPath) { sendMessageToBusWithPayload(TILESET_LOADED_KEY, std::make_pair("tilesetPath", tilesetPath.GetText())); } void sendMessageToBus(carb::events::EventType eventType) { const auto iApp = carb::getCachedInterface<omni::kit::IApp>(); const auto bus = iApp->getMessageBusEventStream(); bus->push(eventType); } void sendMessageToBus(const std::string_view& eventKey) { const auto eventType = carb::events::typeFromString(eventKey.data()); sendMessageToBus(eventType); } } // namespace cesium::omniverse::Broadcast
3,094
C++
35.411764
118
0.739819
CesiumGS/cesium-omniverse/src/core/src/OmniWebMapServiceRasterOverlay.cpp
#include "cesium/omniverse/OmniWebMapServiceRasterOverlay.h" #include "cesium/omniverse/AssetRegistry.h" #include "cesium/omniverse/Context.h" #include "cesium/omniverse/GltfUtil.h" #include "cesium/omniverse/Logger.h" #include "cesium/omniverse/OmniGeoreference.h" #include "cesium/omniverse/UsdUtil.h" #include <CesiumRasterOverlays/WebMapServiceRasterOverlay.h> #include <CesiumUsdSchemas/webMapServiceRasterOverlay.h> namespace cesium::omniverse { OmniWebMapServiceRasterOverlay::OmniWebMapServiceRasterOverlay(Context* pContext, const pxr::SdfPath& path) : OmniRasterOverlay(pContext, path) { reload(); } CesiumRasterOverlays::RasterOverlay* OmniWebMapServiceRasterOverlay::getRasterOverlay() const { return _pWebMapServiceRasterOverlay.get(); } std::string OmniWebMapServiceRasterOverlay::getBaseUrl() const { const auto cesiumWebMapServiceRasterOverlay = UsdUtil::getCesiumWebMapServiceRasterOverlay(_pContext->getUsdStage(), _path); if (!UsdUtil::isSchemaValid(cesiumWebMapServiceRasterOverlay)) { return ""; } std::string baseUrl; cesiumWebMapServiceRasterOverlay.GetBaseUrlAttr().Get(&baseUrl); return baseUrl; } int OmniWebMapServiceRasterOverlay::getMinimumLevel() const { const auto cesiumWebMapServiceRasterOverlay = UsdUtil::getCesiumWebMapServiceRasterOverlay(_pContext->getUsdStage(), _path); if (!UsdUtil::isSchemaValid(cesiumWebMapServiceRasterOverlay)) { return 0; } int minimumLevel; cesiumWebMapServiceRasterOverlay.GetMinimumLevelAttr().Get(&minimumLevel); return minimumLevel; } int OmniWebMapServiceRasterOverlay::getMaximumLevel() const { const auto cesiumWebMapServiceRasterOverlay = UsdUtil::getCesiumWebMapServiceRasterOverlay(_pContext->getUsdStage(), _path); if (!UsdUtil::isSchemaValid(cesiumWebMapServiceRasterOverlay)) { return 14; } int maximumLevel; cesiumWebMapServiceRasterOverlay.GetMaximumLevelAttr().Get(&maximumLevel); return maximumLevel; } int OmniWebMapServiceRasterOverlay::getTileWidth() const { const auto cesiumWebMapServiceRasterOverlay = UsdUtil::getCesiumWebMapServiceRasterOverlay(_pContext->getUsdStage(), _path); if (!UsdUtil::isSchemaValid(cesiumWebMapServiceRasterOverlay)) { return 256; } int tileWidth; cesiumWebMapServiceRasterOverlay.GetTileWidthAttr().Get(&tileWidth); return tileWidth; } int OmniWebMapServiceRasterOverlay::getTileHeight() const { const auto cesiumWebMapServiceRasterOverlay = UsdUtil::getCesiumWebMapServiceRasterOverlay(_pContext->getUsdStage(), _path); if (!UsdUtil::isSchemaValid(cesiumWebMapServiceRasterOverlay)) { return 256; } int tileHeight; cesiumWebMapServiceRasterOverlay.GetTileHeightAttr().Get(&tileHeight); return tileHeight; } std::string OmniWebMapServiceRasterOverlay::getLayers() const { const auto cesiumWebMapServiceRasterOverlay = UsdUtil::getCesiumWebMapServiceRasterOverlay(_pContext->getUsdStage(), _path); if (!UsdUtil::isSchemaValid(cesiumWebMapServiceRasterOverlay)) { return "1"; } std::string layers; cesiumWebMapServiceRasterOverlay.GetLayersAttr().Get(&layers); return layers; } void OmniWebMapServiceRasterOverlay::reload() { const auto rasterOverlayName = UsdUtil::getName(_pContext->getUsdStage(), _path); auto options = createRasterOverlayOptions(); options.loadErrorCallback = [this](const CesiumRasterOverlays::RasterOverlayLoadFailureDetails& error) { _pContext->getLogger()->error(error.message); }; CesiumRasterOverlays::WebMapServiceRasterOverlayOptions wmsOptions; const auto minimumLevel = getMinimumLevel(); const auto maximumLevel = getMaximumLevel(); const auto tileWidth = getTileWidth(); const auto tileHeight = getTileHeight(); std::string layers = getLayers(); wmsOptions.minimumLevel = minimumLevel; wmsOptions.maximumLevel = maximumLevel; wmsOptions.layers = layers; wmsOptions.tileWidth = tileWidth; wmsOptions.tileHeight = tileHeight; _pWebMapServiceRasterOverlay = new CesiumRasterOverlays::WebMapServiceRasterOverlay( rasterOverlayName, getBaseUrl(), std::vector<CesiumAsync::IAssetAccessor::THeader>(), wmsOptions, options); } } // namespace cesium::omniverse
4,354
C++
34.406504
115
0.758842
CesiumGS/cesium-omniverse/src/core/src/OmniPolygonRasterOverlay.cpp
#include "cesium/omniverse/OmniPolygonRasterOverlay.h" #include "cesium/omniverse/AssetRegistry.h" #include "cesium/omniverse/Context.h" #include "cesium/omniverse/GltfUtil.h" #include "cesium/omniverse/Logger.h" #include "cesium/omniverse/OmniCartographicPolygon.h" #include "cesium/omniverse/OmniGeoreference.h" #include "cesium/omniverse/OmniGlobeAnchor.h" #include "cesium/omniverse/UsdUtil.h" #include <CesiumGeospatial/Ellipsoid.h> #include <CesiumRasterOverlays/RasterizedPolygonsOverlay.h> #include <CesiumUsdSchemas/polygonRasterOverlay.h> namespace cesium::omniverse { OmniPolygonRasterOverlay::OmniPolygonRasterOverlay(Context* pContext, const pxr::SdfPath& path) : OmniRasterOverlay(pContext, path) {} std::vector<pxr::SdfPath> OmniPolygonRasterOverlay::getCartographicPolygonPaths() const { const auto cesiumPolygonRasterOverlay = UsdUtil::getCesiumPolygonRasterOverlay(_pContext->getUsdStage(), _path); if (!UsdUtil::isSchemaValid(cesiumPolygonRasterOverlay)) { return {}; } pxr::SdfPathVector targets; cesiumPolygonRasterOverlay.GetCartographicPolygonBindingRel().GetForwardedTargets(&targets); return targets; } CesiumRasterOverlays::RasterOverlay* OmniPolygonRasterOverlay::getRasterOverlay() const { return _pPolygonRasterOverlay.get(); } bool OmniPolygonRasterOverlay::getInvertSelection() const { const auto cesiumPolygonRasterOverlay = UsdUtil::getCesiumPolygonRasterOverlay(_pContext->getUsdStage(), _path); if (!UsdUtil::isSchemaValid(cesiumPolygonRasterOverlay)) { return false; } bool invertSelection; cesiumPolygonRasterOverlay.GetInvertSelectionAttr().Get(&invertSelection); return invertSelection; } bool OmniPolygonRasterOverlay::getExcludeSelectedTiles() const { auto cesiumPolygonRasterOverlay = UsdUtil::getCesiumPolygonRasterOverlay(_pContext->getUsdStage(), _path); bool val; cesiumPolygonRasterOverlay.GetExcludeSelectedTilesAttr().Get(&val); return val; } std::shared_ptr<Cesium3DTilesSelection::RasterizedPolygonsTileExcluder> OmniPolygonRasterOverlay::getExcluder() { return _pExcluder; } void OmniPolygonRasterOverlay::reload() { const auto rasterOverlayName = UsdUtil::getName(_pContext->getUsdStage(), _path); const auto cartographicPolygonPaths = getCartographicPolygonPaths(); std::vector<CesiumGeospatial::CartographicPolygon> polygons; const CesiumGeospatial::Ellipsoid* pEllipsoid = nullptr; for (const auto& cartographicPolygonPath : cartographicPolygonPaths) { const auto pCartographicPolygon = _pContext->getAssetRegistry().getCartographicPolygon(cartographicPolygonPath); if (!pCartographicPolygon) { continue; } const auto pGlobeAnchor = _pContext->getAssetRegistry().getGlobeAnchor(cartographicPolygonPath); if (!pGlobeAnchor) { continue; } const auto georeferencePath = pGlobeAnchor->getResolvedGeoreferencePath(); if (georeferencePath.IsEmpty()) { continue; } const auto pGeoreference = _pContext->getAssetRegistry().getGeoreference(georeferencePath); if (!pGeoreference) { continue; } const auto& ellipsoid = pGeoreference->getEllipsoid(); if (!pEllipsoid) { pEllipsoid = &ellipsoid; } else if (*pEllipsoid != ellipsoid) { return; // All cartographic polygons must use the same ellipsoid } const auto cartographics = pCartographicPolygon->getCartographics(); std::vector<glm::dvec2> polygon; for (const auto& cartographic : cartographics) { polygon.emplace_back(cartographic.longitude, cartographic.latitude); } polygons.emplace_back(polygon); } if (polygons.empty()) { return; } if (!pEllipsoid) { return; } const auto projection = CesiumGeospatial::GeographicProjection(*pEllipsoid); auto options = createRasterOverlayOptions(); options.loadErrorCallback = [this](const CesiumRasterOverlays::RasterOverlayLoadFailureDetails& error) { _pContext->getLogger()->error(error.message); }; _pPolygonRasterOverlay = new CesiumRasterOverlays::RasterizedPolygonsOverlay( rasterOverlayName, polygons, getInvertSelection(), *pEllipsoid, projection, options); if (getExcludeSelectedTiles()) { auto pPolygons = _pPolygonRasterOverlay.get(); _pExcluder = std::make_shared<Cesium3DTilesSelection::RasterizedPolygonsTileExcluder>(pPolygons); } } } // namespace cesium::omniverse
4,610
C++
34.198473
120
0.7282
CesiumGS/cesium-omniverse/src/core/src/AssetRegistry.cpp
#include "cesium/omniverse/AssetRegistry.h" #include "cesium/omniverse/Context.h" #include "cesium/omniverse/CppUtil.h" #include "cesium/omniverse/OmniCartographicPolygon.h" #include "cesium/omniverse/OmniData.h" #include "cesium/omniverse/OmniGeoreference.h" #include "cesium/omniverse/OmniGlobeAnchor.h" #include "cesium/omniverse/OmniIonRasterOverlay.h" #include "cesium/omniverse/OmniIonServer.h" #include "cesium/omniverse/OmniPolygonRasterOverlay.h" #include "cesium/omniverse/OmniTileMapServiceRasterOverlay.h" #include "cesium/omniverse/OmniTileset.h" #include "cesium/omniverse/OmniWebMapServiceRasterOverlay.h" #include "cesium/omniverse/OmniWebMapTileServiceRasterOverlay.h" #include "cesium/omniverse/UsdUtil.h" #include "cesium/omniverse/Viewport.h" namespace cesium::omniverse { AssetRegistry::AssetRegistry(Context* pContext) : _pContext(pContext) {} AssetRegistry::~AssetRegistry() = default; void AssetRegistry::onUpdateFrame(const gsl::span<const Viewport>& viewports, bool waitForLoadingTiles) { for (const auto& pTileset : _tilesets) { pTileset->onUpdateFrame(viewports, waitForLoadingTiles); } } OmniData& AssetRegistry::addData(const pxr::SdfPath& path) { return *_datas.insert(_datas.end(), std::make_unique<OmniData>(_pContext, path))->get(); } void AssetRegistry::removeData(const pxr::SdfPath& path) { CppUtil::eraseIf(_datas, [&path](const auto& pData) { return pData->getPath() == path; }); } OmniData* AssetRegistry::getData(const pxr::SdfPath& path) const { for (const auto& pData : _datas) { if (pData->getPath() == path) { return pData.get(); } } return nullptr; } OmniData* AssetRegistry::getFirstData() const { if (_datas.empty()) { return nullptr; } return _datas.front().get(); } OmniTileset& AssetRegistry::addTileset(const pxr::SdfPath& path) { return *_tilesets.insert(_tilesets.end(), std::make_unique<OmniTileset>(_pContext, path, _tilesetId++))->get(); } void AssetRegistry::removeTileset(const pxr::SdfPath& path) { CppUtil::eraseIf(_tilesets, [&path](const auto& pTileset) { return pTileset->getPath() == path; }); } OmniTileset* AssetRegistry::getTileset(const pxr::SdfPath& path) const { for (const auto& pTileset : _tilesets) { if (pTileset->getPath() == path) { return pTileset.get(); } } return nullptr; } const std::vector<std::unique_ptr<OmniTileset>>& AssetRegistry::getTilesets() const { return _tilesets; } OmniIonRasterOverlay& AssetRegistry::addIonRasterOverlay(const pxr::SdfPath& path) { return *_ionRasterOverlays .insert(_ionRasterOverlays.end(), std::make_unique<OmniIonRasterOverlay>(_pContext, path)) ->get(); } void AssetRegistry::removeIonRasterOverlay(const pxr::SdfPath& path) { CppUtil::eraseIf( _ionRasterOverlays, [&path](const auto& pIonRasterOverlay) { return pIonRasterOverlay->getPath() == path; }); } OmniIonRasterOverlay* AssetRegistry::getIonRasterOverlay(const pxr::SdfPath& path) const { for (const auto& pIonRasterOverlay : _ionRasterOverlays) { if (pIonRasterOverlay->getPath() == path) { return pIonRasterOverlay.get(); } } return nullptr; } OmniIonRasterOverlay* AssetRegistry::getIonRasterOverlayByIonAssetId(int64_t ionAssetId) const { for (const auto& pIonRasterOverlay : _ionRasterOverlays) { if (pIonRasterOverlay->getIonAssetId() == ionAssetId) { return pIonRasterOverlay.get(); } } return nullptr; } const std::vector<std::unique_ptr<OmniIonRasterOverlay>>& AssetRegistry::getIonRasterOverlays() const { return _ionRasterOverlays; } OmniPolygonRasterOverlay& AssetRegistry::addPolygonRasterOverlay(const pxr::SdfPath& path) { return *_polygonRasterOverlays .insert(_polygonRasterOverlays.end(), std::make_unique<OmniPolygonRasterOverlay>(_pContext, path)) ->get(); } void AssetRegistry::removePolygonRasterOverlay(const pxr::SdfPath& path) { CppUtil::eraseIf(_polygonRasterOverlays, [&path](const auto& pPolygonRasterOverlay) { return pPolygonRasterOverlay->getPath() == path; }); } OmniPolygonRasterOverlay* AssetRegistry::getPolygonRasterOverlay(const pxr::SdfPath& path) const { for (const auto& pPolygonRasterOverlay : _polygonRasterOverlays) { if (pPolygonRasterOverlay->getPath() == path) { return pPolygonRasterOverlay.get(); } } return nullptr; } OmniWebMapServiceRasterOverlay& AssetRegistry::addWebMapServiceRasterOverlay(const pxr::SdfPath& path) { return *_webMapServiceRasterOverlays .insert( _webMapServiceRasterOverlays.end(), std::make_unique<OmniWebMapServiceRasterOverlay>(_pContext, path)) ->get(); } void AssetRegistry::removeWebMapServiceRasterOverlay(const pxr::SdfPath& path) { CppUtil::eraseIf(_webMapServiceRasterOverlays, [&path](const auto& pWebMapServiceRasterOverlay) { return pWebMapServiceRasterOverlay->getPath() == path; }); } OmniWebMapServiceRasterOverlay* AssetRegistry::getWebMapServiceRasterOverlay(const pxr::SdfPath& path) const { for (const auto& pWebMapServiceRasterOverlay : _webMapServiceRasterOverlays) { if (pWebMapServiceRasterOverlay->getPath() == path) { return pWebMapServiceRasterOverlay.get(); } } return nullptr; } OmniTileMapServiceRasterOverlay& AssetRegistry::addTileMapServiceRasterOverlay(const pxr::SdfPath& path) { return *_tileMapServiceRasterOverlays .insert( _tileMapServiceRasterOverlays.end(), std::make_unique<OmniTileMapServiceRasterOverlay>(_pContext, path)) ->get(); } void AssetRegistry::removeTileMapServiceRasterOverlay(const pxr::SdfPath& path) { CppUtil::eraseIf(_tileMapServiceRasterOverlays, [&path](const auto& pTileMapServiceRasterOverlay) { return pTileMapServiceRasterOverlay->getPath() == path; }); } OmniTileMapServiceRasterOverlay* AssetRegistry::getTileMapServiceRasterOverlay(const pxr::SdfPath& path) const { for (const auto& pTileMapServiceRasterOverlay : _tileMapServiceRasterOverlays) { if (pTileMapServiceRasterOverlay->getPath() == path) { return pTileMapServiceRasterOverlay.get(); } } return nullptr; } OmniWebMapTileServiceRasterOverlay& AssetRegistry::addWebMapTileServiceRasterOverlay(const pxr::SdfPath& path) { return *_webMapTileServiceRasterOverlays .insert( _webMapTileServiceRasterOverlays.end(), std::make_unique<OmniWebMapTileServiceRasterOverlay>(_pContext, path)) ->get(); } void AssetRegistry::removeWebMapTileServiceRasterOverlay(const pxr::SdfPath& path) { CppUtil::eraseIf(_webMapTileServiceRasterOverlays, [&path](const auto& pWebMapTileServiceRasterOverlay) { return pWebMapTileServiceRasterOverlay->getPath() == path; }); } OmniWebMapTileServiceRasterOverlay* AssetRegistry::getWebMapTileServiceRasterOverlay(const pxr::SdfPath& path) const { for (const auto& pWebMapTileServiceRasterOverlay : _webMapTileServiceRasterOverlays) { if (pWebMapTileServiceRasterOverlay->getPath() == path) { return pWebMapTileServiceRasterOverlay.get(); } } return nullptr; } const std::vector<std::unique_ptr<OmniPolygonRasterOverlay>>& AssetRegistry::getPolygonRasterOverlays() const { return _polygonRasterOverlays; } OmniRasterOverlay* AssetRegistry::getRasterOverlay(const pxr::SdfPath& path) const { const auto pIonRasterOverlay = getIonRasterOverlay(path); if (pIonRasterOverlay) { return pIonRasterOverlay; } const auto pPolygonRasterOverlay = getPolygonRasterOverlay(path); if (pPolygonRasterOverlay) { return pPolygonRasterOverlay; } const auto pWebMapServiceRasterOverlay = getWebMapServiceRasterOverlay(path); if (pWebMapServiceRasterOverlay) { return pWebMapServiceRasterOverlay; } const auto pTileMapServiceRasterOverlay = getTileMapServiceRasterOverlay(path); if (pTileMapServiceRasterOverlay) { return pTileMapServiceRasterOverlay; } const auto pWebMapTileServiceRasterOverlay = getWebMapTileServiceRasterOverlay(path); if (pWebMapTileServiceRasterOverlay) { return pWebMapTileServiceRasterOverlay; } return nullptr; } OmniGeoreference& AssetRegistry::addGeoreference(const pxr::SdfPath& path) { return *_georeferences.insert(_georeferences.end(), std::make_unique<OmniGeoreference>(_pContext, path))->get(); } void AssetRegistry::removeGeoreference(const pxr::SdfPath& path) { CppUtil::eraseIf(_georeferences, [&path](const auto& pGeoreference) { return pGeoreference->getPath() == path; }); } OmniGeoreference* AssetRegistry::getGeoreference(const pxr::SdfPath& path) const { for (const auto& pGeoreference : _georeferences) { if (pGeoreference->getPath() == path) { return pGeoreference.get(); } } return nullptr; } const std::vector<std::unique_ptr<OmniGeoreference>>& AssetRegistry::getGeoreferences() const { return _georeferences; } OmniGeoreference* AssetRegistry::getFirstGeoreference() const { if (_georeferences.empty()) { return nullptr; } return _georeferences.front().get(); } OmniGlobeAnchor& AssetRegistry::addGlobeAnchor(const pxr::SdfPath& path) { return *_globeAnchors.insert(_globeAnchors.end(), std::make_unique<OmniGlobeAnchor>(_pContext, path))->get(); } void AssetRegistry::removeGlobeAnchor(const pxr::SdfPath& path) { CppUtil::eraseIf(_globeAnchors, [&path](const auto& pGlobeAnchor) { return pGlobeAnchor->getPath() == path; }); } OmniGlobeAnchor* AssetRegistry::getGlobeAnchor(const pxr::SdfPath& path) const { for (const auto& pGlobeAnchor : _globeAnchors) { if (pGlobeAnchor->getPath() == path) { return pGlobeAnchor.get(); } } return nullptr; } const std::vector<std::unique_ptr<OmniGlobeAnchor>>& AssetRegistry::getGlobeAnchors() const { return _globeAnchors; } OmniIonServer& AssetRegistry::addIonServer(const pxr::SdfPath& path) { return *_ionServers.insert(_ionServers.end(), std::make_unique<OmniIonServer>(_pContext, path))->get(); } void AssetRegistry::removeIonServer(const pxr::SdfPath& path) { CppUtil::eraseIf(_ionServers, [&path](const auto& pIonServer) { return pIonServer->getPath() == path; }); } OmniIonServer* AssetRegistry::getIonServer(const pxr::SdfPath& path) const { for (const auto& pIonServer : _ionServers) { if (pIonServer->getPath() == path) { return pIonServer.get(); } } return nullptr; } const std::vector<std::unique_ptr<OmniIonServer>>& AssetRegistry::getIonServers() const { return _ionServers; } OmniIonServer* AssetRegistry::getFirstIonServer() const { if (_ionServers.empty()) { return nullptr; } return _ionServers.front().get(); } OmniCartographicPolygon& AssetRegistry::addCartographicPolygon(const pxr::SdfPath& path) { return *_cartographicPolygons .insert(_cartographicPolygons.end(), std::make_unique<OmniCartographicPolygon>(_pContext, path)) ->get(); } void AssetRegistry::removeCartographicPolygon(const pxr::SdfPath& path) { CppUtil::eraseIf(_cartographicPolygons, [&path](const auto& pCartographicPolygon) { return pCartographicPolygon->getPath() == path; }); } OmniCartographicPolygon* AssetRegistry::getCartographicPolygon(const pxr::SdfPath& path) const { for (const auto& pCartographicPolygon : _cartographicPolygons) { if (pCartographicPolygon->getPath() == path) { return pCartographicPolygon.get(); } } return nullptr; } const std::vector<std::unique_ptr<OmniCartographicPolygon>>& AssetRegistry::getCartographicPolygons() const { return _cartographicPolygons; } AssetType AssetRegistry::getAssetType(const pxr::SdfPath& path) const { if (getData(path)) { return AssetType::DATA; } else if (getTileset(path)) { return AssetType::TILESET; } else if (getIonRasterOverlay(path)) { return AssetType::ION_RASTER_OVERLAY; } else if (getPolygonRasterOverlay(path)) { return AssetType::POLYGON_RASTER_OVERLAY; } else if (getGeoreference(path)) { return AssetType::GEOREFERENCE; } else if (getIonServer(path)) { return AssetType::ION_SERVER; } else if (getCartographicPolygon(path)) { return AssetType::CARTOGRAPHIC_POLYGON; } else if (getGlobeAnchor(path)) { // Globe anchor needs to be checked last since prim types take precedence over API schemas return AssetType::GLOBE_ANCHOR; } else { return AssetType::OTHER; } } bool AssetRegistry::hasAsset(const pxr::SdfPath& path) const { return getAssetType(path) != AssetType::OTHER; } void AssetRegistry::clear() { _datas.clear(); _tilesets.clear(); _ionRasterOverlays.clear(); _polygonRasterOverlays.clear(); _georeferences.clear(); _globeAnchors.clear(); _ionServers.clear(); _cartographicPolygons.clear(); } } // namespace cesium::omniverse
13,357
C++
33.427835
118
0.701954
CesiumGS/cesium-omniverse/src/core/src/OmniWebMapTileServiceRasterOverlay.cpp
#include "cesium/omniverse/OmniWebMapTileServiceRasterOverlay.h" #include "cesium/omniverse/AssetRegistry.h" #include "cesium/omniverse/Context.h" #include "cesium/omniverse/GltfUtil.h" #include "cesium/omniverse/Logger.h" #include "cesium/omniverse/OmniGeoreference.h" #include "cesium/omniverse/UsdUtil.h" #include <CesiumRasterOverlays/WebMapTileServiceRasterOverlay.h> #include <CesiumUsdSchemas/webMapTileServiceRasterOverlay.h> #include <string> namespace cesium::omniverse { OmniWebMapTileServiceRasterOverlay::OmniWebMapTileServiceRasterOverlay(Context* pContext, const pxr::SdfPath& path) : OmniRasterOverlay(pContext, path) { reload(); } CesiumRasterOverlays::RasterOverlay* OmniWebMapTileServiceRasterOverlay::getRasterOverlay() const { return _pWebMapTileServiceRasterOverlay.get(); } std::string OmniWebMapTileServiceRasterOverlay::getUrl() const { const auto cesiumWebMapTileServiceRasterOverlay = UsdUtil::getCesiumWebMapTileServiceRasterOverlay(_pContext->getUsdStage(), _path); if (!UsdUtil::isSchemaValid(cesiumWebMapTileServiceRasterOverlay)) { return ""; } std::string url; cesiumWebMapTileServiceRasterOverlay.GetUrlAttr().Get(&url); return url; } std::string OmniWebMapTileServiceRasterOverlay::getLayer() const { const auto cesiumWebMapTileServiceRasterOverlay = UsdUtil::getCesiumWebMapTileServiceRasterOverlay(_pContext->getUsdStage(), _path); if (!UsdUtil::isSchemaValid(cesiumWebMapTileServiceRasterOverlay)) { return ""; } std::string layer; cesiumWebMapTileServiceRasterOverlay.GetLayerAttr().Get(&layer); return layer; } std::string OmniWebMapTileServiceRasterOverlay::getTileMatrixSetId() const { const auto cesiumWebMapTileServiceRasterOverlay = UsdUtil::getCesiumWebMapTileServiceRasterOverlay(_pContext->getUsdStage(), _path); if (!UsdUtil::isSchemaValid(cesiumWebMapTileServiceRasterOverlay)) { return ""; } std::string val; cesiumWebMapTileServiceRasterOverlay.GetTileMatrixSetIdAttr().Get(&val); return val; } std::string OmniWebMapTileServiceRasterOverlay::getStyle() const { const auto cesiumWebMapTileServiceRasterOverlay = UsdUtil::getCesiumWebMapTileServiceRasterOverlay(_pContext->getUsdStage(), _path); if (!UsdUtil::isSchemaValid(cesiumWebMapTileServiceRasterOverlay)) { return ""; } std::string val; cesiumWebMapTileServiceRasterOverlay.GetStyleAttr().Get(&val); return val; } std::string OmniWebMapTileServiceRasterOverlay::getFormat() const { const auto cesiumWebMapTileServiceRasterOverlay = UsdUtil::getCesiumWebMapTileServiceRasterOverlay(_pContext->getUsdStage(), _path); if (!UsdUtil::isSchemaValid(cesiumWebMapTileServiceRasterOverlay)) { return ""; } std::string val; cesiumWebMapTileServiceRasterOverlay.GetFormatAttr().Get(&val); return val; } int OmniWebMapTileServiceRasterOverlay::getMinimumZoomLevel() const { const auto cesiumWebMapTileServiceRasterOverlay = UsdUtil::getCesiumWebMapTileServiceRasterOverlay(_pContext->getUsdStage(), _path); if (!UsdUtil::isSchemaValid(cesiumWebMapTileServiceRasterOverlay)) { return 0; } int val; cesiumWebMapTileServiceRasterOverlay.GetMinimumZoomLevelAttr().Get(&val); return val; } int OmniWebMapTileServiceRasterOverlay::getMaximumZoomLevel() const { const auto cesiumWebMapTileServiceRasterOverlay = UsdUtil::getCesiumWebMapTileServiceRasterOverlay(_pContext->getUsdStage(), _path); if (!UsdUtil::isSchemaValid(cesiumWebMapTileServiceRasterOverlay)) { return 0; } int val; cesiumWebMapTileServiceRasterOverlay.GetMaximumZoomLevelAttr().Get(&val); return val; } bool OmniWebMapTileServiceRasterOverlay::getSpecifyZoomLevels() const { const auto cesiumWebMapTileServiceRasterOverlay = UsdUtil::getCesiumWebMapTileServiceRasterOverlay(_pContext->getUsdStage(), _path); if (!UsdUtil::isSchemaValid(cesiumWebMapTileServiceRasterOverlay)) { return false; } bool val; cesiumWebMapTileServiceRasterOverlay.GetSpecifyZoomLevelsAttr().Get(&val); return val; } bool OmniWebMapTileServiceRasterOverlay::getUseWebMercatorProjection() const { const auto cesiumWebMapTileServiceRasterOverlay = UsdUtil::getCesiumWebMapTileServiceRasterOverlay(_pContext->getUsdStage(), _path); if (!UsdUtil::isSchemaValid(cesiumWebMapTileServiceRasterOverlay)) { return false; } bool val; cesiumWebMapTileServiceRasterOverlay.GetUseWebMercatorProjectionAttr().Get(&val); return val; } bool OmniWebMapTileServiceRasterOverlay::getSpecifyTilingScheme() const { const auto cesiumWebMapTileServiceRasterOverlay = UsdUtil::getCesiumWebMapTileServiceRasterOverlay(_pContext->getUsdStage(), _path); if (!UsdUtil::isSchemaValid(cesiumWebMapTileServiceRasterOverlay)) { return false; } bool val; cesiumWebMapTileServiceRasterOverlay.GetSpecifyTilingSchemeAttr().Get(&val); return val; } double OmniWebMapTileServiceRasterOverlay::getNorth() const { const auto cesiumWebMapTileServiceRasterOverlay = UsdUtil::getCesiumWebMapTileServiceRasterOverlay(_pContext->getUsdStage(), _path); if (!UsdUtil::isSchemaValid(cesiumWebMapTileServiceRasterOverlay)) { return 90; } double val; cesiumWebMapTileServiceRasterOverlay.GetNorthAttr().Get(&val); return val; } double OmniWebMapTileServiceRasterOverlay::getSouth() const { const auto cesiumWebMapTileServiceRasterOverlay = UsdUtil::getCesiumWebMapTileServiceRasterOverlay(_pContext->getUsdStage(), _path); if (!UsdUtil::isSchemaValid(cesiumWebMapTileServiceRasterOverlay)) { return -90; } double val; cesiumWebMapTileServiceRasterOverlay.GetSouthAttr().Get(&val); return val; } double OmniWebMapTileServiceRasterOverlay::getEast() const { const auto cesiumWebMapTileServiceRasterOverlay = UsdUtil::getCesiumWebMapTileServiceRasterOverlay(_pContext->getUsdStage(), _path); if (!UsdUtil::isSchemaValid(cesiumWebMapTileServiceRasterOverlay)) { return 180; } double val; cesiumWebMapTileServiceRasterOverlay.GetEastAttr().Get(&val); return val; } double OmniWebMapTileServiceRasterOverlay::getWest() const { const auto cesiumWebMapTileServiceRasterOverlay = UsdUtil::getCesiumWebMapTileServiceRasterOverlay(_pContext->getUsdStage(), _path); if (!UsdUtil::isSchemaValid(cesiumWebMapTileServiceRasterOverlay)) { return -180; } double val; cesiumWebMapTileServiceRasterOverlay.GetWestAttr().Get(&val); return val; } bool OmniWebMapTileServiceRasterOverlay::getSpecifyTileMatrixSetLabels() const { const auto cesiumWebMapTileServiceRasterOverlay = UsdUtil::getCesiumWebMapTileServiceRasterOverlay(_pContext->getUsdStage(), _path); if (!UsdUtil::isSchemaValid(cesiumWebMapTileServiceRasterOverlay)) { return false; } bool val; cesiumWebMapTileServiceRasterOverlay.GetSpecifyTileMatrixSetLabelsAttr().Get(&val); return val; } std::vector<std::string> OmniWebMapTileServiceRasterOverlay::getTileMatrixSetLabels() const { const auto cesiumWebMapTileServiceRasterOverlay = UsdUtil::getCesiumWebMapTileServiceRasterOverlay(_pContext->getUsdStage(), _path); if (!UsdUtil::isSchemaValid(cesiumWebMapTileServiceRasterOverlay)) { return {}; } std::string val; cesiumWebMapTileServiceRasterOverlay.GetTileMatrixSetLabelsAttr().Get(&val); std::vector<std::string> matrixSetLabels; size_t pos = 0; while ((pos = val.find(',')) != std::string::npos) { matrixSetLabels.push_back(val.substr(0, pos)); val.erase(0, pos + 1); } matrixSetLabels.push_back(val); return matrixSetLabels; } std::string OmniWebMapTileServiceRasterOverlay::getTileMatrixSetLabelPrefix() const { const auto cesiumWebMapTileServiceRasterOverlay = UsdUtil::getCesiumWebMapTileServiceRasterOverlay(_pContext->getUsdStage(), _path); if (!UsdUtil::isSchemaValid(cesiumWebMapTileServiceRasterOverlay)) { return ""; } std::string val; cesiumWebMapTileServiceRasterOverlay.GetTileMatrixSetLabelPrefixAttr().Get(&val); return val; } int OmniWebMapTileServiceRasterOverlay::getRootTilesX() const { const auto cesiumWebMapTileServiceRasterOverlay = UsdUtil::getCesiumWebMapTileServiceRasterOverlay(_pContext->getUsdStage(), _path); if (!UsdUtil::isSchemaValid(cesiumWebMapTileServiceRasterOverlay)) { return 1; } int val; cesiumWebMapTileServiceRasterOverlay.GetRootTilesXAttr().Get(&val); return val; } int OmniWebMapTileServiceRasterOverlay::getRootTilesY() const { const auto cesiumWebMapTileServiceRasterOverlay = UsdUtil::getCesiumWebMapTileServiceRasterOverlay(_pContext->getUsdStage(), _path); if (!UsdUtil::isSchemaValid(cesiumWebMapTileServiceRasterOverlay)) { return 1; } int val; cesiumWebMapTileServiceRasterOverlay.GetRootTilesYAttr().Get(&val); return val; } void OmniWebMapTileServiceRasterOverlay::reload() { const auto rasterOverlayName = UsdUtil::getName(_pContext->getUsdStage(), _path); auto options = createRasterOverlayOptions(); options.loadErrorCallback = [this](const CesiumRasterOverlays::RasterOverlayLoadFailureDetails& error) { _pContext->getLogger()->error(error.message); }; CesiumRasterOverlays::WebMapTileServiceRasterOverlayOptions wmtsOptions; const auto tileMatrixSetId = getTileMatrixSetId(); if (!tileMatrixSetId.empty()) { wmtsOptions.tileMatrixSetID = tileMatrixSetId; } const auto style = getStyle(); if (!style.empty()) { wmtsOptions.style = style; } const auto layer = getLayer(); if (!layer.empty()) { wmtsOptions.layer = layer; } const auto format = getFormat(); if (!format.empty()) { wmtsOptions.format = format; } if (getSpecifyZoomLevels()) { wmtsOptions.minimumLevel = getMinimumZoomLevel(); wmtsOptions.maximumLevel = getMaximumZoomLevel(); } CesiumGeospatial::Projection projection; const auto useWebMercatorProjection = getUseWebMercatorProjection(); if (useWebMercatorProjection) { projection = CesiumGeospatial::WebMercatorProjection(); wmtsOptions.projection = projection; } else { projection = CesiumGeospatial::GeographicProjection(); wmtsOptions.projection = projection; } if (getSpecifyTilingScheme()) { CesiumGeospatial::GlobeRectangle globeRectangle = CesiumGeospatial::GlobeRectangle::fromDegrees(getWest(), getSouth(), getEast(), getNorth()); CesiumGeometry::Rectangle coverageRectangle = CesiumGeospatial::projectRectangleSimple(projection, globeRectangle); wmtsOptions.coverageRectangle = coverageRectangle; const auto rootTilesX = getRootTilesX(); const auto rootTilesY = getRootTilesY(); wmtsOptions.tilingScheme = CesiumGeometry::QuadtreeTilingScheme(coverageRectangle, rootTilesX, rootTilesY); } if (getSpecifyTileMatrixSetLabels()) { const auto tileMatrixSetLabels = getTileMatrixSetLabels(); if (!tileMatrixSetLabels.empty()) { wmtsOptions.tileMatrixLabels = getTileMatrixSetLabels(); } } else { const auto tileMatrixSetLabelPrefix = getTileMatrixSetLabelPrefix(); if (!tileMatrixSetLabelPrefix.empty()) { std::vector<std::string> labels; for (size_t level = 0; level <= 25; ++level) { std::string label{tileMatrixSetLabelPrefix}; label.append(std::to_string(level)); labels.emplace_back(label); } wmtsOptions.tileMatrixLabels = labels; } } _pWebMapTileServiceRasterOverlay = new CesiumRasterOverlays::WebMapTileServiceRasterOverlay( rasterOverlayName, getUrl(), std::vector<CesiumAsync::IAssetAccessor::THeader>(), wmtsOptions, options); } } // namespace cesium::omniverse
12,199
C++
34.672515
115
0.734404
CesiumGS/cesium-omniverse/src/core/src/OmniData.cpp
#include "cesium/omniverse/OmniData.h" #include "cesium/omniverse/Context.h" #include "cesium/omniverse/UsdUtil.h" #include <CesiumUsdSchemas/data.h> namespace cesium::omniverse { OmniData::OmniData(Context* pContext, const pxr::SdfPath& path) : _pContext(pContext) , _path(path) {} const pxr::SdfPath& OmniData::getPath() const { return _path; } pxr::SdfPath OmniData::getSelectedIonServerPath() const { const auto cesiumData = UsdUtil::getCesiumData(_pContext->getUsdStage(), _path); if (!UsdUtil::isSchemaValid(cesiumData)) { return {}; } pxr::SdfPathVector targets; cesiumData.GetSelectedIonServerRel().GetForwardedTargets(&targets); if (targets.empty()) { return {}; } return targets.front(); } bool OmniData::getDebugDisableMaterials() const { const auto cesiumData = UsdUtil::getCesiumData(_pContext->getUsdStage(), _path); if (!UsdUtil::isSchemaValid(cesiumData)) { return false; } bool disableMaterials; cesiumData.GetDebugDisableMaterialsAttr().Get(&disableMaterials); return disableMaterials; } bool OmniData::getDebugDisableTextures() const { const auto cesiumData = UsdUtil::getCesiumData(_pContext->getUsdStage(), _path); if (!UsdUtil::isSchemaValid(cesiumData)) { return false; } bool disableTextures; cesiumData.GetDebugDisableTexturesAttr().Get(&disableTextures); return disableTextures; } bool OmniData::getDebugDisableGeometryPool() const { const auto cesiumData = UsdUtil::getCesiumData(_pContext->getUsdStage(), _path); if (!UsdUtil::isSchemaValid(cesiumData)) { return false; } bool disableGeometryPool; cesiumData.GetDebugDisableGeometryPoolAttr().Get(&disableGeometryPool); return disableGeometryPool; } bool OmniData::getDebugDisableMaterialPool() const { const auto cesiumData = UsdUtil::getCesiumData(_pContext->getUsdStage(), _path); if (!UsdUtil::isSchemaValid(cesiumData)) { return false; } bool disableMaterialPool; cesiumData.GetDebugDisableMaterialPoolAttr().Get(&disableMaterialPool); return disableMaterialPool; } bool OmniData::getDebugDisableTexturePool() const { const auto cesiumData = UsdUtil::getCesiumData(_pContext->getUsdStage(), _path); if (!UsdUtil::isSchemaValid(cesiumData)) { return false; } bool disableTexturePool; cesiumData.GetDebugDisableTexturePoolAttr().Get(&disableTexturePool); return disableTexturePool; } uint64_t OmniData::getDebugGeometryPoolInitialCapacity() const { const auto cesiumData = UsdUtil::getCesiumData(_pContext->getUsdStage(), _path); if (!UsdUtil::isSchemaValid(cesiumData)) { return 2048; } uint64_t geometryPoolInitialCapacity; cesiumData.GetDebugGeometryPoolInitialCapacityAttr().Get(&geometryPoolInitialCapacity); return geometryPoolInitialCapacity; } uint64_t OmniData::getDebugMaterialPoolInitialCapacity() const { const auto cesiumData = UsdUtil::getCesiumData(_pContext->getUsdStage(), _path); if (!UsdUtil::isSchemaValid(cesiumData)) { return 2048; } uint64_t materialPoolInitialCapacity; cesiumData.GetDebugMaterialPoolInitialCapacityAttr().Get(&materialPoolInitialCapacity); return materialPoolInitialCapacity; } uint64_t OmniData::getDebugTexturePoolInitialCapacity() const { const auto cesiumData = UsdUtil::getCesiumData(_pContext->getUsdStage(), _path); if (!UsdUtil::isSchemaValid(cesiumData)) { return 2048; } uint64_t texturePoolInitialCapacity; cesiumData.GetDebugTexturePoolInitialCapacityAttr().Get(&texturePoolInitialCapacity); return texturePoolInitialCapacity; } bool OmniData::getDebugRandomColors() const { const auto cesiumData = UsdUtil::getCesiumData(_pContext->getUsdStage(), _path); if (!UsdUtil::isSchemaValid(cesiumData)) { return false; } bool debugRandomColors; cesiumData.GetDebugRandomColorsAttr().Get(&debugRandomColors); return debugRandomColors; } bool OmniData::getDebugDisableGeoreferencing() const { const auto cesiumData = UsdUtil::getCesiumData(_pContext->getUsdStage(), _path); if (!UsdUtil::isSchemaValid(cesiumData)) { return false; } bool debugDisableGeoreferencing; cesiumData.GetDebugDisableGeoreferencingAttr().Get(&debugDisableGeoreferencing); return debugDisableGeoreferencing; } } // namespace cesium::omniverse
4,464
C++
27.806451
91
0.727599
CesiumGS/cesium-omniverse/src/core/src/OmniRasterOverlay.cpp
#include "cesium/omniverse/OmniRasterOverlay.h" #include "cesium/omniverse/AssetRegistry.h" #include "cesium/omniverse/Context.h" #include "cesium/omniverse/FabricRasterOverlaysInfo.h" #include "cesium/omniverse/GltfUtil.h" #include "cesium/omniverse/Logger.h" #include "cesium/omniverse/OmniIonServer.h" #include "cesium/omniverse/UsdUtil.h" #include <CesiumIonClient/Token.h> #include <CesiumUsdSchemas/rasterOverlay.h> namespace cesium::omniverse { OmniRasterOverlay::OmniRasterOverlay(Context* pContext, const pxr::SdfPath& path) : _pContext(pContext) , _path(path) {} const pxr::SdfPath& OmniRasterOverlay::getPath() const { return _path; } bool OmniRasterOverlay::getShowCreditsOnScreen() const { const auto cesiumRasterOverlay = UsdUtil::getCesiumRasterOverlay(_pContext->getUsdStage(), _path); if (!UsdUtil::isSchemaValid(cesiumRasterOverlay)) { return false; } bool showCreditsOnScreen; cesiumRasterOverlay.GetShowCreditsOnScreenAttr().Get(&showCreditsOnScreen); return showCreditsOnScreen; } double OmniRasterOverlay::getAlpha() const { const auto cesiumRasterOverlay = UsdUtil::getCesiumRasterOverlay(_pContext->getUsdStage(), _path); if (!UsdUtil::isSchemaValid(cesiumRasterOverlay)) { return 1.0; } float alpha; cesiumRasterOverlay.GetAlphaAttr().Get(&alpha); return static_cast<double>(alpha); } float OmniRasterOverlay::getMaximumScreenSpaceError() const { const auto cesiumRasterOverlay = UsdUtil::getCesiumRasterOverlay(_pContext->getUsdStage(), _path); if (!UsdUtil::isSchemaValid(cesiumRasterOverlay)) { return 2.0f; } float value; cesiumRasterOverlay.GetMaximumScreenSpaceErrorAttr().Get(&value); return static_cast<float>(value); } int OmniRasterOverlay::getMaximumTextureSize() const { const auto cesiumRasterOverlay = UsdUtil::getCesiumRasterOverlay(_pContext->getUsdStage(), _path); if (!UsdUtil::isSchemaValid(cesiumRasterOverlay)) { return 2048; } int value; cesiumRasterOverlay.GetMaximumTextureSizeAttr().Get(&value); return static_cast<int>(value); } int OmniRasterOverlay::getMaximumSimultaneousTileLoads() const { const auto cesiumRasterOverlay = UsdUtil::getCesiumRasterOverlay(_pContext->getUsdStage(), _path); if (!UsdUtil::isSchemaValid(cesiumRasterOverlay)) { return 20; } int value; cesiumRasterOverlay.GetMaximumSimultaneousTileLoadsAttr().Get(&value); return static_cast<int>(value); } int OmniRasterOverlay::getSubTileCacheBytes() const { const auto cesiumRasterOverlay = UsdUtil::getCesiumRasterOverlay(_pContext->getUsdStage(), _path); if (!UsdUtil::isSchemaValid(cesiumRasterOverlay)) { return 16777216; } int value; cesiumRasterOverlay.GetSubTileCacheBytesAttr().Get(&value); return static_cast<int>(value); } FabricOverlayRenderMethod OmniRasterOverlay::getOverlayRenderMethod() const { const auto cesiumRasterOverlay = UsdUtil::getCesiumRasterOverlay(_pContext->getUsdStage(), _path); if (!UsdUtil::isSchemaValid(cesiumRasterOverlay)) { return FabricOverlayRenderMethod::OVERLAY; } pxr::TfToken overlayRenderMethod; cesiumRasterOverlay.GetOverlayRenderMethodAttr().Get(&overlayRenderMethod); if (overlayRenderMethod == pxr::CesiumTokens->overlay) { return FabricOverlayRenderMethod::OVERLAY; } else if (overlayRenderMethod == pxr::CesiumTokens->clip) { return FabricOverlayRenderMethod::CLIPPING; } _pContext->getLogger()->warn("Invalid overlay render method encountered {}.", overlayRenderMethod.GetText()); return FabricOverlayRenderMethod::OVERLAY; } CesiumRasterOverlays::RasterOverlayOptions OmniRasterOverlay::createRasterOverlayOptions() const { CesiumRasterOverlays::RasterOverlayOptions options; options.ktx2TranscodeTargets = GltfUtil::getKtx2TranscodeTargets(); setRasterOverlayOptionsFromUsd(options); return options; } void OmniRasterOverlay::updateRasterOverlayOptions() const { const auto pRasterOverlay = getRasterOverlay(); if (pRasterOverlay) { setRasterOverlayOptionsFromUsd(pRasterOverlay->getOptions()); } } void OmniRasterOverlay::setRasterOverlayOptionsFromUsd(CesiumRasterOverlays::RasterOverlayOptions& options) const { options.showCreditsOnScreen = getShowCreditsOnScreen(); options.maximumScreenSpaceError = getMaximumScreenSpaceError(); options.maximumTextureSize = getMaximumTextureSize(); options.maximumSimultaneousTileLoads = getMaximumSimultaneousTileLoads(); options.subTileCacheBytes = getSubTileCacheBytes(); } } // namespace cesium::omniverse
4,681
C++
32.927536
115
0.754112
CesiumGS/cesium-omniverse/src/core/src/OmniIonServer.cpp
#include "cesium/omniverse/OmniIonServer.h" #include "cesium/omniverse/CesiumIonSession.h" #include "cesium/omniverse/Context.h" #include "cesium/omniverse/UsdUtil.h" #include <CesiumUsdSchemas/ionServer.h> namespace cesium::omniverse { OmniIonServer::OmniIonServer(Context* pContext, const pxr::SdfPath& path) : _pContext(pContext) , _path(path) , _session(std::make_shared<CesiumIonSession>( pContext->getAsyncSystem(), pContext->getAssetAccessor(), getIonServerUrl(), getIonServerApiUrl(), getIonServerApplicationId())) { _session->resume(); } const pxr::SdfPath& OmniIonServer::getPath() const { return _path; } std::shared_ptr<CesiumIonSession> OmniIonServer::getSession() const { return _session; } std::string OmniIonServer::getIonServerUrl() const { const auto cesiumIonServer = UsdUtil::getCesiumIonServer(_pContext->getUsdStage(), _path); if (!UsdUtil::isSchemaValid(cesiumIonServer)) { return ""; } std::string ionServerUrl; cesiumIonServer.GetIonServerUrlAttr().Get(&ionServerUrl); return ionServerUrl; } std::string OmniIonServer::getIonServerApiUrl() const { const auto cesiumIonServer = UsdUtil::getCesiumIonServer(_pContext->getUsdStage(), _path); if (!UsdUtil::isSchemaValid(cesiumIonServer)) { return ""; } std::string ionServerApiUrl; cesiumIonServer.GetIonServerApiUrlAttr().Get(&ionServerApiUrl); return ionServerApiUrl; } int64_t OmniIonServer::getIonServerApplicationId() const { const auto cesiumIonServer = UsdUtil::getCesiumIonServer(_pContext->getUsdStage(), _path); if (!UsdUtil::isSchemaValid(cesiumIonServer)) { return 0; } int64_t ionServerApplicationId; cesiumIonServer.GetIonServerApplicationIdAttr().Get(&ionServerApplicationId); return ionServerApplicationId; } CesiumIonClient::Token OmniIonServer::getToken() const { const auto cesiumIonServer = UsdUtil::getCesiumIonServer(_pContext->getUsdStage(), _path); if (!UsdUtil::isSchemaValid(cesiumIonServer)) { return {}; } std::string projectDefaultIonAccessToken; std::string projectDefaultIonAccessTokenId; cesiumIonServer.GetProjectDefaultIonAccessTokenAttr().Get(&projectDefaultIonAccessToken); cesiumIonServer.GetProjectDefaultIonAccessTokenIdAttr().Get(&projectDefaultIonAccessTokenId); CesiumIonClient::Token t; t.id = projectDefaultIonAccessTokenId; t.token = projectDefaultIonAccessToken; return t; } void OmniIonServer::setToken(const CesiumIonClient::Token& token) { const auto cesiumIonServer = UsdUtil::getCesiumIonServer(_pContext->getUsdStage(), _path); if (!UsdUtil::isSchemaValid(cesiumIonServer)) { return; } cesiumIonServer.GetProjectDefaultIonAccessTokenAttr().Set(token.token); cesiumIonServer.GetProjectDefaultIonAccessTokenIdAttr().Set(token.id); } } // namespace cesium::omniverse
2,961
C++
29.536082
97
0.729483
CesiumGS/cesium-omniverse/src/core/src/FabricMaterial.cpp
#include "cesium/omniverse/FabricMaterial.h" #include "cesium/omniverse/Context.h" #include "cesium/omniverse/CppUtil.h" #include "cesium/omniverse/DataType.h" #include "cesium/omniverse/FabricAttributesBuilder.h" #include "cesium/omniverse/FabricFeaturesInfo.h" #include "cesium/omniverse/FabricMaterialDescriptor.h" #include "cesium/omniverse/FabricMaterialInfo.h" #include "cesium/omniverse/FabricPropertyDescriptor.h" #include "cesium/omniverse/FabricRasterOverlaysInfo.h" #include "cesium/omniverse/FabricResourceManager.h" #include "cesium/omniverse/FabricTexture.h" #include "cesium/omniverse/FabricTextureInfo.h" #include "cesium/omniverse/FabricUtil.h" #include "cesium/omniverse/GltfUtil.h" #include "cesium/omniverse/Logger.h" #include "cesium/omniverse/MetadataUtil.h" #include "cesium/omniverse/UsdTokens.h" #include "cesium/omniverse/UsdUtil.h" #include <CesiumGltf/MeshPrimitive.h> #include <glm/gtc/random.hpp> #include <omni/fabric/FabricUSD.h> #include <omni/fabric/SimStageWithHistory.h> #include <spdlog/fmt/fmt.h> namespace cesium::omniverse { namespace { // Should match raster_overlays length in cesium.mdl const uint64_t MAX_RASTER_OVERLAY_COUNT = 16; const auto DEFAULT_DEBUG_COLOR = glm::dvec3(1.0, 1.0, 1.0); const auto DEFAULT_ALPHA = 1.0f; const auto DEFAULT_DISPLAY_COLOR = glm::dvec3(1.0, 1.0, 1.0); const auto DEFAULT_DISPLAY_OPACITY = 1.0; const auto DEFAULT_TEXCOORD_INDEX = uint64_t(0); const auto DEFAULT_FEATURE_ID_PRIMVAR_NAME = std::string("_FEATURE_ID_0"); const auto DEFAULT_NULL_FEATURE_ID = -1; const auto DEFAULT_OFFSET = 0; const auto DEFAULT_SCALE = 1; const auto DEFAULT_NO_DATA = 0; const auto DEFAULT_VALUE = 0; struct FeatureIdCounts { uint64_t indexCount; uint64_t attributeCount; uint64_t textureCount; uint64_t totalCount; }; FeatureIdCounts getFeatureIdCounts(const FabricMaterialDescriptor& materialDescriptor) { const auto& featureIdTypes = materialDescriptor.getFeatureIdTypes(); auto featureIdCount = featureIdTypes.size(); uint64_t indexCount = 0; uint64_t attributeCount = 0; uint64_t textureCount = 0; for (uint64_t i = 0; i < featureIdCount; ++i) { const auto featureIdType = featureIdTypes[i]; switch (featureIdType) { case FabricFeatureIdType::INDEX: ++indexCount; break; case FabricFeatureIdType::ATTRIBUTE: ++attributeCount; break; case FabricFeatureIdType::TEXTURE: ++textureCount; break; } } return FeatureIdCounts{indexCount, attributeCount, textureCount, featureIdCount}; } struct RasterOverlayIndices { std::vector<uint64_t> overlayRasterOverlayIndices; std::vector<uint64_t> clippingRasterOverlayIndices; }; RasterOverlayIndices getRasterOverlayIndices(const Context& context, const FabricMaterialDescriptor& materialDescriptor) { uint64_t overlayRasterOverlayCount = 0; uint64_t clippingRasterOverlayCount = 0; uint64_t totalRasterOverlayCount = 0; std::vector<uint64_t> overlayRasterOverlayIndices; std::vector<uint64_t> clippingRasterOverlayIndices; for (const auto& method : materialDescriptor.getRasterOverlayRenderMethods()) { switch (method) { case FabricOverlayRenderMethod::OVERLAY: if (overlayRasterOverlayCount < MAX_RASTER_OVERLAY_COUNT) { overlayRasterOverlayIndices.push_back(totalRasterOverlayCount); } ++overlayRasterOverlayCount; break; case FabricOverlayRenderMethod::CLIPPING: if (clippingRasterOverlayCount < MAX_RASTER_OVERLAY_COUNT) { clippingRasterOverlayIndices.push_back(totalRasterOverlayCount); } ++clippingRasterOverlayCount; break; } ++totalRasterOverlayCount; } if (overlayRasterOverlayCount > MAX_RASTER_OVERLAY_COUNT) { context.getLogger()->warn( "Number of overlay raster overlays ({}) exceeds maximum raster overlay count ({}). Excess " "raster overlays " "will be ignored.", overlayRasterOverlayCount, MAX_RASTER_OVERLAY_COUNT); } if (clippingRasterOverlayCount > MAX_RASTER_OVERLAY_COUNT) { context.getLogger()->warn( "Number of clipping raster overlays ({}) exceeds maximum raster overlay count ({}). Excess " "raster overlays " "will be ignored.", clippingRasterOverlayCount, MAX_RASTER_OVERLAY_COUNT); } return RasterOverlayIndices{std::move(overlayRasterOverlayIndices), std::move(clippingRasterOverlayIndices)}; } uint64_t getRasterOverlayCount(const FabricMaterialDescriptor& materialDescriptor) { return materialDescriptor.getRasterOverlayRenderMethods().size(); } bool isClippingEnabled(const FabricMaterialDescriptor& materialDescriptor) { return CppUtil::contains(materialDescriptor.getRasterOverlayRenderMethods(), FabricOverlayRenderMethod::CLIPPING); } FabricAlphaMode getInitialAlphaMode(const FabricMaterialDescriptor& materialDescriptor, const FabricMaterialInfo& materialInfo) { if (materialInfo.alphaMode == FabricAlphaMode::BLEND) { return materialInfo.alphaMode; } if (isClippingEnabled(materialDescriptor)) { return FabricAlphaMode::MASK; } return materialInfo.alphaMode; } int getAlphaMode(FabricAlphaMode alphaMode, double displayOpacity) { return static_cast<int>(displayOpacity < 1.0 ? FabricAlphaMode::BLEND : alphaMode); } glm::dvec4 getTileColor(const glm::dvec3& debugColor, const glm::dvec3& displayColor, double displayOpacity) { return {debugColor * displayColor, displayOpacity}; } void createConnection( omni::fabric::StageReaderWriter& fabricStage, const omni::fabric::Path& outputPath, const omni::fabric::Path& inputPath, const omni::fabric::Token& inputName) { fabricStage.createConnection(inputPath, inputName, omni::fabric::Connection{outputPath, FabricTokens::outputs_out}); } void destroyConnection( omni::fabric::StageReaderWriter& fabricStage, const omni::fabric::Path& inputPath, const omni::fabric::Token& inputName) { fabricStage.destroyConnection(inputPath, inputName); } template <DataType T> constexpr DataTypeUtil::GetMdlInternalPropertyTransformedType<DataTypeUtil::getMdlInternalPropertyType<T>()> getOffset(const FabricPropertyInfo<T>& info) { constexpr auto mdlType = DataTypeUtil::getMdlInternalPropertyType<T>(); using TransformedType = DataTypeUtil::GetNativeType<DataTypeUtil::getTransformedType<T>()>; using MdlTransformedType = DataTypeUtil::GetMdlInternalPropertyTransformedType<mdlType>; return static_cast<MdlTransformedType>(info.offset.value_or(TransformedType{DEFAULT_OFFSET})); } template <DataType T> constexpr DataTypeUtil::GetMdlInternalPropertyTransformedType<DataTypeUtil::getMdlInternalPropertyType<T>()> getScale(const FabricPropertyInfo<T>& info) { constexpr auto mdlType = DataTypeUtil::getMdlInternalPropertyType<T>(); using TransformedType = DataTypeUtil::GetNativeType<DataTypeUtil::getTransformedType<T>()>; using MdlTransformedType = DataTypeUtil::GetMdlInternalPropertyTransformedType<mdlType>; return static_cast<MdlTransformedType>(info.scale.value_or(TransformedType{DEFAULT_SCALE})); } template <DataType T> constexpr DataTypeUtil::GetMdlInternalPropertyRawType<DataTypeUtil::getMdlInternalPropertyType<T>()> getNoData(const FabricPropertyInfo<T>& info) { constexpr auto mdlType = DataTypeUtil::getMdlInternalPropertyType<T>(); using RawType = DataTypeUtil::GetNativeType<T>; using MdlRawType = DataTypeUtil::GetMdlInternalPropertyRawType<mdlType>; return static_cast<MdlRawType>(info.noData.value_or(RawType{DEFAULT_NO_DATA})); } template <DataType T> constexpr DataTypeUtil::GetMdlInternalPropertyTransformedType<DataTypeUtil::getMdlInternalPropertyType<T>()> getDefaultValue(const FabricPropertyInfo<T>& info) { constexpr auto mdlType = DataTypeUtil::getMdlInternalPropertyType<T>(); using TransformedType = DataTypeUtil::GetNativeType<DataTypeUtil::getTransformedType<T>()>; using MdlTransformedType = DataTypeUtil::GetMdlInternalPropertyTransformedType<mdlType>; return static_cast<MdlTransformedType>(info.defaultValue.value_or(TransformedType{DEFAULT_VALUE})); } template <DataType T> constexpr DataTypeUtil::GetMdlInternalPropertyRawType<DataTypeUtil::getMdlInternalPropertyType<T>()> getMaximumValue() { constexpr auto mdlType = DataTypeUtil::getMdlInternalPropertyType<T>(); using RawComponentType = DataTypeUtil::GetNativeType<DataTypeUtil::getComponentType<T>()>; using MdlRawType = DataTypeUtil::GetMdlInternalPropertyRawType<mdlType>; if constexpr (DataTypeUtil::isNormalized<T>()) { return MdlRawType{std::numeric_limits<RawComponentType>::max()}; } return MdlRawType{0}; } void createAttributes( const Context& context, omni::fabric::StageReaderWriter& fabricStage, const omni::fabric::Path& path, FabricAttributesBuilder& attributes, const omni::fabric::Token& subidentifier) { // clang-format off attributes.addAttribute(FabricTypes::inputs_excludeFromWhiteMode, FabricTokens::inputs_excludeFromWhiteMode); attributes.addAttribute(FabricTypes::outputs_out, FabricTokens::outputs_out); attributes.addAttribute(FabricTypes::info_implementationSource, FabricTokens::info_implementationSource); attributes.addAttribute(FabricTypes::info_mdl_sourceAsset, FabricTokens::info_mdl_sourceAsset); attributes.addAttribute(FabricTypes::info_mdl_sourceAsset_subIdentifier, FabricTokens::info_mdl_sourceAsset_subIdentifier); attributes.addAttribute(FabricTypes::_paramColorSpace, FabricTokens::_paramColorSpace); attributes.addAttribute(FabricTypes::_sdrMetadata, FabricTokens::_sdrMetadata); attributes.addAttribute(FabricTypes::Shader, FabricTokens::Shader); attributes.addAttribute(FabricTypes::_cesium_tilesetId, FabricTokens::_cesium_tilesetId); // clang-format on attributes.createAttributes(path); // clang-format off const auto inputsExcludeFromWhiteModeFabric = fabricStage.getAttributeWr<bool>(path, FabricTokens::inputs_excludeFromWhiteMode); const auto infoImplementationSourceFabric = fabricStage.getAttributeWr<omni::fabric::TokenC>(path, FabricTokens::info_implementationSource); const auto infoMdlSourceAssetFabric = fabricStage.getAttributeWr<omni::fabric::AssetPath>(path, FabricTokens::info_mdl_sourceAsset); const auto infoMdlSourceAssetSubIdentifierFabric = fabricStage.getAttributeWr<omni::fabric::TokenC>(path, FabricTokens::info_mdl_sourceAsset_subIdentifier); // clang-format on fabricStage.setArrayAttributeSize(path, FabricTokens::_paramColorSpace, 0); fabricStage.setArrayAttributeSize(path, FabricTokens::_sdrMetadata, 0); *inputsExcludeFromWhiteModeFabric = false; *infoImplementationSourceFabric = FabricTokens::sourceAsset; infoMdlSourceAssetFabric->assetPath = context.getCesiumMdlPathToken(); infoMdlSourceAssetFabric->resolvedPath = pxr::TfToken(); *infoMdlSourceAssetSubIdentifierFabric = subidentifier; } void setTextureValuesCommon( omni::fabric::StageReaderWriter& fabricStage, const omni::fabric::Path& path, const pxr::TfToken& textureAssetPathToken, const FabricTextureInfo& textureInfo, uint64_t texcoordIndex) { auto offset = textureInfo.offset; auto rotation = textureInfo.rotation; auto scale = textureInfo.scale; if (!textureInfo.flipVertical) { // gltf/pbr.mdl does texture transform math in glTF coordinates (top-left origin), so we needed to convert // the translation and scale parameters to work in that space. This doesn't handle rotation yet because we // haven't needed it for raster overlays. offset = {offset.x, 1.0 - offset.y - scale.y}; scale = {scale.x, scale.y}; } const auto textureFabric = fabricStage.getAttributeWr<omni::fabric::AssetPath>(path, FabricTokens::inputs_texture); const auto texCoordIndexFabric = fabricStage.getAttributeWr<int>(path, FabricTokens::inputs_tex_coord_index); const auto wrapSFabric = fabricStage.getAttributeWr<int>(path, FabricTokens::inputs_wrap_s); const auto wrapTFabric = fabricStage.getAttributeWr<int>(path, FabricTokens::inputs_wrap_t); const auto offsetFabric = fabricStage.getAttributeWr<pxr::GfVec2f>(path, FabricTokens::inputs_tex_coord_offset); const auto rotationFabric = fabricStage.getAttributeWr<float>(path, FabricTokens::inputs_tex_coord_rotation); const auto scaleFabric = fabricStage.getAttributeWr<pxr::GfVec2f>(path, FabricTokens::inputs_tex_coord_scale); textureFabric->assetPath = textureAssetPathToken; textureFabric->resolvedPath = pxr::TfToken(); *texCoordIndexFabric = static_cast<int>(texcoordIndex); *wrapSFabric = textureInfo.wrapS; *wrapTFabric = textureInfo.wrapT; *offsetFabric = UsdUtil::glmToUsdVector(glm::fvec2(offset)); *rotationFabric = static_cast<float>(rotation); *scaleFabric = UsdUtil::glmToUsdVector(glm::fvec2(scale)); } void setTextureValuesCommonChannels( omni::fabric::StageReaderWriter& fabricStage, const omni::fabric::Path& path, const pxr::TfToken& textureAssetPathToken, const FabricTextureInfo& textureInfo, uint64_t texcoordIndex) { setTextureValuesCommon(fabricStage, path, textureAssetPathToken, textureInfo, texcoordIndex); auto channelCount = glm::min(textureInfo.channels.size(), uint64_t(4)); auto channels = glm::u8vec4(0); for (uint64_t i = 0; i < channelCount; ++i) { channels[i] = textureInfo.channels[i]; } channelCount = glm::max(channelCount, uint64_t(1)); const auto channelsFabric = fabricStage.getAttributeWr<glm::i32vec4>(path, FabricTokens::inputs_channels); *channelsFabric = static_cast<glm::i32vec4>(channels); if (fabricStage.attributeExists(path, FabricTokens::inputs_channel_count)) { const auto channelCountFabric = fabricStage.getAttributeWr<int>(path, FabricTokens::inputs_channel_count); *channelCountFabric = static_cast<int>(channelCount); } } std::string getStringFabric( omni::fabric::StageReaderWriter& fabricStage, const omni::fabric::Path& path, omni::fabric::TokenC attributeName) { const auto valueFabric = fabricStage.getArrayAttributeRd<uint8_t>(path, attributeName); return {reinterpret_cast<const char*>(valueFabric.data()), valueFabric.size()}; } void setStringFabric( omni::fabric::StageReaderWriter& fabricStage, const omni::fabric::Path& path, omni::fabric::TokenC attributeName, const std::string& value) { fabricStage.setArrayAttributeSize(path, attributeName, value.size()); const auto valueFabric = fabricStage.getArrayAttributeWr<uint8_t>(path, attributeName); memcpy(valueFabric.data(), value.data(), value.size()); } template <MdlInternalPropertyType T> void setPropertyValues( omni::fabric::StageReaderWriter& fabricStage, const omni::fabric::Path& path, const DataTypeUtil::GetMdlInternalPropertyTransformedType<T>& offset, const DataTypeUtil::GetMdlInternalPropertyTransformedType<T>& scale, const DataTypeUtil::GetMdlInternalPropertyRawType<T>& maximumValue, bool hasNoData, const DataTypeUtil::GetMdlInternalPropertyRawType<T>& noData, const DataTypeUtil::GetMdlInternalPropertyTransformedType<T>& defaultValue) { using MdlRawType = DataTypeUtil::GetMdlInternalPropertyRawType<T>; using MdlTransformedType = DataTypeUtil::GetMdlInternalPropertyTransformedType<T>; const auto hasNoDataFabric = fabricStage.getAttributeWr<bool>(path, FabricTokens::inputs_has_no_data); const auto noDataFabric = fabricStage.getAttributeWr<MdlRawType>(path, FabricTokens::inputs_no_data); const auto defaultValueFabric = fabricStage.getAttributeWr<MdlTransformedType>(path, FabricTokens::inputs_default_value); *hasNoDataFabric = hasNoData; *noDataFabric = static_cast<MdlRawType>(noData); *defaultValueFabric = static_cast<MdlTransformedType>(defaultValue); if (fabricStage.attributeExists(path, FabricTokens::inputs_offset)) { const auto offsetFabric = fabricStage.getAttributeWr<MdlTransformedType>(path, FabricTokens::inputs_offset); *offsetFabric = static_cast<MdlTransformedType>(offset); } if (fabricStage.attributeExists(path, FabricTokens::inputs_scale)) { const auto scaleFabric = fabricStage.getAttributeWr<MdlTransformedType>(path, FabricTokens::inputs_scale); *scaleFabric = static_cast<MdlTransformedType>(scale); } if (fabricStage.attributeExists(path, FabricTokens::inputs_maximum_value)) { const auto maximumValueFabric = fabricStage.getAttributeWr<MdlRawType>(path, FabricTokens::inputs_maximum_value); *maximumValueFabric = static_cast<MdlRawType>(maximumValue); } } template <MdlInternalPropertyType T> void setPropertyAttributePropertyValues( omni::fabric::StageReaderWriter& fabricStage, const omni::fabric::Path& path, const std::string& primvarName, const DataTypeUtil::GetMdlInternalPropertyTransformedType<T>& offset, const DataTypeUtil::GetMdlInternalPropertyTransformedType<T>& scale, const DataTypeUtil::GetMdlInternalPropertyRawType<T>& maximumValue, bool hasNoData, const DataTypeUtil::GetMdlInternalPropertyRawType<T>& noData, const DataTypeUtil::GetMdlInternalPropertyTransformedType<T>& defaultValue) { setStringFabric(fabricStage, path, FabricTokens::inputs_primvar_name, primvarName); setPropertyValues<T>(fabricStage, path, offset, scale, maximumValue, hasNoData, noData, defaultValue); } template <MdlInternalPropertyType T> void setPropertyTexturePropertyValues( omni::fabric::StageReaderWriter& fabricStage, const omni::fabric::Path& path, const pxr::TfToken& textureAssetPathToken, const FabricTextureInfo& textureInfo, uint64_t texcoordIndex, const DataTypeUtil::GetMdlInternalPropertyTransformedType<T>& offset, const DataTypeUtil::GetMdlInternalPropertyTransformedType<T>& scale, const DataTypeUtil::GetMdlInternalPropertyRawType<T>& maximumValue, bool hasNoData, const DataTypeUtil::GetMdlInternalPropertyRawType<T>& noData, const DataTypeUtil::GetMdlInternalPropertyTransformedType<T>& defaultValue) { setTextureValuesCommonChannels(fabricStage, path, textureAssetPathToken, textureInfo, texcoordIndex); setPropertyValues<T>(fabricStage, path, offset, scale, maximumValue, hasNoData, noData, defaultValue); } template <MdlInternalPropertyType T> void setPropertyTablePropertyValues( omni::fabric::StageReaderWriter& fabricStage, const omni::fabric::Path& path, const pxr::TfToken& propertyTableTextureAssetPathToken, const DataTypeUtil::GetMdlInternalPropertyTransformedType<T>& offset, const DataTypeUtil::GetMdlInternalPropertyTransformedType<T>& scale, const DataTypeUtil::GetMdlInternalPropertyRawType<T>& maximumValue, bool hasNoData, const DataTypeUtil::GetMdlInternalPropertyRawType<T>& noData, const DataTypeUtil::GetMdlInternalPropertyTransformedType<T>& defaultValue) { const auto textureFabric = fabricStage.getAttributeWr<omni::fabric::AssetPath>(path, FabricTokens::inputs_property_table_texture); textureFabric->assetPath = propertyTableTextureAssetPathToken; textureFabric->resolvedPath = pxr::TfToken(); setPropertyValues<T>(fabricStage, path, offset, scale, maximumValue, hasNoData, noData, defaultValue); } template <MdlInternalPropertyType T> void clearPropertyAttributeProperty(omni::fabric::StageReaderWriter& fabricStage, const omni::fabric::Path& path) { using MdlRawType = DataTypeUtil::GetMdlInternalPropertyRawType<T>; using MdlTransformedType = DataTypeUtil::GetMdlInternalPropertyTransformedType<T>; setPropertyAttributePropertyValues<T>( fabricStage, path, "", MdlTransformedType{0}, MdlTransformedType{0}, MdlRawType{0}, false, MdlRawType{0}, MdlTransformedType{0}); } template <MdlInternalPropertyType T> void clearPropertyTextureProperty( omni::fabric::StageReaderWriter& fabricStage, const omni::fabric::Path& path, const pxr::TfToken& defaultTransparentTextureAssetPathToken) { using MdlRawType = DataTypeUtil::GetMdlInternalPropertyRawType<T>; using MdlTransformedType = DataTypeUtil::GetMdlInternalPropertyTransformedType<T>; setPropertyTexturePropertyValues<T>( fabricStage, path, defaultTransparentTextureAssetPathToken, GltfUtil::getDefaultTextureInfo(), DEFAULT_TEXCOORD_INDEX, MdlTransformedType{0}, MdlTransformedType{0}, MdlRawType{0}, false, MdlRawType{0}, MdlTransformedType{0}); } template <MdlInternalPropertyType T> void clearPropertyTableProperty( omni::fabric::StageReaderWriter& fabricStage, const omni::fabric::Path& path, const pxr::TfToken& defaultTransparentTextureAssetPathToken) { using MdlRawType = DataTypeUtil::GetMdlInternalPropertyRawType<T>; using MdlTransformedType = DataTypeUtil::GetMdlInternalPropertyTransformedType<T>; setPropertyTablePropertyValues<T>( fabricStage, path, defaultTransparentTextureAssetPathToken, MdlTransformedType{0}, MdlTransformedType{0}, MdlRawType{0}, false, MdlRawType{0}, MdlTransformedType{0}); } } // namespace FabricMaterial::FabricMaterial( Context* pContext, const omni::fabric::Path& path, const FabricMaterialDescriptor& materialDescriptor, const pxr::TfToken& defaultWhiteTextureAssetPathToken, const pxr::TfToken& defaultTransparentTextureAssetPathToken, bool debugRandomColors, int64_t poolId) : _pContext(pContext) , _materialPath(path) , _materialDescriptor(materialDescriptor) , _defaultWhiteTextureAssetPathToken(defaultWhiteTextureAssetPathToken) , _defaultTransparentTextureAssetPathToken(defaultTransparentTextureAssetPathToken) , _debugRandomColors(debugRandomColors) , _poolId(poolId) , _stageId(pContext->getUsdStageId()) , _usesDefaultMaterial(!materialDescriptor.hasTilesetMaterial()) { if (stageDestroyed()) { return; } initializeNodes(); if (_usesDefaultMaterial) { initializeDefaultMaterial(); } else { initializeExistingMaterial(FabricUtil::toFabricPath(materialDescriptor.getTilesetMaterialPath())); } reset(); } FabricMaterial::~FabricMaterial() { // The code below is temporarily commented out to avoid a crash. // It will cause a leak, but since this only happens when materials // pools are destroyed (which doesn't happen during normal usage) it // shouldn't be a huge concern. // // See https://github.com/CesiumGS/cesium-omniverse/issues/444 for details. // if (stageDestroyed()) { // return; // } // for (const auto& path : _allPaths) { // FabricUtil::destroyPrim(_pContext->getFabricStage(), path); // } } void FabricMaterial::setActive(bool active) { if (stageDestroyed()) { return; } if (!active) { reset(); } } const omni::fabric::Path& FabricMaterial::getPath() const { return _materialPath; } const FabricMaterialDescriptor& FabricMaterial::getMaterialDescriptor() const { return _materialDescriptor; } int64_t FabricMaterial::getPoolId() const { return _poolId; } void FabricMaterial::initializeNodes() { auto& fabricStage = _pContext->getFabricStage(); // Create base color texture const auto hasBaseColorTexture = _materialDescriptor.hasBaseColorTexture(); if (hasBaseColorTexture) { const auto baseColorTexturePath = FabricUtil::joinPaths(_materialPath, FabricTokens::base_color_texture); createTexture(baseColorTexturePath); _baseColorTexturePath = baseColorTexturePath; _allPaths.push_back(baseColorTexturePath); } // Create raster overlays const auto rasterOverlayCount = getRasterOverlayCount(_materialDescriptor); _rasterOverlayPaths.reserve(rasterOverlayCount); for (uint64_t i = 0; i < rasterOverlayCount; ++i) { const auto rasterOverlayPath = FabricUtil::joinPaths(_materialPath, FabricTokens::raster_overlay_n(i)); createRasterOverlay(rasterOverlayPath); _rasterOverlayPaths.push_back(rasterOverlayPath); _allPaths.push_back(rasterOverlayPath); } // Create feature ids const auto& featureIdTypes = _materialDescriptor.getFeatureIdTypes(); const auto featureIdCounts = getFeatureIdCounts(_materialDescriptor); _featureIdPaths.reserve(featureIdCounts.totalCount); _featureIdIndexPaths.reserve(featureIdCounts.indexCount); _featureIdAttributePaths.reserve(featureIdCounts.attributeCount); _featureIdTexturePaths.reserve(featureIdCounts.textureCount); for (uint64_t i = 0; i < featureIdCounts.totalCount; ++i) { const auto featureIdType = featureIdTypes[i]; const auto featureIdPath = FabricUtil::joinPaths(_materialPath, FabricTokens::feature_id_n(i)); switch (featureIdType) { case FabricFeatureIdType::INDEX: createFeatureIdIndex(featureIdPath); _featureIdIndexPaths.push_back(featureIdPath); break; case FabricFeatureIdType::ATTRIBUTE: createFeatureIdAttribute(featureIdPath); _featureIdAttributePaths.push_back(featureIdPath); break; case FabricFeatureIdType::TEXTURE: createFeatureIdTexture(featureIdPath); _featureIdTexturePaths.push_back(featureIdPath); break; } _featureIdPaths.push_back(featureIdPath); _allPaths.push_back(featureIdPath); } // Create properties const auto& properties = _materialDescriptor.getStyleableProperties(); for (uint64_t i = 0; i < properties.size(); ++i) { const auto& property = properties[i]; const auto storageType = property.storageType; const auto type = property.type; const auto& propertyPath = FabricUtil::joinPaths(_materialPath, FabricTokens::property_n(i)); switch (storageType) { case FabricPropertyStorageType::ATTRIBUTE: createPropertyAttributeProperty(propertyPath, type); _propertyAttributePropertyPaths[type].push_back(propertyPath); break; case FabricPropertyStorageType::TEXTURE: createPropertyTextureProperty(propertyPath, type); _propertyTexturePropertyPaths[type].push_back(propertyPath); break; case FabricPropertyStorageType::TABLE: createPropertyTableProperty(propertyPath, type); _propertyTablePropertyPaths[type].push_back(propertyPath); // Create connection from the feature id node to the property table property node const auto featureIdSetIndex = property.featureIdSetIndex; const auto& featureIdPath = _featureIdPaths[featureIdSetIndex]; createConnection(fabricStage, featureIdPath, propertyPath, FabricTokens::inputs_feature_id); break; } _propertyPaths.push_back(propertyPath); _allPaths.push_back(propertyPath); } } void FabricMaterial::initializeDefaultMaterial() { auto& fabricStage = _pContext->getFabricStage(); const auto rasterOverlayIndices = getRasterOverlayIndices(*_pContext, _materialDescriptor); const auto hasBaseColorTexture = _materialDescriptor.hasBaseColorTexture(); // Create material const auto& materialPath = _materialPath; createMaterial(materialPath); _allPaths.push_back(materialPath); // Create shader const auto shaderPath = FabricUtil::joinPaths(materialPath, FabricTokens::cesium_internal_material); createShader(shaderPath); _shaderPath = shaderPath; _allPaths.push_back(shaderPath); const auto& overlayRasterOverlayIndices = rasterOverlayIndices.overlayRasterOverlayIndices; const auto& clippingRasterOverlayIndices = rasterOverlayIndices.clippingRasterOverlayIndices; const auto overlayRasterOverlayCount = overlayRasterOverlayIndices.size(); const auto clippingRasterOverlayCount = clippingRasterOverlayIndices.size(); // Create overlay raster overlay resolver if there are multiple overlay raster overlays if (overlayRasterOverlayCount > 1) { const auto rasterOverlayResolverPath = FabricUtil::joinPaths(materialPath, FabricTokens::raster_overlay_resolver); createRasterOverlayResolver(rasterOverlayResolverPath, overlayRasterOverlayCount); _overlayRasterOverlayResolverPath = rasterOverlayResolverPath; _allPaths.push_back(rasterOverlayResolverPath); } // Create clipping raster overlay resolver if there are multiple clipping raster overlays if (clippingRasterOverlayCount > 1) { const auto clippingRasterOverlayResolverPath = FabricUtil::joinPaths(materialPath, FabricTokens::clipping_raster_overlay_resolver); createClippingRasterOverlayResolver(clippingRasterOverlayResolverPath, clippingRasterOverlayCount); _clippingRasterOverlayResolverPath = clippingRasterOverlayResolverPath; _allPaths.push_back(_clippingRasterOverlayResolverPath); } // Create connection from shader to material createConnection(fabricStage, shaderPath, materialPath, FabricTokens::outputs_mdl_surface); createConnection(fabricStage, shaderPath, materialPath, FabricTokens::outputs_mdl_displacement); createConnection(fabricStage, shaderPath, materialPath, FabricTokens::outputs_mdl_volume); // Create connection from base color texture to shader if (hasBaseColorTexture) { createConnection(fabricStage, _baseColorTexturePath, shaderPath, FabricTokens::inputs_base_color_texture); } if (overlayRasterOverlayCount == 1) { // Create connection from raster overlay to shader const auto& rasterOverlayPath = _rasterOverlayPaths[overlayRasterOverlayIndices.front()]; createConnection(fabricStage, rasterOverlayPath, shaderPath, FabricTokens::inputs_raster_overlay); } else if (overlayRasterOverlayCount > 1) { // Create connection from raster overlay resolver to shader createConnection( fabricStage, _overlayRasterOverlayResolverPath, shaderPath, FabricTokens::inputs_raster_overlay); // Create connections from raster overlays to raster overlay resolver for (uint64_t i = 0; i < overlayRasterOverlayCount; ++i) { const auto& rasterOverlayPath = _rasterOverlayPaths[overlayRasterOverlayIndices[i]]; createConnection( fabricStage, rasterOverlayPath, _overlayRasterOverlayResolverPath, FabricTokens::inputs_raster_overlay_n(i)); } } if (clippingRasterOverlayCount == 1) { // Create connection from raster overlay to shader const auto& rasterOverlayPath = _rasterOverlayPaths[clippingRasterOverlayIndices.front()]; createConnection(fabricStage, rasterOverlayPath, shaderPath, FabricTokens::inputs_alpha_clip); } else if (clippingRasterOverlayCount > 1) { // Create connection from raster overlay resolver to shader createConnection(fabricStage, _clippingRasterOverlayResolverPath, shaderPath, FabricTokens::inputs_alpha_clip); // Create connections from raster overlays to raster overlay resolver for (uint64_t i = 0; i < clippingRasterOverlayCount; ++i) { const auto& rasterOverlayPath = _rasterOverlayPaths[clippingRasterOverlayIndices[i]]; createConnection( fabricStage, rasterOverlayPath, _clippingRasterOverlayResolverPath, FabricTokens::inputs_raster_overlay_n(i)); } } } void FabricMaterial::initializeExistingMaterial(const omni::fabric::Path& path) { auto& fabricStage = _pContext->getFabricStage(); const auto copiedPaths = FabricUtil::copyMaterial(fabricStage, path, _materialPath); for (const auto& copiedPath : copiedPaths) { fabricStage.createAttribute(copiedPath, FabricTokens::_cesium_tilesetId, FabricTypes::_cesium_tilesetId); _allPaths.push_back(copiedPath); const auto mdlIdentifier = FabricUtil::getMdlIdentifier(fabricStage, copiedPath); if (mdlIdentifier == FabricTokens::cesium_base_color_texture_float4) { _copiedBaseColorTexturePaths.push_back(copiedPath); } else if (mdlIdentifier == FabricTokens::cesium_raster_overlay_float4) { _copiedRasterOverlayPaths.push_back(copiedPath); } else if (mdlIdentifier == FabricTokens::cesium_feature_id_int) { _copiedFeatureIdPaths.push_back(copiedPath); } else if (FabricUtil::isCesiumPropertyNode(mdlIdentifier)) { _copiedPropertyPaths.push_back(copiedPath); } } createConnectionsToCopiedPaths(); createConnectionsToProperties(); } void FabricMaterial::createMaterial(const omni::fabric::Path& path) { auto& fabricStage = _pContext->getFabricStage(); fabricStage.createPrim(path); FabricAttributesBuilder attributes(_pContext); attributes.addAttribute(FabricTypes::Material, FabricTokens::Material); attributes.addAttribute(FabricTypes::_cesium_tilesetId, FabricTokens::_cesium_tilesetId); attributes.createAttributes(path); } void FabricMaterial::createShader(const omni::fabric::Path& path) { auto& fabricStage = _pContext->getFabricStage(); fabricStage.createPrim(path); FabricAttributesBuilder attributes(_pContext); attributes.addAttribute(FabricTypes::inputs_tile_color, FabricTokens::inputs_tile_color); attributes.addAttribute(FabricTypes::inputs_alpha_cutoff, FabricTokens::inputs_alpha_cutoff); attributes.addAttribute(FabricTypes::inputs_alpha_mode, FabricTokens::inputs_alpha_mode); attributes.addAttribute(FabricTypes::inputs_base_alpha, FabricTokens::inputs_base_alpha); attributes.addAttribute(FabricTypes::inputs_base_color_factor, FabricTokens::inputs_base_color_factor); attributes.addAttribute(FabricTypes::inputs_emissive_factor, FabricTokens::inputs_emissive_factor); attributes.addAttribute(FabricTypes::inputs_metallic_factor, FabricTokens::inputs_metallic_factor); attributes.addAttribute(FabricTypes::inputs_roughness_factor, FabricTokens::inputs_roughness_factor); createAttributes(*_pContext, fabricStage, path, attributes, FabricTokens::cesium_internal_material); } void FabricMaterial::createTextureCommon( const omni::fabric::Path& path, const omni::fabric::Token& subIdentifier, const std::vector<std::pair<omni::fabric::Type, omni::fabric::Token>>& additionalAttributes) { auto& fabricStage = _pContext->getFabricStage(); fabricStage.createPrim(path); FabricAttributesBuilder attributes(_pContext); attributes.addAttribute(FabricTypes::inputs_tex_coord_offset, FabricTokens::inputs_tex_coord_offset); attributes.addAttribute(FabricTypes::inputs_tex_coord_rotation, FabricTokens::inputs_tex_coord_rotation); attributes.addAttribute(FabricTypes::inputs_tex_coord_scale, FabricTokens::inputs_tex_coord_scale); attributes.addAttribute(FabricTypes::inputs_tex_coord_index, FabricTokens::inputs_tex_coord_index); attributes.addAttribute(FabricTypes::inputs_texture, FabricTokens::inputs_texture); attributes.addAttribute(FabricTypes::inputs_wrap_s, FabricTokens::inputs_wrap_s); attributes.addAttribute(FabricTypes::inputs_wrap_t, FabricTokens::inputs_wrap_t); for (const auto& additionalAttribute : additionalAttributes) { attributes.addAttribute(additionalAttribute.first, additionalAttribute.second); } createAttributes(*_pContext, fabricStage, path, attributes, subIdentifier); // _paramColorSpace is an array of pairs: [texture_parameter_token, color_space_enum], [texture_parameter_token, color_space_enum], ... fabricStage.setArrayAttributeSize(path, FabricTokens::_paramColorSpace, 2); const auto paramColorSpaceFabric = fabricStage.getArrayAttributeWr<omni::fabric::TokenC>(path, FabricTokens::_paramColorSpace); paramColorSpaceFabric[0] = FabricTokens::inputs_texture; paramColorSpaceFabric[1] = FabricTokens::_auto; } void FabricMaterial::createTexture(const omni::fabric::Path& path) { return createTextureCommon(path, FabricTokens::cesium_internal_texture_lookup); } void FabricMaterial::createRasterOverlay(const omni::fabric::Path& path) { static const auto additionalAttributes = std::vector<std::pair<omni::fabric::Type, omni::fabric::Token>>{{ std::make_pair(FabricTypes::inputs_alpha, FabricTokens::inputs_alpha), }}; return createTextureCommon(path, FabricTokens::cesium_internal_raster_overlay_lookup, additionalAttributes); } void FabricMaterial::createRasterOverlayResolverCommon( const omni::fabric::Path& path, uint64_t rasterOverlayCount, const omni::fabric::Token& subidentifier) { auto& fabricStage = _pContext->getFabricStage(); fabricStage.createPrim(path); FabricAttributesBuilder attributes(_pContext); attributes.addAttribute(FabricTypes::inputs_raster_overlay_count, FabricTokens::inputs_raster_overlay_count); createAttributes(*_pContext, fabricStage, path, attributes, subidentifier); const auto rasterOverlayCountFabric = fabricStage.getAttributeWr<int>(path, FabricTokens::inputs_raster_overlay_count); *rasterOverlayCountFabric = static_cast<int>(rasterOverlayCount); } void FabricMaterial::createRasterOverlayResolver(const omni::fabric::Path& path, uint64_t rasterOverlayCount) { createRasterOverlayResolverCommon(path, rasterOverlayCount, FabricTokens::cesium_internal_raster_overlay_resolver); } void FabricMaterial::createClippingRasterOverlayResolver( const omni::fabric::Path& path, uint64_t clippingRasterOverlayCount) { createRasterOverlayResolverCommon( path, clippingRasterOverlayCount, FabricTokens::cesium_internal_clipping_raster_overlay_resolver); } void FabricMaterial::createFeatureIdIndex(const omni::fabric::Path& path) { createFeatureIdAttribute(path); } void FabricMaterial::createFeatureIdAttribute(const omni::fabric::Path& path) { auto& fabricStage = _pContext->getFabricStage(); fabricStage.createPrim(path); FabricAttributesBuilder attributes(_pContext); attributes.addAttribute(FabricTypes::inputs_primvar_name, FabricTokens::inputs_primvar_name); attributes.addAttribute(FabricTypes::inputs_null_feature_id, FabricTokens::inputs_null_feature_id); createAttributes( *_pContext, fabricStage, path, attributes, FabricTokens::cesium_internal_feature_id_attribute_lookup); } void FabricMaterial::createFeatureIdTexture(const omni::fabric::Path& path) { static const auto additionalAttributes = std::vector<std::pair<omni::fabric::Type, omni::fabric::Token>>{{ std::make_pair(FabricTypes::inputs_channels, FabricTokens::inputs_channels), std::make_pair(FabricTypes::inputs_channel_count, FabricTokens::inputs_channel_count), std::make_pair(FabricTypes::inputs_null_feature_id, FabricTokens::inputs_null_feature_id), }}; return createTextureCommon(path, FabricTokens::cesium_internal_feature_id_texture_lookup, additionalAttributes); } void FabricMaterial::createPropertyAttributePropertyInt( const omni::fabric::Path& path, const omni::fabric::Token& subidentifier, const omni::fabric::Type& noDataType, const omni::fabric::Type& defaultValueType) { auto& fabricStage = _pContext->getFabricStage(); fabricStage.createPrim(path); FabricAttributesBuilder attributes(_pContext); attributes.addAttribute(FabricTypes::inputs_primvar_name, FabricTokens::inputs_primvar_name); attributes.addAttribute(FabricTypes::inputs_has_no_data, FabricTokens::inputs_has_no_data); attributes.addAttribute(noDataType, FabricTokens::inputs_no_data); attributes.addAttribute(defaultValueType, FabricTokens::inputs_default_value); createAttributes(*_pContext, fabricStage, path, attributes, subidentifier); } void FabricMaterial::createPropertyAttributePropertyNormalizedInt( const omni::fabric::Path& path, const omni::fabric::Token& subidentifier, const omni::fabric::Type& noDataType, const omni::fabric::Type& defaultValueType, const omni::fabric::Type& offsetType, const omni::fabric::Type& scaleType, const omni::fabric::Type& maximumValueType) { auto& fabricStage = _pContext->getFabricStage(); fabricStage.createPrim(path); FabricAttributesBuilder attributes(_pContext); attributes.addAttribute(FabricTypes::inputs_primvar_name, FabricTokens::inputs_primvar_name); attributes.addAttribute(FabricTypes::inputs_has_no_data, FabricTokens::inputs_has_no_data); attributes.addAttribute(noDataType, FabricTokens::inputs_no_data); attributes.addAttribute(defaultValueType, FabricTokens::inputs_default_value); attributes.addAttribute(offsetType, FabricTokens::inputs_offset); attributes.addAttribute(scaleType, FabricTokens::inputs_scale); attributes.addAttribute(maximumValueType, FabricTokens::inputs_maximum_value); createAttributes(*_pContext, fabricStage, path, attributes, subidentifier); } void FabricMaterial::createPropertyAttributePropertyFloat( const omni::fabric::Path& path, const omni::fabric::Token& subidentifier, const omni::fabric::Type& noDataType, const omni::fabric::Type& defaultValueType, const omni::fabric::Type& offsetType, const omni::fabric::Type& scaleType) { auto& fabricStage = _pContext->getFabricStage(); fabricStage.createPrim(path); FabricAttributesBuilder attributes(_pContext); attributes.addAttribute(FabricTypes::inputs_primvar_name, FabricTokens::inputs_primvar_name); attributes.addAttribute(FabricTypes::inputs_has_no_data, FabricTokens::inputs_has_no_data); attributes.addAttribute(noDataType, FabricTokens::inputs_no_data); attributes.addAttribute(defaultValueType, FabricTokens::inputs_default_value); attributes.addAttribute(offsetType, FabricTokens::inputs_offset); attributes.addAttribute(scaleType, FabricTokens::inputs_scale); createAttributes(*_pContext, fabricStage, path, attributes, subidentifier); } void FabricMaterial::createPropertyAttributeProperty(const omni::fabric::Path& path, MdlInternalPropertyType type) { switch (type) { case MdlInternalPropertyType::INT32: createPropertyAttributePropertyInt( path, FabricTokens::cesium_internal_property_attribute_int_lookup, FabricTypes::inputs_no_data_int, FabricTypes::inputs_default_value_int); break; case MdlInternalPropertyType::VEC2_INT32: createPropertyAttributePropertyInt( path, FabricTokens::cesium_internal_property_attribute_int2_lookup, FabricTypes::inputs_no_data_int2, FabricTypes::inputs_default_value_int2); break; case MdlInternalPropertyType::VEC3_INT32: createPropertyAttributePropertyInt( path, FabricTokens::cesium_internal_property_attribute_int3_lookup, FabricTypes::inputs_no_data_int3, FabricTypes::inputs_default_value_int3); break; case MdlInternalPropertyType::VEC4_INT32: createPropertyAttributePropertyInt( path, FabricTokens::cesium_internal_property_attribute_int4_lookup, FabricTypes::inputs_no_data_int4, FabricTypes::inputs_default_value_int4); break; case MdlInternalPropertyType::INT32_NORM: createPropertyAttributePropertyNormalizedInt( path, FabricTokens::cesium_internal_property_attribute_normalized_int_lookup, FabricTypes::inputs_no_data_int, FabricTypes::inputs_default_value_float, FabricTypes::inputs_offset_float, FabricTypes::inputs_scale_float, FabricTypes::inputs_maximum_value_int); break; case MdlInternalPropertyType::VEC2_INT32_NORM: createPropertyAttributePropertyNormalizedInt( path, FabricTokens::cesium_internal_property_attribute_normalized_int2_lookup, FabricTypes::inputs_no_data_int2, FabricTypes::inputs_default_value_float2, FabricTypes::inputs_offset_float2, FabricTypes::inputs_scale_float2, FabricTypes::inputs_maximum_value_int2); break; case MdlInternalPropertyType::VEC3_INT32_NORM: createPropertyAttributePropertyNormalizedInt( path, FabricTokens::cesium_internal_property_attribute_normalized_int3_lookup, FabricTypes::inputs_no_data_int3, FabricTypes::inputs_default_value_float3, FabricTypes::inputs_offset_float3, FabricTypes::inputs_scale_float3, FabricTypes::inputs_maximum_value_int3); break; case MdlInternalPropertyType::VEC4_INT32_NORM: createPropertyAttributePropertyNormalizedInt( path, FabricTokens::cesium_internal_property_attribute_normalized_int4_lookup, FabricTypes::inputs_no_data_int4, FabricTypes::inputs_default_value_float4, FabricTypes::inputs_offset_float4, FabricTypes::inputs_scale_float4, FabricTypes::inputs_maximum_value_int4); break; case MdlInternalPropertyType::FLOAT32: createPropertyAttributePropertyFloat( path, FabricTokens::cesium_internal_property_attribute_float_lookup, FabricTypes::inputs_no_data_float, FabricTypes::inputs_default_value_float, FabricTypes::inputs_offset_float, FabricTypes::inputs_scale_float); break; case MdlInternalPropertyType::VEC2_FLOAT32: createPropertyAttributePropertyFloat( path, FabricTokens::cesium_internal_property_attribute_float2_lookup, FabricTypes::inputs_no_data_float2, FabricTypes::inputs_default_value_float2, FabricTypes::inputs_offset_float2, FabricTypes::inputs_scale_float2); break; case MdlInternalPropertyType::VEC3_FLOAT32: createPropertyAttributePropertyFloat( path, FabricTokens::cesium_internal_property_attribute_float3_lookup, FabricTypes::inputs_no_data_float3, FabricTypes::inputs_default_value_float3, FabricTypes::inputs_offset_float3, FabricTypes::inputs_scale_float3); break; case MdlInternalPropertyType::VEC4_FLOAT32: createPropertyAttributePropertyFloat( path, FabricTokens::cesium_internal_property_attribute_float4_lookup, FabricTypes::inputs_no_data_float4, FabricTypes::inputs_default_value_float4, FabricTypes::inputs_offset_float4, FabricTypes::inputs_scale_float4); break; case MdlInternalPropertyType::MAT2_INT32: case MdlInternalPropertyType::MAT2_FLOAT32: case MdlInternalPropertyType::MAT2_INT32_NORM: case MdlInternalPropertyType::MAT3_INT32: case MdlInternalPropertyType::MAT3_FLOAT32: case MdlInternalPropertyType::MAT3_INT32_NORM: case MdlInternalPropertyType::MAT4_INT32: case MdlInternalPropertyType::MAT4_FLOAT32: case MdlInternalPropertyType::MAT4_INT32_NORM: break; } } void FabricMaterial::createPropertyTexturePropertyInt( const omni::fabric::Path& path, const omni::fabric::Token& subidentifier, const omni::fabric::Type& noDataType, const omni::fabric::Type& defaultValueType) { static const auto additionalAttributes = std::vector<std::pair<omni::fabric::Type, omni::fabric::Token>>{{ std::make_pair(FabricTypes::inputs_channels, FabricTokens::inputs_channels), std::make_pair(FabricTypes::inputs_has_no_data, FabricTokens::inputs_has_no_data), std::make_pair(noDataType, FabricTokens::inputs_no_data), std::make_pair(defaultValueType, FabricTokens::inputs_default_value), }}; return createTextureCommon(path, subidentifier, additionalAttributes); } void FabricMaterial::createPropertyTexturePropertyNormalizedInt( const omni::fabric::Path& path, const omni::fabric::Token& subidentifier, const omni::fabric::Type& noDataType, const omni::fabric::Type& defaultValueType, const omni::fabric::Type& offsetType, const omni::fabric::Type& scaleType, const omni::fabric::Type& maximumValueType) { static const auto additionalAttributes = std::vector<std::pair<omni::fabric::Type, omni::fabric::Token>>{{ std::make_pair(FabricTypes::inputs_channels, FabricTokens::inputs_channels), std::make_pair(FabricTypes::inputs_has_no_data, FabricTokens::inputs_has_no_data), std::make_pair(noDataType, FabricTokens::inputs_no_data), std::make_pair(defaultValueType, FabricTokens::inputs_default_value), std::make_pair(offsetType, FabricTokens::inputs_offset), std::make_pair(scaleType, FabricTokens::inputs_scale), std::make_pair(maximumValueType, FabricTokens::inputs_maximum_value), }}; return createTextureCommon(path, subidentifier, additionalAttributes); } void FabricMaterial::createPropertyTextureProperty(const omni::fabric::Path& path, MdlInternalPropertyType type) { switch (type) { case MdlInternalPropertyType::INT32: createPropertyTexturePropertyInt( path, FabricTokens::cesium_internal_property_texture_int_lookup, FabricTypes::inputs_no_data_int, FabricTypes::inputs_default_value_int); break; case MdlInternalPropertyType::VEC2_INT32: createPropertyTexturePropertyInt( path, FabricTokens::cesium_internal_property_texture_int2_lookup, FabricTypes::inputs_no_data_int2, FabricTypes::inputs_default_value_int2); break; case MdlInternalPropertyType::VEC3_INT32: createPropertyTexturePropertyInt( path, FabricTokens::cesium_internal_property_texture_int3_lookup, FabricTypes::inputs_no_data_int3, FabricTypes::inputs_default_value_int3); break; case MdlInternalPropertyType::VEC4_INT32: createPropertyTexturePropertyInt( path, FabricTokens::cesium_internal_property_texture_int4_lookup, FabricTypes::inputs_no_data_int4, FabricTypes::inputs_default_value_int4); break; case MdlInternalPropertyType::INT32_NORM: createPropertyTexturePropertyNormalizedInt( path, FabricTokens::cesium_internal_property_texture_normalized_int_lookup, FabricTypes::inputs_no_data_int, FabricTypes::inputs_default_value_float, FabricTypes::inputs_offset_float, FabricTypes::inputs_scale_float, FabricTypes::inputs_maximum_value_int); break; case MdlInternalPropertyType::VEC2_INT32_NORM: createPropertyTexturePropertyNormalizedInt( path, FabricTokens::cesium_internal_property_texture_normalized_int2_lookup, FabricTypes::inputs_no_data_int2, FabricTypes::inputs_default_value_float2, FabricTypes::inputs_offset_float2, FabricTypes::inputs_scale_float2, FabricTypes::inputs_maximum_value_int2); break; case MdlInternalPropertyType::VEC3_INT32_NORM: createPropertyTexturePropertyNormalizedInt( path, FabricTokens::cesium_internal_property_texture_normalized_int3_lookup, FabricTypes::inputs_no_data_int3, FabricTypes::inputs_default_value_float3, FabricTypes::inputs_offset_float3, FabricTypes::inputs_scale_float3, FabricTypes::inputs_maximum_value_int3); break; case MdlInternalPropertyType::VEC4_INT32_NORM: createPropertyTexturePropertyNormalizedInt( path, FabricTokens::cesium_internal_property_texture_normalized_int4_lookup, FabricTypes::inputs_no_data_int4, FabricTypes::inputs_default_value_float4, FabricTypes::inputs_offset_float4, FabricTypes::inputs_scale_float4, FabricTypes::inputs_maximum_value_int4); break; case MdlInternalPropertyType::FLOAT32: case MdlInternalPropertyType::VEC2_FLOAT32: case MdlInternalPropertyType::VEC3_FLOAT32: case MdlInternalPropertyType::VEC4_FLOAT32: case MdlInternalPropertyType::MAT2_INT32: case MdlInternalPropertyType::MAT2_FLOAT32: case MdlInternalPropertyType::MAT2_INT32_NORM: case MdlInternalPropertyType::MAT3_INT32: case MdlInternalPropertyType::MAT3_FLOAT32: case MdlInternalPropertyType::MAT3_INT32_NORM: case MdlInternalPropertyType::MAT4_INT32: case MdlInternalPropertyType::MAT4_FLOAT32: case MdlInternalPropertyType::MAT4_INT32_NORM: break; } } void FabricMaterial::createPropertyTablePropertyInt( const omni::fabric::Path& path, const omni::fabric::Token& subidentifier, const omni::fabric::Type& noDataType, const omni::fabric::Type& defaultValueType) { auto& fabricStage = _pContext->getFabricStage(); fabricStage.createPrim(path); FabricAttributesBuilder attributes(_pContext); attributes.addAttribute(FabricTypes::inputs_property_table_texture, FabricTokens::inputs_property_table_texture); attributes.addAttribute(FabricTypes::inputs_has_no_data, FabricTokens::inputs_has_no_data); attributes.addAttribute(noDataType, FabricTokens::inputs_no_data); attributes.addAttribute(defaultValueType, FabricTokens::inputs_default_value); createAttributes(*_pContext, fabricStage, path, attributes, subidentifier); } void FabricMaterial::createPropertyTablePropertyNormalizedInt( const omni::fabric::Path& path, const omni::fabric::Token& subidentifier, const omni::fabric::Type& noDataType, const omni::fabric::Type& defaultValueType, const omni::fabric::Type& offsetType, const omni::fabric::Type& scaleType, const omni::fabric::Type& maximumValueType) { auto& fabricStage = _pContext->getFabricStage(); fabricStage.createPrim(path); FabricAttributesBuilder attributes(_pContext); attributes.addAttribute(FabricTypes::inputs_property_table_texture, FabricTokens::inputs_property_table_texture); attributes.addAttribute(FabricTypes::inputs_has_no_data, FabricTokens::inputs_has_no_data); attributes.addAttribute(noDataType, FabricTokens::inputs_no_data); attributes.addAttribute(defaultValueType, FabricTokens::inputs_default_value); attributes.addAttribute(offsetType, FabricTokens::inputs_offset); attributes.addAttribute(scaleType, FabricTokens::inputs_scale); attributes.addAttribute(maximumValueType, FabricTokens::inputs_maximum_value); createAttributes(*_pContext, fabricStage, path, attributes, subidentifier); } void FabricMaterial::createPropertyTablePropertyFloat( const omni::fabric::Path& path, const omni::fabric::Token& subidentifier, const omni::fabric::Type& noDataType, const omni::fabric::Type& defaultValueType, const omni::fabric::Type& offsetType, const omni::fabric::Type& scaleType) { auto& fabricStage = _pContext->getFabricStage(); fabricStage.createPrim(path); FabricAttributesBuilder attributes(_pContext); attributes.addAttribute(FabricTypes::inputs_property_table_texture, FabricTokens::inputs_property_table_texture); attributes.addAttribute(FabricTypes::inputs_has_no_data, FabricTokens::inputs_has_no_data); attributes.addAttribute(noDataType, FabricTokens::inputs_no_data); attributes.addAttribute(defaultValueType, FabricTokens::inputs_default_value); attributes.addAttribute(offsetType, FabricTokens::inputs_offset); attributes.addAttribute(scaleType, FabricTokens::inputs_scale); createAttributes(*_pContext, fabricStage, path, attributes, subidentifier); } void FabricMaterial::createPropertyTableProperty(const omni::fabric::Path& path, MdlInternalPropertyType type) { switch (type) { case MdlInternalPropertyType::INT32: createPropertyTablePropertyInt( path, FabricTokens::cesium_internal_property_table_int_lookup, FabricTypes::inputs_no_data_int, FabricTypes::inputs_default_value_int); break; case MdlInternalPropertyType::VEC2_INT32: createPropertyTablePropertyInt( path, FabricTokens::cesium_internal_property_table_int2_lookup, FabricTypes::inputs_no_data_int2, FabricTypes::inputs_default_value_int2); break; case MdlInternalPropertyType::VEC3_INT32: createPropertyTablePropertyInt( path, FabricTokens::cesium_internal_property_table_int3_lookup, FabricTypes::inputs_no_data_int3, FabricTypes::inputs_default_value_int3); break; case MdlInternalPropertyType::VEC4_INT32: createPropertyTablePropertyInt( path, FabricTokens::cesium_internal_property_table_int4_lookup, FabricTypes::inputs_no_data_int4, FabricTypes::inputs_default_value_int4); break; case MdlInternalPropertyType::INT32_NORM: createPropertyTablePropertyNormalizedInt( path, FabricTokens::cesium_internal_property_table_normalized_int_lookup, FabricTypes::inputs_no_data_int, FabricTypes::inputs_default_value_float, FabricTypes::inputs_offset_float, FabricTypes::inputs_scale_float, FabricTypes::inputs_maximum_value_int); break; case MdlInternalPropertyType::VEC2_INT32_NORM: createPropertyTablePropertyNormalizedInt( path, FabricTokens::cesium_internal_property_table_normalized_int2_lookup, FabricTypes::inputs_no_data_int2, FabricTypes::inputs_default_value_float2, FabricTypes::inputs_offset_float2, FabricTypes::inputs_scale_float2, FabricTypes::inputs_maximum_value_int2); break; case MdlInternalPropertyType::VEC3_INT32_NORM: createPropertyTablePropertyNormalizedInt( path, FabricTokens::cesium_internal_property_table_normalized_int3_lookup, FabricTypes::inputs_no_data_int3, FabricTypes::inputs_default_value_float3, FabricTypes::inputs_offset_float3, FabricTypes::inputs_scale_float3, FabricTypes::inputs_maximum_value_int3); break; case MdlInternalPropertyType::VEC4_INT32_NORM: createPropertyTablePropertyNormalizedInt( path, FabricTokens::cesium_internal_property_table_normalized_int4_lookup, FabricTypes::inputs_no_data_int4, FabricTypes::inputs_default_value_float4, FabricTypes::inputs_offset_float4, FabricTypes::inputs_scale_float4, FabricTypes::inputs_maximum_value_int4); break; case MdlInternalPropertyType::FLOAT32: createPropertyTablePropertyFloat( path, FabricTokens::cesium_internal_property_table_float_lookup, FabricTypes::inputs_no_data_float, FabricTypes::inputs_default_value_float, FabricTypes::inputs_offset_float, FabricTypes::inputs_scale_float); break; case MdlInternalPropertyType::VEC2_FLOAT32: createPropertyTablePropertyFloat( path, FabricTokens::cesium_internal_property_table_float2_lookup, FabricTypes::inputs_no_data_float2, FabricTypes::inputs_default_value_float2, FabricTypes::inputs_offset_float2, FabricTypes::inputs_scale_float2); break; case MdlInternalPropertyType::VEC3_FLOAT32: createPropertyTablePropertyFloat( path, FabricTokens::cesium_internal_property_table_float3_lookup, FabricTypes::inputs_no_data_float3, FabricTypes::inputs_default_value_float3, FabricTypes::inputs_offset_float3, FabricTypes::inputs_scale_float3); break; case MdlInternalPropertyType::VEC4_FLOAT32: createPropertyTablePropertyFloat( path, FabricTokens::cesium_internal_property_table_float4_lookup, FabricTypes::inputs_no_data_float4, FabricTypes::inputs_default_value_float4, FabricTypes::inputs_offset_float4, FabricTypes::inputs_scale_float4); break; case MdlInternalPropertyType::MAT2_INT32: case MdlInternalPropertyType::MAT2_FLOAT32: case MdlInternalPropertyType::MAT2_INT32_NORM: case MdlInternalPropertyType::MAT3_INT32: case MdlInternalPropertyType::MAT3_FLOAT32: case MdlInternalPropertyType::MAT3_INT32_NORM: case MdlInternalPropertyType::MAT4_INT32: case MdlInternalPropertyType::MAT4_FLOAT32: case MdlInternalPropertyType::MAT4_INT32_NORM: break; } } void FabricMaterial::reset() { if (_usesDefaultMaterial) { setShaderValues( _shaderPath, GltfUtil::getDefaultMaterialInfo(), DEFAULT_DISPLAY_COLOR, DEFAULT_DISPLAY_OPACITY); } if (_materialDescriptor.hasBaseColorTexture()) { setTextureValues( _baseColorTexturePath, _defaultWhiteTextureAssetPathToken, GltfUtil::getDefaultTextureInfo(), DEFAULT_TEXCOORD_INDEX); } for (const auto& featureIdIndexPath : _featureIdIndexPaths) { setFeatureIdIndexValues(featureIdIndexPath, DEFAULT_NULL_FEATURE_ID); } for (const auto& featureIdAttributePath : _featureIdAttributePaths) { setFeatureIdAttributeValues(featureIdAttributePath, DEFAULT_FEATURE_ID_PRIMVAR_NAME, DEFAULT_NULL_FEATURE_ID); } for (const auto& featureIdTexturePath : _featureIdTexturePaths) { setFeatureIdTextureValues( featureIdTexturePath, _defaultTransparentTextureAssetPathToken, GltfUtil::getDefaultTextureInfo(), DEFAULT_TEXCOORD_INDEX, DEFAULT_NULL_FEATURE_ID); } for (const auto& [type, paths] : _propertyAttributePropertyPaths) { for (const auto& path : paths) { CALL_TEMPLATED_FUNCTION_WITH_RUNTIME_MDL_TYPE( clearPropertyAttributeProperty, type, _pContext->getFabricStage(), path); } } for (const auto& [type, paths] : _propertyTexturePropertyPaths) { for (const auto& path : paths) { CALL_TEMPLATED_FUNCTION_WITH_RUNTIME_MDL_TYPE( clearPropertyTextureProperty, type, _pContext->getFabricStage(), path, _defaultTransparentTextureAssetPathToken); } } for (const auto& [type, paths] : _propertyTablePropertyPaths) { for (const auto& path : paths) { CALL_TEMPLATED_FUNCTION_WITH_RUNTIME_MDL_TYPE( clearPropertyTableProperty, type, _pContext->getFabricStage(), path, _defaultTransparentTextureAssetPathToken); } } for (const auto& rasterOverlayPath : _rasterOverlayPaths) { setRasterOverlayValues( rasterOverlayPath, _defaultTransparentTextureAssetPathToken, GltfUtil::getDefaultTextureInfo(), DEFAULT_TEXCOORD_INDEX, DEFAULT_ALPHA); } for (const auto& path : _allPaths) { auto& fabricStage = _pContext->getFabricStage(); const auto tilesetIdFabric = fabricStage.getAttributeWr<int64_t>(path, FabricTokens::_cesium_tilesetId); *tilesetIdFabric = FabricUtil::NO_TILESET_ID; } } void FabricMaterial::setMaterial( const CesiumGltf::Model& model, const CesiumGltf::MeshPrimitive& primitive, int64_t tilesetId, const FabricMaterialInfo& materialInfo, const FabricFeaturesInfo& featuresInfo, FabricTexture* pBaseColorTexture, const std::vector<std::shared_ptr<FabricTexture>>& featureIdTextures, const std::vector<std::shared_ptr<FabricTexture>>& propertyTextures, const std::vector<std::shared_ptr<FabricTexture>>& propertyTableTextures, const glm::dvec3& displayColor, double displayOpacity, const std::unordered_map<uint64_t, uint64_t>& texcoordIndexMapping, const std::vector<uint64_t>& featureIdIndexSetIndexMapping, const std::vector<uint64_t>& featureIdAttributeSetIndexMapping, const std::vector<uint64_t>& featureIdTextureSetIndexMapping, const std::unordered_map<uint64_t, uint64_t>& propertyTextureIndexMapping) { if (stageDestroyed()) { return; } if (_usesDefaultMaterial) { _alphaMode = getInitialAlphaMode(_materialDescriptor, materialInfo); if (_debugRandomColors) { const auto r = glm::linearRand(0.0, 1.0); const auto g = glm::linearRand(0.0, 1.0); const auto b = glm::linearRand(0.0, 1.0); _debugColor = glm::dvec3(r, g, b); } else { _debugColor = DEFAULT_DEBUG_COLOR; } setShaderValues(_shaderPath, materialInfo, displayColor, displayOpacity); } if (_materialDescriptor.hasBaseColorTexture()) { const auto& textureInfo = materialInfo.baseColorTexture.value(); const auto& textureAssetPath = pBaseColorTexture->getAssetPathToken(); const auto texcoordIndex = texcoordIndexMapping.at(textureInfo.setIndex); setTextureValues(_baseColorTexturePath, textureAssetPath, textureInfo, texcoordIndex); } const auto featureIdCounts = getFeatureIdCounts(_materialDescriptor); for (uint64_t i = 0; i < featureIdCounts.indexCount; ++i) { const auto featureIdSetIndex = featureIdIndexSetIndexMapping[i]; const auto featureId = featuresInfo.featureIds[featureIdSetIndex]; const auto& featureIdPath = _featureIdPaths[featureIdSetIndex]; const auto nullFeatureId = CppUtil::defaultValue(featureId.nullFeatureId, DEFAULT_NULL_FEATURE_ID); setFeatureIdIndexValues(featureIdPath, nullFeatureId); } for (uint64_t i = 0; i < featureIdCounts.attributeCount; ++i) { const auto featureIdSetIndex = featureIdAttributeSetIndexMapping[i]; const auto featureId = featuresInfo.featureIds[featureIdSetIndex]; const auto attributeSetIndex = std::get<uint64_t>(featureId.featureIdStorage); const auto attributeName = fmt::format("_FEATURE_ID_{}", attributeSetIndex); const auto& featureIdPath = _featureIdPaths[featureIdSetIndex]; const auto nullFeatureId = CppUtil::defaultValue(featureId.nullFeatureId, DEFAULT_NULL_FEATURE_ID); setFeatureIdAttributeValues(featureIdPath, attributeName, nullFeatureId); } for (uint64_t i = 0; i < featureIdCounts.textureCount; ++i) { const auto featureIdSetIndex = featureIdTextureSetIndexMapping[i]; const auto& featureId = featuresInfo.featureIds[featureIdSetIndex]; const auto& textureInfo = std::get<FabricTextureInfo>(featureId.featureIdStorage); const auto& textureAssetPath = featureIdTextures[i]->getAssetPathToken(); const auto texcoordIndex = texcoordIndexMapping.at(textureInfo.setIndex); const auto& featureIdPath = _featureIdPaths[featureIdSetIndex]; const auto nullFeatureId = CppUtil::defaultValue(featureId.nullFeatureId, DEFAULT_NULL_FEATURE_ID); setFeatureIdTextureValues(featureIdPath, textureAssetPath, textureInfo, texcoordIndex, nullFeatureId); } const auto& properties = _materialDescriptor.getStyleableProperties(); if (!properties.empty()) { const auto getPropertyPath = [this, &properties](const std::string& propertyId) { const auto index = CppUtil::indexOfByMember(properties, &FabricPropertyDescriptor::propertyId, propertyId); assert(index != properties.size()); return _propertyPaths[index]; }; const auto unsupportedCallback = []([[maybe_unused]] const std::string& propertyId, [[maybe_unused]] const std::string& warning) {}; MetadataUtil::forEachStyleablePropertyAttributeProperty( *_pContext, model, primitive, [this, &getPropertyPath]( const std::string& propertyId, [[maybe_unused]] const auto& propertyAttributePropertyView, const auto& property) { constexpr auto type = std::decay_t<decltype(property)>::Type; constexpr auto mdlType = DataTypeUtil::getMdlInternalPropertyType<type>(); const auto& primvarName = property.attribute; const auto& propertyPath = getPropertyPath(propertyId); const auto& propertyInfo = property.propertyInfo; const auto hasNoData = propertyInfo.noData.has_value(); const auto offset = getOffset(propertyInfo); const auto scale = getScale(propertyInfo); const auto noData = getNoData(propertyInfo); const auto defaultValue = getDefaultValue(propertyInfo); constexpr auto maximumValue = getMaximumValue<type>(); setPropertyAttributePropertyValues<mdlType>( _pContext->getFabricStage(), propertyPath, primvarName, offset, scale, maximumValue, hasNoData, noData, defaultValue); }, unsupportedCallback); MetadataUtil::forEachStyleablePropertyTextureProperty( *_pContext, model, primitive, [this, &propertyTextures, &texcoordIndexMapping, &propertyTextureIndexMapping, &getPropertyPath]( const std::string& propertyId, [[maybe_unused]] const auto& propertyTexturePropertyView, const auto& property) { constexpr auto type = std::decay_t<decltype(property)>::Type; constexpr auto mdlType = DataTypeUtil::getMdlInternalPropertyType<type>(); const auto& textureInfo = property.textureInfo; const auto textureIndex = property.textureIndex; const auto& propertyPath = getPropertyPath(propertyId); const auto texcoordIndex = texcoordIndexMapping.at(textureInfo.setIndex); const auto propertyTextureIndex = propertyTextureIndexMapping.at(textureIndex); const auto& textureAssetPath = propertyTextures[propertyTextureIndex]->getAssetPathToken(); const auto& propertyInfo = property.propertyInfo; const auto hasNoData = propertyInfo.noData.has_value(); const auto offset = getOffset(propertyInfo); const auto scale = getScale(propertyInfo); const auto noData = getNoData(propertyInfo); const auto defaultValue = getDefaultValue(propertyInfo); constexpr auto maximumValue = getMaximumValue<type>(); setPropertyTexturePropertyValues<mdlType>( _pContext->getFabricStage(), propertyPath, textureAssetPath, textureInfo, texcoordIndex, offset, scale, maximumValue, hasNoData, noData, defaultValue); }, unsupportedCallback); uint64_t propertyTablePropertyCounter = 0; MetadataUtil::forEachStyleablePropertyTableProperty( *_pContext, model, primitive, [this, &propertyTableTextures, &propertyTablePropertyCounter, &getPropertyPath]( const std::string& propertyId, [[maybe_unused]] const auto& propertyTablePropertyView, const auto& property) { constexpr auto type = std::decay_t<decltype(property)>::Type; constexpr auto mdlType = DataTypeUtil::getMdlInternalPropertyType<type>(); const auto& propertyPath = getPropertyPath(propertyId); const auto textureIndex = propertyTablePropertyCounter++; const auto& textureAssetPath = propertyTableTextures[textureIndex]->getAssetPathToken(); const auto& propertyInfo = property.propertyInfo; const auto hasNoData = propertyInfo.noData.has_value(); const auto offset = getOffset(propertyInfo); const auto scale = getScale(propertyInfo); const auto noData = getNoData(propertyInfo); const auto defaultValue = getDefaultValue(propertyInfo); constexpr auto maximumValue = getMaximumValue<type>(); setPropertyTablePropertyValues<mdlType>( _pContext->getFabricStage(), propertyPath, textureAssetPath, offset, scale, maximumValue, hasNoData, noData, defaultValue); }, unsupportedCallback); } for (const auto& path : _allPaths) { auto& fabricStage = _pContext->getFabricStage(); const auto tilesetIdFabric = fabricStage.getAttributeWr<int64_t>(path, FabricTokens::_cesium_tilesetId); *tilesetIdFabric = tilesetId; } } void FabricMaterial::createConnectionsToCopiedPaths() { auto& fabricStage = _pContext->getFabricStage(); const auto hasBaseColorTexture = _materialDescriptor.hasBaseColorTexture(); const auto rasterOverlay = getRasterOverlayCount(_materialDescriptor); const auto featureIdCount = getFeatureIdCounts(_materialDescriptor).totalCount; for (const auto& copiedPath : _copiedBaseColorTexturePaths) { if (hasBaseColorTexture) { createConnection(fabricStage, _baseColorTexturePath, copiedPath, FabricTokens::inputs_base_color_texture); } } for (const auto& copiedPath : _copiedRasterOverlayPaths) { const auto indexFabric = fabricStage.getAttributeRd<int>(copiedPath, FabricTokens::inputs_raster_overlay_index); const auto index = static_cast<uint64_t>(CppUtil::defaultValue(indexFabric, 0)); if (index < rasterOverlay) { createConnection(fabricStage, _rasterOverlayPaths[index], copiedPath, FabricTokens::inputs_raster_overlay); } } for (const auto& copiedPath : _copiedFeatureIdPaths) { const auto indexFabric = fabricStage.getAttributeRd<int>(copiedPath, FabricTokens::inputs_feature_id_set_index); const auto index = static_cast<uint64_t>(CppUtil::defaultValue(indexFabric, 0)); if (index < featureIdCount) { createConnection(fabricStage, _featureIdPaths[index], copiedPath, FabricTokens::inputs_feature_id); } } } void FabricMaterial::destroyConnectionsToCopiedPaths() { auto& fabricStage = _pContext->getFabricStage(); for (const auto& copiedPath : _copiedBaseColorTexturePaths) { destroyConnection(fabricStage, copiedPath, FabricTokens::inputs_base_color_texture); } for (const auto& copiedPath : _copiedRasterOverlayPaths) { destroyConnection(fabricStage, copiedPath, FabricTokens::inputs_raster_overlay); } for (const auto& copiedPath : _copiedFeatureIdPaths) { destroyConnection(fabricStage, copiedPath, FabricTokens::inputs_feature_id); } } void FabricMaterial::createConnectionsToProperties() { auto& fabricStage = _pContext->getFabricStage(); const auto& properties = _materialDescriptor.getStyleableProperties(); const auto& unsupportedPropertyWarnings = _materialDescriptor.getUnsupportedPropertyWarnings(); for (const auto& propertyPathExternal : _copiedPropertyPaths) { const auto propertyId = getStringFabric(fabricStage, propertyPathExternal, FabricTokens::inputs_property_id); const auto mdlIdentifier = FabricUtil::getMdlIdentifier(fabricStage, propertyPathExternal); const auto propertyTypeExternal = FabricUtil::getMdlExternalPropertyType(mdlIdentifier); const auto index = CppUtil::indexOfByMember(properties, &FabricPropertyDescriptor::propertyId, propertyId); if (index == properties.size()) { if (CppUtil::contains(unsupportedPropertyWarnings, propertyId)) { _pContext->getLogger()->oneTimeWarning(unsupportedPropertyWarnings.at(propertyId)); } else { _pContext->getLogger()->oneTimeWarning( "Could not find property \"{}\" referenced by {}. A default value will be returned instead.", propertyId, mdlIdentifier.getText()); } continue; } const auto propertyTypeInternal = properties[index].type; if (!FabricUtil::typesCompatible(propertyTypeExternal, propertyTypeInternal)) { _pContext->getLogger()->oneTimeWarning( "Property \"{}\" referenced by {} has incompatible type. A default value will be returned instead.", propertyId, mdlIdentifier.getText()); continue; } const auto& propertyPathInternal = _propertyPaths[index]; createConnection(fabricStage, propertyPathInternal, propertyPathExternal, FabricTokens::inputs_property_value); } } void FabricMaterial::destroyConnectionsToProperties() { auto& fabricStage = _pContext->getFabricStage(); for (const auto& copiedPath : _copiedPropertyPaths) { destroyConnection(fabricStage, copiedPath, FabricTokens::inputs_property_value); } } void FabricMaterial::setRasterOverlay( FabricTexture* pTexture, const FabricTextureInfo& textureInfo, uint64_t rasterOverlayIndex, double alpha, const std::unordered_map<uint64_t, uint64_t>& rasterOverlayTexcoordIndexMapping) { if (stageDestroyed()) { return; } if (rasterOverlayIndex >= _rasterOverlayPaths.size()) { return; } const auto& textureAssetPath = pTexture->getAssetPathToken(); const auto texcoordIndex = rasterOverlayTexcoordIndexMapping.at(textureInfo.setIndex); const auto& rasterOverlay = _rasterOverlayPaths[rasterOverlayIndex]; setRasterOverlayValues(rasterOverlay, textureAssetPath, textureInfo, texcoordIndex, alpha); } void FabricMaterial::setRasterOverlayAlpha(uint64_t rasterOverlayIndex, double alpha) { if (stageDestroyed()) { return; } if (rasterOverlayIndex >= _rasterOverlayPaths.size()) { return; } const auto& rasterOverlayPath = _rasterOverlayPaths[rasterOverlayIndex]; setRasterOverlayAlphaValue(rasterOverlayPath, alpha); } void FabricMaterial::setDisplayColorAndOpacity(const glm::dvec3& displayColor, double displayOpacity) { if (stageDestroyed()) { return; } if (!_usesDefaultMaterial) { return; } auto& fabricStage = _pContext->getFabricStage(); const auto tileColorFabric = fabricStage.getAttributeWr<glm::fvec4>(_shaderPath, FabricTokens::inputs_tile_color); const auto alphaModeFabric = fabricStage.getAttributeWr<int>(_shaderPath, FabricTokens::inputs_alpha_mode); *tileColorFabric = glm::fvec4(getTileColor(_debugColor, displayColor, displayOpacity)); *alphaModeFabric = getAlphaMode(_alphaMode, displayOpacity); } void FabricMaterial::updateShaderInput(const omni::fabric::Path& path, const omni::fabric::Token& attributeName) { if (stageDestroyed()) { return; } auto& fabricStage = _pContext->getFabricStage(); const auto iFabricStage = carb::getCachedInterface<omni::fabric::IStageReaderWriter>(); const auto copiedShaderPath = FabricUtil::getCopiedShaderPath(_materialPath, path); const auto attributesToCopy = std::vector<omni::fabric::TokenC>{attributeName.asTokenC()}; assert(fabricStage.primExists(copiedShaderPath)); iFabricStage->copySpecifiedAttributes( fabricStage.getId(), path, attributesToCopy.data(), copiedShaderPath, attributesToCopy.data(), attributesToCopy.size()); if (attributeName == FabricTokens::inputs_raster_overlay_index || attributeName == FabricTokens::inputs_feature_id_set_index) { destroyConnectionsToCopiedPaths(); createConnectionsToCopiedPaths(); } if (attributeName == FabricTokens::inputs_property_id) { destroyConnectionsToProperties(); createConnectionsToProperties(); } } void FabricMaterial::clearRasterOverlay(uint64_t rasterOverlayIndex) { if (stageDestroyed()) { return; } if (rasterOverlayIndex >= _rasterOverlayPaths.size()) { return; } const auto& rasterOverlayPath = _rasterOverlayPaths[rasterOverlayIndex]; setRasterOverlayValues( rasterOverlayPath, _defaultTransparentTextureAssetPathToken, GltfUtil::getDefaultTextureInfo(), DEFAULT_TEXCOORD_INDEX, DEFAULT_ALPHA); } void FabricMaterial::setShaderValues( const omni::fabric::Path& path, const FabricMaterialInfo& materialInfo, const glm::dvec3& displayColor, double displayOpacity) { auto& fabricStage = _pContext->getFabricStage(); const auto tileColorFabric = fabricStage.getAttributeWr<pxr::GfVec4f>(path, FabricTokens::inputs_tile_color); const auto alphaCutoffFabric = fabricStage.getAttributeWr<float>(path, FabricTokens::inputs_alpha_cutoff); const auto alphaModeFabric = fabricStage.getAttributeWr<int>(path, FabricTokens::inputs_alpha_mode); const auto baseAlphaFabric = fabricStage.getAttributeWr<float>(path, FabricTokens::inputs_base_alpha); const auto baseColorFactorFabric = fabricStage.getAttributeWr<pxr::GfVec3f>(path, FabricTokens::inputs_base_color_factor); const auto emissiveFactorFabric = fabricStage.getAttributeWr<pxr::GfVec3f>(path, FabricTokens::inputs_emissive_factor); const auto metallicFactorFabric = fabricStage.getAttributeWr<float>(path, FabricTokens::inputs_metallic_factor); const auto roughnessFactorFabric = fabricStage.getAttributeWr<float>(path, FabricTokens::inputs_roughness_factor); *tileColorFabric = UsdUtil::glmToUsdVector(glm::fvec4(getTileColor(_debugColor, displayColor, displayOpacity))); *alphaCutoffFabric = static_cast<float>(materialInfo.alphaCutoff); *alphaModeFabric = getAlphaMode(_alphaMode, displayOpacity); *baseAlphaFabric = static_cast<float>(materialInfo.baseAlpha); *baseColorFactorFabric = UsdUtil::glmToUsdVector(glm::fvec3(materialInfo.baseColorFactor)); *emissiveFactorFabric = UsdUtil::glmToUsdVector(glm::fvec3(materialInfo.emissiveFactor)); *metallicFactorFabric = static_cast<float>(materialInfo.metallicFactor); *roughnessFactorFabric = static_cast<float>(materialInfo.roughnessFactor); } void FabricMaterial::setTextureValues( const omni::fabric::Path& path, const pxr::TfToken& textureAssetPathToken, const FabricTextureInfo& textureInfo, uint64_t texcoordIndex) { setTextureValuesCommon(_pContext->getFabricStage(), path, textureAssetPathToken, textureInfo, texcoordIndex); } void FabricMaterial::setRasterOverlayValues( const omni::fabric::Path& path, const pxr::TfToken& textureAssetPathToken, const FabricTextureInfo& textureInfo, uint64_t texcoordIndex, double alpha) { setTextureValuesCommon(_pContext->getFabricStage(), path, textureAssetPathToken, textureInfo, texcoordIndex); setRasterOverlayAlphaValue(path, alpha); } void FabricMaterial::setRasterOverlayAlphaValue(const omni::fabric::Path& path, double alpha) { const auto alphaFabric = _pContext->getFabricStage().getAttributeWr<float>(path, FabricTokens::inputs_alpha); *alphaFabric = static_cast<float>(alpha); } void FabricMaterial::setFeatureIdIndexValues(const omni::fabric::Path& path, int nullFeatureId) { setFeatureIdAttributeValues(path, pxr::UsdTokens->vertexId.GetString(), nullFeatureId); } void FabricMaterial::setFeatureIdAttributeValues( const omni::fabric::Path& path, const std::string& primvarName, int nullFeatureId) { auto& fabricStage = _pContext->getFabricStage(); setStringFabric(fabricStage, path, FabricTokens::inputs_primvar_name, primvarName); const auto nullFeatureIdFabric = fabricStage.getAttributeWr<int>(path, FabricTokens::inputs_null_feature_id); *nullFeatureIdFabric = nullFeatureId; } void FabricMaterial::setFeatureIdTextureValues( const omni::fabric::Path& path, const pxr::TfToken& textureAssetPathToken, const FabricTextureInfo& textureInfo, uint64_t texcoordIndex, int nullFeatureId) { auto& fabricStage = _pContext->getFabricStage(); setTextureValuesCommonChannels(fabricStage, path, textureAssetPathToken, textureInfo, texcoordIndex); const auto nullFeatureIdFabric = fabricStage.getAttributeWr<int>(path, FabricTokens::inputs_null_feature_id); *nullFeatureIdFabric = nullFeatureId; } bool FabricMaterial::stageDestroyed() { // Tile render resources may be processed asynchronously even after the tileset and stage have been destroyed. // Add this check to all public member functions, including constructors and destructors, to prevent them from // modifying the stage. return _stageId != _pContext->getUsdStageId(); } } // namespace cesium::omniverse
87,750
C++
44.139403
160
0.700536
CesiumGS/cesium-omniverse/src/core/src/UsdScopedEdit.cpp
#include "cesium/omniverse/UsdScopedEdit.h" namespace cesium::omniverse { UsdScopedEdit::UsdScopedEdit(const pxr::UsdStageWeakPtr& pStage) : _pStage(pStage) , _sessionLayer(_pStage->GetSessionLayer()) , _sessionLayerWasEditable(_sessionLayer->PermissionToEdit()) , _originalEditTarget(_pStage->GetEditTarget()) { _sessionLayer->SetPermissionToEdit(true); _pStage->SetEditTarget(pxr::UsdEditTarget(_sessionLayer)); } UsdScopedEdit::~UsdScopedEdit() { _sessionLayer->SetPermissionToEdit(_sessionLayerWasEditable); _pStage->SetEditTarget(_originalEditTarget); } } // namespace cesium::omniverse
629
C++
28.999999
65
0.748808
CesiumGS/cesium-omniverse/src/core/src/FabricTexture.cpp
#include "cesium/omniverse/FabricTexture.h" #include "cesium/omniverse/Context.h" #include "cesium/omniverse/FabricTextureInfo.h" #include "cesium/omniverse/Logger.h" #include "cesium/omniverse/UsdUtil.h" #include <CesiumGltf/ImageCesium.h> #include <carb/Types.h> #include <omni/ui/ImageProvider/DynamicTextureProvider.h> #include <array> namespace cesium::omniverse { namespace { carb::Format getCompressedImageFormat(CesiumGltf::GpuCompressedPixelFormat pixelFormat, TransferFunction transferFunction) { switch (pixelFormat) { case CesiumGltf::GpuCompressedPixelFormat::BC1_RGB: switch (transferFunction) { case TransferFunction::LINEAR: return carb::Format::eBC1_RGBA_UNORM; case TransferFunction::SRGB: return carb::Format::eBC1_RGBA_SRGB; } return carb::Format::eUnknown; case CesiumGltf::GpuCompressedPixelFormat::BC3_RGBA: switch (transferFunction) { case TransferFunction::LINEAR: return carb::Format::eBC3_RGBA_UNORM; case TransferFunction::SRGB: return carb::Format::eBC3_RGBA_SRGB; } return carb::Format::eUnknown; case CesiumGltf::GpuCompressedPixelFormat::BC4_R: return carb::Format::eBC4_R_UNORM; case CesiumGltf::GpuCompressedPixelFormat::BC5_RG: return carb::Format::eBC5_RG_UNORM; case CesiumGltf::GpuCompressedPixelFormat::BC7_RGBA: switch (transferFunction) { case TransferFunction::LINEAR: return carb::Format::eBC7_RGBA_UNORM; case TransferFunction::SRGB: return carb::Format::eBC7_RGBA_SRGB; } return carb::Format::eUnknown; default: // Unsupported compressed texture format. return carb::Format::eUnknown; } } carb::Format getUncompressedImageFormat(uint64_t channels, uint64_t bytesPerChannel, TransferFunction transferFunction) { switch (channels) { case 1: switch (bytesPerChannel) { case 1: return carb::Format::eR8_UNORM; case 2: return carb::Format::eR16_UNORM; } break; case 2: switch (bytesPerChannel) { case 1: return carb::Format::eRG8_UNORM; case 2: return carb::Format::eRG16_UNORM; } break; case 4: switch (bytesPerChannel) { case 1: switch (transferFunction) { case TransferFunction::LINEAR: return carb::Format::eRGBA8_UNORM; case TransferFunction::SRGB: return carb::Format::eRGBA8_SRGB; } break; case 2: return carb::Format::eRGBA16_UNORM; } break; } return carb::Format::eUnknown; } } // namespace FabricTexture::FabricTexture(Context* pContext, const std::string& name, int64_t poolId) : _pContext(pContext) , _pTexture(std::make_unique<omni::ui::DynamicTextureProvider>(name)) , _assetPathToken(UsdUtil::getDynamicTextureProviderAssetPathToken(name)) , _poolId(poolId) { reset(); } FabricTexture::~FabricTexture() = default; void FabricTexture::setImage(const CesiumGltf::ImageCesium& image, TransferFunction transferFunction) { carb::Format imageFormat; const auto isCompressed = image.compressedPixelFormat != CesiumGltf::GpuCompressedPixelFormat::NONE; if (isCompressed) { imageFormat = getCompressedImageFormat(image.compressedPixelFormat, transferFunction); } else { imageFormat = getUncompressedImageFormat( static_cast<uint64_t>(image.channels), static_cast<uint64_t>(image.bytesPerChannel), transferFunction); } if (imageFormat == carb::Format::eUnknown) { _pContext->getLogger()->warn("Invalid image format"); } else { // As of Kit 105.1, omni::ui::kAutoCalculateStride doesn't work for compressed textures. This value somehow works. const auto stride = isCompressed ? 4ULL * static_cast<uint64_t>(image.width) : omni::ui::kAutoCalculateStride; const auto data = reinterpret_cast<const uint8_t*>(image.pixelData.data()); const auto dimensions = carb::Uint2{static_cast<uint32_t>(image.width), static_cast<uint32_t>(image.height)}; _pTexture->setBytesData(data, dimensions, stride, imageFormat); } } void FabricTexture::setBytes( const std::vector<std::byte>& bytes, uint64_t width, uint64_t height, carb::Format format) { const auto data = reinterpret_cast<const uint8_t*>(bytes.data()); const auto dimensions = carb::Uint2{static_cast<uint32_t>(width), static_cast<uint32_t>(height)}; _pTexture->setBytesData(data, dimensions, omni::ui::kAutoCalculateStride, format); } void FabricTexture::setActive(bool active) { if (!active) { reset(); } } const pxr::TfToken& FabricTexture::getAssetPathToken() const { return _assetPathToken; } int64_t FabricTexture::getPoolId() const { return _poolId; } void FabricTexture::reset() { const auto bytes = std::array<uint8_t, 4>{{255, 255, 255, 255}}; const auto size = carb::Uint2{1, 1}; _pTexture->setBytesData(bytes.data(), size, omni::ui::kAutoCalculateStride, carb::Format::eRGBA8_SRGB); } } // namespace cesium::omniverse
5,664
C++
34.40625
122
0.617232
CesiumGS/cesium-omniverse/src/core/src/FabricTexturePool.cpp
#include "cesium/omniverse/FabricTexturePool.h" #include "cesium/omniverse/Context.h" #include <spdlog/fmt/fmt.h> namespace cesium::omniverse { FabricTexturePool::FabricTexturePool(Context* pContext, int64_t poolId, uint64_t initialCapacity) : ObjectPool<FabricTexture>() , _pContext(pContext) , _poolId(poolId) { setCapacity(initialCapacity); } int64_t FabricTexturePool::getPoolId() const { return _poolId; } std::shared_ptr<FabricTexture> FabricTexturePool::createObject(uint64_t objectId) const { const auto contextId = _pContext->getContextId(); const auto name = fmt::format("/cesium_texture_pool_{}_object_{}_context_{}", _poolId, objectId, contextId); return std::make_shared<FabricTexture>(_pContext, name, _poolId); } void FabricTexturePool::setActive(FabricTexture* pTexture, bool active) const { pTexture->setActive(active); } }; // namespace cesium::omniverse
917
C++
28.612902
112
0.733915
CesiumGS/cesium-omniverse/src/core/src/UsdTokens.cpp
#include "cesium/omniverse/UsdTokens.h" #include <spdlog/fmt/fmt.h> // clang-format off PXR_NAMESPACE_OPEN_SCOPE #ifdef CESIUM_OMNI_MSVC __pragma(warning(push)) __pragma(warning(disable: 4003)) #endif #ifdef CESIUM_OMNI_CLANG #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wgnu-zero-variadic-macro-arguments" #endif TF_DEFINE_PUBLIC_TOKENS( UsdTokens, USD_TOKENS); #ifdef CESIUM_OMNI_CLANG #pragma clang diagnostic pop #endif #ifdef CESIUM_OMNI_MSVC __pragma(warning(pop)) #endif PXR_NAMESPACE_CLOSE_SCOPE // clang-format on namespace cesium::omniverse::FabricTokens { FABRIC_DEFINE_TOKENS(USD_TOKENS); namespace { std::mutex tokenMutex; std::vector<omni::fabric::Token> feature_id_tokens; std::vector<omni::fabric::Token> raster_overlay_tokens; std::vector<omni::fabric::Token> inputs_raster_overlay_tokens; std::vector<omni::fabric::Token> primvars_st_tokens; std::vector<omni::fabric::Token> property_tokens; const omni::fabric::TokenC getToken(std::vector<omni::fabric::Token>& tokens, uint64_t index, const std::string_view& prefix) { const auto lock = std::scoped_lock(tokenMutex); const auto size = index + 1; if (size > tokens.size()) { tokens.resize(size); } auto& token = tokens[index]; if (token.asTokenC() == omni::fabric::kUninitializedToken) { const auto tokenStr = fmt::format("{}_{}", prefix, index); token = omni::fabric::Token(tokenStr.c_str()); } return token.asTokenC(); } } // namespace const omni::fabric::TokenC feature_id_n(uint64_t index) { return getToken(feature_id_tokens, index, "feature_id"); } const omni::fabric::TokenC raster_overlay_n(uint64_t index) { return getToken(raster_overlay_tokens, index, "raster_overlay"); } const omni::fabric::TokenC inputs_raster_overlay_n(uint64_t index) { return getToken(inputs_raster_overlay_tokens, index, "inputs:raster_overlay"); } const omni::fabric::TokenC primvars_st_n(uint64_t index) { return getToken(primvars_st_tokens, index, "primvars:st"); } const omni::fabric::TokenC property_n(uint64_t index) { return getToken(property_tokens, index, "property"); } } // namespace cesium::omniverse::FabricTokens
2,365
C++
26.835294
104
0.664693
CesiumGS/cesium-omniverse/src/core/src/OmniIonRasterOverlay.cpp
#include "cesium/omniverse/OmniIonRasterOverlay.h" #include "cesium/omniverse/AssetRegistry.h" #include "cesium/omniverse/Broadcast.h" #include "cesium/omniverse/Context.h" #include "cesium/omniverse/Logger.h" #include "cesium/omniverse/OmniIonServer.h" #include "cesium/omniverse/UsdUtil.h" #include <CesiumAsync/IAssetResponse.h> #include <CesiumIonClient/Token.h> #include <CesiumRasterOverlays/IonRasterOverlay.h> #include <CesiumUsdSchemas/ionRasterOverlay.h> #include <CesiumUtility/IntrusivePointer.h> namespace cesium::omniverse { namespace {} // namespace OmniIonRasterOverlay::OmniIonRasterOverlay(Context* pContext, const pxr::SdfPath& path) : OmniRasterOverlay(pContext, path) { reload(); } int64_t OmniIonRasterOverlay::getIonAssetId() const { const auto cesiumIonRasterOverlay = UsdUtil::getCesiumIonRasterOverlay(_pContext->getUsdStage(), _path); if (!UsdUtil::isSchemaValid(cesiumIonRasterOverlay)) { return 0; } int64_t ionAssetId; cesiumIonRasterOverlay.GetIonAssetIdAttr().Get(&ionAssetId); return ionAssetId; } CesiumIonClient::Token OmniIonRasterOverlay::getIonAccessToken() const { const auto cesiumIonRasterOverlay = UsdUtil::getCesiumIonRasterOverlay(_pContext->getUsdStage(), _path); if (!UsdUtil::isSchemaValid(cesiumIonRasterOverlay)) { return {}; } std::string ionAccessToken; cesiumIonRasterOverlay.GetIonAccessTokenAttr().Get(&ionAccessToken); if (!ionAccessToken.empty()) { CesiumIonClient::Token t; t.token = ionAccessToken; return t; } const auto ionServerPath = getResolvedIonServerPath(); if (ionServerPath.IsEmpty()) { return {}; } const auto pIonServer = _pContext->getAssetRegistry().getIonServer(ionServerPath); if (!pIonServer) { return {}; } return pIonServer->getToken(); } std::string OmniIonRasterOverlay::getIonApiUrl() const { const auto ionServerPath = getResolvedIonServerPath(); if (ionServerPath.IsEmpty()) { return {}; } const auto pIonServer = _pContext->getAssetRegistry().getIonServer(ionServerPath); if (!pIonServer) { return {}; } return pIonServer->getIonServerApiUrl(); } pxr::SdfPath OmniIonRasterOverlay::getResolvedIonServerPath() const { const auto cesiumIonRasterOverlay = UsdUtil::getCesiumIonRasterOverlay(_pContext->getUsdStage(), _path); if (!UsdUtil::isSchemaValid(cesiumIonRasterOverlay)) { return {}; } pxr::SdfPathVector targets; cesiumIonRasterOverlay.GetIonServerBindingRel().GetForwardedTargets(&targets); if (!targets.empty()) { return targets.front(); } // Fall back to using the first ion server if there's no explicit binding const auto pIonServer = _pContext->getAssetRegistry().getFirstIonServer(); if (pIonServer) { return pIonServer->getPath(); } return {}; } CesiumRasterOverlays::RasterOverlay* OmniIonRasterOverlay::getRasterOverlay() const { return _pIonRasterOverlay.get(); } void OmniIonRasterOverlay::reload() { const auto rasterOverlayIonAssetId = getIonAssetId(); const auto rasterOverlayIonAccessToken = getIonAccessToken(); const auto rasterOverlayIonApiUrl = getIonApiUrl(); if (rasterOverlayIonAssetId <= 0 || rasterOverlayIonAccessToken.token.empty() || rasterOverlayIonApiUrl.empty()) { return; } const auto rasterOverlayName = UsdUtil::getName(_pContext->getUsdStage(), _path); auto options = createRasterOverlayOptions(); options.loadErrorCallback = [this, rasterOverlayIonAssetId, rasterOverlayName]( const CesiumRasterOverlays::RasterOverlayLoadFailureDetails& error) { // Check for a 401 connecting to Cesium ion, which means the token is invalid // (or perhaps the asset ID is). Also check for a 404, because ion returns 404 // when the token is valid but not authorized for the asset. const auto statusCode = error.pRequest && error.pRequest->response() ? error.pRequest->response()->statusCode() : 0; if (error.type == CesiumRasterOverlays::RasterOverlayLoadType::CesiumIon && (statusCode == 401 || statusCode == 404)) { Broadcast::showTroubleshooter({}, 0, "", rasterOverlayIonAssetId, rasterOverlayName, error.message); } _pContext->getLogger()->error(error.message); }; _pIonRasterOverlay = new CesiumRasterOverlays::IonRasterOverlay( rasterOverlayName, rasterOverlayIonAssetId, rasterOverlayIonAccessToken.token, options, rasterOverlayIonApiUrl); } } // namespace cesium::omniverse
4,675
C++
31.6993
120
0.708449
CesiumGS/cesium-omniverse/src/core/src/SettingsWrapper.cpp
#include "cesium/omniverse/SettingsWrapper.h" #include <carb/InterfaceUtils.h> #include <carb/settings/ISettings.h> #include <spdlog/fmt/bundled/format.h> namespace cesium::omniverse::Settings { namespace { const uint64_t MAX_SESSIONS = 10; const std::string_view SESSION_ION_SERVER_URL_BASE = "/persistent/exts/cesium.omniverse/sessions/session{}/ionServerUrl"; const std::string_view SESSION_USER_ACCESS_TOKEN_BASE = "/persistent/exts/cesium.omniverse/sessions/session{}/userAccessToken"; const char* MAX_CACHE_ITEMS_PATH = "/persistent/exts/cesium.omniverse/maxCacheItems"; std::string getIonApiUrlSettingPath(const uint64_t index) { return fmt::format(SESSION_ION_SERVER_URL_BASE, index); } std::string getAccessTokenSettingPath(const uint64_t index) { return fmt::format(SESSION_USER_ACCESS_TOKEN_BASE, index); } } // namespace std::vector<AccessToken> getAccessTokens() { const auto iSettings = carb::getCachedInterface<carb::settings::ISettings>(); std::vector<AccessToken> accessTokens; accessTokens.reserve(MAX_SESSIONS); for (uint64_t i = 0; i < MAX_SESSIONS; ++i) { const auto ionApiUrlKey = getIonApiUrlSettingPath(i); const auto accessTokenKey = getAccessTokenSettingPath(i); const auto ionApiUrlValue = iSettings->getStringBuffer(ionApiUrlKey.c_str()); const auto accessTokenValue = iSettings->getStringBuffer(accessTokenKey.c_str()); if (ionApiUrlValue && accessTokenValue) { // In C++ 20 this can be emplace_back without the {} accessTokens.push_back({ionApiUrlValue, accessTokenValue}); } } return accessTokens; } void setAccessToken(const AccessToken& accessToken) { const auto iSettings = carb::getCachedInterface<carb::settings::ISettings>(); const auto oldAccessTokens = getAccessTokens(); std::vector<AccessToken> newAccessTokens; newAccessTokens.reserve(oldAccessTokens.size() + 1); // Worst case we'll be growing by 1, so preempt that. for (const auto& oldAccessToken : oldAccessTokens) { if (oldAccessToken.ionApiUrl == accessToken.ionApiUrl) { continue; } newAccessTokens.push_back(oldAccessToken); } newAccessTokens.push_back(accessToken); clearTokens(); for (uint64_t i = 0; i < newAccessTokens.size(); ++i) { const auto ionApiUrlKey = getIonApiUrlSettingPath(i); const auto accessTokenKey = getAccessTokenSettingPath(i); iSettings->set(ionApiUrlKey.c_str(), newAccessTokens[i].ionApiUrl.c_str()); iSettings->set(accessTokenKey.c_str(), newAccessTokens[i].accessToken.c_str()); } } void removeAccessToken(const std::string& ionApiUrl) { const auto iSettings = carb::getCachedInterface<carb::settings::ISettings>(); const auto oldAccessTokens = getAccessTokens(); std::vector<AccessToken> newAccessTokens; newAccessTokens.reserve(oldAccessTokens.size()); for (auto& oldAccessToken : oldAccessTokens) { if (oldAccessToken.ionApiUrl == ionApiUrl) { continue; } newAccessTokens.push_back(oldAccessToken); } clearTokens(); for (uint64_t i = 0; i < newAccessTokens.size(); ++i) { const auto ionApiUrlKey = getIonApiUrlSettingPath(i); const auto accessTokenKey = getAccessTokenSettingPath(i); iSettings->set(ionApiUrlKey.c_str(), newAccessTokens[i].ionApiUrl.c_str()); iSettings->set(accessTokenKey.c_str(), newAccessTokens[i].accessToken.c_str()); } } void clearTokens() { const auto iSettings = carb::getCachedInterface<carb::settings::ISettings>(); for (uint64_t i = 0; i < MAX_SESSIONS; ++i) { const auto serverKey = getIonApiUrlSettingPath(i); const auto tokenKey = getAccessTokenSettingPath(i); iSettings->destroyItem(serverKey.c_str()); iSettings->destroyItem(tokenKey.c_str()); } } uint64_t getMaxCacheItems() { const int64_t defaultMaxCacheItems = 4096; const auto iSettings = carb::getCachedInterface<carb::settings::ISettings>(); iSettings->setDefaultInt64(MAX_CACHE_ITEMS_PATH, defaultMaxCacheItems); auto maxCacheItems = iSettings->getAsInt64(MAX_CACHE_ITEMS_PATH); return static_cast<uint64_t>(maxCacheItems); } } // namespace cesium::omniverse::Settings
4,311
C++
33.496
110
0.700765
CesiumGS/cesium-omniverse/src/core/src/LoggerSink.cpp
#include "cesium/omniverse/LoggerSink.h" namespace cesium::omniverse { LoggerSink::LoggerSink(omni::log::Level logLevel) : _logLevel(logLevel) { switch (logLevel) { case omni::log::Level::eVerbose: set_level(spdlog::level::trace); break; case omni::log::Level::eInfo: set_level(spdlog::level::info); break; case omni::log::Level::eWarn: set_level(spdlog::level::warn); break; case omni::log::Level::eError: set_level(spdlog::level::err); break; case omni::log::Level::eFatal: set_level(spdlog::level::critical); break; default: break; } } void LoggerSink::sink_it_([[maybe_unused]] const spdlog::details::log_msg& msg) { // The reason we don't need to provide a log channel as the first argument to each of these OMNI_LOG_ functions is // because CARB_PLUGIN_IMPL calls CARB_GLOBALS_EX which calls OMNI_GLOBALS_ADD_DEFAULT_CHANNEL and sets the channel // name to our plugin name: cesium.omniverse.plugin switch (_logLevel) { case omni::log::Level::eVerbose: OMNI_LOG_VERBOSE("%s", formatMessage(msg).c_str()); break; case omni::log::Level::eInfo: OMNI_LOG_INFO("%s", formatMessage(msg).c_str()); break; case omni::log::Level::eWarn: OMNI_LOG_WARN("%s", formatMessage(msg).c_str()); break; case omni::log::Level::eError: OMNI_LOG_ERROR("%s", formatMessage(msg).c_str()); break; case omni::log::Level::eFatal: OMNI_LOG_FATAL("%s", formatMessage(msg).c_str()); break; default: break; } } void LoggerSink::flush_() {} std::string LoggerSink::formatMessage(const spdlog::details::log_msg& msg) { // Frustratingly, spdlog::formatter isn't thread safe. So even though our sink // itself doesn't need to be protected by a mutex, the formatter does. // See https://github.com/gabime/spdlog/issues/897 std::scoped_lock<std::mutex> lock(_formatMutex); spdlog::memory_buf_t formatted; formatter_->format(msg, formatted); return fmt::to_string(formatted); } } // namespace cesium::omniverse
2,305
C++
33.41791
119
0.593059
CesiumGS/cesium-omniverse/src/core/src/UsdNotificationHandler.cpp
#include "cesium/omniverse/UsdNotificationHandler.h" #include "cesium/omniverse/AssetRegistry.h" #include "cesium/omniverse/Context.h" #include "cesium/omniverse/CppUtil.h" #include "cesium/omniverse/FabricResourceManager.h" #include "cesium/omniverse/FabricUtil.h" #include "cesium/omniverse/OmniCartographicPolygon.h" #include "cesium/omniverse/OmniGeoreference.h" #include "cesium/omniverse/OmniGlobeAnchor.h" #include "cesium/omniverse/OmniIonRasterOverlay.h" #include "cesium/omniverse/OmniIonServer.h" #include "cesium/omniverse/OmniPolygonRasterOverlay.h" #include "cesium/omniverse/OmniRasterOverlay.h" #include "cesium/omniverse/OmniTileMapServiceRasterOverlay.h" #include "cesium/omniverse/OmniTileset.h" #include "cesium/omniverse/OmniWebMapServiceRasterOverlay.h" #include "cesium/omniverse/OmniWebMapTileServiceRasterOverlay.h" #include "cesium/omniverse/UsdTokens.h" #include "cesium/omniverse/UsdUtil.h" #include <CesiumUsdSchemas/tokens.h> #include <pxr/usd/usd/primRange.h> #include <pxr/usd/usdShade/shader.h> namespace cesium::omniverse { namespace { bool isPrimOrDescendant(const pxr::SdfPath& descendantPath, const pxr::SdfPath& path) { if (descendantPath == path) { return true; } for (const auto& ancestorPath : descendantPath.GetAncestorsRange()) { if (ancestorPath == path) { return true; } } return false; } void updateRasterOverlayBindings(const Context& context, const pxr::SdfPath& rasterOverlayPath) { const auto& tilesets = context.getAssetRegistry().getTilesets(); // Update tilesets that reference this raster overlay for (const auto& pTileset : tilesets) { if (CppUtil::contains(pTileset->getRasterOverlayPaths(), rasterOverlayPath)) { pTileset->reload(); } } } void updateRasterOverlayBindingsAlpha(const Context& context, const pxr::SdfPath& rasterOverlayPath) { const auto& tilesets = context.getAssetRegistry().getTilesets(); // Update tilesets that reference this raster overlay for (const auto& pTileset : tilesets) { if (CppUtil::contains(pTileset->getRasterOverlayPaths(), rasterOverlayPath)) { pTileset->updateRasterOverlayAlpha(rasterOverlayPath); } } } void updateIonServerBindings(const Context& context) { // Update all tilesets. Some tilesets may have referenced this ion server implicitly. const auto& tilesets = context.getAssetRegistry().getTilesets(); for (const auto& pTileset : tilesets) { pTileset->reload(); } // Update all raster overlays. Some raster overlays may have referenced this ion server implicitly. const auto& ionRasterOverlays = context.getAssetRegistry().getIonRasterOverlays(); for (const auto& pIonRasterOverlay : ionRasterOverlays) { pIonRasterOverlay->reload(); updateRasterOverlayBindings(context, pIonRasterOverlay->getPath()); } } void updateCartographicPolygonBindings(const Context& context, const pxr::SdfPath& cartographicPolygonPath) { // Update polygon raster overlays that reference this cartographic polygon const auto& polygonRasterOverlays = context.getAssetRegistry().getPolygonRasterOverlays(); for (const auto& pPolygonRasterOverlay : polygonRasterOverlays) { const auto paths = pPolygonRasterOverlay->getCartographicPolygonPaths(); if (CppUtil::contains(paths, cartographicPolygonPath)) { pPolygonRasterOverlay->reload(); updateRasterOverlayBindings(context, pPolygonRasterOverlay->getPath()); } } } void updateGlobeAnchorBindings(const Context& context, const pxr::SdfPath& globeAnchorPath) { // Don't need to update tilesets. Globe anchor changes are handled automatically in the update loop. if (context.getAssetRegistry().getCartographicPolygon(globeAnchorPath)) { // Update cartographic polygon that this globe anchor is attached to updateCartographicPolygonBindings(context, globeAnchorPath); } } void updateGeoreferenceBindings(const Context& context) { // Don't need to update tilesets. Georeference changes are handled automatically in the update loop. // Update all globe anchors. Some globe anchors may have referenced this georeference implicitly. const auto& globeAnchors = context.getAssetRegistry().getGlobeAnchors(); for (const auto& pGlobeAnchor : globeAnchors) { pGlobeAnchor->updateByGeoreference(); updateGlobeAnchorBindings(context, pGlobeAnchor->getPath()); } } bool isFirstData(const Context& context, const pxr::SdfPath& dataPath) { const auto pData = context.getAssetRegistry().getData(dataPath); const auto pFirstData = context.getAssetRegistry().getFirstData(); return pData && pData == pFirstData; } [[nodiscard]] bool processCesiumDataChanged( const Context& context, const pxr::SdfPath& dataPath, const std::vector<pxr::TfToken>& properties) { if (!isFirstData(context, dataPath)) { return false; } auto reloadStage = false; auto updateGeoreference = false; // No change tracking needed for // * selectedIonServer // * projectDefaultIonAccessToken (deprecated) // * projectDefaultIonAccessTokenId (deprecated) for (const auto& property : properties) { if (property == pxr::CesiumTokens->cesiumDebugDisableMaterials || property == pxr::CesiumTokens->cesiumDebugDisableTextures || property == pxr::CesiumTokens->cesiumDebugDisableGeometryPool || property == pxr::CesiumTokens->cesiumDebugDisableMaterialPool || property == pxr::CesiumTokens->cesiumDebugDisableTexturePool || property == pxr::CesiumTokens->cesiumDebugGeometryPoolInitialCapacity || property == pxr::CesiumTokens->cesiumDebugMaterialPoolInitialCapacity || property == pxr::CesiumTokens->cesiumDebugTexturePoolInitialCapacity || property == pxr::CesiumTokens->cesiumDebugRandomColors) { reloadStage = true; } else if (property == pxr::CesiumTokens->cesiumDebugDisableGeoreferencing) { updateGeoreference = true; } } if (updateGeoreference) { updateGeoreferenceBindings(context); } return reloadStage; } void processCesiumGlobeAnchorChanged( const Context& context, const pxr::SdfPath& globeAnchorPath, const std::vector<pxr::TfToken>& properties) { const auto pGlobeAnchor = context.getAssetRegistry().getGlobeAnchor(globeAnchorPath); if (!pGlobeAnchor) { return; } // No change tracking needed for // * adjustOrientation auto updateByGeoreference = false; auto updateByPrimLocalTransform = false; auto updateByGeographicCoordinates = false; auto updateByEcefPosition = false; auto updateBindings = false; auto resetOrientation = false; const auto detectTransformChanges = pGlobeAnchor->getDetectTransformChanges(); // clang-format off for (const auto& property : properties) { if (detectTransformChanges && (property == pxr::UsdTokens->xformOp_translate || property == pxr::UsdTokens->xformOp_rotateXYZ || property == pxr::UsdTokens->xformOp_rotateXZY || property == pxr::UsdTokens->xformOp_rotateYXZ || property == pxr::UsdTokens->xformOp_rotateYZX || property == pxr::UsdTokens->xformOp_rotateZXY || property == pxr::UsdTokens->xformOp_rotateZYX || property == pxr::UsdTokens->xformOp_orient || property == pxr::UsdTokens->xformOp_scale)) { updateByPrimLocalTransform = true; updateBindings = true; } else if (property == pxr::CesiumTokens->cesiumAnchorLongitude || property == pxr::CesiumTokens->cesiumAnchorLatitude || property == pxr::CesiumTokens->cesiumAnchorHeight) { updateByGeographicCoordinates = true; updateBindings = true; } else if (property == pxr::CesiumTokens->cesiumAnchorPosition) { updateByEcefPosition = true; updateBindings = true; } else if (property == pxr::CesiumTokens->cesiumAnchorGeoreferenceBinding) { updateByGeoreference = true; updateBindings = true; } else if (detectTransformChanges && property == pxr::CesiumTokens->cesiumAnchorDetectTransformChanges) { updateByPrimLocalTransform = true; updateBindings = true; resetOrientation = true; } } // clang-format on if (updateByGeoreference) { pGlobeAnchor->updateByGeoreference(); } if (updateByEcefPosition) { pGlobeAnchor->updateByEcefPosition(); } if (updateByGeographicCoordinates) { pGlobeAnchor->updateByGeographicCoordinates(); } if (updateByPrimLocalTransform) { pGlobeAnchor->updateByPrimLocalTransform(resetOrientation); } if (updateBindings) { updateGlobeAnchorBindings(context, globeAnchorPath); } } void processCesiumTilesetChanged( const Context& context, const pxr::SdfPath& tilesetPath, const std::vector<pxr::TfToken>& properties) { const auto pTileset = context.getAssetRegistry().getTileset(tilesetPath); if (!pTileset) { return; } // Process globe anchor API schema first processCesiumGlobeAnchorChanged(context, tilesetPath, properties); auto reload = false; auto updateTilesetOptions = false; auto updateDisplayColorAndOpacity = false; // No change tracking needed for // * suspendUpdate // * georeferenceBinding // * Transform changes (handled automatically in update loop) // clang-format off for (const auto& property : properties) { if (property == pxr::CesiumTokens->cesiumSourceType || property == pxr::CesiumTokens->cesiumUrl || property == pxr::CesiumTokens->cesiumIonAssetId || property == pxr::CesiumTokens->cesiumIonAccessToken || property == pxr::CesiumTokens->cesiumIonServerBinding || property == pxr::CesiumTokens->cesiumSmoothNormals || property == pxr::CesiumTokens->cesiumShowCreditsOnScreen || property == pxr::CesiumTokens->cesiumRasterOverlayBinding || property == pxr::UsdTokens->material_binding) { reload = true; } else if ( property == pxr::CesiumTokens->cesiumMaximumScreenSpaceError || property == pxr::CesiumTokens->cesiumPreloadAncestors || property == pxr::CesiumTokens->cesiumPreloadSiblings || property == pxr::CesiumTokens->cesiumForbidHoles || property == pxr::CesiumTokens->cesiumMaximumSimultaneousTileLoads || property == pxr::CesiumTokens->cesiumMaximumCachedBytes || property == pxr::CesiumTokens->cesiumLoadingDescendantLimit || property == pxr::CesiumTokens->cesiumEnableFrustumCulling || property == pxr::CesiumTokens->cesiumEnableFogCulling || property == pxr::CesiumTokens->cesiumEnforceCulledScreenSpaceError || property == pxr::CesiumTokens->cesiumCulledScreenSpaceError || property == pxr::CesiumTokens->cesiumMainThreadLoadingTimeLimit) { updateTilesetOptions = true; } else if ( property == pxr::UsdTokens->primvars_displayColor || property == pxr::UsdTokens->primvars_displayOpacity) { updateDisplayColorAndOpacity = true; } } // clang-format on if (reload) { pTileset->reload(); } if (updateTilesetOptions) { pTileset->updateTilesetOptions(); } if (updateDisplayColorAndOpacity) { pTileset->updateDisplayColorAndOpacity(); } } void processCesiumRasterOverlayChanged( const Context& context, const pxr::SdfPath& rasterOverlayPath, const std::vector<pxr::TfToken>& properties) { const auto pRasterOverlay = context.getAssetRegistry().getRasterOverlay(rasterOverlayPath); if (!pRasterOverlay) { return; } auto reload = false; auto updateBindings = false; auto updateRasterOverlayAlpha = false; auto updateRasterOverlayOptions = false; for (const auto& property : properties) { if (property == pxr::CesiumTokens->cesiumShowCreditsOnScreen) { reload = true; updateBindings = true; } else if (property == pxr::CesiumTokens->cesiumOverlayRenderMethod) { updateBindings = true; } else if (property == pxr::CesiumTokens->cesiumAlpha) { updateRasterOverlayAlpha = true; } else if ( property == pxr::CesiumTokens->cesiumMaximumScreenSpaceError || property == pxr::CesiumTokens->cesiumMaximumTextureSize || property == pxr::CesiumTokens->cesiumMaximumSimultaneousTileLoads || property == pxr::CesiumTokens->cesiumSubTileCacheBytes) { updateRasterOverlayOptions = true; } } if (reload) { pRasterOverlay->reload(); } if (updateBindings) { updateRasterOverlayBindings(context, rasterOverlayPath); } if (updateRasterOverlayAlpha) { updateRasterOverlayBindingsAlpha(context, rasterOverlayPath); } if (updateRasterOverlayOptions) { pRasterOverlay->updateRasterOverlayOptions(); } } void processCesiumIonRasterOverlayChanged( const Context& context, const pxr::SdfPath& ionRasterOverlayPath, const std::vector<pxr::TfToken>& properties) { const auto pIonRasterOverlay = context.getAssetRegistry().getIonRasterOverlay(ionRasterOverlayPath); if (!pIonRasterOverlay) { return; } // Process base class first processCesiumRasterOverlayChanged(context, ionRasterOverlayPath, properties); auto reload = false; auto updateBindings = false; for (const auto& property : properties) { if (property == pxr::CesiumTokens->cesiumIonAssetId || property == pxr::CesiumTokens->cesiumIonAccessToken || property == pxr::CesiumTokens->cesiumIonServerBinding) { reload = true; updateBindings = true; } } if (reload) { pIonRasterOverlay->reload(); } if (updateBindings) { updateRasterOverlayBindings(context, ionRasterOverlayPath); } } void processCesiumPolygonRasterOverlayChanged( const Context& context, const pxr::SdfPath& polygonRasterOverlayPath, const std::vector<pxr::TfToken>& properties) { const auto pPolygonRasterOverlay = context.getAssetRegistry().getPolygonRasterOverlay(polygonRasterOverlayPath); if (!pPolygonRasterOverlay) { return; } // Process base class first processCesiumRasterOverlayChanged(context, polygonRasterOverlayPath, properties); auto reload = false; auto updateBindings = false; for (const auto& property : properties) { if (property == pxr::CesiumTokens->cesiumCartographicPolygonBinding || property == pxr::CesiumTokens->cesiumInvertSelection || property == pxr::CesiumTokens->cesiumExcludeSelectedTiles) { reload = true; updateBindings = true; } } if (reload) { pPolygonRasterOverlay->reload(); } if (updateBindings) { updateRasterOverlayBindings(context, polygonRasterOverlayPath); } } void processCesiumWebMapServiceRasterOverlayChanged( const Context& context, const pxr::SdfPath& webMapServiceRasterOverlayPath, const std::vector<pxr::TfToken>& properties) { const auto pWebMapServiceRasterOverlay = context.getAssetRegistry().getWebMapServiceRasterOverlay(webMapServiceRasterOverlayPath); if (!pWebMapServiceRasterOverlay) { return; } // Process base class first processCesiumRasterOverlayChanged(context, webMapServiceRasterOverlayPath, properties); auto reload = false; auto updateBindings = false; for (const auto& property : properties) { if (property == pxr::CesiumTokens->cesiumBaseUrl || property == pxr::CesiumTokens->cesiumLayers || property == pxr::CesiumTokens->cesiumTileWidth || property == pxr::CesiumTokens->cesiumTileHeight || property == pxr::CesiumTokens->cesiumMinimumLevel || property == pxr::CesiumTokens->cesiumMaximumLevel) { reload = true; updateBindings = true; } } if (reload) { pWebMapServiceRasterOverlay->reload(); } if (updateBindings) { updateRasterOverlayBindings(context, webMapServiceRasterOverlayPath); } } void processCesiumTileMapServiceRasterOverlayChanged( const Context& context, const pxr::SdfPath& tileMapServiceRasterOverlayPath, const std::vector<pxr::TfToken>& properties) { const auto pTileMapServiceRasterOverlay = context.getAssetRegistry().getTileMapServiceRasterOverlay(tileMapServiceRasterOverlayPath); if (!pTileMapServiceRasterOverlay) { return; } // Process base class first processCesiumRasterOverlayChanged(context, tileMapServiceRasterOverlayPath, properties); auto reload = false; auto updateBindings = false; for (const auto& property : properties) { if (property == pxr::CesiumTokens->cesiumUrl || property == pxr::CesiumTokens->cesiumMinimumZoomLevel || property == pxr::CesiumTokens->cesiumMaximumZoomLevel) { reload = true; updateBindings = true; } } if (reload) { pTileMapServiceRasterOverlay->reload(); } if (updateBindings) { updateRasterOverlayBindings(context, tileMapServiceRasterOverlayPath); } } void processCesiumWebMapTileServiceRasterOverlayChanged( const Context& context, const pxr::SdfPath& webMapTileServiceRasterOverlayPath, const std::vector<pxr::TfToken>& properties) { const auto pWebMapTileServiceRasterOverlay = context.getAssetRegistry().getWebMapTileServiceRasterOverlay(webMapTileServiceRasterOverlayPath); if (!pWebMapTileServiceRasterOverlay) { return; } // Process base class first processCesiumRasterOverlayChanged(context, webMapTileServiceRasterOverlayPath, properties); auto reload = false; auto updateBindings = false; for (const auto& property : properties) { if (property == pxr::CesiumTokens->cesiumUrl || property == pxr::CesiumTokens->cesiumLayer || property == pxr::CesiumTokens->cesiumStyle || property == pxr::CesiumTokens->cesiumFormat || property == pxr::CesiumTokens->cesiumTileMatrixSetId || property == pxr::CesiumTokens->cesiumSpecifyTileMatrixSetLabels || property == pxr::CesiumTokens->cesiumTileMatrixSetLabelPrefix || property == pxr::CesiumTokens->cesiumTileMatrixSetLabels || property == pxr::CesiumTokens->cesiumUseWebMercatorProjection || property == pxr::CesiumTokens->cesiumSpecifyTilingScheme || property == pxr::CesiumTokens->cesiumRootTilesX || property == pxr::CesiumTokens->cesiumRootTilesY || property == pxr::CesiumTokens->cesiumWest || property == pxr::CesiumTokens->cesiumEast || property == pxr::CesiumTokens->cesiumSouth || property == pxr::CesiumTokens->cesiumNorth || property == pxr::CesiumTokens->cesiumSpecifyZoomLevels || property == pxr::CesiumTokens->cesiumMinimumZoomLevel || property == pxr::CesiumTokens->cesiumMaximumZoomLevel) { reload = true; updateBindings = true; } } if (reload) { pWebMapTileServiceRasterOverlay->reload(); } if (updateBindings) { updateRasterOverlayBindings(context, webMapTileServiceRasterOverlayPath); } } void processCesiumGeoreferenceChanged(const Context& context, const std::vector<pxr::TfToken>& properties) { auto updateBindings = false; // clang-format off for (const auto& property : properties) { if (property == pxr::CesiumTokens->cesiumGeoreferenceOriginLongitude || property == pxr::CesiumTokens->cesiumGeoreferenceOriginLatitude || property == pxr::CesiumTokens->cesiumGeoreferenceOriginHeight) { updateBindings = true; } } // clang-format on if (updateBindings) { updateGeoreferenceBindings(context); } } void processCesiumIonServerChanged( Context& context, const pxr::SdfPath& ionServerPath, const std::vector<pxr::TfToken>& properties) { auto reloadSession = false; auto updateBindings = false; // No change tracking needed for // * displayName // clang-format off for (const auto& property : properties) { if (property == pxr::CesiumTokens->cesiumIonServerUrl || property == pxr::CesiumTokens->cesiumIonServerApiUrl || property == pxr::CesiumTokens->cesiumIonServerApplicationId) { reloadSession = true; updateBindings = true; } else if ( property == pxr::CesiumTokens->cesiumProjectDefaultIonAccessToken || property == pxr::CesiumTokens->cesiumProjectDefaultIonAccessTokenId) { updateBindings = true; } } // clang-format on if (reloadSession) { context.getAssetRegistry().removeIonServer(ionServerPath); context.getAssetRegistry().addIonServer(ionServerPath); } if (updateBindings) { updateIonServerBindings(context); } } void processCesiumCartographicPolygonChanged( const Context& context, const pxr::SdfPath& cartographicPolygonPath, const std::vector<pxr::TfToken>& properties) { // Process globe anchor API schema first processCesiumGlobeAnchorChanged(context, cartographicPolygonPath, properties); auto updateBindings = false; for (const auto& property : properties) { if (property == pxr::UsdTokens->points) { updateBindings = true; } } if (updateBindings) { updateCartographicPolygonBindings(context, cartographicPolygonPath); } } void processUsdShaderChanged( const Context& context, const pxr::SdfPath& shaderPath, const std::vector<pxr::TfToken>& properties) { const auto usdShader = UsdUtil::getUsdShader(context.getUsdStage(), shaderPath); const auto shaderPathFabric = FabricUtil::toFabricPath(shaderPath); const auto materialPath = shaderPath.GetParentPath(); const auto materialPathFabric = FabricUtil::toFabricPath(materialPath); if (!UsdUtil::isUsdMaterial(context.getUsdStage(), materialPath)) { // Skip if parent path is not a material return; } for (const auto& property : properties) { const auto inputNamespace = std::string_view("inputs:"); const auto& attributeName = property.GetString(); if (attributeName.rfind(inputNamespace) != 0) { // Skip if changed attribute is not a shader input return; } const auto inputName = pxr::TfToken(attributeName.substr(inputNamespace.size())); const auto shaderInput = usdShader.GetInput(inputName); if (!shaderInput.IsDefined()) { // Skip if changed attribute is not a shader input return; } if (shaderInput.HasConnectedSource()) { // Skip if shader input is connected to something else return; } if (!FabricUtil::materialHasCesiumNodes(context.getFabricStage(), materialPathFabric)) { // Simple materials can be skipped. We only need to handle materials that have been copied to each tile. return; } if (!FabricUtil::isShaderConnectedToMaterial(context.getFabricStage(), materialPathFabric, shaderPathFabric)) { // Skip if shader is not connected to the material return; } const auto& tilesets = context.getAssetRegistry().getTilesets(); for (const auto& pTileset : tilesets) { if (pTileset->getMaterialPath() == materialPath) { pTileset->updateShaderInput(shaderPath, property); } } context.getFabricResourceManager().updateShaderInput(materialPath, shaderPath, property); } } [[nodiscard]] bool processCesiumDataRemoved(Context& context, const pxr::SdfPath& dataPath) { const auto reloadStage = isFirstData(context, dataPath); context.getAssetRegistry().removeData(dataPath); return reloadStage; } void processCesiumTilesetRemoved(Context& context, const pxr::SdfPath& tilesetPath) { context.getAssetRegistry().removeTileset(tilesetPath); } void processCesiumIonRasterOverlayRemoved(Context& context, const pxr::SdfPath& ionRasterOverlayPath) { context.getAssetRegistry().removeIonRasterOverlay(ionRasterOverlayPath); updateRasterOverlayBindings(context, ionRasterOverlayPath); } void processCesiumPolygonRasterOverlayRemoved(Context& context, const pxr::SdfPath& polygonRasterOverlayPath) { context.getAssetRegistry().removePolygonRasterOverlay(polygonRasterOverlayPath); updateRasterOverlayBindings(context, polygonRasterOverlayPath); } void processCesiumWebMapServiceRasterOverlayRemoved( Context& context, const pxr::SdfPath& webMapServiceRasterOverlayPath) { context.getAssetRegistry().removeWebMapServiceRasterOverlay(webMapServiceRasterOverlayPath); updateRasterOverlayBindings(context, webMapServiceRasterOverlayPath); } void processCesiumTileMapServiceRasterOverlayRemoved( Context& context, const pxr::SdfPath& tileMapServiceRasterOverlayPath) { context.getAssetRegistry().removeTileMapServiceRasterOverlay(tileMapServiceRasterOverlayPath); updateRasterOverlayBindings(context, tileMapServiceRasterOverlayPath); } void processCesiumWebMapTileServiceRasterOverlayRemoved( Context& context, const pxr::SdfPath& webMapTileServiceRasterOverlayPath) { context.getAssetRegistry().removeWebMapServiceRasterOverlay(webMapTileServiceRasterOverlayPath); updateRasterOverlayBindings(context, webMapTileServiceRasterOverlayPath); } void processCesiumGeoreferenceRemoved(Context& context, const pxr::SdfPath& georeferencePath) { context.getAssetRegistry().removeGeoreference(georeferencePath); updateGeoreferenceBindings(context); } void processCesiumGlobeAnchorRemoved(Context& context, const pxr::SdfPath& globeAnchorPath) { context.getAssetRegistry().removeGlobeAnchor(globeAnchorPath); updateGlobeAnchorBindings(context, globeAnchorPath); } void processCesiumIonServerRemoved(Context& context, const pxr::SdfPath& ionServerPath) { context.getAssetRegistry().removeIonServer(ionServerPath); updateIonServerBindings(context); } void processCesiumCartographicPolygonRemoved(Context& context, const pxr::SdfPath& cartographicPolygonPath) { context.getAssetRegistry().removeCartographicPolygon(cartographicPolygonPath); processCesiumGlobeAnchorRemoved(context, cartographicPolygonPath); updateCartographicPolygonBindings(context, cartographicPolygonPath); } [[nodiscard]] bool processCesiumDataAdded(Context& context, const pxr::SdfPath& dataPath) { if (context.getAssetRegistry().getData(dataPath)) { return false; } context.getAssetRegistry().addData(dataPath); return isFirstData(context, dataPath); } void processCesiumGlobeAnchorAdded(Context& context, const pxr::SdfPath& globeAnchorPath) { if (context.getAssetRegistry().getGlobeAnchor(globeAnchorPath)) { return; } context.getAssetRegistry().addGlobeAnchor(globeAnchorPath); updateGlobeAnchorBindings(context, globeAnchorPath); } void processCesiumTilesetAdded(Context& context, const pxr::SdfPath& tilesetPath) { if (UsdUtil::hasCesiumGlobeAnchor(context.getUsdStage(), tilesetPath)) { processCesiumGlobeAnchorAdded(context, tilesetPath); } if (context.getAssetRegistry().getTileset(tilesetPath)) { return; } context.getAssetRegistry().addTileset(tilesetPath); } void processCesiumIonRasterOverlayAdded(Context& context, const pxr::SdfPath& ionRasterOverlayPath) { if (context.getAssetRegistry().getIonRasterOverlay(ionRasterOverlayPath)) { return; } context.getAssetRegistry().addIonRasterOverlay(ionRasterOverlayPath); updateRasterOverlayBindings(context, ionRasterOverlayPath); } void processCesiumPolygonRasterOverlayAdded(Context& context, const pxr::SdfPath& polygonRasterOverlayPath) { if (context.getAssetRegistry().getPolygonRasterOverlay(polygonRasterOverlayPath)) { return; } context.getAssetRegistry().addPolygonRasterOverlay(polygonRasterOverlayPath); updateRasterOverlayBindings(context, polygonRasterOverlayPath); } void processCesiumWebMapServiceRasterOverlayAdded( Context& context, const pxr::SdfPath& webMapServiceRasterOverlayPath) { if (context.getAssetRegistry().getWebMapServiceRasterOverlay(webMapServiceRasterOverlayPath)) { return; } context.getAssetRegistry().addWebMapServiceRasterOverlay(webMapServiceRasterOverlayPath); updateRasterOverlayBindings(context, webMapServiceRasterOverlayPath); } void processCesiumTileMapServiceRasterOverlayAdded( Context& context, const pxr::SdfPath& tileMapServiceRasterOverlayPath) { if (context.getAssetRegistry().getTileMapServiceRasterOverlay(tileMapServiceRasterOverlayPath)) { return; } context.getAssetRegistry().addTileMapServiceRasterOverlay(tileMapServiceRasterOverlayPath); updateRasterOverlayBindings(context, tileMapServiceRasterOverlayPath); } void processCesiumWebMapTileServiceRasterOverlayAdded( Context& context, const pxr::SdfPath& webMapTileServiceRasterOverlayPath) { if (context.getAssetRegistry().getWebMapTileServiceRasterOverlay(webMapTileServiceRasterOverlayPath)) { return; } context.getAssetRegistry().addWebMapTileServiceRasterOverlay(webMapTileServiceRasterOverlayPath); updateRasterOverlayBindings(context, webMapTileServiceRasterOverlayPath); } void processCesiumGeoreferenceAdded(Context& context, const pxr::SdfPath& georeferencePath) { if (context.getAssetRegistry().getGeoreference(georeferencePath)) { return; } context.getAssetRegistry().addGeoreference(georeferencePath); updateGeoreferenceBindings(context); } void processCesiumIonServerAdded(Context& context, const pxr::SdfPath& ionServerPath) { if (context.getAssetRegistry().getIonServer(ionServerPath)) { return; } context.getAssetRegistry().addIonServer(ionServerPath); updateIonServerBindings(context); } void processCesiumCartographicPolygonAdded(Context& context, const pxr::SdfPath& cartographicPolygonPath) { if (UsdUtil::hasCesiumGlobeAnchor(context.getUsdStage(), cartographicPolygonPath)) { processCesiumGlobeAnchorAdded(context, cartographicPolygonPath); } if (context.getAssetRegistry().getCartographicPolygon(cartographicPolygonPath)) { return; } context.getAssetRegistry().addCartographicPolygon(cartographicPolygonPath); updateCartographicPolygonBindings(context, cartographicPolygonPath); } } // namespace UsdNotificationHandler::UsdNotificationHandler(Context* pContext) : _pContext(pContext) , _noticeListenerKey( pxr::TfNotice::Register(pxr::TfCreateWeakPtr(this), &UsdNotificationHandler::onObjectsChanged)) {} UsdNotificationHandler::~UsdNotificationHandler() { pxr::TfNotice::Revoke(_noticeListenerKey); } void UsdNotificationHandler::onStageLoaded() { // Insert prims manually since USD doesn't notify us about changes when the stage is first loaded for (const auto& prim : _pContext->getUsdStage()->Traverse()) { const auto type = getTypeFromStage(prim.GetPath()); if (type != ChangedPrimType::OTHER) { insertAddedPrim(prim.GetPath(), type); } } // Process changes immediately processChangedPrims(); } void UsdNotificationHandler::onUpdateFrame() { const auto reloadStage = processChangedPrims(); if (reloadStage) { _pContext->reloadStage(); } } void UsdNotificationHandler::clear() { _changedPrims.clear(); } bool UsdNotificationHandler::processChangedPrims() { std::vector<ChangedPrim> consolidatedChangedPrims; ChangedPrim* pPrevious = nullptr; for (const auto& changedPrim : _changedPrims) { if (pPrevious && changedPrim.primPath == pPrevious->primPath) { if (pPrevious->changedType == ChangedType::PRIM_ADDED && changedPrim.changedType == ChangedType::PROPERTY_CHANGED) { // Ignore property changes that occur immediately after the prim is added. This avoids unecessary churn. continue; } if (pPrevious->changedType == ChangedType::PROPERTY_CHANGED && changedPrim.changedType == ChangedType::PROPERTY_CHANGED) { // Consolidate property changes so that they can be processed together CppUtil::append(pPrevious->properties, changedPrim.properties); continue; } } consolidatedChangedPrims.push_back(changedPrim); pPrevious = &consolidatedChangedPrims.back(); } _changedPrims.clear(); auto reloadStage = false; for (const auto& changedPrim : consolidatedChangedPrims) { reloadStage = processChangedPrim(changedPrim) || reloadStage; } // Process newly added changes if (!_changedPrims.empty()) { reloadStage = processChangedPrims() || reloadStage; } return reloadStage; } bool UsdNotificationHandler::processChangedPrim(const ChangedPrim& changedPrim) const { auto reloadStage = false; switch (changedPrim.changedType) { case ChangedType::PROPERTY_CHANGED: switch (changedPrim.primType) { case ChangedPrimType::CESIUM_DATA: reloadStage = processCesiumDataChanged(*_pContext, changedPrim.primPath, changedPrim.properties); break; case ChangedPrimType::CESIUM_TILESET: processCesiumTilesetChanged(*_pContext, changedPrim.primPath, changedPrim.properties); break; case ChangedPrimType::CESIUM_ION_RASTER_OVERLAY: processCesiumIonRasterOverlayChanged(*_pContext, changedPrim.primPath, changedPrim.properties); break; case ChangedPrimType::CESIUM_POLYGON_RASTER_OVERLAY: processCesiumPolygonRasterOverlayChanged(*_pContext, changedPrim.primPath, changedPrim.properties); break; case ChangedPrimType::CESIUM_WEB_MAP_SERVICE_RASTER_OVERLAY: processCesiumWebMapServiceRasterOverlayChanged( *_pContext, changedPrim.primPath, changedPrim.properties); break; case ChangedPrimType::CESIUM_TILE_MAP_SERVICE_RASTER_OVERLAY: processCesiumTileMapServiceRasterOverlayChanged( *_pContext, changedPrim.primPath, changedPrim.properties); break; case ChangedPrimType::CESIUM_WEB_MAP_TILE_SERVICE_RASTER_OVERLAY: processCesiumWebMapTileServiceRasterOverlayChanged( *_pContext, changedPrim.primPath, changedPrim.properties); break; case ChangedPrimType::CESIUM_GEOREFERENCE: processCesiumGeoreferenceChanged(*_pContext, changedPrim.properties); break; case ChangedPrimType::CESIUM_GLOBE_ANCHOR: processCesiumGlobeAnchorChanged(*_pContext, changedPrim.primPath, changedPrim.properties); break; case ChangedPrimType::CESIUM_ION_SERVER: processCesiumIonServerChanged(*_pContext, changedPrim.primPath, changedPrim.properties); break; case ChangedPrimType::CESIUM_CARTOGRAPHIC_POLYGON: processCesiumCartographicPolygonChanged(*_pContext, changedPrim.primPath, changedPrim.properties); break; case ChangedPrimType::USD_SHADER: processUsdShaderChanged(*_pContext, changedPrim.primPath, changedPrim.properties); break; case ChangedPrimType::OTHER: break; } break; case ChangedType::PRIM_ADDED: switch (changedPrim.primType) { case ChangedPrimType::CESIUM_DATA: reloadStage = processCesiumDataAdded(*_pContext, changedPrim.primPath); break; case ChangedPrimType::CESIUM_TILESET: processCesiumTilesetAdded(*_pContext, changedPrim.primPath); break; case ChangedPrimType::CESIUM_ION_RASTER_OVERLAY: processCesiumIonRasterOverlayAdded(*_pContext, changedPrim.primPath); break; case ChangedPrimType::CESIUM_POLYGON_RASTER_OVERLAY: processCesiumPolygonRasterOverlayAdded(*_pContext, changedPrim.primPath); break; case ChangedPrimType::CESIUM_WEB_MAP_SERVICE_RASTER_OVERLAY: processCesiumWebMapServiceRasterOverlayAdded(*_pContext, changedPrim.primPath); break; case ChangedPrimType::CESIUM_TILE_MAP_SERVICE_RASTER_OVERLAY: processCesiumTileMapServiceRasterOverlayAdded(*_pContext, changedPrim.primPath); break; case ChangedPrimType::CESIUM_WEB_MAP_TILE_SERVICE_RASTER_OVERLAY: processCesiumWebMapTileServiceRasterOverlayAdded(*_pContext, changedPrim.primPath); break; case ChangedPrimType::CESIUM_GEOREFERENCE: processCesiumGeoreferenceAdded(*_pContext, changedPrim.primPath); break; case ChangedPrimType::CESIUM_GLOBE_ANCHOR: processCesiumGlobeAnchorAdded(*_pContext, changedPrim.primPath); break; case ChangedPrimType::CESIUM_ION_SERVER: processCesiumIonServerAdded(*_pContext, changedPrim.primPath); break; case ChangedPrimType::CESIUM_CARTOGRAPHIC_POLYGON: processCesiumCartographicPolygonAdded(*_pContext, changedPrim.primPath); break; case ChangedPrimType::USD_SHADER: case ChangedPrimType::OTHER: break; } break; case ChangedType::PRIM_REMOVED: switch (changedPrim.primType) { case ChangedPrimType::CESIUM_DATA: reloadStage = processCesiumDataRemoved(*_pContext, changedPrim.primPath); break; case ChangedPrimType::CESIUM_TILESET: processCesiumTilesetRemoved(*_pContext, changedPrim.primPath); break; case ChangedPrimType::CESIUM_ION_RASTER_OVERLAY: processCesiumIonRasterOverlayRemoved(*_pContext, changedPrim.primPath); break; case ChangedPrimType::CESIUM_POLYGON_RASTER_OVERLAY: processCesiumPolygonRasterOverlayRemoved(*_pContext, changedPrim.primPath); break; case ChangedPrimType::CESIUM_WEB_MAP_SERVICE_RASTER_OVERLAY: processCesiumWebMapServiceRasterOverlayRemoved(*_pContext, changedPrim.primPath); break; case ChangedPrimType::CESIUM_TILE_MAP_SERVICE_RASTER_OVERLAY: processCesiumTileMapServiceRasterOverlayRemoved(*_pContext, changedPrim.primPath); break; case ChangedPrimType::CESIUM_WEB_MAP_TILE_SERVICE_RASTER_OVERLAY: processCesiumWebMapTileServiceRasterOverlayRemoved(*_pContext, changedPrim.primPath); break; case ChangedPrimType::CESIUM_GEOREFERENCE: processCesiumGeoreferenceRemoved(*_pContext, changedPrim.primPath); break; case ChangedPrimType::CESIUM_GLOBE_ANCHOR: processCesiumGlobeAnchorRemoved(*_pContext, changedPrim.primPath); break; case ChangedPrimType::CESIUM_ION_SERVER: processCesiumIonServerRemoved(*_pContext, changedPrim.primPath); break; case ChangedPrimType::CESIUM_CARTOGRAPHIC_POLYGON: processCesiumCartographicPolygonRemoved(*_pContext, changedPrim.primPath); break; case ChangedPrimType::USD_SHADER: case ChangedPrimType::OTHER: break; } break; } return reloadStage; } void UsdNotificationHandler::onObjectsChanged(const pxr::UsdNotice::ObjectsChanged& objectsChanged) { if (!_pContext->hasUsdStage()) { return; } const auto resyncedPaths = objectsChanged.GetResyncedPaths(); for (const auto& path : resyncedPaths) { if (path.IsPrimPath()) { if (UsdUtil::primExists(_pContext->getUsdStage(), path)) { // A prim is resynced when it is added to the stage or when an API schema is applied to it, e.g. when // a material or globe anchor is assigned to a tileset for the first time. We let onPrimAdded get // called potentially multiple times so that API schemas can be registered. There are checks later // that prevent the prim from being added to the asset registry twice. onPrimAdded(path); } else { onPrimRemoved(path); } } else if (path.IsPropertyPath()) { onPropertyChanged(path); } } const auto changedPaths = objectsChanged.GetChangedInfoOnlyPaths(); for (const auto& path : changedPaths) { if (path.IsPropertyPath()) { onPropertyChanged(path); } } } void UsdNotificationHandler::onPrimAdded(const pxr::SdfPath& primPath) { const auto type = getTypeFromStage(primPath); if (type != ChangedPrimType::OTHER) { insertAddedPrim(primPath, type); } // USD only notifies us about the top-most prim being added. Find all descendant prims // and add those as well (recursively) const auto prim = _pContext->getUsdStage()->GetPrimAtPath(primPath); for (const auto& child : prim.GetAllChildren()) { onPrimAdded(child.GetPath()); } } void UsdNotificationHandler::onPrimRemoved(const pxr::SdfPath& primPath) { // USD only notifies us about the top-most prim being removed. Find all descendant prims // and remove those as well. Since the prims no longer exist on the stage we need // to look the paths in _changedPrims and the asset registry. // Remove prims that haven't been added to asset registry yet // This needs to be an index-based for loop since _changedPrims can grow in size const auto changedPrimsCount = _changedPrims.size(); for (uint64_t i = 0; i < changedPrimsCount; ++i) { if (_changedPrims[i].changedType == ChangedType::PRIM_ADDED) { if (isPrimOrDescendant(_changedPrims[i].primPath, primPath)) { insertRemovedPrim(_changedPrims[i].primPath, _changedPrims[i].primType); } } } // Remove prims in the asset registry const auto& tilesets = _pContext->getAssetRegistry().getTilesets(); for (const auto& pTileset : tilesets) { const auto tilesetPath = pTileset->getPath(); if (isPrimOrDescendant(tilesetPath, primPath)) { insertRemovedPrim(tilesetPath, ChangedPrimType::CESIUM_TILESET); } } const auto& ionRasterOverlays = _pContext->getAssetRegistry().getIonRasterOverlays(); for (const auto& pIonRasterOverlay : ionRasterOverlays) { const auto ionRasterOverlayPath = pIonRasterOverlay->getPath(); if (isPrimOrDescendant(ionRasterOverlayPath, primPath)) { insertRemovedPrim(ionRasterOverlayPath, ChangedPrimType::CESIUM_ION_RASTER_OVERLAY); } } const auto& polygonRasterOverlays = _pContext->getAssetRegistry().getPolygonRasterOverlays(); for (const auto& pPolygonRasterOverlay : polygonRasterOverlays) { const auto polygonRasterOverlayPath = pPolygonRasterOverlay->getPath(); if (isPrimOrDescendant(polygonRasterOverlayPath, primPath)) { insertRemovedPrim(polygonRasterOverlayPath, ChangedPrimType::CESIUM_POLYGON_RASTER_OVERLAY); } } const auto& georeferences = _pContext->getAssetRegistry().getGeoreferences(); for (const auto& pGeoreference : georeferences) { const auto georeferencePath = pGeoreference->getPath(); if (isPrimOrDescendant(georeferencePath, primPath)) { insertRemovedPrim(georeferencePath, ChangedPrimType::CESIUM_GEOREFERENCE); } } const auto& ionServers = _pContext->getAssetRegistry().getIonServers(); for (const auto& pIonServer : ionServers) { const auto ionServerPath = pIonServer->getPath(); if (isPrimOrDescendant(ionServerPath, primPath)) { insertRemovedPrim(ionServerPath, ChangedPrimType::CESIUM_ION_SERVER); } } const auto& cartographicPolygons = _pContext->getAssetRegistry().getCartographicPolygons(); for (const auto& pCartographicPolygon : cartographicPolygons) { const auto cartographicPolygonPath = pCartographicPolygon->getPath(); if (isPrimOrDescendant(cartographicPolygonPath, primPath)) { insertRemovedPrim(cartographicPolygonPath, ChangedPrimType::CESIUM_CARTOGRAPHIC_POLYGON); } } const auto& globeAnchors = _pContext->getAssetRegistry().getGlobeAnchors(); for (const auto& pGlobeAnchor : globeAnchors) { const auto globeAnchorPath = pGlobeAnchor->getPath(); const auto type = getTypeFromAssetRegistry(globeAnchorPath); if (type == ChangedPrimType::CESIUM_GLOBE_ANCHOR) { // Make sure it's not one of the types previously handled (e.g. cartographic polygon or tileset) if (isPrimOrDescendant(globeAnchorPath, primPath)) { insertRemovedPrim(globeAnchorPath, ChangedPrimType::CESIUM_GLOBE_ANCHOR); } } } } void UsdNotificationHandler::onPropertyChanged(const pxr::SdfPath& propertyPath) { const auto& propertyName = propertyPath.GetNameToken(); const auto primPath = propertyPath.GetPrimPath(); const auto type = getTypeFromStage(primPath); if (type != ChangedPrimType::OTHER) { insertPropertyChanged(primPath, type, propertyName); } } void UsdNotificationHandler::insertAddedPrim(const pxr::SdfPath& primPath, ChangedPrimType primType) { // In C++ 20 this can be emplace_back without the {} _changedPrims.push_back({primPath, {}, primType, ChangedType::PRIM_ADDED}); } void UsdNotificationHandler::insertRemovedPrim(const pxr::SdfPath& primPath, ChangedPrimType primType) { // In C++ 20 this can be emplace_back without the {} _changedPrims.push_back({primPath, {}, primType, ChangedType::PRIM_REMOVED}); } void UsdNotificationHandler::insertPropertyChanged( const pxr::SdfPath& primPath, ChangedPrimType primType, const pxr::TfToken& propertyName) { // In C++ 20 this can be emplace_back without the {} _changedPrims.push_back({primPath, {propertyName}, primType, ChangedType::PROPERTY_CHANGED}); } UsdNotificationHandler::ChangedPrimType UsdNotificationHandler::getTypeFromStage(const pxr::SdfPath& path) const { if (UsdUtil::isCesiumData(_pContext->getUsdStage(), path)) { return ChangedPrimType::CESIUM_DATA; } else if (UsdUtil::isCesiumTileset(_pContext->getUsdStage(), path)) { return ChangedPrimType::CESIUM_TILESET; } else if (UsdUtil::isCesiumIonRasterOverlay(_pContext->getUsdStage(), path)) { return ChangedPrimType::CESIUM_ION_RASTER_OVERLAY; } else if (UsdUtil::isCesiumPolygonRasterOverlay(_pContext->getUsdStage(), path)) { return ChangedPrimType::CESIUM_POLYGON_RASTER_OVERLAY; } else if (UsdUtil::isCesiumWebMapServiceRasterOverlay(_pContext->getUsdStage(), path)) { return ChangedPrimType::CESIUM_WEB_MAP_SERVICE_RASTER_OVERLAY; } else if (UsdUtil::isCesiumTileMapServiceRasterOverlay(_pContext->getUsdStage(), path)) { return ChangedPrimType::CESIUM_TILE_MAP_SERVICE_RASTER_OVERLAY; } else if (UsdUtil::isCesiumWebMapTileServiceRasterOverlay(_pContext->getUsdStage(), path)) { return ChangedPrimType::CESIUM_WEB_MAP_TILE_SERVICE_RASTER_OVERLAY; } else if (UsdUtil::isCesiumGeoreference(_pContext->getUsdStage(), path)) { return ChangedPrimType::CESIUM_GEOREFERENCE; } else if (UsdUtil::isCesiumIonServer(_pContext->getUsdStage(), path)) { return ChangedPrimType::CESIUM_ION_SERVER; } else if (UsdUtil::isCesiumCartographicPolygon(_pContext->getUsdStage(), path)) { return ChangedPrimType::CESIUM_CARTOGRAPHIC_POLYGON; } else if (UsdUtil::isUsdShader(_pContext->getUsdStage(), path)) { return ChangedPrimType::USD_SHADER; } else if (UsdUtil::hasCesiumGlobeAnchor(_pContext->getUsdStage(), path)) { // Globe anchor needs to be checked last since prim types take precedence over API schemas return ChangedPrimType::CESIUM_GLOBE_ANCHOR; } return ChangedPrimType::OTHER; } UsdNotificationHandler::ChangedPrimType UsdNotificationHandler::getTypeFromAssetRegistry(const pxr::SdfPath& path) const { const auto assetType = _pContext->getAssetRegistry().getAssetType(path); switch (assetType) { case AssetType::DATA: return ChangedPrimType::CESIUM_DATA; case AssetType::TILESET: return ChangedPrimType::CESIUM_TILESET; case AssetType::ION_RASTER_OVERLAY: return ChangedPrimType::CESIUM_ION_RASTER_OVERLAY; case AssetType::POLYGON_RASTER_OVERLAY: return ChangedPrimType::CESIUM_POLYGON_RASTER_OVERLAY; case AssetType::WEB_MAP_SERVICE_RASTER_OVERLAY: return ChangedPrimType::CESIUM_WEB_MAP_SERVICE_RASTER_OVERLAY; case AssetType::TILE_MAP_SERVICE_RASTER_OVERLAY: return ChangedPrimType::CESIUM_TILE_MAP_SERVICE_RASTER_OVERLAY; case AssetType::WEB_MAP_TILE_SERVICE_RASTER_OVERLAY: return ChangedPrimType::CESIUM_WEB_MAP_TILE_SERVICE_RASTER_OVERLAY; case AssetType::GEOREFERENCE: return ChangedPrimType::CESIUM_GEOREFERENCE; case AssetType::GLOBE_ANCHOR: return ChangedPrimType::CESIUM_GLOBE_ANCHOR; case AssetType::ION_SERVER: return ChangedPrimType::CESIUM_ION_SERVER; case AssetType::CARTOGRAPHIC_POLYGON: return ChangedPrimType::CESIUM_CARTOGRAPHIC_POLYGON; case AssetType::OTHER: return ChangedPrimType::OTHER; } return ChangedPrimType::OTHER; } } // namespace cesium::omniverse
51,453
C++
39.64297
120
0.684625
CesiumGS/cesium-omniverse/src/core/src/FabricGeometry.cpp
#include "cesium/omniverse/FabricGeometry.h" #include "cesium/omniverse/Context.h" #include "cesium/omniverse/DataType.h" #include "cesium/omniverse/FabricAttributesBuilder.h" #include "cesium/omniverse/FabricMaterial.h" #include "cesium/omniverse/FabricResourceManager.h" #include "cesium/omniverse/FabricUtil.h" #include "cesium/omniverse/FabricVertexAttributeDescriptor.h" #include "cesium/omniverse/GltfUtil.h" #include "cesium/omniverse/MathUtil.h" #include "cesium/omniverse/UsdTokens.h" #include "cesium/omniverse/UsdUtil.h" #include <glm/fwd.hpp> #ifdef CESIUM_OMNI_MSVC #pragma push_macro("OPAQUE") #undef OPAQUE #endif #include <CesiumGltf/Model.h> #include <omni/fabric/FabricUSD.h> #include <omni/fabric/SimStageWithHistory.h> #include <pxr/base/gf/range3d.h> namespace cesium::omniverse { namespace { const auto DEFAULT_DOUBLE_SIDED = false; const auto DEFAULT_EXTENT = std::array<glm::dvec3, 2>{{glm::dvec3(0.0, 0.0, 0.0), glm::dvec3(0.0, 0.0, 0.0)}}; const auto DEFAULT_POSITION = glm::dvec3(0.0, 0.0, 0.0); const auto DEFAULT_ORIENTATION = glm::dquat(1.0, 0.0, 0.0, 0.0); const auto DEFAULT_SCALE = glm::dvec3(1.0, 1.0, 1.0); const auto DEFAULT_MATRIX = glm::dmat4(1.0); const auto DEFAULT_VISIBILITY = false; template <DataType T> void setVertexAttributeValues( omni::fabric::StageReaderWriter& fabricStage, const omni::fabric::Path& path, const CesiumGltf::Model& model, const CesiumGltf::MeshPrimitive& primitive, const FabricVertexAttributeDescriptor& attribute, uint64_t repeat) { const auto accessor = GltfUtil::getVertexAttributeValues<T>(model, primitive, attribute.gltfAttributeName); fabricStage.setArrayAttributeSize(path, attribute.fabricAttributeName, accessor.size() * repeat); const auto fabricValues = fabricStage.getArrayAttributeWr<DataTypeUtil::GetNativeType<DataTypeUtil::getPrimvarType<T>()>>( path, attribute.fabricAttributeName); accessor.fill(fabricValues, repeat); } } // namespace FabricGeometry::FabricGeometry( Context* pContext, const omni::fabric::Path& path, const FabricGeometryDescriptor& geometryDescriptor, int64_t poolId) : _pContext(pContext) , _path(path) , _geometryDescriptor(geometryDescriptor) , _poolId(poolId) , _stageId(pContext->getUsdStageId()) { if (stageDestroyed()) { return; } initialize(); reset(); } FabricGeometry::~FabricGeometry() { if (stageDestroyed()) { return; } FabricUtil::destroyPrim(_pContext->getFabricStage(), _path); } void FabricGeometry::setActive(bool active) { if (stageDestroyed()) { return; } if (!active) { reset(); } } void FabricGeometry::setVisibility(bool visible) { if (stageDestroyed()) { return; } auto& fabricStage = _pContext->getFabricStage(); const auto worldVisibilityFabric = fabricStage.getAttributeWr<bool>(_path, FabricTokens::_worldVisibility); *worldVisibilityFabric = visible; } const omni::fabric::Path& FabricGeometry::getPath() const { return _path; } const FabricGeometryDescriptor& FabricGeometry::getGeometryDescriptor() const { return _geometryDescriptor; } int64_t FabricGeometry::getPoolId() const { return _poolId; } void FabricGeometry::setMaterial(const omni::fabric::Path& materialPath) { if (stageDestroyed()) { return; } auto& fabricStage = _pContext->getFabricStage(); fabricStage.setArrayAttributeSize(_path, FabricTokens::material_binding, 1); const auto materialBindingFabric = fabricStage.getArrayAttributeWr<omni::fabric::PathC>(_path, FabricTokens::material_binding); materialBindingFabric[0] = materialPath; } void FabricGeometry::initialize() { const auto hasNormals = _geometryDescriptor.hasNormals(); const auto hasVertexColors = _geometryDescriptor.hasVertexColors(); const auto texcoordSetCount = _geometryDescriptor.getTexcoordSetCount(); const auto& customVertexAttributes = _geometryDescriptor.getCustomVertexAttributes(); const auto customVertexAttributesCount = customVertexAttributes.size(); const auto hasVertexIds = _geometryDescriptor.hasVertexIds(); auto& fabricStage = _pContext->getFabricStage(); fabricStage.createPrim(_path); // clang-format off FabricAttributesBuilder attributes(_pContext); attributes.addAttribute(FabricTypes::faceVertexCounts, FabricTokens::faceVertexCounts); attributes.addAttribute(FabricTypes::faceVertexIndices, FabricTokens::faceVertexIndices); attributes.addAttribute(FabricTypes::points, FabricTokens::points); attributes.addAttribute(FabricTypes::extent, FabricTokens::extent); attributes.addAttribute(FabricTypes::_worldExtent, FabricTokens::_worldExtent); attributes.addAttribute(FabricTypes::_worldVisibility, FabricTokens::_worldVisibility); attributes.addAttribute(FabricTypes::primvars, FabricTokens::primvars); attributes.addAttribute(FabricTypes::primvarInterpolations, FabricTokens::primvarInterpolations); attributes.addAttribute(FabricTypes::Mesh, FabricTokens::Mesh); attributes.addAttribute(FabricTypes::_cesium_tilesetId, FabricTokens::_cesium_tilesetId); attributes.addAttribute(FabricTypes::_cesium_gltfLocalToEcefTransform, FabricTokens::_cesium_gltfLocalToEcefTransform); attributes.addAttribute(FabricTypes::_worldPosition, FabricTokens::_worldPosition); attributes.addAttribute(FabricTypes::_worldOrientation, FabricTokens::_worldOrientation); attributes.addAttribute(FabricTypes::_worldScale, FabricTokens::_worldScale); attributes.addAttribute(FabricTypes::doubleSided, FabricTokens::doubleSided); attributes.addAttribute(FabricTypes::subdivisionScheme, FabricTokens::subdivisionScheme); attributes.addAttribute(FabricTypes::material_binding, FabricTokens::material_binding); // clang-format on for (uint64_t i = 0; i < texcoordSetCount; ++i) { attributes.addAttribute(FabricTypes::primvars_st, FabricTokens::primvars_st_n(i)); } if (hasNormals) { attributes.addAttribute(FabricTypes::primvars_normals, FabricTokens::primvars_normals); } if (hasVertexColors) { attributes.addAttribute(FabricTypes::primvars_COLOR_0, FabricTokens::primvars_COLOR_0); } if (hasVertexIds) { attributes.addAttribute(FabricTypes::primvars_vertexId, FabricTokens::primvars_vertexId); } for (const auto& customVertexAttribute : customVertexAttributes) { attributes.addAttribute( FabricUtil::getPrimvarType(customVertexAttribute.type), customVertexAttribute.fabricAttributeName); } attributes.createAttributes(_path); const auto subdivisionSchemeFabric = fabricStage.getAttributeWr<omni::fabric::TokenC>(_path, FabricTokens::subdivisionScheme); *subdivisionSchemeFabric = FabricTokens::none; // Initialize primvars uint64_t primvarsCount = 0; uint64_t primvarIndexNormal = 0; uint64_t primvarIndexVertexColor = 0; uint64_t primvarIndexVertexId = 0; std::vector<uint64_t> primvarIndexStArray; primvarIndexStArray.reserve(texcoordSetCount); for (uint64_t i = 0; i < texcoordSetCount; ++i) { primvarIndexStArray.push_back(primvarsCount++); } std::vector<uint64_t> primvarIndexCustomVertexAttributesArray; primvarIndexCustomVertexAttributesArray.reserve(customVertexAttributesCount); for (uint64_t i = 0; i < customVertexAttributesCount; ++i) { primvarIndexCustomVertexAttributesArray.push_back(primvarsCount++); } if (hasNormals) { primvarIndexNormal = primvarsCount++; } if (hasVertexColors) { primvarIndexVertexColor = primvarsCount++; } if (hasVertexIds) { primvarIndexVertexId = primvarsCount++; } fabricStage.setArrayAttributeSize(_path, FabricTokens::primvars, primvarsCount); fabricStage.setArrayAttributeSize(_path, FabricTokens::primvarInterpolations, primvarsCount); // clang-format off const auto primvarsFabric = fabricStage.getArrayAttributeWr<omni::fabric::TokenC>(_path, FabricTokens::primvars); const auto primvarInterpolationsFabric = fabricStage.getArrayAttributeWr<omni::fabric::TokenC>(_path, FabricTokens::primvarInterpolations); // clang-format on for (uint64_t i = 0; i < texcoordSetCount; ++i) { primvarsFabric[primvarIndexStArray[i]] = FabricTokens::primvars_st_n(i); primvarInterpolationsFabric[primvarIndexStArray[i]] = FabricTokens::vertex; } for (uint64_t i = 0; i < customVertexAttributesCount; ++i) { const auto& customVertexAttribute = CppUtil::getElementByIndex(customVertexAttributes, i); primvarsFabric[primvarIndexCustomVertexAttributesArray[i]] = customVertexAttribute.fabricAttributeName; primvarInterpolationsFabric[primvarIndexCustomVertexAttributesArray[i]] = FabricTokens::vertex; } if (hasNormals) { primvarsFabric[primvarIndexNormal] = FabricTokens::primvars_normals; primvarInterpolationsFabric[primvarIndexNormal] = FabricTokens::vertex; } if (hasVertexColors) { primvarsFabric[primvarIndexVertexColor] = FabricTokens::primvars_COLOR_0; primvarInterpolationsFabric[primvarIndexVertexColor] = FabricTokens::vertex; } if (hasVertexIds) { primvarsFabric[primvarIndexVertexId] = FabricTokens::primvars_vertexId; primvarInterpolationsFabric[primvarIndexVertexId] = FabricTokens::vertex; } } void FabricGeometry::reset() { const auto hasNormals = _geometryDescriptor.hasNormals(); const auto hasVertexColors = _geometryDescriptor.hasVertexColors(); const auto texcoordSetCount = _geometryDescriptor.getTexcoordSetCount(); const auto& customVertexAttributes = _geometryDescriptor.getCustomVertexAttributes(); const auto hasVertexIds = _geometryDescriptor.hasVertexIds(); auto& fabricStage = _pContext->getFabricStage(); // clang-format off const auto doubleSidedFabric = fabricStage.getAttributeWr<bool>(_path, FabricTokens::doubleSided); const auto extentFabric = fabricStage.getAttributeWr<pxr::GfRange3d>(_path, FabricTokens::extent); const auto worldExtentFabric = fabricStage.getAttributeWr<pxr::GfRange3d>(_path, FabricTokens::_worldExtent); const auto worldVisibilityFabric = fabricStage.getAttributeWr<bool>(_path, FabricTokens::_worldVisibility); const auto gltfLocalToEcefTransformFabric = fabricStage.getAttributeWr<pxr::GfMatrix4d>(_path, FabricTokens::_cesium_gltfLocalToEcefTransform); const auto worldPositionFabric = fabricStage.getAttributeWr<pxr::GfVec3d>(_path, FabricTokens::_worldPosition); const auto worldOrientationFabric = fabricStage.getAttributeWr<pxr::GfQuatf>(_path, FabricTokens::_worldOrientation); const auto worldScaleFabric = fabricStage.getAttributeWr<pxr::GfVec3f>(_path, FabricTokens::_worldScale); const auto tilesetIdFabric = fabricStage.getAttributeWr<int64_t>(_path, FabricTokens::_cesium_tilesetId); // clang-format on *doubleSidedFabric = DEFAULT_DOUBLE_SIDED; *extentFabric = UsdUtil::glmToUsdExtent(DEFAULT_EXTENT); *worldExtentFabric = UsdUtil::glmToUsdExtent(DEFAULT_EXTENT); *worldVisibilityFabric = DEFAULT_VISIBILITY; *gltfLocalToEcefTransformFabric = UsdUtil::glmToUsdMatrix(DEFAULT_MATRIX); *worldPositionFabric = UsdUtil::glmToUsdVector(DEFAULT_POSITION); *worldOrientationFabric = UsdUtil::glmToUsdQuat(glm::fquat(DEFAULT_ORIENTATION)); *worldScaleFabric = UsdUtil::glmToUsdVector(glm::fvec3(DEFAULT_SCALE)); *tilesetIdFabric = FabricUtil::NO_TILESET_ID; fabricStage.setArrayAttributeSize(_path, FabricTokens::material_binding, 0); fabricStage.setArrayAttributeSize(_path, FabricTokens::faceVertexCounts, 0); fabricStage.setArrayAttributeSize(_path, FabricTokens::faceVertexIndices, 0); fabricStage.setArrayAttributeSize(_path, FabricTokens::points, 0); for (uint64_t i = 0; i < texcoordSetCount; ++i) { fabricStage.setArrayAttributeSize(_path, FabricTokens::primvars_st_n(i), 0); } for (const auto& customVertexAttribute : customVertexAttributes) { fabricStage.setArrayAttributeSize(_path, customVertexAttribute.fabricAttributeName, 0); } if (hasNormals) { fabricStage.setArrayAttributeSize(_path, FabricTokens::primvars_normals, 0); } if (hasVertexColors) { fabricStage.setArrayAttributeSize(_path, FabricTokens::primvars_COLOR_0, 0); } if (hasVertexIds) { fabricStage.setArrayAttributeSize(_path, FabricTokens::primvars_vertexId, 0); } } void FabricGeometry::setGeometry( int64_t tilesetId, const glm::dmat4& ecefToPrimWorldTransform, const glm::dmat4& gltfLocalToEcefTransform, const CesiumGltf::Model& model, const CesiumGltf::MeshPrimitive& primitive, const FabricMaterialInfo& materialInfo, bool smoothNormals, const std::unordered_map<uint64_t, uint64_t>& texcoordIndexMapping, const std::unordered_map<uint64_t, uint64_t>& rasterOverlayTexcoordIndexMapping) { if (stageDestroyed()) { return; } const auto hasNormals = _geometryDescriptor.hasNormals(); const auto hasVertexColors = _geometryDescriptor.hasVertexColors(); const auto& customVertexAttributes = _geometryDescriptor.getCustomVertexAttributes(); const auto hasVertexIds = _geometryDescriptor.hasVertexIds(); auto& fabricStage = _pContext->getFabricStage(); const auto positions = GltfUtil::getPositions(model, primitive); const auto indices = GltfUtil::getIndices(model, primitive, positions); const auto normals = GltfUtil::getNormals(model, primitive, positions, indices, smoothNormals); const auto vertexColors = GltfUtil::getVertexColors(model, primitive, 0); const auto vertexIds = GltfUtil::getVertexIds(positions); const auto gltfLocalExtent = GltfUtil::getExtent(model, primitive); const auto faceVertexCounts = GltfUtil::getFaceVertexCounts(indices); if (positions.size() == 0 || indices.size() == 0 || !gltfLocalExtent.has_value()) { return; } const auto doubleSided = materialInfo.doubleSided; const auto gltfLocalToPrimWorldTransform = ecefToPrimWorldTransform * gltfLocalToEcefTransform; const auto [primWorldPosition, primWorldOrientation, primWorldScale] = MathUtil::decompose(gltfLocalToPrimWorldTransform); const auto primWorldExtent = MathUtil::transformExtent(gltfLocalExtent.value(), gltfLocalToPrimWorldTransform); if (primitive.mode == CesiumGltf::MeshPrimitive::Mode::POINTS) { const auto numVoxels = positions.size(); const auto shapeHalfSize = 1.5f; fabricStage.setArrayAttributeSize(_path, FabricTokens::points, numVoxels * 8); fabricStage.setArrayAttributeSize(_path, FabricTokens::faceVertexCounts, numVoxels * 2 * 6); fabricStage.setArrayAttributeSize(_path, FabricTokens::faceVertexIndices, numVoxels * 6 * 2 * 3); const auto pointsFabric = fabricStage.getArrayAttributeWr<glm::fvec3>(_path, FabricTokens::points); const auto faceVertexCountsFabric = fabricStage.getArrayAttributeWr<int>(_path, FabricTokens::faceVertexCounts); const auto faceVertexIndicesFabric = fabricStage.getArrayAttributeWr<int>(_path, FabricTokens::faceVertexIndices); if (hasVertexColors) { fabricStage.setArrayAttributeSize(_path, FabricTokens::primvars_COLOR_0, numVoxels * 8); const auto vertexColorsFabric = fabricStage.getArrayAttributeWr<glm::fvec4>(_path, FabricTokens::primvars_COLOR_0); vertexColors.fill(vertexColorsFabric, 8); } if (hasVertexIds) { fabricStage.setArrayAttributeSize(_path, FabricTokens::primvars_vertexId, numVoxels * 8); const auto vertexIdsFabric = fabricStage.getArrayAttributeWr<float>(_path, FabricTokens::primvars_vertexId); vertexIds.fill(vertexIdsFabric, 8); } for (const auto& customVertexAttribute : customVertexAttributes) { CALL_TEMPLATED_FUNCTION_WITH_RUNTIME_DATA_TYPE( setVertexAttributeValues, customVertexAttribute.type, fabricStage, _path, model, primitive, customVertexAttribute, uint64_t(8)); } uint64_t vertIndex = 0; uint64_t vertexCountsIndex = 0; uint64_t faceVertexIndex = 0; for (uint64_t voxelIndex = 0; voxelIndex < numVoxels; ++voxelIndex) { const auto& center = positions.get(voxelIndex); pointsFabric[vertIndex++] = glm::fvec3{-shapeHalfSize, -shapeHalfSize, -shapeHalfSize} + center; pointsFabric[vertIndex++] = glm::fvec3{-shapeHalfSize, shapeHalfSize, -shapeHalfSize} + center; pointsFabric[vertIndex++] = glm::fvec3{shapeHalfSize, shapeHalfSize, -shapeHalfSize} + center; pointsFabric[vertIndex++] = glm::fvec3{shapeHalfSize, -shapeHalfSize, -shapeHalfSize} + center; pointsFabric[vertIndex++] = glm::fvec3{-shapeHalfSize, -shapeHalfSize, shapeHalfSize} + center; pointsFabric[vertIndex++] = glm::fvec3{-shapeHalfSize, shapeHalfSize, shapeHalfSize} + center; pointsFabric[vertIndex++] = glm::fvec3{shapeHalfSize, shapeHalfSize, shapeHalfSize} + center; pointsFabric[vertIndex++] = glm::fvec3{shapeHalfSize, -shapeHalfSize, shapeHalfSize} + center; for (int i = 0; i < 6; ++i) { faceVertexCountsFabric[vertexCountsIndex++] = 3; faceVertexCountsFabric[vertexCountsIndex++] = 3; } // front faceVertexIndicesFabric[faceVertexIndex++] = 0 + static_cast<int>(voxelIndex * 8); faceVertexIndicesFabric[faceVertexIndex++] = 1 + static_cast<int>(voxelIndex * 8); faceVertexIndicesFabric[faceVertexIndex++] = 2 + static_cast<int>(voxelIndex * 8); faceVertexIndicesFabric[faceVertexIndex++] = 0 + static_cast<int>(voxelIndex * 8); faceVertexIndicesFabric[faceVertexIndex++] = 2 + static_cast<int>(voxelIndex * 8); faceVertexIndicesFabric[faceVertexIndex++] = 3 + static_cast<int>(voxelIndex * 8); // left faceVertexIndicesFabric[faceVertexIndex++] = 4 + static_cast<int>(voxelIndex * 8); faceVertexIndicesFabric[faceVertexIndex++] = 5 + static_cast<int>(voxelIndex * 8); faceVertexIndicesFabric[faceVertexIndex++] = 1 + static_cast<int>(voxelIndex * 8); faceVertexIndicesFabric[faceVertexIndex++] = 4 + static_cast<int>(voxelIndex * 8); faceVertexIndicesFabric[faceVertexIndex++] = 1 + static_cast<int>(voxelIndex * 8); faceVertexIndicesFabric[faceVertexIndex++] = 0 + static_cast<int>(voxelIndex * 8); // right faceVertexIndicesFabric[faceVertexIndex++] = 3 + static_cast<int>(voxelIndex * 8); faceVertexIndicesFabric[faceVertexIndex++] = 2 + static_cast<int>(voxelIndex * 8); faceVertexIndicesFabric[faceVertexIndex++] = 6 + static_cast<int>(voxelIndex * 8); faceVertexIndicesFabric[faceVertexIndex++] = 3 + static_cast<int>(voxelIndex * 8); faceVertexIndicesFabric[faceVertexIndex++] = 6 + static_cast<int>(voxelIndex * 8); faceVertexIndicesFabric[faceVertexIndex++] = 7 + static_cast<int>(voxelIndex * 8); // top faceVertexIndicesFabric[faceVertexIndex++] = 1 + static_cast<int>(voxelIndex * 8); faceVertexIndicesFabric[faceVertexIndex++] = 5 + static_cast<int>(voxelIndex * 8); faceVertexIndicesFabric[faceVertexIndex++] = 6 + static_cast<int>(voxelIndex * 8); faceVertexIndicesFabric[faceVertexIndex++] = 1 + static_cast<int>(voxelIndex * 8); faceVertexIndicesFabric[faceVertexIndex++] = 5 + static_cast<int>(voxelIndex * 8); faceVertexIndicesFabric[faceVertexIndex++] = 2 + static_cast<int>(voxelIndex * 8); // bottom faceVertexIndicesFabric[faceVertexIndex++] = 3 + static_cast<int>(voxelIndex * 8); faceVertexIndicesFabric[faceVertexIndex++] = 7 + static_cast<int>(voxelIndex * 8); faceVertexIndicesFabric[faceVertexIndex++] = 4 + static_cast<int>(voxelIndex * 8); faceVertexIndicesFabric[faceVertexIndex++] = 3 + static_cast<int>(voxelIndex * 8); faceVertexIndicesFabric[faceVertexIndex++] = 4 + static_cast<int>(voxelIndex * 8); faceVertexIndicesFabric[faceVertexIndex++] = 0 + static_cast<int>(voxelIndex * 8); // back faceVertexIndicesFabric[faceVertexIndex++] = 7 + static_cast<int>(voxelIndex * 8); faceVertexIndicesFabric[faceVertexIndex++] = 6 + static_cast<int>(voxelIndex * 8); faceVertexIndicesFabric[faceVertexIndex++] = 5 + static_cast<int>(voxelIndex * 8); faceVertexIndicesFabric[faceVertexIndex++] = 7 + static_cast<int>(voxelIndex * 8); faceVertexIndicesFabric[faceVertexIndex++] = 5 + static_cast<int>(voxelIndex * 8); faceVertexIndicesFabric[faceVertexIndex++] = 4 + static_cast<int>(voxelIndex * 8); } } else { fabricStage.setArrayAttributeSize(_path, FabricTokens::faceVertexCounts, faceVertexCounts.size()); fabricStage.setArrayAttributeSize(_path, FabricTokens::faceVertexIndices, indices.size()); fabricStage.setArrayAttributeSize(_path, FabricTokens::points, positions.size()); const auto faceVertexCountsFabric = fabricStage.getArrayAttributeWr<int>(_path, FabricTokens::faceVertexCounts); const auto faceVertexIndicesFabric = fabricStage.getArrayAttributeWr<int>(_path, FabricTokens::faceVertexIndices); const auto pointsFabric = fabricStage.getArrayAttributeWr<glm::fvec3>(_path, FabricTokens::points); faceVertexCounts.fill(faceVertexCountsFabric); indices.fill(faceVertexIndicesFabric); positions.fill(pointsFabric); const auto fillTexcoords = [this, &fabricStage](uint64_t texcoordIndex, const TexcoordsAccessor& texcoords) { assert(texcoordIndex < _geometryDescriptor.getTexcoordSetCount()); const auto& primvarStToken = FabricTokens::primvars_st_n(texcoordIndex); fabricStage.setArrayAttributeSize(_path, primvarStToken, texcoords.size()); const auto stFabric = fabricStage.getArrayAttributeWr<glm::fvec2>(_path, primvarStToken); texcoords.fill(stFabric); }; for (const auto& [gltfSetIndex, primvarStIndex] : texcoordIndexMapping) { const auto texcoords = GltfUtil::getTexcoords(model, primitive, gltfSetIndex); fillTexcoords(primvarStIndex, texcoords); } for (const auto& [gltfSetIndex, primvarStIndex] : rasterOverlayTexcoordIndexMapping) { const auto texcoords = GltfUtil::getRasterOverlayTexcoords(model, primitive, gltfSetIndex); fillTexcoords(primvarStIndex, texcoords); } if (hasNormals) { fabricStage.setArrayAttributeSize(_path, FabricTokens::primvars_normals, normals.size()); const auto normalsFabric = fabricStage.getArrayAttributeWr<glm::fvec3>(_path, FabricTokens::primvars_normals); normals.fill(normalsFabric); } if (hasVertexColors) { fabricStage.setArrayAttributeSize(_path, FabricTokens::primvars_COLOR_0, vertexColors.size()); const auto vertexColorsFabric = fabricStage.getArrayAttributeWr<glm::fvec4>(_path, FabricTokens::primvars_COLOR_0); vertexColors.fill(vertexColorsFabric); } if (hasVertexIds) { fabricStage.setArrayAttributeSize(_path, FabricTokens::primvars_vertexId, vertexIds.size()); const auto vertexIdsFabric = fabricStage.getArrayAttributeWr<float>(_path, FabricTokens::primvars_vertexId); vertexIds.fill(vertexIdsFabric); } for (const auto& customVertexAttribute : customVertexAttributes) { CALL_TEMPLATED_FUNCTION_WITH_RUNTIME_DATA_TYPE( setVertexAttributeValues, customVertexAttribute.type, fabricStage, _path, model, primitive, customVertexAttribute, uint64_t(1)); } } // clang-format off const auto doubleSidedFabric = fabricStage.getAttributeWr<bool>(_path, FabricTokens::doubleSided); const auto extentFabric = fabricStage.getAttributeWr<pxr::GfRange3d>(_path, FabricTokens::extent); const auto worldExtentFabric = fabricStage.getAttributeWr<pxr::GfRange3d>(_path, FabricTokens::_worldExtent); const auto gltfLocalToEcefTransformFabric = fabricStage.getAttributeWr<pxr::GfMatrix4d>(_path, FabricTokens::_cesium_gltfLocalToEcefTransform); const auto worldPositionFabric = fabricStage.getAttributeWr<pxr::GfVec3d>(_path, FabricTokens::_worldPosition); const auto worldOrientationFabric = fabricStage.getAttributeWr<pxr::GfQuatf>(_path, FabricTokens::_worldOrientation); const auto worldScaleFabric = fabricStage.getAttributeWr<pxr::GfVec3f>(_path, FabricTokens::_worldScale); const auto tilesetIdFabric = fabricStage.getAttributeWr<int64_t>(_path, FabricTokens::_cesium_tilesetId); // clang-format on *doubleSidedFabric = doubleSided; *extentFabric = UsdUtil::glmToUsdExtent(gltfLocalExtent.value()); *worldExtentFabric = UsdUtil::glmToUsdExtent(primWorldExtent); *gltfLocalToEcefTransformFabric = UsdUtil::glmToUsdMatrix(gltfLocalToEcefTransform); *worldPositionFabric = UsdUtil::glmToUsdVector(primWorldPosition); *worldOrientationFabric = UsdUtil::glmToUsdQuat(glm::fquat(primWorldOrientation)); *worldScaleFabric = UsdUtil::glmToUsdVector(glm::fvec3(primWorldScale)); *tilesetIdFabric = tilesetId; } bool FabricGeometry::stageDestroyed() { // Tile render resources may be processed asynchronously even after the tileset and stage have been destroyed. // Add this check to all public member functions, including constructors and destructors, to prevent them from // modifying the stage. return _stageId != _pContext->getUsdStageId(); } }; // namespace cesium::omniverse
26,371
C++
46.688969
147
0.712373
CesiumGS/cesium-omniverse/src/core/src/FabricUtil.cpp
#include "cesium/omniverse/FabricUtil.h" #include "cesium/omniverse/Context.h" #include "cesium/omniverse/DataType.h" #include "cesium/omniverse/DataTypeUtil.h" #include "cesium/omniverse/FabricStatistics.h" #include "cesium/omniverse/MathUtil.h" #include "cesium/omniverse/UsdTokens.h" #include "cesium/omniverse/UsdUtil.h" #include <omni/fabric/FabricUSD.h> #include <omni/fabric/SimStageWithHistory.h> #include <pxr/base/gf/matrix4d.h> #include <pxr/base/gf/quatf.h> #include <pxr/base/gf/range3d.h> #include <pxr/base/gf/vec2f.h> #include <pxr/base/gf/vec3f.h> #include <spdlog/fmt/fmt.h> #include <sstream> namespace cesium::omniverse::FabricUtil { namespace { const std::string_view NO_DATA_STRING = "[No Data]"; const std::string_view TYPE_NOT_SUPPORTED_STRING = "[Type Not Supported]"; // Wraps the token type so that we can define a custom stream insertion operator class TokenWrapper { private: omni::fabric::TokenC token; public: friend std::ostream& operator<<(std::ostream& os, const TokenWrapper& tokenWrapper); }; std::ostream& operator<<(std::ostream& os, const TokenWrapper& tokenWrapper) { os << omni::fabric::Token(tokenWrapper.token).getString(); return os; } // Wraps a boolean so that we print "true" and "false" instead of 0 and 1 class BoolWrapper { private: bool value; public: friend std::ostream& operator<<(std::ostream& os, const BoolWrapper& boolWrapper); }; std::ostream& operator<<(std::ostream& os, const BoolWrapper& boolWrapper) { os << (boolWrapper.value ? "true" : "false"); return os; } class AssetWrapper { private: omni::fabric::AssetPath asset; public: friend std::ostream& operator<<(std::ostream& os, const AssetWrapper& assetWrapper); }; std::ostream& operator<<(std::ostream& os, const AssetWrapper& assetWrapper) { if (assetWrapper.asset.assetPath.IsEmpty()) { os << NO_DATA_STRING; return os; } os << "Asset Path: " << assetWrapper.asset.assetPath.GetText() << ", Resolved Path: " << assetWrapper.asset.resolvedPath.GetText(); return os; } template <typename T> std::string printAttributeValue(const T* values, uint64_t elementCount, uint64_t componentCount, bool isArray) { std::stringstream stream; if (isArray) { stream << "["; } for (uint64_t i = 0; i < elementCount; ++i) { if (componentCount > 1) { stream << "["; } for (uint64_t j = 0; j < componentCount; ++j) { stream << values[i * componentCount + j]; if (j < componentCount - 1) { stream << ","; } } if (componentCount > 1) { stream << "]"; } if (elementCount > 1 && i < elementCount - 1) { stream << ","; } } if (isArray) { stream << "]"; } return stream.str(); } template <bool IsArray, typename BaseType, uint64_t ComponentCount> std::string printAttributeValue( omni::fabric::StageReaderWriter& fabricStage, const omni::fabric::Path& primPath, const omni::fabric::Token& attributeName, const omni::fabric::AttributeRole& role) { using ElementType = std::array<BaseType, ComponentCount>; if constexpr (IsArray) { const auto values = fabricStage.getArrayAttributeRd<ElementType>(primPath, attributeName); const auto elementCount = values.size(); if (elementCount == 0) { return std::string(NO_DATA_STRING); } const auto valuesPtr = values.front().data(); if (role == omni::fabric::AttributeRole::eText) { return std::string(reinterpret_cast<const char*>(valuesPtr), elementCount); } return printAttributeValue<BaseType>(valuesPtr, elementCount, ComponentCount, true); } else { const auto pValue = fabricStage.getAttributeRd<ElementType>(primPath, attributeName); if (!pValue) { return std::string(NO_DATA_STRING); } return printAttributeValue<BaseType>(pValue->data(), 1, ComponentCount, false); } } std::string printConnection( omni::fabric::StageReaderWriter& fabricStage, const omni::fabric::Path& primPath, const omni::fabric::Token& attributeName) { const auto pConnection = fabricStage.getConnection(primPath, attributeName); if (!pConnection) { return std::string(NO_DATA_STRING); } const auto path = omni::fabric::Path(pConnection->path).getText(); const auto attrName = omni::fabric::Token(pConnection->attrName).getText(); return fmt::format("Path: {}, Attribute Name: {}", path, attrName); } std::string printAttributeValue( omni::fabric::StageReaderWriter& fabricStage, const omni::fabric::Path& primPath, const omni::fabric::AttrNameAndType& attribute) { const auto attributeType = attribute.type; const auto baseType = attributeType.baseType; const auto componentCount = attributeType.componentCount; const auto name = attribute.name; const auto arrayDepth = attributeType.arrayDepth; const auto role = attributeType.role; // This switch statement should cover most of the attribute types we expect to see on the stage. // This includes the USD types in SdfValueTypeNames and Fabric types like assets and tokens. // We can add more as needed. if (arrayDepth == 0) { switch (baseType) { case omni::fabric::BaseDataType::eAsset: switch (componentCount) { case 1: return printAttributeValue<false, AssetWrapper, 1>(fabricStage, primPath, name, role); default: break; } break; case omni::fabric::BaseDataType::eConnection: switch (componentCount) { case 1: return printConnection(fabricStage, primPath, name); default: break; } break; case omni::fabric::BaseDataType::eToken: switch (componentCount) { case 1: return printAttributeValue<false, TokenWrapper, 1>(fabricStage, primPath, name, role); default: break; } break; case omni::fabric::BaseDataType::eBool: switch (componentCount) { case 1: return printAttributeValue<false, BoolWrapper, 1>(fabricStage, primPath, name, role); default: break; } break; case omni::fabric::BaseDataType::eUChar: switch (componentCount) { case 1: return printAttributeValue<false, uint8_t, 1>(fabricStage, primPath, name, role); default: break; } break; case omni::fabric::BaseDataType::eInt: switch (componentCount) { case 1: return printAttributeValue<false, int32_t, 1>(fabricStage, primPath, name, role); case 2: return printAttributeValue<false, int32_t, 2>(fabricStage, primPath, name, role); case 3: return printAttributeValue<false, int32_t, 3>(fabricStage, primPath, name, role); case 4: return printAttributeValue<false, int32_t, 4>(fabricStage, primPath, name, role); default: break; } break; case omni::fabric::BaseDataType::eUInt: switch (componentCount) { case 1: return printAttributeValue<false, uint32_t, 1>(fabricStage, primPath, name, role); default: break; } break; case omni::fabric::BaseDataType::eInt64: switch (componentCount) { case 1: return printAttributeValue<false, int64_t, 1>(fabricStage, primPath, name, role); default: break; } break; case omni::fabric::BaseDataType::eUInt64: switch (componentCount) { case 1: return printAttributeValue<false, uint64_t, 1>(fabricStage, primPath, name, role); default: break; } break; case omni::fabric::BaseDataType::eFloat: switch (componentCount) { case 1: return printAttributeValue<false, float, 1>(fabricStage, primPath, name, role); case 2: return printAttributeValue<false, float, 2>(fabricStage, primPath, name, role); case 3: return printAttributeValue<false, float, 3>(fabricStage, primPath, name, role); case 4: return printAttributeValue<false, float, 4>(fabricStage, primPath, name, role); default: break; } break; case omni::fabric::BaseDataType::eDouble: switch (componentCount) { case 1: return printAttributeValue<false, double, 1>(fabricStage, primPath, name, role); case 2: return printAttributeValue<false, double, 2>(fabricStage, primPath, name, role); case 3: return printAttributeValue<false, double, 3>(fabricStage, primPath, name, role); case 4: return printAttributeValue<false, double, 4>(fabricStage, primPath, name, role); case 6: return printAttributeValue<false, double, 6>(fabricStage, primPath, name, role); case 9: return printAttributeValue<false, double, 9>(fabricStage, primPath, name, role); case 16: return printAttributeValue<false, double, 16>(fabricStage, primPath, name, role); default: break; } break; // Due to legacy support the eRelationship type is defined as a scalar value but is secretly an array case omni::fabric::BaseDataType::eRelationship: switch (componentCount) { case 1: return printAttributeValue<true, uint64_t, 1>(fabricStage, primPath, name, role); default: break; } break; default: break; } } else if (arrayDepth == 1) { switch (baseType) { case omni::fabric::BaseDataType::eAsset: switch (componentCount) { case 1: return printAttributeValue<true, AssetWrapper, 1>(fabricStage, primPath, name, role); default: break; } break; case omni::fabric::BaseDataType::eToken: switch (componentCount) { case 1: return printAttributeValue<true, TokenWrapper, 1>(fabricStage, primPath, name, role); default: break; } break; case omni::fabric::BaseDataType::eBool: switch (componentCount) { case 1: return printAttributeValue<true, BoolWrapper, 1>(fabricStage, primPath, name, role); default: break; } break; case omni::fabric::BaseDataType::eUChar: switch (componentCount) { case 1: return printAttributeValue<true, uint8_t, 1>(fabricStage, primPath, name, role); default: break; } break; case omni::fabric::BaseDataType::eInt: switch (componentCount) { case 1: return printAttributeValue<true, int32_t, 1>(fabricStage, primPath, name, role); case 2: return printAttributeValue<true, int32_t, 2>(fabricStage, primPath, name, role); case 3: return printAttributeValue<true, int32_t, 3>(fabricStage, primPath, name, role); case 4: return printAttributeValue<true, int32_t, 4>(fabricStage, primPath, name, role); default: break; } break; case omni::fabric::BaseDataType::eUInt: switch (componentCount) { case 1: return printAttributeValue<true, uint32_t, 1>(fabricStage, primPath, name, role); default: break; } break; case omni::fabric::BaseDataType::eInt64: switch (componentCount) { case 1: return printAttributeValue<true, int64_t, 1>(fabricStage, primPath, name, role); default: break; } break; case omni::fabric::BaseDataType::eUInt64: switch (componentCount) { case 1: return printAttributeValue<true, uint64_t, 1>(fabricStage, primPath, name, role); default: break; } break; case omni::fabric::BaseDataType::eFloat: switch (componentCount) { case 1: return printAttributeValue<true, float, 1>(fabricStage, primPath, name, role); case 2: return printAttributeValue<true, float, 2>(fabricStage, primPath, name, role); case 3: return printAttributeValue<true, float, 3>(fabricStage, primPath, name, role); case 4: return printAttributeValue<true, float, 4>(fabricStage, primPath, name, role); default: break; } break; case omni::fabric::BaseDataType::eDouble: switch (componentCount) { case 1: return printAttributeValue<true, double, 1>(fabricStage, primPath, name, role); case 2: return printAttributeValue<true, double, 2>(fabricStage, primPath, name, role); case 3: return printAttributeValue<true, double, 3>(fabricStage, primPath, name, role); case 4: return printAttributeValue<true, double, 4>(fabricStage, primPath, name, role); case 6: return printAttributeValue<true, double, 6>(fabricStage, primPath, name, role); case 9: return printAttributeValue<true, double, 9>(fabricStage, primPath, name, role); case 16: return printAttributeValue<true, double, 16>(fabricStage, primPath, name, role); default: break; } break; default: break; } } return std::string(TYPE_NOT_SUPPORTED_STRING); } } // namespace std::string printFabricStage(omni::fabric::StageReaderWriter& fabricStage) { std::stringstream stream; // For extra debugging. This gets printed to the console. fabricStage.printBucketNames(); // This returns ALL the buckets const auto& buckets = fabricStage.findPrims({}); for (uint64_t bucketId = 0; bucketId < buckets.bucketCount(); ++bucketId) { const auto& attributes = fabricStage.getAttributeNamesAndTypes(buckets, bucketId); const auto& primPaths = fabricStage.getPathArray(buckets, bucketId); for (const auto& primPath : primPaths) { const auto primPathString = primPath.getText(); const auto primPathUint64 = primPath.asPathC().path; stream << fmt::format("Prim: {} ({})\n", primPathString, primPathUint64); stream << fmt::format(" Attributes:\n"); for (const auto& attribute : attributes) { const auto attributeName = attribute.name.getText(); const auto attributeType = attribute.type.getTypeName(); const auto attributeBaseType = attribute.type.baseType; const auto attributeValue = printAttributeValue(fabricStage, primPath, attribute); stream << fmt::format(" Attribute: {}\n", attributeName); stream << fmt::format(" Type: {}\n", attributeType); if (attributeBaseType != omni::fabric::BaseDataType::eTag) { stream << fmt::format(" Value: {}\n", attributeValue); } } } } return stream.str(); } FabricStatistics getStatistics(omni::fabric::StageReaderWriter& fabricStage) { FabricStatistics statistics; const auto geometryBuckets = fabricStage.findPrims( {omni::fabric::AttrNameAndType(FabricTypes::_cesium_tilesetId, FabricTokens::_cesium_tilesetId)}, {omni::fabric::AttrNameAndType(FabricTypes::Mesh, FabricTokens::Mesh)}); const auto materialBuckets = fabricStage.findPrims( {omni::fabric::AttrNameAndType(FabricTypes::_cesium_tilesetId, FabricTokens::_cesium_tilesetId)}, {omni::fabric::AttrNameAndType(FabricTypes::Material, FabricTokens::Material)}); for (uint64_t bucketId = 0; bucketId < geometryBuckets.bucketCount(); ++bucketId) { const auto paths = fabricStage.getPathArray(geometryBuckets, bucketId); statistics.geometriesCapacity += paths.size(); for (const auto& path : paths) { const auto worldVisibilityFabric = fabricStage.getAttributeRd<bool>(path, FabricTokens::_worldVisibility); const auto faceVertexCountsFabric = fabricStage.getArrayAttributeRd<int>(path, FabricTokens::faceVertexCounts); const auto tilesetIdFabric = fabricStage.getAttributeRd<int64_t>(path, FabricTokens::_cesium_tilesetId); assert(worldVisibilityFabric); assert(tilesetIdFabric); if (*tilesetIdFabric == NO_TILESET_ID) { continue; } ++statistics.geometriesLoaded; const auto triangleCount = faceVertexCountsFabric.size(); statistics.trianglesLoaded += triangleCount; if (*worldVisibilityFabric) { ++statistics.geometriesRendered; statistics.trianglesRendered += triangleCount; } } } for (uint64_t bucketId = 0; bucketId < materialBuckets.bucketCount(); ++bucketId) { auto paths = fabricStage.getPathArray(materialBuckets, bucketId); const auto tilesetIdFabric = fabricStage.getAttributeArrayRd<int64_t>(materialBuckets, bucketId, FabricTokens::_cesium_tilesetId); statistics.materialsCapacity += paths.size(); for (uint64_t i = 0; i < paths.size(); ++i) { if (tilesetIdFabric[i] == NO_TILESET_ID) { continue; } ++statistics.materialsLoaded; } } return statistics; } void destroyPrim(omni::fabric::StageReaderWriter& fabricStage, const omni::fabric::Path& path) { fabricStage.destroyPrim(path); // Prims removed from Fabric need special handling for their removal to be reflected in the Hydra render index // This workaround may not be needed in future Kit versions, but is needed as of Kit 105.0 const omni::fabric::Path changeTrackingPath("/TempChangeTracking"); if (!fabricStage.getAttributeRd<omni::fabric::PathC>(changeTrackingPath, FabricTokens::_deletedPrims)) { return; } const auto deletedPrimsSize = fabricStage.getArrayAttributeSize(changeTrackingPath, FabricTokens::_deletedPrims); fabricStage.setArrayAttributeSize(changeTrackingPath, FabricTokens::_deletedPrims, deletedPrimsSize + 1); const auto deletedPrimsFabric = fabricStage.getArrayAttributeWr<omni::fabric::PathC>(changeTrackingPath, FabricTokens::_deletedPrims); deletedPrimsFabric[deletedPrimsSize] = path; } void setTilesetTransform( omni::fabric::StageReaderWriter& fabricStage, int64_t tilesetId, const glm::dmat4& ecefToPrimWorldTransform) { const auto buckets = fabricStage.findPrims( {omni::fabric::AttrNameAndType(FabricTypes::_cesium_tilesetId, FabricTokens::_cesium_tilesetId)}, {omni::fabric::AttrNameAndType( FabricTypes::_cesium_gltfLocalToEcefTransform, FabricTokens::_cesium_gltfLocalToEcefTransform)}); for (uint64_t bucketId = 0; bucketId < buckets.bucketCount(); ++bucketId) { // clang-format off const auto tilesetIdFabric = fabricStage.getAttributeArrayRd<int64_t>(buckets, bucketId, FabricTokens::_cesium_tilesetId); const auto gltfLocalToEcefTransformFabric = fabricStage.getAttributeArrayRd<pxr::GfMatrix4d>(buckets, bucketId, FabricTokens::_cesium_gltfLocalToEcefTransform); const auto extentFabric = fabricStage.getAttributeArrayRd<pxr::GfRange3d>(buckets, bucketId, FabricTokens::extent); const auto worldPositionFabric = fabricStage.getAttributeArrayWr<pxr::GfVec3d>(buckets, bucketId, FabricTokens::_worldPosition); const auto worldOrientationFabric = fabricStage.getAttributeArrayWr<pxr::GfQuatf>(buckets, bucketId, FabricTokens::_worldOrientation); const auto worldScaleFabric = fabricStage.getAttributeArrayWr<pxr::GfVec3f>(buckets, bucketId, FabricTokens::_worldScale); const auto worldExtentFabric = fabricStage.getAttributeArrayWr<pxr::GfRange3d>(buckets, bucketId, FabricTokens::_worldExtent); // clang-format on for (uint64_t i = 0; i < tilesetIdFabric.size(); ++i) { if (tilesetIdFabric[i] == tilesetId) { const auto gltfLocalToEcefTransform = UsdUtil::usdToGlmMatrix(gltfLocalToEcefTransformFabric[i]); const auto gltfLocalToPrimWorldTransform = ecefToPrimWorldTransform * gltfLocalToEcefTransform; const auto gltfLocalExtent = UsdUtil::usdToGlmExtent(extentFabric[i]); const auto [primWorldPosition, primWorldOrientation, primWorldScale] = MathUtil::decompose(gltfLocalToPrimWorldTransform); const auto primWorldExtent = MathUtil::transformExtent(gltfLocalExtent, gltfLocalToPrimWorldTransform); worldPositionFabric[i] = UsdUtil::glmToUsdVector(primWorldPosition); worldOrientationFabric[i] = UsdUtil::glmToUsdQuat(glm::fquat(primWorldOrientation)); worldScaleFabric[i] = UsdUtil::glmToUsdVector(glm::fvec3(primWorldScale)); worldExtentFabric[i] = UsdUtil::glmToUsdExtent(primWorldExtent); } } } } omni::fabric::Path toFabricPath(const pxr::SdfPath& path) { return {omni::fabric::asInt(path)}; } omni::fabric::Token toFabricToken(const pxr::TfToken& token) { return {omni::fabric::asInt(token)}; } omni::fabric::Path joinPaths(const omni::fabric::Path& absolutePath, const omni::fabric::Token& relativePath) { return {fmt::format("{}/{}", absolutePath.getText(), relativePath.getText()).c_str()}; } omni::fabric::Path getCopiedShaderPath(const omni::fabric::Path& materialPath, const omni::fabric::Path& shaderPath) { // materialPath is the FabricMaterial path // shaderPath is the USD shader path return FabricUtil::joinPaths(materialPath, omni::fabric::Token(UsdUtil::getSafeName(shaderPath.getText()).c_str())); } namespace { struct FabricConnection { omni::fabric::Connection* pConnection; omni::fabric::Token attributeName; }; std::vector<FabricConnection> getConnections(omni::fabric::StageReaderWriter& fabricStage, const omni::fabric::Path& path) { std::vector<FabricConnection> connections; const auto attributes = fabricStage.getAttributeNamesAndTypes(path); const auto& names = attributes.first; const auto& types = attributes.second; for (uint64_t i = 0; i < names.size(); ++i) { const auto& name = names[i]; const auto& type = types[i]; if (type.baseType == omni::fabric::BaseDataType::eConnection) { const auto pConnection = fabricStage.getConnection(path, name); if (pConnection) { // In C++ 20 this can be emplace_back without the {} connections.push_back({pConnection, name}); } } } return connections; } bool isOutput(const omni::fabric::Token& attributeName) { return attributeName == FabricTokens::outputs_out; } bool isConnection(const omni::fabric::Type& attributeType) { return attributeType.baseType == omni::fabric::BaseDataType::eConnection; } bool isEmptyToken( omni::fabric::StageReaderWriter& fabricStage, const omni::fabric::Path& path, const omni::fabric::Token& attributeName, const omni::fabric::Type& attributeType) { if (attributeType.baseType == omni::fabric::BaseDataType::eToken) { const auto pAttributeValue = fabricStage.getAttributeRd<omni::fabric::Token>(path, attributeName); if (!pAttributeValue || pAttributeValue->size() == 0) { return true; } } return false; } std::vector<omni::fabric::TokenC> getAttributesToCopy(omni::fabric::StageReaderWriter& fabricStage, const omni::fabric::Path& path) { std::vector<omni::fabric::TokenC> attributeNames; const auto attributes = fabricStage.getAttributeNamesAndTypes(path); const auto& names = attributes.first; const auto& types = attributes.second; for (uint64_t i = 0; i < names.size(); ++i) { const auto& name = names[i]; const auto& type = types[i]; if (!isOutput(name) && !isConnection(type) && !isEmptyToken(fabricStage, path, name, type)) { attributeNames.push_back(name.asTokenC()); } } return attributeNames; } struct FabricAttribute { omni::fabric::Token name; omni::fabric::Type type; }; std::vector<FabricAttribute> getAttributesToCreate(omni::fabric::StageReaderWriter& fabricStage, const omni::fabric::Path& path) { std::vector<FabricAttribute> attributeNames; const auto attributes = fabricStage.getAttributeNamesAndTypes(path); const auto& names = attributes.first; const auto& types = attributes.second; for (uint64_t i = 0; i < names.size(); ++i) { const auto& name = names[i]; const auto& type = types[i]; if (isOutput(name) || isEmptyToken(fabricStage, path, name, type)) { // In C++ 20 this can be emplace_back without the {} attributeNames.push_back({name, type}); } } return attributeNames; } void getConnectedPrimsRecursive( omni::fabric::StageReaderWriter& fabricStage, const omni::fabric::Path& path, std::vector<omni::fabric::Path>& connectedPaths) { const auto connections = getConnections(fabricStage, path); for (const auto& connection : connections) { if (!CppUtil::contains(connectedPaths, connection.pConnection->path)) { connectedPaths.push_back(connection.pConnection->path); getConnectedPrimsRecursive(fabricStage, connection.pConnection->path, connectedPaths); } } } std::vector<omni::fabric::Path> getPrimsInMaterialNetwork(omni::fabric::StageReaderWriter& fabricStage, const omni::fabric::Path& path) { std::vector<omni::fabric::Path> paths; paths.push_back(path); getConnectedPrimsRecursive(fabricStage, path, paths); return paths; } omni::fabric::Path getMaterialSource(omni::fabric::StageReaderWriter& fabricStage, const omni::fabric::Path& path) { if (fabricStage.attributeExistsWithType(path, FabricTokens::_materialSource, FabricTypes::_materialSource)) { const auto materialSourceFabric = fabricStage.getArrayAttributeRd<omni::fabric::PathC>(path, FabricTokens::_materialSource); if (!materialSourceFabric.empty()) { return *materialSourceFabric.begin(); } } return path; } } // namespace std::vector<omni::fabric::Path> copyMaterial( omni::fabric::StageReaderWriter& fabricStage, const omni::fabric::Path& srcMaterialPath, const omni::fabric::Path& dstMaterialPath) { const auto iFabricStage = carb::getCachedInterface<omni::fabric::IStageReaderWriter>(); const auto materialSourcePath = getMaterialSource(fabricStage, srcMaterialPath); const auto srcPaths = getPrimsInMaterialNetwork(fabricStage, materialSourcePath); std::vector<omni::fabric::Path> dstPaths; dstPaths.reserve(srcPaths.size()); for (const auto& srcPath : srcPaths) { auto dstPath = omni::fabric::Path(); if (srcPath == materialSourcePath) { dstPath = dstMaterialPath; } else { const auto name = omni::fabric::Token(std::strrchr(srcPath.getText(), '/') + 1); dstPath = FabricUtil::getCopiedShaderPath(dstMaterialPath, srcMaterialPath.appendChild(name)); } dstPaths.push_back(dstPath); fabricStage.createPrim(dstPath); // This excludes connections, outputs, and empty tokens // The material network will be reconnected later once all the prims have been copied // The reason for excluding outputs and empty tokens is so that Omniverse doesn't print the warning // [Warning] [omni.fabric.plugin] Warning: input has no valid data const auto attributesToCopy = getAttributesToCopy(fabricStage, srcPath); iFabricStage->copySpecifiedAttributes( fabricStage.getId(), srcPath, attributesToCopy.data(), dstPath, attributesToCopy.data(), attributesToCopy.size()); // Add the outputs and empty tokens back. This doesn't print a warning. const auto attributesToCreate = getAttributesToCreate(fabricStage, srcPath); for (const auto& attribute : attributesToCreate) { fabricStage.createAttribute(dstPath, attribute.name, attribute.type); } } // Reconnect the prims for (uint64_t i = 0; i < srcPaths.size(); ++i) { const auto& srcPath = srcPaths[i]; const auto& dstPath = dstPaths[i]; const auto connections = getConnections(fabricStage, srcPath); for (const auto& connection : connections) { const auto index = CppUtil::indexOf(srcPaths, connection.pConnection->path); assert(index != srcPaths.size()); // Ensure that all connections are part of the material network const auto dstConnection = omni::fabric::Connection{dstPaths[index].asPathC(), connection.pConnection->attrName}; fabricStage.createConnection(dstPath, connection.attributeName, dstConnection); } } return dstPaths; } bool materialHasCesiumNodes(omni::fabric::StageReaderWriter& fabricStage, const omni::fabric::Path& materialPath) { const auto materialSourcePath = getMaterialSource(fabricStage, materialPath); const auto paths = getPrimsInMaterialNetwork(fabricStage, materialSourcePath); for (const auto& path : paths) { const auto mdlIdentifier = getMdlIdentifier(fabricStage, path); if (isCesiumNode(mdlIdentifier)) { return true; } } return false; } bool isCesiumNode(const omni::fabric::Token& mdlIdentifier) { return mdlIdentifier == FabricTokens::cesium_base_color_texture_float4 || mdlIdentifier == FabricTokens::cesium_raster_overlay_float4 || mdlIdentifier == FabricTokens::cesium_feature_id_int || isCesiumPropertyNode(mdlIdentifier); } bool isCesiumPropertyNode(const omni::fabric::Token& mdlIdentifier) { return mdlIdentifier == FabricTokens::cesium_property_int || mdlIdentifier == FabricTokens::cesium_property_int2 || mdlIdentifier == FabricTokens::cesium_property_int3 || mdlIdentifier == FabricTokens::cesium_property_int4 || mdlIdentifier == FabricTokens::cesium_property_float || mdlIdentifier == FabricTokens::cesium_property_float2 || mdlIdentifier == FabricTokens::cesium_property_float3 || mdlIdentifier == FabricTokens::cesium_property_float4; } bool isShaderConnectedToMaterial( omni::fabric::StageReaderWriter& fabricStage, const omni::fabric::Path& materialPath, const omni::fabric::Path& shaderPath) { const auto materialSourcePath = getMaterialSource(fabricStage, materialPath); const auto paths = getPrimsInMaterialNetwork(fabricStage, materialSourcePath); return CppUtil::contains(paths, shaderPath); } omni::fabric::Token getMdlIdentifier(omni::fabric::StageReaderWriter& fabricStage, const omni::fabric::Path& path) { if (fabricStage.attributeExists(path, FabricTokens::info_mdl_sourceAsset_subIdentifier)) { const auto pInfoMdlSourceAssetSubIdentifierFabric = fabricStage.getAttributeRd<omni::fabric::Token>(path, FabricTokens::info_mdl_sourceAsset_subIdentifier); if (pInfoMdlSourceAssetSubIdentifierFabric) { return *pInfoMdlSourceAssetSubIdentifierFabric; } } return {}; } omni::fabric::Type getPrimvarType(DataType type) { const auto baseDataType = DataTypeUtil::getPrimvarBaseDataType(type); const auto componentCount = DataTypeUtil::getComponentCount(type); return {baseDataType, static_cast<uint8_t>(componentCount), 1, omni::fabric::AttributeRole::eNone}; } MdlExternalPropertyType getMdlExternalPropertyType(const omni::fabric::Token& mdlIdentifier) { assert(isCesiumPropertyNode(mdlIdentifier)); if (mdlIdentifier == FabricTokens::cesium_property_int) { return MdlExternalPropertyType::INT32; } else if (mdlIdentifier == FabricTokens::cesium_property_int2) { return MdlExternalPropertyType::VEC2_INT32; } else if (mdlIdentifier == FabricTokens::cesium_property_int3) { return MdlExternalPropertyType::VEC3_INT32; } else if (mdlIdentifier == FabricTokens::cesium_property_int4) { return MdlExternalPropertyType::VEC4_INT32; } else if (mdlIdentifier == FabricTokens::cesium_property_float) { return MdlExternalPropertyType::FLOAT32; } else if (mdlIdentifier == FabricTokens::cesium_property_float2) { return MdlExternalPropertyType::VEC2_FLOAT32; } else if (mdlIdentifier == FabricTokens::cesium_property_float3) { return MdlExternalPropertyType::VEC3_FLOAT32; } else if (mdlIdentifier == FabricTokens::cesium_property_float4) { return MdlExternalPropertyType::VEC4_FLOAT32; } return MdlExternalPropertyType::INT32; } bool typesCompatible(MdlExternalPropertyType externalType, MdlInternalPropertyType internalType) { switch (externalType) { case MdlExternalPropertyType::INT32: switch (internalType) { case MdlInternalPropertyType::INT32: return true; default: return false; } case MdlExternalPropertyType::FLOAT32: switch (internalType) { case MdlInternalPropertyType::FLOAT32: case MdlInternalPropertyType::INT32_NORM: return true; default: return false; } case MdlExternalPropertyType::VEC2_INT32: switch (internalType) { case MdlInternalPropertyType::VEC2_INT32: return true; default: return false; } case MdlExternalPropertyType::VEC2_FLOAT32: switch (internalType) { case MdlInternalPropertyType::VEC2_FLOAT32: case MdlInternalPropertyType::VEC2_INT32_NORM: return true; default: return false; } case MdlExternalPropertyType::VEC3_INT32: switch (internalType) { case MdlInternalPropertyType::VEC3_INT32: return true; default: return false; } case MdlExternalPropertyType::VEC3_FLOAT32: switch (internalType) { case MdlInternalPropertyType::VEC3_FLOAT32: case MdlInternalPropertyType::VEC3_INT32_NORM: return true; default: return false; } case MdlExternalPropertyType::VEC4_INT32: switch (internalType) { case MdlInternalPropertyType::VEC4_INT32: return true; default: return false; } case MdlExternalPropertyType::VEC4_FLOAT32: switch (internalType) { case MdlInternalPropertyType::VEC4_FLOAT32: case MdlInternalPropertyType::VEC4_INT32_NORM: return true; default: return false; } case MdlExternalPropertyType::MAT2_FLOAT32: switch (internalType) { case MdlInternalPropertyType::MAT2_INT32: case MdlInternalPropertyType::MAT2_FLOAT32: case MdlInternalPropertyType::MAT2_INT32_NORM: return true; default: return false; } case MdlExternalPropertyType::MAT3_FLOAT32: switch (internalType) { case MdlInternalPropertyType::MAT3_INT32: case MdlInternalPropertyType::MAT3_FLOAT32: case MdlInternalPropertyType::MAT3_INT32_NORM: return true; default: return false; } case MdlExternalPropertyType::MAT4_FLOAT32: switch (internalType) { case MdlInternalPropertyType::MAT4_INT32: case MdlInternalPropertyType::MAT4_FLOAT32: case MdlInternalPropertyType::MAT4_INT32_NORM: return true; default: return false; } } return false; } } // namespace cesium::omniverse::FabricUtil
39,284
C++
39.5
168
0.60279
CesiumGS/cesium-omniverse/src/core/src/MathUtil.cpp
#include "cesium/omniverse/MathUtil.h" #include <glm/gtx/euler_angles.hpp> #include <glm/gtx/matrix_decompose.hpp> namespace cesium::omniverse::MathUtil { EulerAngleOrder getReversedEulerAngleOrder(EulerAngleOrder eulerAngleOrder) { switch (eulerAngleOrder) { case EulerAngleOrder::XYZ: return EulerAngleOrder::ZYX; case EulerAngleOrder::XZY: return EulerAngleOrder::YZX; case EulerAngleOrder::YXZ: return EulerAngleOrder::ZXY; case EulerAngleOrder::YZX: return EulerAngleOrder::XZY; case EulerAngleOrder::ZXY: return EulerAngleOrder::YXZ; case EulerAngleOrder::ZYX: return EulerAngleOrder::XYZ; } return EulerAngleOrder::XYZ; } DecomposedEuler decomposeEuler(const glm::dmat4& matrix, EulerAngleOrder eulerAngleOrder) { glm::dvec3 scale; glm::dquat rotation; glm::dvec3 translation; glm::dvec3 skew; glm::dvec4 perspective; [[maybe_unused]] const auto decomposable = glm::decompose(matrix, scale, rotation, translation, skew, perspective); assert(decomposable); const auto rotationMatrix = glm::mat4_cast(rotation); glm::dvec3 rotationEuler(0.0); switch (eulerAngleOrder) { case EulerAngleOrder::XYZ: glm::extractEulerAngleXYZ(rotationMatrix, rotationEuler.x, rotationEuler.y, rotationEuler.z); break; case EulerAngleOrder::XZY: glm::extractEulerAngleXZY(rotationMatrix, rotationEuler.x, rotationEuler.z, rotationEuler.y); break; case EulerAngleOrder::YXZ: glm::extractEulerAngleYXZ(rotationMatrix, rotationEuler.y, rotationEuler.x, rotationEuler.z); break; case EulerAngleOrder::YZX: glm::extractEulerAngleYZX(rotationMatrix, rotationEuler.y, rotationEuler.z, rotationEuler.x); break; case EulerAngleOrder::ZXY: glm::extractEulerAngleZXY(rotationMatrix, rotationEuler.z, rotationEuler.x, rotationEuler.y); break; case EulerAngleOrder::ZYX: glm::extractEulerAngleZYX(rotationMatrix, rotationEuler.z, rotationEuler.y, rotationEuler.x); break; } return {translation, rotationEuler, scale}; } Decomposed decompose(const glm::dmat4& matrix) { glm::dvec3 scale; glm::dquat rotation; glm::dvec3 translation; glm::dvec3 skew; glm::dvec4 perspective; [[maybe_unused]] const auto decomposable = glm::decompose(matrix, scale, rotation, translation, skew, perspective); assert(decomposable); return {translation, rotation, scale}; } glm::dmat4 composeEuler( const glm::dvec3& translation, const glm::dvec3& rotation, const glm::dvec3& scale, EulerAngleOrder eulerAngleOrder) { const auto translationMatrix = glm::translate(glm::dmat4(1.0), translation); const auto scaleMatrix = glm::scale(glm::dmat4(1.0), scale); auto rotationMatrix = glm::dmat4(1.0); switch (eulerAngleOrder) { case EulerAngleOrder::XYZ: rotationMatrix = glm::eulerAngleXYZ(rotation.x, rotation.y, rotation.z); break; case EulerAngleOrder::XZY: rotationMatrix = glm::eulerAngleXZY(rotation.x, rotation.z, rotation.y); break; case EulerAngleOrder::YXZ: rotationMatrix = glm::eulerAngleYXZ(rotation.y, rotation.x, rotation.z); break; case EulerAngleOrder::YZX: rotationMatrix = glm::eulerAngleYZX(rotation.y, rotation.z, rotation.x); break; case EulerAngleOrder::ZXY: rotationMatrix = glm::eulerAngleZXY(rotation.z, rotation.x, rotation.y); break; case EulerAngleOrder::ZYX: rotationMatrix = glm::eulerAngleZYX(rotation.z, rotation.y, rotation.x); break; } return translationMatrix * rotationMatrix * scaleMatrix; } glm::dmat4 compose(const glm::dvec3& translation, const glm::dquat& rotation, const glm::dvec3& scale) { const auto translationMatrix = glm::translate(glm::dmat4(1.0), translation); const auto rotationMatrix = glm::mat4_cast(rotation); const auto scaleMatrix = glm::scale(glm::dmat4(1.0), scale); return translationMatrix * rotationMatrix * scaleMatrix; } bool equal(const CesiumGeospatial::Cartographic& a, const CesiumGeospatial::Cartographic& b) { const auto& aVec = *reinterpret_cast<const glm::dvec3*>(&a); const auto& bVec = *reinterpret_cast<const glm::dvec3*>(&b); return aVec == bVec; } bool epsilonEqual(const CesiumGeospatial::Cartographic& a, const CesiumGeospatial::Cartographic& b, double epsilon) { const auto& aVec = *reinterpret_cast<const glm::dvec3*>(&a); const auto& bVec = *reinterpret_cast<const glm::dvec3*>(&b); return glm::all(glm::epsilonEqual(aVec, bVec, epsilon)); } bool epsilonEqual(const glm::dmat4& a, const glm::dmat4& b, double epsilon) { return glm::all(glm::epsilonEqual(a[0], b[0], epsilon)) && glm::all(glm::epsilonEqual(a[1], b[1], epsilon)) && glm::all(glm::epsilonEqual(a[2], b[2], epsilon)) && glm::all(glm::epsilonEqual(a[3], b[3], epsilon)); } bool epsilonEqual(const glm::dvec3& a, const glm::dvec3& b, double epsilon) { return glm::all(glm::epsilonEqual(a, b, epsilon)); } bool epsilonEqual(const glm::dquat& a, const glm::dquat& b, double epsilon) { return glm::all(glm::epsilonEqual(a, b, epsilon)); } glm::dvec3 getCorner(const std::array<glm::dvec3, 2>& extent, uint64_t index) { return { (index & 1) ? extent[1].x : extent[0].x, (index & 2) ? extent[1].y : extent[0].y, (index & 4) ? extent[1].z : extent[0].z, }; } std::array<glm::dvec3, 2> transformExtent(const std::array<glm::dvec3, 2>& extent, const glm::dmat4& transform) { const auto min = std::numeric_limits<double>::lowest(); const auto max = std::numeric_limits<double>::max(); glm::dvec3 transformedMin(max); glm::dvec3 transformedMax(min); for (uint64_t i = 0; i < 8; ++i) { const auto position = MathUtil::getCorner(extent, i); const auto transformedPosition = glm::dvec3(transform * glm::dvec4(position, 1.0)); transformedMin = glm::min(transformedMin, transformedPosition); transformedMax = glm::max(transformedMax, transformedPosition); } return {{transformedMin, transformedMax}}; } } // namespace cesium::omniverse::MathUtil
6,440
C++
36.666666
119
0.664286
CesiumGS/cesium-omniverse/src/core/include/cesium/omniverse/OmniTileMapServiceRasterOverlay.h
#pragma once #include "cesium/omniverse/OmniRasterOverlay.h" #include <CesiumRasterOverlays/TileMapServiceRasterOverlay.h> #include <CesiumUtility/IntrusivePointer.h> #include <string> namespace cesium::omniverse { class OmniTileMapServiceRasterOverlay final : public OmniRasterOverlay { public: OmniTileMapServiceRasterOverlay(Context* pContext, const pxr::SdfPath& path); ~OmniTileMapServiceRasterOverlay() override = default; OmniTileMapServiceRasterOverlay(const OmniTileMapServiceRasterOverlay&) = delete; OmniTileMapServiceRasterOverlay& operator=(const OmniTileMapServiceRasterOverlay&) = delete; OmniTileMapServiceRasterOverlay(OmniTileMapServiceRasterOverlay&&) noexcept = default; OmniTileMapServiceRasterOverlay& operator=(OmniTileMapServiceRasterOverlay&&) noexcept = default; [[nodiscard]] CesiumRasterOverlays::RasterOverlay* getRasterOverlay() const override; [[nodiscard]] std::string getUrl() const; [[nodiscard]] int getMinimumZoomLevel() const; [[nodiscard]] int getMaximumZoomLevel() const; [[nodiscard]] bool getSpecifyZoomLevels() const; void reload() override; private: CesiumUtility::IntrusivePointer<CesiumRasterOverlays::TileMapServiceRasterOverlay> _pTileMapServiceRasterOverlay; }; } // namespace cesium::omniverse
1,306
C
39.843749
117
0.795559
CesiumGS/cesium-omniverse/src/core/include/cesium/omniverse/AssetTroubleshootingDetails.h
#pragma once #include <cstdint> namespace cesium::omniverse { struct AssetTroubleshootingDetails { int64_t assetId; bool assetExistsInUserAccount{false}; }; } // namespace cesium::omniverse
202
C
14.615383
41
0.747525
CesiumGS/cesium-omniverse/src/core/include/cesium/omniverse/TokenTroubleshootingDetails.h
#pragma once #include <CesiumIonClient/Token.h> namespace cesium::omniverse { struct TokenTroubleshootingDetails { CesiumIonClient::Token token; bool isValid{false}; bool allowsAccessToAsset{false}; bool associatedWithUserAccount{false}; bool showDetails{false}; }; } // namespace cesium::omniverse
323
C
19.249999
42
0.749226
CesiumGS/cesium-omniverse/src/core/include/cesium/omniverse/UsdNotificationHandler.h
#pragma once #include <pxr/usd/usd/notice.h> namespace cesium::omniverse { class Context; class UsdNotificationHandler final : public pxr::TfWeakBase { public: UsdNotificationHandler(Context* pContext); ~UsdNotificationHandler(); UsdNotificationHandler(const UsdNotificationHandler&) = delete; UsdNotificationHandler& operator=(const UsdNotificationHandler&) = delete; UsdNotificationHandler(UsdNotificationHandler&&) noexcept = delete; UsdNotificationHandler& operator=(UsdNotificationHandler&&) noexcept = delete; void onStageLoaded(); void onUpdateFrame(); void clear(); private: enum class ChangedPrimType { CESIUM_DATA, CESIUM_TILESET, CESIUM_ION_RASTER_OVERLAY, CESIUM_POLYGON_RASTER_OVERLAY, CESIUM_WEB_MAP_SERVICE_RASTER_OVERLAY, CESIUM_TILE_MAP_SERVICE_RASTER_OVERLAY, CESIUM_WEB_MAP_TILE_SERVICE_RASTER_OVERLAY, CESIUM_GEOREFERENCE, CESIUM_GLOBE_ANCHOR, CESIUM_ION_SERVER, CESIUM_CARTOGRAPHIC_POLYGON, USD_SHADER, OTHER, }; enum class ChangedType { PROPERTY_CHANGED, PRIM_ADDED, PRIM_REMOVED, }; struct ChangedPrim { pxr::SdfPath primPath; std::vector<pxr::TfToken> properties; ChangedPrimType primType; ChangedType changedType; }; bool processChangedPrims(); [[nodiscard]] bool processChangedPrim(const ChangedPrim& changedPrim) const; bool alreadyRegistered(const pxr::SdfPath& path); void onObjectsChanged(const pxr::UsdNotice::ObjectsChanged& objectsChanged); void onPrimAdded(const pxr::SdfPath& path); void onPrimRemoved(const pxr::SdfPath& path); void onPropertyChanged(const pxr::SdfPath& path); void insertAddedPrim(const pxr::SdfPath& primPath, ChangedPrimType primType); void insertRemovedPrim(const pxr::SdfPath& primPath, ChangedPrimType primType); void insertPropertyChanged(const pxr::SdfPath& primPath, ChangedPrimType primType, const pxr::TfToken& propertyName); ChangedPrimType getTypeFromStage(const pxr::SdfPath& path) const; ChangedPrimType getTypeFromAssetRegistry(const pxr::SdfPath& path) const; Context* _pContext; pxr::TfNotice::Key _noticeListenerKey; std::vector<ChangedPrim> _changedPrims; }; } // namespace cesium::omniverse
2,368
C
30.171052
116
0.708193
CesiumGS/cesium-omniverse/src/core/include/cesium/omniverse/Context.h
#pragma once #include <pxr/usd/usd/common.h> #include <filesystem> #include <memory> #include <vector> #include <gsl/span> namespace omni::fabric { class StageReaderWriter; } namespace CesiumUtility { class CreditSystem; } namespace CesiumAsync { class AsyncSystem; class IAssetAccessor; class ICacheDatabase; } // namespace CesiumAsync namespace cesium::omniverse { class AssetRegistry; class CesiumIonServerManager; class FabricResourceManager; class Logger; class TaskProcessor; class UsdNotificationHandler; struct RenderStatistics; struct Viewport; class Context { public: Context(const std::filesystem::path& cesiumExtensionLocation); ~Context(); Context(const Context&) = delete; Context& operator=(const Context&) = delete; Context(Context&&) noexcept = delete; Context& operator=(Context&&) noexcept = delete; [[nodiscard]] const std::filesystem::path& getCesiumExtensionLocation() const; [[nodiscard]] const std::filesystem::path& getCertificatePath() const; [[nodiscard]] const pxr::TfToken& getCesiumMdlPathToken() const; [[nodiscard]] std::shared_ptr<TaskProcessor> getTaskProcessor() const; [[nodiscard]] const CesiumAsync::AsyncSystem& getAsyncSystem() const; [[nodiscard]] std::shared_ptr<CesiumAsync::IAssetAccessor> getAssetAccessor() const; [[nodiscard]] std::shared_ptr<CesiumUtility::CreditSystem> getCreditSystem() const; [[nodiscard]] std::shared_ptr<Logger> getLogger() const; [[nodiscard]] const AssetRegistry& getAssetRegistry() const; [[nodiscard]] AssetRegistry& getAssetRegistry(); [[nodiscard]] const FabricResourceManager& getFabricResourceManager() const; [[nodiscard]] FabricResourceManager& getFabricResourceManager(); [[nodiscard]] const CesiumIonServerManager& getCesiumIonServerManager() const; [[nodiscard]] CesiumIonServerManager& getCesiumIonServerManager(); void clearStage(); void reloadStage(); void clearAccessorCache(); void onUpdateFrame(const gsl::span<const Viewport>& viewports, bool waitForLoadingTiles); void onUsdStageChanged(int64_t stageId); [[nodiscard]] const pxr::UsdStageWeakPtr& getUsdStage() const; [[nodiscard]] pxr::UsdStageWeakPtr& getUsdStage(); [[nodiscard]] int64_t getUsdStageId() const; [[nodiscard]] bool hasUsdStage() const; [[nodiscard]] omni::fabric::StageReaderWriter& getFabricStage() const; [[nodiscard]] RenderStatistics getRenderStatistics() const; [[nodiscard]] int64_t getContextId() const; private: std::filesystem::path _cesiumExtensionLocation; std::filesystem::path _certificatePath; pxr::TfToken _cesiumMdlPathToken; std::shared_ptr<TaskProcessor> _pTaskProcessor; std::unique_ptr<CesiumAsync::AsyncSystem> _pAsyncSystem; std::shared_ptr<Logger> _pLogger; std::shared_ptr<CesiumAsync::IAssetAccessor> _pAssetAccessor; std::shared_ptr<CesiumAsync::ICacheDatabase> _pCacheDatabase; std::shared_ptr<CesiumUtility::CreditSystem> _pCreditSystem; std::unique_ptr<AssetRegistry> _pAssetRegistry; std::unique_ptr<FabricResourceManager> _pFabricResourceManager; std::unique_ptr<CesiumIonServerManager> _pCesiumIonServerManager; std::unique_ptr<UsdNotificationHandler> _pUsdNotificationHandler; int64_t _contextId; pxr::UsdStageWeakPtr _pUsdStage; std::unique_ptr<omni::fabric::StageReaderWriter> _pFabricStage; int64_t _usdStageId{0}; }; } // namespace cesium::omniverse
3,467
C
33
93
0.744159
CesiumGS/cesium-omniverse/src/core/include/cesium/omniverse/UsdScopedEdit.h
#include <pxr/usd/usd/stage.h> namespace cesium::omniverse { class UsdScopedEdit { public: UsdScopedEdit(const pxr::UsdStageWeakPtr& pStage); ~UsdScopedEdit(); UsdScopedEdit(const UsdScopedEdit&) = delete; UsdScopedEdit& operator=(const UsdScopedEdit&) = delete; UsdScopedEdit(UsdScopedEdit&&) noexcept = delete; UsdScopedEdit& operator=(UsdScopedEdit&&) noexcept = delete; private: pxr::UsdStageWeakPtr _pStage; pxr::SdfLayerHandle _sessionLayer; bool _sessionLayerWasEditable; pxr::UsdEditTarget _originalEditTarget; }; } // namespace cesium::omniverse
603
C
26.454544
64
0.729685
CesiumGS/cesium-omniverse/src/core/include/cesium/omniverse/FabricFeaturesUtil.h
#pragma once #include <cstdint> #include <vector> namespace cesium::omniverse { struct FabricFeatureId; struct FabricFeaturesInfo; enum class FabricFeatureIdType; } // namespace cesium::omniverse namespace cesium::omniverse::FabricFeaturesUtil { FabricFeatureIdType getFeatureIdType(const FabricFeatureId& featureId); std::vector<FabricFeatureIdType> getFeatureIdTypes(const FabricFeaturesInfo& featuresInfo); std::vector<uint64_t> getSetIndexMapping(const FabricFeaturesInfo& featuresInfo, FabricFeatureIdType type); bool hasFeatureIdType(const FabricFeaturesInfo& featuresInfo, FabricFeatureIdType type); } // namespace cesium::omniverse::FabricFeaturesUtil
665
C
32.299998
107
0.83609
CesiumGS/cesium-omniverse/src/core/include/cesium/omniverse/FabricVertexAttributeDescriptor.h
#pragma once #include "cesium/omniverse/DataType.h" #include <omni/fabric/IToken.h> namespace cesium::omniverse { struct FabricVertexAttributeDescriptor { DataType type; omni::fabric::Token fabricAttributeName; std::string gltfAttributeName; // Make sure to update this function when adding new fields to the struct // In C++ 20 we can use the default equality comparison (= default) // clang-format off bool operator==(const FabricVertexAttributeDescriptor& other) const { return type == other.type && fabricAttributeName == other.fabricAttributeName && gltfAttributeName == other.gltfAttributeName; } // clang-format on // This is needed for std::set to be sorted bool operator<(const FabricVertexAttributeDescriptor& other) const { return fabricAttributeName < other.fabricAttributeName; } }; } // namespace cesium::omniverse
930
C
29.032257
77
0.701075
CesiumGS/cesium-omniverse/src/core/include/cesium/omniverse/FabricMaterialPool.h
#pragma once #include "cesium/omniverse/FabricMaterial.h" #include "cesium/omniverse/FabricMaterialDescriptor.h" #include "cesium/omniverse/ObjectPool.h" #include <pxr/usd/usd/common.h> namespace cesium::omniverse { class FabricMaterialPool final : public ObjectPool<FabricMaterial> { public: FabricMaterialPool( Context* pContext, int64_t poolId, const FabricMaterialDescriptor& materialDescriptor, uint64_t initialCapacity, const pxr::TfToken& defaultWhiteTextureAssetPathToken, const pxr::TfToken& defaultTransparentTextureAssetPathToken, bool debugRandomColors); ~FabricMaterialPool() override = default; FabricMaterialPool(const FabricMaterialPool&) = delete; FabricMaterialPool& operator=(const FabricMaterialPool&) = delete; FabricMaterialPool(FabricMaterialPool&&) noexcept = default; FabricMaterialPool& operator=(FabricMaterialPool&&) noexcept = default; [[nodiscard]] const FabricMaterialDescriptor& getMaterialDescriptor() const; [[nodiscard]] int64_t getPoolId() const; void updateShaderInput(const pxr::SdfPath& shaderPath, const pxr::TfToken& attributeName); protected: std::shared_ptr<FabricMaterial> createObject(uint64_t objectId) const override; void setActive(FabricMaterial* pMaterial, bool active) const override; private: Context* _pContext; int64_t _poolId; FabricMaterialDescriptor _materialDescriptor; pxr::TfToken _defaultWhiteTextureAssetPathToken; pxr::TfToken _defaultTransparentTextureAssetPathToken; bool _debugRandomColors; }; } // namespace cesium::omniverse
1,632
C
34.499999
94
0.756127
CesiumGS/cesium-omniverse/src/core/include/cesium/omniverse/FabricGeometry.h
#pragma once #include "cesium/omniverse/FabricGeometryDescriptor.h" #include <glm/fwd.hpp> #include <omni/fabric/IPath.h> namespace CesiumGltf { struct MeshPrimitive; struct Model; } // namespace CesiumGltf namespace cesium::omniverse { class Context; struct FabricMaterialInfo; class FabricGeometry { public: FabricGeometry( Context* pContext, const omni::fabric::Path& path, const FabricGeometryDescriptor& geometryDescriptor, int64_t poolId); ~FabricGeometry(); FabricGeometry(const FabricGeometry&) = delete; FabricGeometry& operator=(const FabricGeometry&) = delete; FabricGeometry(FabricGeometry&&) noexcept = default; FabricGeometry& operator=(FabricGeometry&&) noexcept = default; void setGeometry( int64_t tilesetId, const glm::dmat4& ecefToPrimWorldTransform, const glm::dmat4& gltfLocalToEcefTransform, const CesiumGltf::Model& model, const CesiumGltf::MeshPrimitive& primitive, const FabricMaterialInfo& materialInfo, bool smoothNormals, const std::unordered_map<uint64_t, uint64_t>& texcoordIndexMapping, const std::unordered_map<uint64_t, uint64_t>& rasterOverlayTexcoordIndexMapping); void setActive(bool active); void setVisibility(bool visible); [[nodiscard]] const omni::fabric::Path& getPath() const; [[nodiscard]] const FabricGeometryDescriptor& getGeometryDescriptor() const; [[nodiscard]] int64_t getPoolId() const; void setMaterial(const omni::fabric::Path& materialPath); private: void initialize(); void reset(); bool stageDestroyed(); Context* _pContext; omni::fabric::Path _path; FabricGeometryDescriptor _geometryDescriptor; int64_t _poolId; int64_t _stageId; }; } // namespace cesium::omniverse
1,829
C
27.59375
89
0.708037
CesiumGS/cesium-omniverse/src/core/include/cesium/omniverse/FabricMaterial.h
#pragma once #include "cesium/omniverse/FabricMaterialDescriptor.h" #include "cesium/omniverse/FabricMaterialInfo.h" #include <glm/glm.hpp> #include <omni/fabric/IPath.h> #include <unordered_map> namespace omni::fabric { struct Type; } namespace omni::ui { class DynamicTextureProvider; } namespace cesium::omniverse { class FabricTexture; enum class MdlInternalPropertyType; struct FabricPropertyDescriptor; struct FabricTextureInfo; class FabricMaterial { public: FabricMaterial( Context* pContext, const omni::fabric::Path& path, const FabricMaterialDescriptor& materialDescriptor, const pxr::TfToken& defaultWhiteTextureAssetPathToken, const pxr::TfToken& defaultTransparentTextureAssetPathToken, bool debugRandomColors, int64_t poolId); ~FabricMaterial(); FabricMaterial(const FabricMaterial&) = delete; FabricMaterial& operator=(const FabricMaterial&) = delete; FabricMaterial(FabricMaterial&&) noexcept = default; FabricMaterial& operator=(FabricMaterial&&) noexcept = default; void setMaterial( const CesiumGltf::Model& model, const CesiumGltf::MeshPrimitive& primitive, int64_t tilesetId, const FabricMaterialInfo& materialInfo, const FabricFeaturesInfo& featuresInfo, FabricTexture* pBaseColorTexture, const std::vector<std::shared_ptr<FabricTexture>>& featureIdTextures, const std::vector<std::shared_ptr<FabricTexture>>& propertyTextures, const std::vector<std::shared_ptr<FabricTexture>>& propertyTableTextures, const glm::dvec3& displayColor, double displayOpacity, const std::unordered_map<uint64_t, uint64_t>& texcoordIndexMapping, const std::vector<uint64_t>& featureIdIndexSetIndexMapping, const std::vector<uint64_t>& featureIdAttributeSetIndexMapping, const std::vector<uint64_t>& featureIdTextureSetIndexMapping, const std::unordered_map<uint64_t, uint64_t>& propertyTextureIndexMapping); void setRasterOverlay( FabricTexture* pTexture, const FabricTextureInfo& textureInfo, uint64_t rasterOverlayIndex, double alpha, const std::unordered_map<uint64_t, uint64_t>& rasterOverlayTexcoordIndexMapping); void setRasterOverlayAlpha(uint64_t rasterOverlayIndex, double alpha); void setDisplayColorAndOpacity(const glm::dvec3& displayColor, double displayOpacity); void updateShaderInput(const omni::fabric::Path& shaderPath, const omni::fabric::Token& attributeName); void clearRasterOverlay(uint64_t rasterOverlayIndex); void setActive(bool active); [[nodiscard]] const omni::fabric::Path& getPath() const; [[nodiscard]] const FabricMaterialDescriptor& getMaterialDescriptor() const; [[nodiscard]] int64_t getPoolId() const; private: void initializeNodes(); void initializeDefaultMaterial(); void initializeExistingMaterial(const omni::fabric::Path& path); void createMaterial(const omni::fabric::Path& path); void createShader(const omni::fabric::Path& path); void createTextureCommon( const omni::fabric::Path& path, const omni::fabric::Token& subIdentifier, const std::vector<std::pair<omni::fabric::Type, omni::fabric::Token>>& additionalAttributes = {}); void createTexture(const omni::fabric::Path& path); void createRasterOverlay(const omni::fabric::Path& path); void createRasterOverlayResolverCommon( const omni::fabric::Path& path, uint64_t textureCount, const omni::fabric::Token& subidentifier); void createRasterOverlayResolver(const omni::fabric::Path& path, uint64_t textureCount); void createClippingRasterOverlayResolver(const omni::fabric::Path& path, uint64_t textureCount); void createFeatureIdIndex(const omni::fabric::Path& path); void createFeatureIdAttribute(const omni::fabric::Path& path); void createFeatureIdTexture(const omni::fabric::Path& path); void createPropertyAttributePropertyInt( const omni::fabric::Path& path, const omni::fabric::Token& subidentifier, const omni::fabric::Type& noDataType, const omni::fabric::Type& defaultValueType); void createPropertyAttributePropertyNormalizedInt( const omni::fabric::Path& path, const omni::fabric::Token& subidentifier, const omni::fabric::Type& noDataType, const omni::fabric::Type& defaultValueType, const omni::fabric::Type& offsetType, const omni::fabric::Type& scaleType, const omni::fabric::Type& maximumValueType); void createPropertyAttributePropertyFloat( const omni::fabric::Path& path, const omni::fabric::Token& subidentifier, const omni::fabric::Type& noDataType, const omni::fabric::Type& defaultValueType, const omni::fabric::Type& offsetType, const omni::fabric::Type& scaleType); void createPropertyAttributeProperty(const omni::fabric::Path& path, MdlInternalPropertyType type); void createPropertyTexturePropertyInt( const omni::fabric::Path& path, const omni::fabric::Token& subidentifier, const omni::fabric::Type& noDataType, const omni::fabric::Type& defaultValueType); void createPropertyTexturePropertyNormalizedInt( const omni::fabric::Path& path, const omni::fabric::Token& subidentifier, const omni::fabric::Type& noDataType, const omni::fabric::Type& defaultValueType, const omni::fabric::Type& offsetType, const omni::fabric::Type& scaleType, const omni::fabric::Type& maximumValueType); void createPropertyTextureProperty(const omni::fabric::Path& path, MdlInternalPropertyType type); void createPropertyTablePropertyInt( const omni::fabric::Path& path, const omni::fabric::Token& subidentifier, const omni::fabric::Type& noDataType, const omni::fabric::Type& defaultValueType); void createPropertyTablePropertyNormalizedInt( const omni::fabric::Path& path, const omni::fabric::Token& subidentifier, const omni::fabric::Type& noDataType, const omni::fabric::Type& defaultValueType, const omni::fabric::Type& offsetType, const omni::fabric::Type& scaleType, const omni::fabric::Type& maximumValueType); void createPropertyTablePropertyFloat( const omni::fabric::Path& path, const omni::fabric::Token& subidentifier, const omni::fabric::Type& noDataType, const omni::fabric::Type& defaultValueType, const omni::fabric::Type& offsetType, const omni::fabric::Type& scaleType); void createPropertyTableProperty(const omni::fabric::Path& path, MdlInternalPropertyType type); void reset(); void setShaderValues( const omni::fabric::Path& path, const FabricMaterialInfo& materialInfo, const glm::dvec3& displayColor, double displayOpacity); void setTextureValues( const omni::fabric::Path& path, const pxr::TfToken& textureAssetPathToken, const FabricTextureInfo& textureInfo, uint64_t texcoordIndex); void setRasterOverlayValues( const omni::fabric::Path& path, const pxr::TfToken& textureAssetPathToken, const FabricTextureInfo& textureInfo, uint64_t texcoordIndex, double alpha); void setRasterOverlayAlphaValue(const omni::fabric::Path& path, double alpha); void setFeatureIdIndexValues(const omni::fabric::Path& path, int nullFeatureId); void setFeatureIdAttributeValues(const omni::fabric::Path& path, const std::string& primvarName, int nullFeatureId); void setFeatureIdTextureValues( const omni::fabric::Path& path, const pxr::TfToken& textureAssetPathToken, const FabricTextureInfo& textureInfo, uint64_t texcoordIndex, int nullFeatureId); void createConnectionsToCopiedPaths(); void destroyConnectionsToCopiedPaths(); void createConnectionsToProperties(); void destroyConnectionsToProperties(); bool stageDestroyed(); Context* _pContext; omni::fabric::Path _materialPath; FabricMaterialDescriptor _materialDescriptor; pxr::TfToken _defaultWhiteTextureAssetPathToken; pxr::TfToken _defaultTransparentTextureAssetPathToken; bool _debugRandomColors; int64_t _poolId; int64_t _stageId; bool _usesDefaultMaterial; FabricAlphaMode _alphaMode{FabricAlphaMode::OPAQUE}; glm::dvec3 _debugColor{1.0, 1.0, 1.0}; omni::fabric::Path _shaderPath; omni::fabric::Path _baseColorTexturePath; std::vector<omni::fabric::Path> _rasterOverlayPaths; omni::fabric::Path _overlayRasterOverlayResolverPath; omni::fabric::Path _clippingRasterOverlayResolverPath; std::vector<omni::fabric::Path> _featureIdPaths; std::vector<omni::fabric::Path> _featureIdIndexPaths; std::vector<omni::fabric::Path> _featureIdAttributePaths; std::vector<omni::fabric::Path> _featureIdTexturePaths; std::vector<omni::fabric::Path> _propertyPaths; std::unordered_map<MdlInternalPropertyType, std::vector<omni::fabric::Path>> _propertyAttributePropertyPaths; std::unordered_map<MdlInternalPropertyType, std::vector<omni::fabric::Path>> _propertyTexturePropertyPaths; std::unordered_map<MdlInternalPropertyType, std::vector<omni::fabric::Path>> _propertyTablePropertyPaths; std::vector<omni::fabric::Path> _copiedBaseColorTexturePaths; std::vector<omni::fabric::Path> _copiedRasterOverlayPaths; std::vector<omni::fabric::Path> _copiedFeatureIdPaths; std::vector<omni::fabric::Path> _copiedPropertyPaths; std::vector<omni::fabric::Path> _allPaths; }; } // namespace cesium::omniverse
9,803
C
41.626087
120
0.714373