file_path
stringlengths 21
202
| content
stringlengths 19
1.02M
| size
int64 19
1.02M
| lang
stringclasses 8
values | avg_line_length
float64 5.88
100
| max_line_length
int64 12
993
| alphanum_fraction
float64 0.27
0.93
|
---|---|---|---|---|---|---|
NVIDIA-Omniverse/IsaacSim-ros_workspaces/noetic_ws/src/isaac_vins/config/isaac_a1/isaac_left.yaml | %YAML:1.0
---
model_type: PINHOLE
camera_name: camera
image_width: 640
image_height: 480
distortion_parameters:
k1: 0.0
k2: 0.0
p1: 0.0
p2: 0.0
projection_parameters:
fx: 732.999267578125
fy: 732.9993286132812
cx: 320
cy: 240
| 250 | YAML | 13.764705 | 24 | 0.664 |
NVIDIA-Omniverse/IsaacSim-ros_workspaces/noetic_ws/src/navigation/carter_2dnav/params/base_local_planner_params.yaml | TrajectoryPlannerROS:
holonomic_robot: false
max_vel_x: 1.2
min_vel_x: 0.1
max_vel_y: 0.0
min_vel_y: 0.0
max_vel_theta: 0.8
min_vel_theta: -0.8
min_in_place_vel_theta: 0.3
acc_lim_theta: 3.2
acc_lim_x: 2.5
acc_lim_y: 0.0
xy_goal_tolerance: 0.25
yaw_goal_tolerance: 0.05
occdist_scale: 0.7
escape_vel: -0.1
meter_scoring: true
path_distance_bias: 0.8
| 386 | YAML | 19.36842 | 29 | 0.642487 |
NVIDIA-Omniverse/IsaacSim-ros_workspaces/noetic_ws/src/navigation/carter_2dnav/params/costmap_common_params.yaml | obstacle_range: 25
raytrace_range: 3
robot_radius: 0.36
cost_scaling_factor: 3.0
observation_sources: laser_scan_sensor
laser_scan_sensor: {sensor_frame: carter_lidar, data_type: LaserScan, topic: scan, marking: true, clearing: true}
| 234 | YAML | 32.571424 | 113 | 0.773504 |
NVIDIA-Omniverse/IsaacSim-ros_workspaces/noetic_ws/src/navigation/carter_2dnav/params/global_costmap_params.yaml | global_costmap:
global_frame: map
robot_base_frame: base_link
update_frequency: 1.0
publish_frequency: 0.5
static_map: true
transform_tolerance: 1.25
inflation_radius: 0.85
| 187 | YAML | 19.888887 | 29 | 0.727273 |
NVIDIA-Omniverse/IsaacSim-ros_workspaces/noetic_ws/src/navigation/carter_2dnav/params/local_costmap_params.yaml | local_costmap:
global_frame: odom
robot_base_frame: base_link
update_frequency: 5.0
publish_frequency: 2.0
static_map: false
rolling_window: true
width: 7.0
height: 7.0
resolution: 0.1
transform_tolerance: 1.25
inflation_radius: 0.32
| 257 | YAML | 17.42857 | 29 | 0.70428 |
NVIDIA-Omniverse/IsaacSim-ros_workspaces/noetic_ws/src/navigation/isaac_ros_navigation_goal/setup.py | from setuptools import setup
from catkin_pkg.python_setup import generate_distutils_setup
d = generate_distutils_setup(
packages=["goal_generators", "obstacle_map"], package_dir={"": "isaac_ros_navigation_goal"}
)
setup(**d)
| 230 | Python | 27.874997 | 95 | 0.743478 |
NVIDIA-Omniverse/IsaacSim-ros_workspaces/noetic_ws/src/navigation/isaac_ros_navigation_goal/isaac_ros_navigation_goal/set_goal.py | #!/usr/bin/env python
from __future__ import absolute_import
import rospy
import actionlib
import sys
from move_base_msgs.msg import MoveBaseAction, MoveBaseGoal
from obstacle_map import GridMap
from goal_generators import RandomGoalGenerator, GoalReader
from geometry_msgs.msg import PoseWithCovarianceStamped
class SetNavigationGoal:
def __init__(self):
self.__goal_generator = self.__create_goal_generator()
action_server_name = rospy.get_param("action_server_name", "move_base")
self._action_client = actionlib.SimpleActionClient(action_server_name, MoveBaseAction)
self.MAX_ITERATION_COUNT = rospy.get_param("iteration_count", 1)
assert self.MAX_ITERATION_COUNT > 0
self.curr_iteration_count = 1
self.__initial_goal_publisher = rospy.Publisher("initialpose", PoseWithCovarianceStamped, queue_size=1)
self.__initial_pose = rospy.get_param("initial_pose", None)
self.__is_initial_pose_sent = True if self.__initial_pose is None else False
def __send_initial_pose(self):
"""
Publishes the initial pose.
This function is only called once that too before sending any goal pose
to the mission server.
"""
goal = PoseWithCovarianceStamped()
goal.header.frame_id = rospy.get_param("frame_id", "map")
goal.header.stamp = rospy.get_rostime()
goal.pose.pose.position.x = self.__initial_pose[0]
goal.pose.pose.position.y = self.__initial_pose[1]
goal.pose.pose.position.z = self.__initial_pose[2]
goal.pose.pose.orientation.x = self.__initial_pose[3]
goal.pose.pose.orientation.y = self.__initial_pose[4]
goal.pose.pose.orientation.z = self.__initial_pose[5]
goal.pose.pose.orientation.w = self.__initial_pose[6]
rospy.sleep(1)
self.__initial_goal_publisher.publish(goal)
def send_goal(self):
"""
Sends the goal to the action server.
"""
if not self.__is_initial_pose_sent:
rospy.loginfo("Sending initial pose")
self.__send_initial_pose()
self.__is_initial_pose_sent = True
# Assumption is that initial pose is set after publishing first time in this duration.
# Can be changed to more sophisticated way. e.g. /particlecloud topic has no msg until
# the initial pose is set.
rospy.sleep(10)
rospy.loginfo("Sending first goal")
self._action_client.wait_for_server()
goal_msg = self.__get_goal()
if goal_msg is None:
rospy.signal_shutdown("Goal message not generated.")
sys.exit(1)
self._action_client.send_goal(goal_msg, feedback_cb=self.__goal_response_callback)
def __goal_response_callback(self, feedback):
"""
Callback function to check the response(goal accpted/rejected) from the server.\n
If the Goal is rejected it stops the execution for now.(We can change to resample the pose if rejected.)
"""
if self.verify_goal_state():
rospy.loginfo("Waiting to reach goal")
wait = self._action_client.wait_for_result()
if self.verify_goal_state():
self.__get_result_callback(True)
def verify_goal_state(self):
print("Action Client State:", self._action_client.get_state(), self._action_client.get_goal_status_text())
if self._action_client.get_state() not in [0, 1, 3]:
rospy.signal_shutdown("Goal Rejected :(")
return False
return True
def __get_goal(self):
goal_msg = MoveBaseGoal()
goal_msg.target_pose.header.frame_id = rospy.get_param("frame_id", "map")
goal_msg.target_pose.header.stamp = rospy.get_rostime()
pose = self.__goal_generator.generate_goal()
# couldn't sample a pose which is not close to obstacles. Rare but might happen in dense maps.
if pose is None:
rospy.logerr("Could not generate next goal. Returning. Possible reasons for this error could be:")
rospy.logerr(
"1. If you are using GoalReader then please make sure iteration count <= no of goals avaiable in file."
)
rospy.logerr(
"2. If RandomGoalGenerator is being used then it was not able to sample a pose which is given distance away from the obstacles."
)
return
rospy.loginfo("Generated goal pose: {0}".format(pose))
goal_msg.target_pose.pose.position.x = pose[0]
goal_msg.target_pose.pose.position.y = pose[1]
goal_msg.target_pose.pose.orientation.x = pose[2]
goal_msg.target_pose.pose.orientation.y = pose[3]
goal_msg.target_pose.pose.orientation.z = pose[4]
goal_msg.target_pose.pose.orientation.w = pose[5]
return goal_msg
def __get_result_callback(self, wait):
if wait and self.curr_iteration_count < self.MAX_ITERATION_COUNT:
self.curr_iteration_count += 1
self.send_goal()
else:
rospy.signal_shutdown("Iteration done or Goal not reached.")
# in this callback func we can compare/compute/log something while the robot is on its way to goal.
def __feedback_callback(self, feedback_msg):
pass
def __create_goal_generator(self):
goal_generator_type = rospy.get_param("goal_generator_type", "RandomGoalGenerator")
goal_generator = None
if goal_generator_type == "RandomGoalGenerator":
if rospy.get_param("map_yaml_path", None) is None:
rospy.loginfo("Yaml file path is not given. Returning..")
sys.exit(1)
yaml_file_path = rospy.get_param("map_yaml_path", None)
grid_map = GridMap(yaml_file_path)
obstacle_search_distance_in_meters = rospy.get_param("obstacle_search_distance_in_meters", 0.2)
assert obstacle_search_distance_in_meters > 0
goal_generator = RandomGoalGenerator(grid_map, obstacle_search_distance_in_meters)
elif goal_generator_type == "GoalReader":
if rospy.get_param("goal_text_file_path", None) is None:
rospy.loginfo("Goal text file path is not given. Returning..")
sys.exit(1)
file_path = rospy.get_param("goal_text_file_path", None)
goal_generator = GoalReader(file_path)
else:
rospy.loginfo("Invalid goal generator specified. Returning...")
sys.exit(1)
return goal_generator
def main():
rospy.init_node("set_goal_py")
set_goal = SetNavigationGoal()
result = set_goal.send_goal()
rospy.spin()
if __name__ == "__main__":
main()
| 6,772 | Python | 40.552147 | 144 | 0.627732 |
NVIDIA-Omniverse/RC-Car-CAD/Readme.md | # RC CAR CAD 1.0

This repository contains engineering data for a remote control car design. This data includes CAD, CAE, BOM and any other data used to design the vehicle. Each release in the repo represents a milestone in the design process.
Release 1.0 is the milestone where the car can be exported to NVIDIA omniverse and the vehicle suspension and steering can be rigged using physics joints.
The purpose of this data set is to give anyone working with NVIDIA omniverse production-quality CAD data to work with as they develop Omniverse applications, extensions, and/or microservices. This data may also be used for demonstrations, tutorials, engineering design process research, or however else it is needed.
The data is being released before it is complete intentionally so that it represents not just a finished product, but also an in-process product throughout its design. In this way the data can be used to facilitate in-process design workflows.
The assembly is modeled using NX. To open the full assembly "_Class1RC.prt". Subassemblies are in corresponding subfolders. Not all of the assemblies and parts are organized correctly, which is common at the early design phase of a product. As the design matures, older data will become better organized and newly introduced data will be disorganized, as is the way of these things. | 1,390 | Markdown | 98.357136 | 382 | 0.805036 |
NVIDIA-Omniverse/usd_scene_construction_utils/setup.py | # SPDX-FileCopyrightText: Copyright (c) 2023 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
# SPDX-License-Identifier: Apache-2.0
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from setuptools import setup, find_packages
setup(
name="usd_scene_construction_utils",
version="0.0.1",
description="",
py_modules=["usd_scene_construction_utils"]
) | 864 | Python | 35.041665 | 98 | 0.752315 |
NVIDIA-Omniverse/usd_scene_construction_utils/DCO.md | Developer Certificate of Origin
Version 1.1
Copyright (C) 2004, 2006 The Linux Foundation and its contributors.
Everyone is permitted to copy and distribute verbatim copies of this
license document, but changing it is not allowed.
Developer's Certificate of Origin 1.1
By making a contribution to this project, I certify that:
(a) The contribution was created in whole or in part by me and I
have the right to submit it under the open source license
indicated in the file; or
(b) The contribution is based upon previous work that, to the best
of my knowledge, is covered under an appropriate open source
license and I have the right under that license to submit that
work with modifications, whether created in whole or in part
by me, under the same open source license (unless I am
permitted to submit under a different license), as indicated
in the file; or
(c) The contribution was provided directly to me by some other
person who certified (a), (b) or (c) and I have not modified
it.
(d) I understand and agree that this project and the contribution
are public and that a record of the contribution (including all
personal information I submit with it, including my sign-off) is
maintained indefinitely and may be redistributed consistent with
this project or the open source license(s) involved. | 1,365 | Markdown | 39.176469 | 68 | 0.76044 |
NVIDIA-Omniverse/usd_scene_construction_utils/README.md | # USD Scene Construction Utilities
USD Scene Construction Utilities is an open-source collection of utilities
built on top of the USD Python API that makes it easy for beginners to create
and modify USD scenes.
<img src="examples/hand_truck_w_boxes/landing_graphic.jpg" height="320"/>
If you find that USD Scene Construction Utilities is too limited for your use case, you may find still
find the open-source code a useful reference for working with the USD
Python API.
> Please note, USD Scene Construction Utilities **is not** a comprehensive USD Python API wrapper. That
> said, it may help you with your project, or you might find the open-source code helpful
> as a reference for learning USD. See the full [disclaimer](#disclaimer)
> below for more information. If run into any issues or have any questions please [let us know](../..//issues)!
## Usage
USD Scene Construction Utilities exposes a variety of utility functions that operating on the USD stage
like this:
```python
from usd_scene_construction_utils import (
new_in_memory_stage, add_plane, add_box, stack, export_stage
)
stage = new_in_memory_stage()
floor = add_plane(stage, "/scene/floor", size=(500, 500))
box = add_box(stage, "/scene/box", size=(100, 100, 100))
stack_prims([floor, box], axis=2)
export_stage(stage, "hello_box.usda", default_prim="/scene")
```
If you don't want to use the higher level functions, you can read the [usd_scene_construction_utils.py](usd_scene_construction_utils.py)
file to learn some ways to use the USD Python API directly.
After building a scene with USD Scene Construction Utilities, we recommend using Omniverse Replicator
for generating synthetic data, while performing additional randomizations that
retain the structure of the scene, like camera position, lighting, and materials.
To get started, you may find the [using replicator with a fully developed scene](https://docs.omniverse.nvidia.com/prod_extensions/prod_extensions/ext_replicator/apis_with_fully_developed_scene.html)
example helpful.
## Installation
### Step 1 - Clone the repo
```bash
git clone https://github.com/NVIDIA-Omniverse/usd_scene_construction_utils
```
### Step 2 - Make it discoverable
If you're outside of omniverse:
```bash
python3 setup.py develop
```
If you're inside omniverse:
```python3
import sys
sys.path.append("/path/to/usd_scene_construction_utils/")
```
## Examples
| Graphic | Example | Description | Omniverse Only |
|---|---|---|---|
| <img src="examples/hello_box/landing_graphic.jpg" width="128"/> | [hello_box](examples/hello_box/) | First example to run. Adds a grid of boxes. Doesn't use any assets. | |
| <img src="examples/bind_mdl_material/landing_graphic.jpg" width="128"/> | [bind_mdl_material](examples/bind_mdl_material/) | Shows how to bind a material to an object. Needs omniverse to access material assets on nucleus server. | :heavy_check_mark: |
| <img src="examples/hand_truck_w_boxes/landing_graphic.jpg" width="128"/>| [hand_truck_w_boxes](examples/hand_truck_w_boxes/) | Create a grid of hand trucks with randomly stacked boxes. Needs omniverse to access cardboard box and hand truck assets. | :heavy_check_mark: |
## Disclaimer
This project **is not** a comprehensive USD Python API wrapper. It currently only exposes
a very limited subset of what USD is capable of and is subject
to change and breaking. The goal of this project is to make it easy to generate
structured scenes using USD and to give you an introduction to USD through
both examples and by reading the usd_scene_construction_utils source code.
If you're developing a larger project using usd_scene_construction_utils as a dependency, you may
want to fork the project, or simply reference the source code you're interested in. We're providing this project because we think the community will
benefit from more open-source code and examples that uses USD.
That said, you may still find usd_scene_construction_utils helpful as-is, and you're welcome to let
us know if you run into any issues, have any questions, or would like to contribute.
## Contributing
- Ask a question, request a feature, file a bug by creating an [issue](#).
- Add new functionality, or fix a bug, by filing a [pull request](#).
## See also
Here are other USD resources we've found helpful.
1. [NVIDIA USD Snippets](https://docs.omniverse.nvidia.com/prod_usd/prod_kit/programmer_ref/usd.html) Super helpful collection of documented USD snippets for getting familiar with directly working with USD Python API.
2. [USD C++ API Docs](https://openusd.org/release/api/index.html). Helpful for learning the full set of USD API functions. Most functions share very similar naming to the Python counterpart.
3. [NVIDIA Omniverse Replicator](https://docs.omniverse.nvidia.com/prod_extensions/prod_extensions/ext_replicator.html) - Helpful for taking USD scenes and efficiently generating synthetic data, like segmentation masks, 3D bounding boxes, depth images and more. Also
includes a variety of utilities for domain randomization.
4. [NVIDIA Omniverse](https://www.nvidia.com/en-us/omniverse/) - Large ecosystem of
tools for creating 3D worlds. Omniverse create is needed for executing many of the
examples here. Assets on the Omniverse nucleus servers make it easy to create
high quality scenes with rich geometries and materials. | 5,356 | Markdown | 47.261261 | 274 | 0.762883 |
NVIDIA-Omniverse/usd_scene_construction_utils/usd_scene_construction_utils.py | # SPDX-FileCopyrightText: Copyright (c) 2023 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
# SPDX-License-Identifier: Apache-2.0
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import os
import numpy as np
import math
from typing import Optional, Sequence, Tuple
from typing_extensions import Literal
from pxr import Gf, Sdf, Usd, UsdGeom, UsdLux, UsdShade
def new_in_memory_stage() -> Usd.Stage:
"""Creates a new in memory USD stage.
Returns:
Usd.Stage: The USD stage.
"""
stage = Usd.Stage.CreateInMemory()
UsdGeom.SetStageUpAxis(stage, UsdGeom.Tokens.z)
return stage
def new_omniverse_stage() -> Usd.Stage:
"""Creates a new Omniverse USD stage.
This method creates a new Omniverse USD stage. This will clear the active
omniverse stage, replacing it with a new one.
Returns:
Usd.Stage: The Omniverse USD stage.
"""
try:
import omni.usd
except ImportError:
raise ImportError("Omniverse not found. This method is unavailable.")
omni.usd.get_context().new_stage()
stage = omni.usd.get_context().get_stage()
UsdGeom.SetStageUpAxis(stage, UsdGeom.Tokens.z)
return stage
def get_omniverse_stage() -> Usd.Stage:
"""Returns the current Omniverse USD stage.
Returns:
Usd.Stage: The currently active Omniverse USD stage.
"""
try:
import omni.usd
except ImportError:
raise ImportError("Omniverse not found. This method is unavailable.")
stage = omni.usd.get_context().get_stage()
return stage
def add_usd_ref(stage: Usd.Stage, path: str, usd_path: str) -> Usd.Prim:
"""Adds an external USD reference to a USD stage.
Args:
stage (:class:`Usd.Stage`): The USD stage to modify.
path (str): The path to add the USD reference.
usd_path (str): The filepath or URL of the USD reference (ie: a Nucleus
server URL).
Returns:
Usd.Prim: The created USD prim.
"""
stage.DefinePrim(path, "Xform")
prim_ref = stage.DefinePrim(os.path.join(path, "ref"))
prim_ref.GetReferences().AddReference(usd_path)
return get_prim(stage, path)
def _make_box_mesh(size: Tuple[float, float, float]):
# private utility function used by make_box
numFaces = 6
numVertexPerFace = 4
# Generate vertices on box
vertices = []
for i in [-1, 1]:
for j in [-1, 1]:
for k in [-1, 1]:
vertices.append((i * size[0], j * size[1], k * size[2]))
# Make faces for box (ccw convention)
faceVertexCounts = [numVertexPerFace] * numFaces
faceVertexIndices = [
2, 0, 1, 3,
4, 6, 7, 5,
0, 4, 5, 1,
6, 2, 3, 7,
0, 2, 6, 4,
5, 7, 3, 1,
]
# Make normals for face vertices
_faceVertexNormals = [
(-1, 0, 0),
(1, 0, 0),
(0, -1, 0),
(0, 1, 0),
(0, 0, -1),
(0, 0, 1),
]
faceVertexNormals = []
for n in _faceVertexNormals:
for i in range(numVertexPerFace):
faceVertexNormals.append(n)
# Assign uv-mapping for face vertices
_faceUvMaps = [
(0, 0), (1, 0), (1, 1), (0, 1)
]
faceUvMaps = []
for i in range(numFaces):
for uvm in _faceUvMaps:
faceUvMaps.append(uvm)
return (vertices, faceVertexCounts, faceVertexIndices, faceVertexNormals,
faceUvMaps)
def add_box(stage: Usd.Stage, path: str, size: Tuple[float, float, float]) -> Usd.Prim:
"""Adds a 3D box to a USD stage.
This adds a 3D box to the USD stage. The box is created with it's center
at (x, y, z) = (0, 0, 0).
Args:
stage (:class:`Usd.Stage`): The USD stage to modify.
path (str): The path to add the USD prim.
size (Tuple[float, float, float]): The size of the box (x, y, z sizes).
Returns:
Usd.Prim: The created USD prim.
"""
half_size = (size[0] / 2, size[1] / 2, size[2] / 2)
stage.DefinePrim(path, "Xform")
(vertices, faceVertexCounts, faceVertexIndices, faceVertexNormals,
faceUvMaps) = _make_box_mesh(half_size)
# create mesh at {path}/mesh, but return prim at {path}
prim: UsdGeom.Mesh = UsdGeom.Mesh.Define(stage, os.path.join(path, "mesh"))
prim.CreateExtentAttr().Set([
(-half_size[0], -half_size[1], -half_size[2]),
(half_size[0], half_size[1], half_size[2])
])
prim.CreateFaceVertexCountsAttr().Set(faceVertexCounts)
prim.CreateFaceVertexIndicesAttr().Set(faceVertexIndices)
var = UsdGeom.Primvar(prim.CreateNormalsAttr())
var.Set(faceVertexNormals)
var.SetInterpolation(UsdGeom.Tokens.faceVarying)
var = UsdGeom.PrimvarsAPI(prim).CreatePrimvar("primvars:st", Sdf.ValueTypeNames.Float2Array)
var.Set(faceUvMaps)
var.SetInterpolation(UsdGeom.Tokens.faceVarying)
prim.CreatePointsAttr().Set(vertices)
prim.CreateSubdivisionSchemeAttr().Set(UsdGeom.Tokens.none)
return get_prim(stage, path)
def add_xform(stage: Usd.Stage, path: str):
"""Adds a USD transform (Xform) to a USD stage.
This method adds a USD Xform to the USD stage at a given path. This is
helpful when you want to add hierarchy to a scene. After you create a
transform, any USD prims located under the transform path will be children
of the transform and can be moved as a group.
Args:
stage (:class:`Usd.Stage`): The USD stage to modify.
path (str): The path to add the USD prim.
Returns:
Usd.Prim: The created USD prim.
"""
stage.DefinePrim(path, "Xform")
return get_prim(stage, path)
def add_plane(
stage: Usd.Stage,
path: str,
size: Tuple[float, float],
uv: Tuple[float, float]=(1, 1)):
"""Adds a 2D plane to a USD stage.
Args:
stage (Usd.Stage): The USD stage to modify.
path (str): The path to add the USD prim.
size (Tuple[float, float]): The size of the 2D plane (x, y).
uv (Tuple[float, float]): The UV mapping for textures applied to the
plane. For example, uv=(1, 1), means the texture will be spread
to fit the full size of the plane. uv=(10, 10) means the texture
will repeat 10 times along each dimension. uv=(5, 10) means the
texture will be scaled to repeat 5 times along the x dimension and
10 times along the y direction.
Returns:
Usd.Prim: The created USD prim.
"""
stage.DefinePrim(path, "Xform")
# create mesh at {path}/mesh, but return prim at {path}
prim: UsdGeom.Mesh = UsdGeom.Mesh.Define(stage, os.path.join(path, "mesh"))
prim.CreateExtentAttr().Set([
(-size[0], -size[1], 0),
(size[0], size[1], 0)
])
prim.CreateFaceVertexCountsAttr().Set([4])
prim.CreateFaceVertexIndicesAttr().Set([0, 1, 3, 2])
var = UsdGeom.Primvar(prim.CreateNormalsAttr())
var.Set([(0, 0, 1)] * 4)
var.SetInterpolation(UsdGeom.Tokens.faceVarying)
var = UsdGeom.PrimvarsAPI(prim).CreatePrimvar("primvars:st",
Sdf.ValueTypeNames.Float2Array)
var.Set(
[(0, 0), (uv[0], 0), (uv[0], uv[1]), (0, uv[1])]
)
var.SetInterpolation(UsdGeom.Tokens.faceVarying)
prim.CreatePointsAttr().Set([
(-size[0], -size[1], 0),
(size[0], -size[1], 0),
(-size[0], size[1], 0),
(size[0], size[1], 0),
])
prim.CreateSubdivisionSchemeAttr().Set(UsdGeom.Tokens.none)
return get_prim(stage, path)
def add_dome_light(stage: Usd.Stage, path: str, intensity: float = 1000,
angle: float = 180, exposure: float=0.) -> UsdLux.DomeLight:
"""Adds a dome light to a USD stage.
Args:
stage (Usd.Stage): The USD stage to modify.
path (str): The path to add the USD prim.
intensity (float): The intensity of the dome light (default 1000).
angle (float): The angle of the dome light (default 180)
exposure (float): THe exposure of the dome light (default 0)
Returns:
UsdLux.DomeLight: The created Dome light.
"""
light = UsdLux.DomeLight.Define(stage, path)
# intensity
light.CreateIntensityAttr().Set(intensity)
light.CreateTextureFormatAttr().Set(UsdLux.Tokens.latlong)
light.CreateExposureAttr().Set(exposure)
# cone angle
shaping = UsdLux.ShapingAPI(light)
shaping.Apply(light.GetPrim())
shaping.CreateShapingConeAngleAttr().Set(angle)
shaping.CreateShapingConeSoftnessAttr()
shaping.CreateShapingFocusAttr()
shaping.CreateShapingFocusTintAttr()
shaping.CreateShapingIesFileAttr()
return light
def add_sphere_light(stage: Usd.Stage, path: str, intensity=30000,
radius=50, angle=180, exposure=0.):
"""Adds a sphere light to a USD stage.
Args:
stage (Usd.Stage): The USD stage to modify.
path (str): The path to add the USD prim.
radius (float): The radius of the sphere light
intensity (float): The intensity of the sphere light (default 1000).
angle (float): The angle of the sphere light (default 180)
exposure (float): THe exposure of the sphere light (default 0)
Returns:
UsdLux.SphereLight: The created sphere light.
"""
light = UsdLux.SphereLight.Define(stage, path)
# intensity
light.CreateIntensityAttr().Set(intensity)
light.CreateRadiusAttr().Set(radius)
light.CreateExposureAttr().Set(exposure)
# cone angle
shaping = UsdLux.ShapingAPI(light)
shaping.Apply(light.GetPrim())
shaping.CreateShapingConeAngleAttr().Set(angle)
shaping.CreateShapingConeSoftnessAttr()
shaping.CreateShapingFocusAttr()
shaping.CreateShapingFocusTintAttr()
shaping.CreateShapingIesFileAttr()
return light
def add_mdl_material(stage: Usd.Stage, path: str, material_url: str,
material_name: Optional[str] = None) -> UsdShade.Material:
"""Adds an Omniverse MDL material to a USD stage.
*Omniverse only*
Args:
stage (Usd.Stage): The USD stage to modify.
path (str): The path to add the USD prim.
material_url (str): The URL of the material, such as on a Nucelus server.
material_name (Optional[str]): An optional name to give the material. If
one is not provided, it will default to the filename of the material
URL (excluding the extension).
returns:
UsdShade.Material: The created USD material.
"""
try:
import omni.usd
except ImportError:
raise ImportError("Omniverse not found. This method is unavailable.")
# Set default mtl_name
if material_name is None:
material_name = os.path.basename(material_url).split('.')[0]
# Create material using omniverse kit
if not stage.GetPrimAtPath(path):
success, result = omni.kit.commands.execute(
"CreateMdlMaterialPrimCommand",
mtl_url=material_url,
mtl_name=material_name,
mtl_path=path
)
# Get material from stage
material = UsdShade.Material(stage.GetPrimAtPath(path))
return material
def add_camera(
stage: Usd.Stage,
path: str,
focal_length: float = 35,
horizontal_aperature: float = 20.955,
vertical_aperature: float = 20.955,
clipping_range: Tuple[float, float] = (0.1, 100000)
) -> UsdGeom.Camera:
"""Adds a camera to a USD stage.
Args:
stage (Usd.Stage): The USD stage to modify.
path (str): The path to add the USD prim.
focal_length (float): The focal length of the camera (default 35).
horizontal_aperature (float): The horizontal aperature of the camera
(default 20.955).
vertical_aperature (float): The vertical aperature of the camera
(default 20.955).
clipping_range (Tuple[float, float]): The clipping range of the camera.
returns:
UsdGeom.Camera: The created USD camera.
"""
camera = UsdGeom.Camera.Define(stage, path)
camera.CreateFocalLengthAttr().Set(focal_length)
camera.CreateHorizontalApertureAttr().Set(horizontal_aperature)
camera.CreateVerticalApertureAttr().Set(vertical_aperature)
camera.CreateClippingRangeAttr().Set(clipping_range)
return camera
def get_prim(stage: Usd.Stage, path: str) -> Usd.Prim:
"""Returns a prim at the specified path in a USD stage.
Args:
stage (Usd.Stage): The USD stage to query.
path (str): The path of the prim.
Returns:
Usd.Prim: The USD prim at the specified path.
"""
return stage.GetPrimAtPath(path)
def get_material(stage: Usd.Stage, path: str) -> UsdShade.Material:
"""Returns a material at the specified path in a USD stage.
Args:
stage (Usd.Stage): The USD stage to query.
path (str): The path of the material.
Returns:
UsdShade.Material: The USD material at the specified path.
"""
prim = get_prim(stage, path)
return UsdShade.Material(prim)
def export_stage(stage: Usd.Stage, filepath: str, default_prim=None):
"""Exports a USD stage to a given filepath.
Args:
stage (Usd.Stage): The USD stage to export.
path (str): The filepath to export the USD stage to.
default_prim (Optional[str]): The path of the USD prim in the
stage to set as the default prim. This is useful when you
want to use the exported USD as a reference, or when you want
to place the USD in Omniverse.
"""
if default_prim is not None:
stage.SetDefaultPrim(get_prim(stage, default_prim))
stage.Export(filepath)
def add_semantics(prim: Usd.Prim, type: str, name: str):
"""Adds semantics to a USD prim.
This function adds semantics to a USD prim. This is useful for assigning
classes to objects when generating synthetic data with Omniverse Replicator.
For example:
add_semantics(dog_prim, "class", "dog")
add_semantics(cat_prim, "class", "cat")
Args:
prim (Usd.Prim): The USD prim to modify.
type (str): The semantics type. This depends on how the data is ingested.
Typically, when using Omniverse replicator you will set this to "class".
name (str): The value of the semantic type. Typically, this would
correspond to the class label.
Returns:
Usd.Prim: The USD prim with added semantics.
"""
prim.AddAppliedSchema(f"SemanticsAPI:{type}_{name}")
prim.CreateAttribute(f"semantic:{type}_{name}:params:semanticType",
Sdf.ValueTypeNames.String).Set(type)
prim.CreateAttribute(f"semantic:{type}_{name}:params:semanticData",
Sdf.ValueTypeNames.String).Set(name)
return prim
def bind_material(prim: Usd.Prim, material: UsdShade.Material):
"""Binds a USD material to a USD prim.
Args:
prim (Usd.Prim): The USD prim to modify.
material (UsdShade.Material): The USD material to bind to the USD prim.
Returns:
Usd.Prim: The modified USD prim with the specified material bound to it.
"""
prim.ApplyAPI(UsdShade.MaterialBindingAPI)
UsdShade.MaterialBindingAPI(prim).Bind(material,
UsdShade.Tokens.strongerThanDescendants)
return prim
def collapse_xform(prim: Usd.Prim):
"""Collapses all xforms on a given USD prim.
This method collapses all Xforms on a given prim. For example,
a series of rotations, translations would be combined into a single matrix
operation.
Args:
prim (Usd.Prim): The Usd.Prim to collapse the transforms of.
Returns:
Usd.Prim: The Usd.Prim.
"""
x = UsdGeom.Xformable(prim)
local = x.GetLocalTransformation()
prim.RemoveProperty("xformOp:translate")
prim.RemoveProperty("xformOp:transform")
prim.RemoveProperty("xformOp:rotateX")
prim.RemoveProperty("xformOp:rotateY")
prim.RemoveProperty("xformOp:rotateZ")
var = x.MakeMatrixXform()
var.Set(local)
return prim
def get_xform_op_order(prim: Usd.Prim):
"""Returns the order of Xform ops on a given prim."""
x = UsdGeom.Xformable(prim)
op_order = x.GetXformOpOrderAttr().Get()
if op_order is not None:
op_order = list(op_order)
return op_order
else:
return []
def set_xform_op_order(prim: Usd.Prim, op_order: Sequence[str]):
"""Sets the order of Xform ops on a given prim"""
x = UsdGeom.Xformable(prim)
x.GetXformOpOrderAttr().Set(op_order)
return prim
def xform_op_move_end_to_front(prim: Usd.Prim):
"""Pops the last xform op on a given prim and adds it to the front."""
order = get_xform_op_order(prim)
end = order.pop(-1)
order.insert(0, end)
set_xform_op_order(prim, order)
return prim
def get_num_xform_ops(prim: Usd.Prim) -> int:
"""Returns the number of xform ops on a given prim."""
return len(get_xform_op_order(prim))
def apply_xform_matrix(prim: Usd.Prim, transform: np.ndarray):
"""Applies a homogeneous transformation matrix to the current prim's xform list.
Args:
prim (Usd.Prim): The USD prim to transform.
transform (np.ndarray): The 4x4 homogeneous transform matrix to apply.
Returns:
Usd.Prim: The modified USD prim with the provided transform applied after current transforms.
"""
x = UsdGeom.Xformable(prim)
x.AddTransformOp(opSuffix=f"num_{get_num_xform_ops(prim)}").Set(
Gf.Matrix4d(transform)
)
xform_op_move_end_to_front(prim)
return prim
def scale(prim: Usd.Prim, scale: Tuple[float, float, float]):
"""Scales a prim along the (x, y, z) dimensions.
Args:
prim (Usd.Prim): The USD prim to scale.
scale (Tuple[float, float, float]): The scaling factors for the (x, y, z) dimensions.
Returns:
Usd.Prim: The scaled prim.
"""
x = UsdGeom.Xformable(prim)
x.AddScaleOp(opSuffix=f"num_{get_num_xform_ops(prim)}").Set(scale)
xform_op_move_end_to_front(prim)
return prim
def translate(prim: Usd.Prim, offset: Tuple[float, float, float]):
"""Translates a prim along the (x, y, z) dimensions.
Args:
prim (Usd.Prim): The USD prim to translate.
offset (Tuple[float, float, float]): The offsets for the (x, y, z) dimensions.
Returns:
Usd.Prim: The translated prim.
"""
x = UsdGeom.Xformable(prim)
x.AddTranslateOp(opSuffix=f"num_{get_num_xform_ops(prim)}").Set(offset)
xform_op_move_end_to_front(prim)
return prim
def rotate_x(prim: Usd.Prim, angle: float):
"""Rotates a prim around the X axis.
Args:
prim (Usd.Prim): The USD prim to rotate.
angle (float): The rotation angle in degrees.
Returns:
Usd.Prim: The rotated prim.
"""
x = UsdGeom.Xformable(prim)
x.AddRotateXOp(opSuffix=f"num_{get_num_xform_ops(prim)}").Set(angle)
xform_op_move_end_to_front(prim)
return prim
def rotate_y(prim: Usd.Prim, angle: float):
"""Rotates a prim around the Y axis.
Args:
prim (Usd.Prim): The USD prim to rotate.
angle (float): The rotation angle in degrees.
Returns:
Usd.Prim: The rotated prim.
"""
x = UsdGeom.Xformable(prim)
x.AddRotateYOp(opSuffix=f"num_{get_num_xform_ops(prim)}").Set(angle)
xform_op_move_end_to_front(prim)
return prim
def rotate_z(prim: Usd.Prim, angle: float):
"""Rotates a prim around the Z axis.
Args:
prim (Usd.Prim): The USD prim to rotate.
angle (float): The rotation angle in degrees.
Returns:
Usd.Prim: The rotated prim.
"""
x = UsdGeom.Xformable(prim)
x.AddRotateZOp(opSuffix=f"num_{get_num_xform_ops(prim)}").Set(angle)
xform_op_move_end_to_front(prim)
return prim
def stack_prims(prims: Sequence[Usd.Prim], axis: int = 2, gap: float = 0, align_center=False):
"""Stacks prims on top of each other (or side-by-side).
This function stacks prims by placing them so their bounding boxes
are adjacent along a given axis.
Args:
prim (Usd.Prim): The USD prims to stack.
axis (int): The axis along which to stack the prims. x=0, y=1, z=2. Default 2.
gap (float): The spacing to add between stacked elements.
Returns:
Sequence[Usd.Prim]: The stacked prims.
"""
for i in range(1, len(prims)):
prev = prims[i - 1]
cur = prims[i]
bb_cur_min, bb_cur_max = compute_bbox(cur)
bb_prev_min, bb_prev_max = compute_bbox(prev)
if align_center:
offset = [
(bb_cur_max[0] + bb_cur_min[0]) / 2. - (bb_prev_max[0] + bb_prev_min[0]) / 2.,
(bb_cur_max[1] + bb_cur_min[1]) / 2. - (bb_prev_max[1] + bb_prev_min[1]) / 2.,
(bb_cur_max[2] + bb_cur_min[2]) / 2. - (bb_prev_max[2] + bb_prev_min[2]) / 2.
]
else:
offset = [0, 0, 0]
offset[axis] = bb_prev_max[axis] - bb_cur_min[axis]
if isinstance(gap, list):
offset[axis] = offset[axis] + gap[i]
else:
offset[axis] = offset[axis] + gap
translate(cur, tuple(offset))
return prims
def compute_bbox(prim: Usd.Prim) -> \
Tuple[Tuple[float, float, float], Tuple[float, float, float]]:
"""Computes the axis-aligned bounding box for a USD prim.
Args:
prim (Usd.Prim): The USD prim to compute the bounding box of.
Returns:
Tuple[Tuple[float, float, float], Tuple[float, float, float]] The ((min_x, min_y, min_z), (max_x, max_y, max_z)) values of the bounding box.
"""
bbox_cache: UsdGeom.BBoxCache = UsdGeom.BBoxCache(
time=Usd.TimeCode.Default(),
includedPurposes=[UsdGeom.Tokens.default_],
useExtentsHint=True
)
total_bounds = Gf.BBox3d()
for p in Usd.PrimRange(prim):
total_bounds = Gf.BBox3d.Combine(
total_bounds, Gf.BBox3d(bbox_cache.ComputeWorldBound(p).ComputeAlignedRange())
)
box = total_bounds.ComputeAlignedBox()
return (box.GetMin(), box.GetMax())
def compute_bbox_size(prim: Usd.Prim) -> Tuple[float, float, float]:
"""Computes the (x, y, z) size of the axis-aligned bounding box for a prim."""
bbox_min, bbox_max = compute_bbox(prim)
size = (
bbox_max[0] - bbox_min[0],
bbox_max[1] - bbox_min[1],
bbox_max[2] - bbox_min[2]
)
return size
def compute_bbox_center(prim: Usd.Prim) -> Tuple[float, float, float]:
"""Computes the (x, y, z) center of the axis-aligned bounding box for a prim."""
bbox_min, bbox_max = compute_bbox(prim)
center = (
(bbox_max[0] + bbox_min[0]) / 2,
(bbox_max[1] + bbox_min[1]) / 2,
(bbox_max[2] + bbox_min[2]) / 2
)
return center
def set_visibility(prim: Usd.Prim,
visibility: Literal["inherited", "invisible"] = "inherited"):
"""Sets the visibility of a prim.
Args:
prim (Usd.Prim): The prim to control the visibility of.
visibility (str): The visibility of the prim. "inherited" if the
prim is visibile as long as it's parent is visible, or invisible if
it's parent is invisible. Otherwise, "invisible" if the prim is
invisible regardless of it's parent's visibility.
Returns:
Usd.Prim: The USD prim.
"""
attr = prim.GetAttribute("visibility")
if attr is None:
prim.CreateAttribute("visibility")
attr.Set(visibility)
return prim
def get_visibility(prim: Usd.Prim):
"""Returns the visibility of a given prim.
See set_visibility for details.
"""
return prim.GetAttribute("visibility").Get()
def rad2deg(x):
"""Convert radians to degrees."""
return 180. * x / math.pi
def deg2rad(x):
"""Convert degrees to radians."""
return math.pi * x / 180.
def compute_sphere_point(
elevation: float,
azimuth: float,
distance: float
) -> Tuple[float, float, float]:
"""Compute a sphere point given an elevation, azimuth and distance.
Args:
elevation (float): The elevation in degrees.
azimuth (float): The azimuth in degrees.
distance (float): The distance.
Returns:
Tuple[float, float, float]: The sphere coordinate.
"""
elevation = rad2deg(elevation)
azimuth = rad2deg(azimuth)
elevation = elevation
camera_xy_distance = math.cos(elevation) * distance
camera_x = math.cos(azimuth) * camera_xy_distance
camera_y = math.sin(azimuth) * camera_xy_distance
camera_z = math.sin(elevation) * distance
eye = (
float(camera_x),
float(camera_y),
float(camera_z)
)
return eye
def compute_look_at_matrix(
at: Tuple[float, float, float],
up: Tuple[float, float, float],
eye: Tuple[float, float, float]
) -> np.ndarray:
"""Computes a 4x4 homogeneous "look at" transformation matrix.
Args:
at (Tuple[float, float, float]): The (x, y, z) location that the transform
should be facing. For example (0, 0, 0) if the transformation should
face the origin.
up (Tuple[float, float, float]): The up axis fot the transform. ie:
(0, 0, 1) for the up-axis to correspond to the z-axis.
eye (Tuple[float, float]): The (x, y, z) location of the transform.
For example, (100, 100, 100) if we want to place a camera at
(x=100,y=100,z=100)
Returns:
np.ndarray: The 4x4 homogeneous transformation matrix.
"""
at = np.array(at)
up = np.array(up)
up = up / np.linalg.norm(up)
eye = np.array(eye)
# forward axis (z)
z_axis = np.array(eye) - np.array(at)
z_axis = z_axis / np.linalg.norm(z_axis)
# right axis (x)
x_axis = np.cross(up, z_axis)
x_axis = x_axis / np.linalg.norm(x_axis)
# up axis
y_axis = np.cross(z_axis, x_axis)
y_axis = y_axis / np.linalg.norm(y_axis)
matrix = np.array([
[x_axis[0], x_axis[1], x_axis[2], 0.0],
[y_axis[0], y_axis[1], y_axis[2], 0.0],
[z_axis[0], z_axis[1], z_axis[2], 0.0],
[eye[0], eye[1], eye[2], 1.0]
])
return matrix
| 26,895 | Python | 29.844037 | 148 | 0.625469 |
NVIDIA-Omniverse/usd_scene_construction_utils/examples/bind_mdl_material/main.py | # SPDX-FileCopyrightText: Copyright (c) 2023 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
# SPDX-License-Identifier: Apache-2.0
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import sys
import os
from pathlib import Path
sys.path.append(f"{Path.home()}/usd_scene_construction_utils") # use your install path
from usd_scene_construction_utils import (
add_mdl_material,
new_omniverse_stage,
add_plane,
add_box,
stack_prims,
bind_material,
add_dome_light
)
stage = new_omniverse_stage()
# Add cardboard material
cardboard = add_mdl_material(
stage,
"/scene/cardboard",
"http://omniverse-content-production.s3-us-west-2.amazonaws.com/Materials/Base/Wall_Board/Cardboard.mdl"
)
# Add concrete material
concrete = add_mdl_material(
stage,
"/scene/concrete",
"http://omniverse-content-production.s3-us-west-2.amazonaws.com/Materials/Base/Masonry/Concrete_Smooth.mdl"
)
# Add floor plane
floor = add_plane(stage, "/scene/floor", size=(500, 500))
# Add box
box = add_box(stage, "/scene/box", size=(100, 100, 100))
# Stack box on floor
stack_prims([floor, box], axis=2)
# Bind materials to objects
bind_material(floor, concrete)
bind_material(box, cardboard)
# Add dome light
light = add_dome_light(stage, "/scene/dome_light") | 1,784 | Python | 28.262295 | 112 | 0.732063 |
NVIDIA-Omniverse/usd_scene_construction_utils/examples/bind_mdl_material/README.md | # Example - Bind MDL Material
This example demonstrates binding materials to objects. It must be run inside
omniverse to pull from the rich set of available MDL materials.
<img src="landing_graphic.jpg" height="320"/>
The example should display a box with a cardboard texture and a floor with
a concrete texture.
## Instructions
1. Modify the path on line 3 of ``main.py`` to the path you cloned usd_scene_construction_utils
2. Launch [Omniverse Code](https://developer.nvidia.com/omniverse/code-app)
3. Open the script editor
4. Copy the code from ``main.py`` into the script editor
5. Run the script editor.
| 617 | Markdown | 31.526314 | 95 | 0.763371 |
NVIDIA-Omniverse/usd_scene_construction_utils/examples/hand_truck_w_boxes/main.py | # SPDX-FileCopyrightText: Copyright (c) 2023 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
# SPDX-License-Identifier: Apache-2.0
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import sys
import os
from pathlib import Path
sys.path.append(f"{Path.home()}/usd_scene_construction_utils") # use your install path
from usd_scene_construction_utils import (
add_usd_ref,
rotate_x,
rotate_y,
rotate_z,
scale,
compute_bbox,
add_xform,
compute_bbox_center,
translate,
set_visibility,
new_omniverse_stage,
add_dome_light,
add_plane,
add_mdl_material,
bind_material
)
import random
from typing import Tuple
box_asset_url = "http://omniverse-content-production.s3-us-west-2.amazonaws.com/Assets/DigitalTwin/Assets/Warehouse/Shipping/Cardboard_Boxes/Flat_A/FlatBox_A02_15x21x8cm_PR_NVD_01.usd"
hand_truck_asset_url = "http://omniverse-content-production.s3-us-west-2.amazonaws.com/Assets/DigitalTwin/Assets/Warehouse/Equipment/Hand_Trucks/Convertible_Aluminum_A/ConvertableAlumHandTruck_A02_PR_NVD_01.usd"
def add_box_of_size(
stage,
path: str,
size: Tuple[float, float, float]
):
"""Adds a box and re-scales it to match the specified dimensions
"""
# Add USD box
prim = add_usd_ref(stage, path, usd_path=box_asset_url)
rotate_x(prim, random.choice([-90, 0, 90, 180]))
rotate_y(prim, random.choice([-90, 0, 90, 180]))
# Scale USD box to fit dimensions
usd_min, usd_max = compute_bbox(prim)
usd_size = (
usd_max[0] - usd_min[0],
usd_max[1] - usd_min[1],
usd_max[2] - usd_min[2]
)
required_scale = (
size[0] / usd_size[0],
size[1] / usd_size[1],
size[2] / usd_size[2]
)
scale(prim, required_scale)
return prim
def add_random_box_stack(
stage,
path: str,
count_range=(1, 5),
size_range=((30, 30, 10), (50, 50, 25)),
angle_range=(-5, 5),
jitter_range=(-3,3)
):
container = add_xform(stage, path)
count = random.randint(*count_range)
# get sizes and sort
sizes = [
(
random.uniform(size_range[0][0], size_range[1][0]),
random.uniform(size_range[0][1], size_range[1][1]),
random.uniform(size_range[0][2], size_range[1][2])
)
for i in range(count)
]
sizes = sorted(sizes, key=lambda x: x[0]**2 + x[1]**2, reverse=True)
boxes = []
for i in range(count):
box_i = add_box_of_size(stage, os.path.join(path, f"box_{i}"), sizes[i])
boxes.append(box_i)
if count > 0:
center = compute_bbox_center(boxes[0])
for i in range(1, count):
prev_box, cur_box = boxes[i - 1], boxes[i]
cur_bbox = compute_bbox(cur_box)
cur_center = compute_bbox_center(cur_box)
prev_bbox = compute_bbox(prev_box)
offset = (
center[0] - cur_center[0],
center[1] - cur_center[1],
prev_bbox[1][2] - cur_bbox[0][2]
)
translate(cur_box, offset)
# add some noise
for i in range(count):
rotate_z(boxes[i], random.uniform(*angle_range))
translate(boxes[i], (
random.uniform(*jitter_range),
random.uniform(*jitter_range),
0
))
return container, boxes
def add_random_box_stacks(
stage,
path: str,
count_range=(0, 3),
):
container = add_xform(stage, path)
stacks = []
count = random.randint(*count_range)
for i in range(count):
stack, items = add_random_box_stack(stage, os.path.join(path, f"stack_{i}"))
stacks.append(stack)
for i in range(count):
cur_stack = stacks[i]
cur_bbox = compute_bbox(cur_stack)
cur_center = compute_bbox_center(cur_stack)
translate(cur_stack, (0, -cur_center[1], -cur_bbox[0][2]))
if i > 0:
prev_bbox = compute_bbox(stacks[i - 1])
translate(cur_stack, (prev_bbox[1][0] - cur_bbox[0][0], 0, 0))
return container, stacks
def add_hand_truck_with_boxes(stage, path: str):
container = add_xform(stage, path)
hand_truck_path = f"{path}/truck"
box_stacks_path = f"{path}/box_stacks"
add_usd_ref(
stage,
hand_truck_path,
hand_truck_asset_url
)
box_stacks_container, box_stacks = add_random_box_stacks(stage, box_stacks_path, count_range=(1,4))
rotate_z(box_stacks_container, 90)
translate(
box_stacks_container,
offset=(0, random.uniform(8, 12), 28)
)
# remove out of bounds stacks
last_visible = box_stacks[0]
for i in range(len(box_stacks)):
_, stack_bbox_max = compute_bbox(box_stacks[i])
print(stack_bbox_max)
if stack_bbox_max[1] > 74:
set_visibility(box_stacks[i], "invisible")
else:
last_visible = box_stacks[i]
# wiggle inide bounds
boxes_bbox = compute_bbox(last_visible)
wiggle = (82 - boxes_bbox[1][1])
translate(box_stacks_container, (0, random.uniform(0, wiggle), 1))
return container
stage = new_omniverse_stage()
light = add_dome_light(stage, "/scene/dome_light")
floor = add_plane(stage, "/scene/floor", size=(1000, 1000))
concrete = add_mdl_material(
stage,
"/scene/materials/concrete",
"http://omniverse-content-production.s3-us-west-2.amazonaws.com/Materials/Base/Masonry/Concrete_Polished.mdl"
)
bind_material(floor, concrete)
all_objects_container = add_xform(stage, "/scene/objects")
for i in range(5):
for j in range(5):
path = f"/scene/objects/hand_truck_{i}_{j}"
current_object = add_hand_truck_with_boxes(stage, path)
rotate_z(current_object, random.uniform(-15, 15))
translate(current_object, (100*i, 150*j, 0))
objects_center = compute_bbox_center(all_objects_container)
translate(all_objects_container, (-objects_center[0], -objects_center[1], 0)) | 6,545 | Python | 30.171428 | 211 | 0.609778 |
NVIDIA-Omniverse/usd_scene_construction_utils/examples/hand_truck_w_boxes/README.md | # Example - Hand Truck with Boxes
This example demonstrates creating a scene with structured randomization.
It creates a grid of hand trucks with boxes scattered on top.
<img src="landing_graphic.jpg" height="320"/>
e
## Instructions
1. Modify the path on line 3 of ``main.py`` to the path you cloned usd_scene_construction_utils
2. Launch [Omniverse Code](https://developer.nvidia.com/omniverse/code-app)
3. Open the script editor
4. Copy the code from ``main.py`` into the script editor
5. Run the script editor.
## Notes
This example defines a few functions. Here are their descriptions.
| Function | Description |
|---|---|
| add_box_of_size | Adds a cardboard box of a given size, with randomly oriented labeling and tape. |
| add_random_box_stack | Adds a stack of cardboard boxes, sorted by cross-section size. Also adds some translation and angle jitter |
| add_random_box_stacks | Adds multiple random box stacks, aligned and stack on x-axis |
| add_hand_truck_with_boxes | Adds a hand truck, places the box stack at an offset so it appears as placed on the truck. Makes any out-of-bounds boxes invisible. Wiggles the visible boxes in the area remaining on the hand truck. |
When developing this example, we started with just a simple function, and added complexity
iteratively by trying rendering, viewing, tweaking, repeat.
| 1,346 | Markdown | 42.451612 | 231 | 0.759287 |
NVIDIA-Omniverse/usd_scene_construction_utils/examples/pallet_with_boxes/main.py | # SPDX-FileCopyrightText: Copyright (c) 2023 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
# SPDX-License-Identifier: Apache-2.0
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import sys
import os
import random
from pathlib import Path
sys.path.append(f"{Path.home()}/usd_scene_construction_utils") # use your install path
sys.path.append(f"{Path.home()}/usd_scene_construction_utils/examples/pallet_with_boxes") # use your install path
from usd_scene_construction_utils import *
PALLET_URIS = [
"http://omniverse-content-production.s3-us-west-2.amazonaws.com/Assets/DigitalTwin/Assets/Warehouse/Shipping/Pallets/Wood/Block_A/BlockPallet_A01_PR_NVD_01.usd",
"http://omniverse-content-production.s3-us-west-2.amazonaws.com/Assets/DigitalTwin/Assets/Warehouse/Shipping/Pallets/Wood/Block_B/BlockPallet_B01_PR_NVD_01.usd",
"http://omniverse-content-production.s3-us-west-2.amazonaws.com/Assets/DigitalTwin/Assets/Warehouse/Shipping/Pallets/Wood/Wing_A/WingPallet_A01_PR_NVD_01.usd"
]
CARDBOARD_BOX_URIS = [
"http://omniverse-content-production.s3-us-west-2.amazonaws.com/Assets/DigitalTwin/Assets/Warehouse/Shipping/Cardboard_Boxes/Cube_A/CubeBox_A02_16cm_PR_NVD_01.usd",
"http://omniverse-content-production.s3-us-west-2.amazonaws.com/Assets/DigitalTwin/Assets/Warehouse/Shipping/Cardboard_Boxes/Flat_A/FlatBox_A05_26x26x11cm_PR_NVD_01.usd",
"http://omniverse-content-production.s3-us-west-2.amazonaws.com/Assets/DigitalTwin/Assets/Warehouse/Shipping/Cardboard_Boxes/Printer_A/PrintersBox_A05_23x28x25cm_PR_NVD_01.usd"
]
def add_pallet(stage, path: str):
prim = add_usd_ref(stage, path, random.choice(PALLET_URIS))
add_semantics(prim, "class", "pallet")
return prim
def add_cardboard_box(stage, path: str):
prim = add_usd_ref(stage, path, random.choice(CARDBOARD_BOX_URIS))
add_semantics(prim, "class", "box")
return prim
def add_pallet_with_box(stage, path: str):
container = add_xform(stage, path)
pallet = add_pallet(stage, os.path.join(path, "pallet"))
box = add_cardboard_box(stage, os.path.join(path, "box"))
pallet_bbox = compute_bbox(pallet)
box_bbox = compute_bbox(box)
translate(box,(0, 0, pallet_bbox[1][2] - box_bbox[0][2]))
rotate_z(pallet, random.uniform(-25, 25))
return container
def add_tree(stage, path: str):
url = "http://omniverse-content-production.s3-us-west-2.amazonaws.com/Assets/Vegetation/Trees/American_Beech.usd"
return add_usd_ref(stage, path, url)
stage = new_omniverse_stage()
brick = add_mdl_material(stage, "/scene/brick", "http://omniverse-content-production.s3-us-west-2.amazonaws.com/Materials/Base/Masonry/Brick_Pavers.mdl")
pallet_box = add_pallet_with_box(stage, "/scene/pallet")
floor = add_plane(stage, "/scene/floor", size=(1000, 1000), uv=(20., 20.))
tree = add_tree(stage, "/scene/tree")
translate(tree, (100, -150, 0))
bind_material(floor, brick)
light = add_dome_light(stage, "/scene/dome_light") | 3,446 | Python | 46.219177 | 180 | 0.74231 |
NVIDIA-Omniverse/usd_scene_construction_utils/examples/add_camera/main.py | # SPDX-FileCopyrightText: Copyright (c) 2023 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
# SPDX-License-Identifier: Apache-2.0
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import sys
from pathlib import Path
sys.path.append(f"{Path.home()}/usd_scene_construction_utils") # use your install path
from usd_scene_construction_utils import (
new_in_memory_stage,
add_box,
add_camera,
compute_look_at_matrix,
apply_xform_matrix,
export_stage
)
stage = new_in_memory_stage()
box = add_box(stage, "/scene/box", size=(100, 100, 100))
camera = add_camera(stage, "/scene/camera")
matrix = compute_look_at_matrix(
at=(0, 0, 0),
up=(0, 0, 1),
eye=(500, 500, 500)
)
apply_xform_matrix(camera, matrix)
export_stage(stage, "add_camera.usda", default_prim="/scene")
| 1,302 | Python | 27.955555 | 98 | 0.72043 |
NVIDIA-Omniverse/usd_scene_construction_utils/examples/render_with_replicator/main.py | # SPDX-FileCopyrightText: Copyright (c) 2023 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
# SPDX-License-Identifier: Apache-2.0
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import sys
import os
import random
from pathlib import Path
sys.path.append(f"{Path.home()}/usd_scene_construction_utils") # use your install path
from usd_scene_construction_utils import *
# set to your output dir
OUTPUT_DIR = f"{Path.home()}/usd_scene_construction_utils/examples/render_with_replicator/output"
def add_box_stack(stage, path: str, box_material):
container = add_xform(stage, path)
boxes = []
for i in range(3):
box_path = f"{path}/box_{i}"
box = add_box(stage, box_path, (random.uniform(20, 30), random.uniform(20, 30), 10))
add_semantics(box, "class", "box_stack")
bind_material(box, box_material)
rotate_z(box, random.uniform(-10, 10))
boxes.append(box)
stack_prims(boxes, axis=2)
return container
def build_scene(stage):
# Add cardboard material
cardboard = add_mdl_material(
stage,
"/scene/cardboard",
"http://omniverse-content-production.s3-us-west-2.amazonaws.com/Materials/Base/Wall_Board/Cardboard.mdl"
)
# Add concrete material
concrete = add_mdl_material(
stage,
"/scene/concrete",
"http://omniverse-content-production.s3-us-west-2.amazonaws.com/Materials/Base/Masonry/Concrete_Smooth.mdl"
)
# Add floor plane
floor = add_plane(stage, "/scene/floor", size=(500, 500))
bind_material(floor, concrete)
# Add box
box_stack = add_box_stack(stage, "/scene/box_stack", box_material=cardboard)
# Stack box on floor
stack_prims([floor, box_stack], axis=2)
# Add dome light
add_dome_light(stage, "/scene/dome_light")
import omni.replicator.core as rep
with rep.new_layer():
stage = new_omniverse_stage()
build_scene(stage)
camera = rep.create.camera()
render_product = rep.create.render_product(camera, (1024, 1024))
box_stack = rep.get.prims(path_pattern="^/scene/box_stack$")
# Setup randomization
with rep.trigger.on_frame(num_frames=100):
with box_stack:
rep.modify.pose(position=rep.distribution.uniform((-100, -100, 0), (100, 100, 0)))
with camera:
rep.modify.pose(position=rep.distribution.uniform((0, 0, 0), (400, 400, 400)), look_at=(0, 0, 0))
writer = rep.WriterRegistry.get("BasicWriter")
writer.initialize(
output_dir=OUTPUT_DIR,
rgb=True,
bounding_box_2d_tight=True,
distance_to_camera=True,
bounding_box_3d=True,
camera_params=True,
instance_id_segmentation=True,
colorize_instance_id_segmentation=False
)
writer.attach([render_product]) | 3,298 | Python | 31.029126 | 115 | 0.671922 |
NVIDIA-Omniverse/usd_scene_construction_utils/examples/render_with_replicator/README.md | # Example - Render with Omniverse Replicator
This example demonstrates how to render a scene constructed with usd_scene_construction_utils
using Omniverse replicator. | 167 | Markdown | 40.99999 | 93 | 0.838323 |
NVIDIA-Omniverse/usd_scene_construction_utils/examples/hello_box/main.py | # SPDX-FileCopyrightText: Copyright (c) 2023 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
# SPDX-License-Identifier: Apache-2.0
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import sys
from pathlib import Path
sys.path.append(f"{Path.home()}/usd_scene_construction_utils") # use your install path
import random
from usd_scene_construction_utils import *
stage = new_omniverse_stage()
# Create floor
floor = add_plane(stage, "/scene/floor", (1000, 1000))
# Add a dome light
light = add_dome_light(stage, "/scene/dome_light")
# Create a grid of boxes
all_boxes = add_xform(stage, "/scene/boxes")
for i in range(5):
for j in range(5):
path = f"/scene/boxes/box_{i}_{j}"
# Add box of random size
size = (
random.uniform(20, 50),
random.uniform(20, 50),
random.uniform(20, 50),
)
box = add_box(stage, path, size=size)
# Set position in xy grid
translate(box, (100*i, 100*j, 0))
# Align z with floor
box_min, _ = compute_bbox(box)
translate(box, (0, 0, -box_min[2]))
# Translate all boxes to have xy center at (0, 0)
boxes_center = compute_bbox_center(all_boxes)
translate("/scene/boxes", (-boxes_center[0], -boxes_center[1], 0))
| 1,760 | Python | 31.018181 | 98 | 0.674432 |
NVIDIA-Omniverse/usd_scene_construction_utils/examples/hello_box/README.md | # Example - Hello Box
This example demonstrates creating a simply box shape and adding a dome light
to a scene.
<img src="landing_graphic.jpg" height="320"/>
It doesn't include any assets, so should load very quickly. This is simply
so you can get quick results and make sure usd_scene_construction_utils is working. Once you're
set up and working, you'll want to use omniverse with a nucleus server so you
can pull from a rich set of assets, like in the [hand truck example](../hand_truck_w_boxes/).
## Instructions
1. Modify the path on line 3 of ``main.py`` to the path you cloned usd_scene_construction_utils
2. Launch [Omniverse Code](https://developer.nvidia.com/omniverse/code-app)
3. Open the script editor
4. Copy the code from ``main.py`` into the script editor
5. Run the script editor.
| 809 | Markdown | 37.571427 | 96 | 0.750309 |
NVIDIA-Omniverse/usd_scene_construction_utils/docs/usd_scene_construction_utils.rst | USD Scene Construction Utilities
================================
.. automodule:: usd_scene_construction_utils
:members: | 125 | reStructuredText | 24.199995 | 44 | 0.568 |
NVIDIA-Omniverse/usd_scene_construction_utils/docs/index.rst | .. USD Scene Construction Utils documentation master file, created by
sphinx-quickstart on Thu Apr 13 09:20:03 2023.
You can adapt this file completely to your liking, but it should at least
contain the root `toctree` directive.
Welcome to USD Scene Construction Utilities's documentation!
============================================================
.. toctree::
:maxdepth: 3
:caption: usd_scene_construction_utils:
usd_scene_construction_utils
Indices and tables
==================
* :ref:`genindex`
* :ref:`modindex`
* :ref:`search`
| 563 | reStructuredText | 24.636363 | 76 | 0.628774 |
NVIDIA-Omniverse/usd_scene_construction_utils/docs/conf.py | # Configuration file for the Sphinx documentation builder.
#
# For the full list of built-in configuration values, see the documentation:
# https://www.sphinx-doc.org/en/master/usage/configuration.html
# -- Project information -----------------------------------------------------
# https://www.sphinx-doc.org/en/master/usage/configuration.html#project-information
project = 'USD Scene Construction Utilities'
copyright = '2023, NVIDIA'
author = 'NVIDIA'
# -- General configuration ---------------------------------------------------
# https://www.sphinx-doc.org/en/master/usage/configuration.html#general-configuration
extensions = [
'sphinx.ext.autodoc',
'sphinx.ext.autosummary',
'sphinx.ext.doctest',
'sphinx.ext.intersphinx',
'sphinx.ext.todo',
'sphinx.ext.coverage',
'sphinx.ext.napoleon',
'sphinx.ext.viewcode',
'sphinxcontrib.katex',
'sphinx.ext.autosectionlabel',
'sphinx_copybutton',
'sphinx_panels',
'myst_parser',
]
templates_path = ['_templates']
exclude_patterns = ['_build', 'Thumbs.db', '.DS_Store']
# -- Options for HTML output -------------------------------------------------
# https://www.sphinx-doc.org/en/master/usage/configuration.html#options-for-html-output
html_theme = 'sphinx_rtd_theme'
html_static_path = ['_static']
| 1,307 | Python | 30.142856 | 87 | 0.627391 |
NVIDIA-Omniverse/kit-extension-sample-spawn-prims/README.md | # Spawn Primitives Extension Sample
## [Spawn Primitives (omni.example.spawn_prims)](exts/omni.example.spawn_prims)

### About
This repo shows how to build an extension in less than 10 minutes. The focus of this sample extension is to show how to create an extension and use omni.kit commands.
#### [README](exts/omni.example.spawn_prims/)
See the [README for this extension](exts/omni.example.spawn_prims/) to learn more about it including how to use it.
#### [Tutorial](exts/omni.example.spawn_prims/tutorial/tutorial.md)
Follow a [step-by-step tutorial](exts/omni.example.spawn_prims/tutorial/tutorial.md) that walks you through how to use omni.ui.scene to build this extension.
## Adding This Extension
To add this extension to your Omniverse app:
1. Go into: `Extension Manager` -> `Hamburger Icon` -> `Settings` -> `Extension Search Path`
2. Add this as a search path: `git://github.com/NVIDIA-Omniverse/kit-extension-sample-spawn-prims.git?branch=main&dir=exts`
Alternatively:
1. Download or Clone the extension, unzip the file if downloaded
2. Copy the `exts` folder path within the extension folder
- i.e. `/home/.../kit-extension-sample-spawn-prims/exts` (Linux) or `C:/.../kit-extension-sample-spawn-prims/ext` (Windows)
3. Go into: `Extension Manager` -> `Hamburger Icon` -> `Settings` -> `Extension Search Path`
4. Add the `exts` folder path as a search path
Make sure no filter is enabled and in both cases you should be able to find the new extension in the `Third Party` tab list.
## Linking with an Omniverse app
For a better developer experience, it is recommended to create a folder link named `app` to the *Omniverse Kit* app installed from *Omniverse Launcher*. A convenience script to use is included.
Run:
```bash
# Windows
> link_app.bat
```
```shell
# Linux
~$ ./link_app.sh
```
If successful you should see `app` folder link in the root of this repo.
If multiple Omniverse apps are installed the script will select the recommended one. Or you can explicitly pass an app:
```bash
# Windows
> link_app.bat --app code
```
```shell
# Linux
~$ ./link_app.sh --app code
```
You can also pass a path that leads to the Omniverse package folder to create the link:
```bash
# Windows
> link_app.bat --path "C:/Users/bob/AppData/Local/ov/pkg/create-2022.1.3"
```
```shell
# Linux
~$ ./link_app.sh --path "home/bob/.local/share/ov/pkg/create-2022.1.3"
```
## Contributing
The source code for this repository is provided as-is and we are not accepting outside contributions. | 2,600 | Markdown | 34.148648 | 193 | 0.738077 |
NVIDIA-Omniverse/kit-extension-sample-spawn-prims/exts/omni.example.spawn_prims/tutorial/tutorial.md | 
# Make an Extension To Spawn Primitives
In this document you learn how to create an Extension inside of Omniverse. Extensions are what make up Omniverse. This tutorial is ideal for those who are beginners to Omniverse Kit.
## Learning Objectives
- Create an Extension
- Use Omni Commands in Omniverse
- Make a functional Button
- Update the Extension's title and description
- Dock the Extension Window
# Prerequisites
- [Set up your environment](https://github.com/NVIDIA-Omniverse/ExtensionEnvironmentTutorial/blob/master/Tutorial.md#4-create-a-git-repository)
- Omniverse Kit 105.1.1 or higher
## Step 1: Create an Extension
Omniverse is made up of all kinds of Extensions that were created by developers. In this section, you create an Extension and learn how the code gets reflected back in Omniverse.
### Step 1.1: Navigate to the Extensions List
In Omniverse, navigate to the *Extensions* Window:

> **Note:** If you don't see the *Extensions* Window, enable **Window > Extensions**:
>
> 
### Step 1.2: Create A New Extension Template Project
Click the **plus** icon, and select ```New Extension Template Project``` to create a extension:

### Step 1.3: Choose a Location for Your Extension
In the following prompt, select the default location for your Extension, and click **Select**:

### Step 1.4: Name your Extension
Next, name your project "kit-exts-spawn-prims":

And name your Extension "my.spawn_prims.ext":

> **Note:** You can choose a different Extension name when publishing. For example: "companyName.extdescrip1.descrip2"
> You **may not** use omni in your extension id.
After this, two things happen.
First, Visual Studio Code starts up, displaying the template Extension code:
> **Note:** If `extension.py` is not open, go to exts > my.spawn_prims.ext > my > spawn_prims > ext > extension.py

Second, a new window appears in Omniverse, called "My Window":

If you click **Add** in *My Window*, the `empty` text changes to `count: 1`, indicating that the button was clicked. Pressing **Add** again increases the number for count. Pressing **Reset** will reset it back to `empty`:

You use this button later to spawn a primitive.
> **Note:** If you close out of VSCode, you can reopen the extension's code by searching for it in the Extension Window and Click the VSCode Icon. This will only work if you have VSCode installed.
> 
## Step 2: Update Your Extension's Metadata
With the Extension created, you can update the metadata in `extension.toml`. This is metadata is used in the Extension details of the *Extensions Manager*. It's also used to inform other systems of the Application.
### Step 2.1: Navigate to `extension.toml`
Navigate to `config/extension.toml`:

### Step 2.2: Name and Describe your Extension
Change the Extension's `title` and `description`:
``` python
title = "Spawn Primitives"
description = "Spawns different primitives utilizing omni kit's commands"
```
Save the file and head back over into Omniverse.
### Step 2.3: Locate the Extension
Select the *Extension* Window, search for your Extension in *Third Party* tab, and select it in the left column to pull up its details:

Now that your template is created, you can start editing the source code and see it reflected in Omniverse.
## Step 3: Update Your Extension's Interface
Currently, your window is called "My Window", and there are two buttons that says, "Add" and "Reset". In this step, you make some changes to better reflect the purpose of your Extension.
### Step 3.1: Navigate to `extension.py`
In Visual Studio Code, navigate to `ext/my.spawn_prims.ext/my/spawn_prims/ext/extension.py` to find the following source code:
``` python
import omni.ext
import omni.ui as ui
# Functions and vars are available to other extension as usual in python: `example.python_ext.some_public_function(x)`
def some_public_function(x: int):
print("[my.spawn_prims.ext] some_public_function was called with x: ", x)
return x ** x
# Any class derived from `omni.ext.IExt` in top level module (defined in `python.modules` of `extension.toml`) will be
# instantiated when extension gets enabled and `on_startup(ext_id)` will be called. Later when extension gets disabled
# on_shutdown() is called.
class MySpawn_primsExtExtension(omni.ext.IExt):
# ext_id is current extension id. It can be used with extension manager to query additional information, like where
# this extension is located on filesystem.
def on_startup(self, ext_id):
print("[my.spawn_prims.ext] my spawn_prims ext startup")
self._count = 0
self._window = ui.Window("My Window", width=300, height=300)
with self._window.frame:
with ui.VStack():
label = ui.Label("")
def on_click():
self._count += 1
label.text = f"count: {self._count}"
def on_reset():
self._count = 0
label.text = "empty"
on_reset()
with ui.HStack():
ui.Button("Add", clicked_fn=on_click)
ui.Button("Reset", clicked_fn=on_reset)
def on_shutdown(self):
print("[my.spawn_prims.ext] my spawn_prims ext shutdown")
```
Next, change some values to better reflect what your Extension does.
### Step 3.2: Update the Window Title
Initialize `ui.Window` with the title "Spawn Primitives", instead of "My window":
``` python
self._window = ui.Window("Spawn Primitives", width=300, height=300)
```
### Step 3.3: Remove the Label and Reset Functionality
Remove the following lines and add `pass` inside `on_click()`
``` python
def on_startup(self, ext_id):
print("[my.spawn_prims.ext] my spawn_prims ext startup")
self._count = 0 # DELETE THIS LINE
self._window = ui.Window("Spawn Primitives", width=300, height=300)
with self._window.frame:
with ui.VStack():
label = ui.Label("") # DELETE THIS LINE
def on_click():
pass # ADD THIS LINE
self._count += 1 # DELETE THIS LINE
label.text = f"count: {self._count}" # DELETE THIS LINE
def on_reset(): # DELETE THIS LINE
self._count = 0 # DELETE THIS LINE
label.text = "empty" # DELETE THIS LINE
on_reset() # DELETE THIS LINE
with ui.HStack():
ui.Button("Add", clicked_fn=on_click)
ui.Button("Reset", clicked_fn=on_reset) # DELETE THIS LINE
```
What your code should look like after removing the lines:
``` python
def on_startup(self, ext_id):
print("[my.spawn_prims.ext] my spawn_prims ext startup")
self._window = ui.Window("Spawn Primitives", width=300, height=300)
with self._window.frame:
with ui.VStack():
def on_click():
pass
with ui.HStack():
ui.Button("Add", clicked_fn=on_click)
```
### Step 3.4: Update the Button Text
Update the `Button` text to "Spawn Cube".
``` python
ui.Button("Spawn Cube", clicked_fn=on_click)
```
### Step 3.5: Review Your Changes
After making the above changes, your code should read as follows:
``` python
import omni.ext
import omni.ui as ui
# Functions and vars are available to other extension as usual in python: `example.python_ext.some_public_function(x)`
def some_public_function(x: int):
print("[my.spawn_prims.ext] some_public_function was called with x: ", x)
return x ** x
# Any class derived from `omni.ext.IExt` in top level module (defined in `python.modules` of `extension.toml`) will be
# instantiated when extension gets enabled and `on_startup(ext_id)` will be called. Later when extension gets disabled
# on_shutdown() is called.
class MySpawn_primsExtExtension(omni.ext.IExt):
# ext_id is current extension id. It can be used with extension manager to query additional information, like where
# this extension is located on filesystem.
def on_startup(self, ext_id):
print("[my.spawn_prims.ext] my spawn_prims ext startup")
self._window = ui.Window("Spawn Primitives", width=300, height=300)
with self._window.frame:
with ui.VStack():
def on_click():
pass
with ui.HStack():
ui.Button("Spawn Cube", clicked_fn=on_click)
def on_shutdown(self):
print("[my.spawn_prims.ext] my spawn_prims ext shutdown")
```
Save the file, and return to Omniverse. There, you'll see your new window with a large button saying "Spawn Cube".

### Step 4: Dock the Extension Window
Omniverse allows you to move Extensions and dock them in any location. To do so, click and drag your window to the desired location.

## Step 5: Prepare Your Commands Window
Commands are actions that take place inside Omniverse. A simple command could be creating an object or changing a color. Commands are composed of a `do` and an `undo` feature. To read more about what commands are and how to create custom commands, read our [documentation](https://docs.omniverse.nvidia.com/kit/docs/omni.kit.commands/latest/Overview.html).
Omniverse allows users and developers to see what commands are being executed as they work in the application. You can find this information in the *Commands* window:

You'll use this window to quickly build out command-based functionality.
> > **Note:** If you don't see the *Commands* window, make sure it is enabled in the Extension Manager / Extension Window by searching for `omni.kit.window.commands`. Then go to **Window > Commands**
### Step 5.1: Move Your Commands Window
Move the Commands window to get a better view, or dock it somewhere convenient:

### Step 5.2: Clear Old Commands
Select the **Clear History** button in the *Commands* window. This makes it easier to see what action takes place when you try to create a cube:

### Step 6: Getting the Command Code
Now that you have the necessary tools, you learn how you can grab one of these commands and use it in the extension. Specifically, you use it create a cube. There are different ways you can create the cube, but for this example, you use **Create** menu in the top bar.
### Step 6.1: Create a Cube
Click **Create > Mesh > Cube** from the top bar:

If the *Create Menu* is not avaliable, go to *Stage Window* and **Right Click > Create > Mesh > Cube**

In the *Viewport*, you'll see your new cube. In the *Commands Window*, you'll see a new command.
> **Note:** If you cannot see the Cube try adding a light to the stage. **Create > Light > Distant Light**
### Step 6.2: Copy the Create Mesh Command
Select the new line **CreateMeshPrimWithDefaultXform** in the Command Window, then click **Selected Commands** to copy the command to the clipboard:

### Step 6.3: Use the Command in Your Extension
Paste the copied command into `on_click()`. The whole file looks like this:
``` python
import omni.ext
import omni.ui as ui
# Functions and vars are available to other extension as usual in python: `example.python_ext.some_public_function(x)`
def some_public_function(x: int):
print("[my.spawn_prims.ext] some_public_function was called with x: ", x)
return x ** x
# Any class derived from `omni.ext.IExt` in top level module (defined in `python.modules` of `extension.toml`) will be
# instantiated when extension gets enabled and `on_startup(ext_id)` will be called. Later when extension gets disabled
# on_shutdown() is called.
class MySpawn_primsExtExtension(omni.ext.IExt):
# ext_id is current extension id. It can be used with extension manager to query additional information, like where
# this extension is located on filesystem.
def on_startup(self, ext_id):
print("[my.spawn_prims.ext] my spawn_prims ext startup")
self._window = ui.Window("Spawn Primitives", width=300, height=300)
with self._window.frame:
with ui.VStack():
def on_click():
import omni.kit.commands
omni.kit.commands.execute('CreateMeshPrimWithDefaultXform',
prim_type='Cube',
above_ground=True)
with ui.HStack():
ui.Button("Spawn Cube", clicked_fn=on_click)
def on_shutdown(self):
print("[my.spawn_prims.ext] my spawn_prims ext shutdown")
```
You added a new import and a command that creates a cube.
### Step 6.4: Group Your Imports
Move the import statement to the top of the module with the other imports:
```python
import omni.ext
import omni.ui as ui
import omni.kit.commands
```
### Step 6.5: Relocate Create Command
Place `omni.kit.commands.execute()` inside the `on_click()` definition and remove `pass`.
``` python
def on_click():
omni.kit.commands.execute('CreateMeshPrimWithDefaultXform',
prim_type='Cube',
above_ground=True)
```
### Step 6.6: Review and Save
Ensure your code matches ours:
``` python
import omni.ext
import omni.ui as ui
import omni.kit.commands
# Functions and vars are available to other extension as usual in python: `example.python_ext.some_public_function(x)`
def some_public_function(x: int):
print("[my.spawn_prims.ext] some_public_function was called with x: ", x)
return x ** x
# Any class derived from `omni.ext.IExt` in top level module (defined in `python.modules` of `extension.toml`) will be
# instantiated when extension gets enabled and `on_startup(ext_id)` will be called. Later when extension gets disabled
# on_shutdown() is called.
class MySpawn_primsExtExtension(omni.ext.IExt):
# ext_id is current extension id. It can be used with extension manager to query additional information, like where
# this extension is located on filesystem.
def on_startup(self, ext_id):
print("[my.spawn_prims.ext] my spawn_prims ext startup")
self._window = ui.Window("Spawn Primitives", width=300, height=300)
with self._window.frame:
with ui.VStack():
def on_click():
omni.kit.commands.execute('CreateMeshPrimWithDefaultXform',
prim_type='Cube',
above_ground=True)
with ui.HStack():
ui.Button("Spawn Cube", clicked_fn=on_click)
def on_shutdown(self):
print("[my.spawn_prims.ext] my spawn_prims ext shutdown")
```
Save your code, and switch back to Omniverse.
### Step 7: Test Your Work
In Omniverse, test your extension by clicking **Spawn Cube**. You should see that a new Cube prim is created with each button press.

Excellent, you now know how to spawn a cube using a function. What's more, you didn't have to reference anything as Omniverse was kind enough to deliver everything you needed.
Continuing on and via same methods, construct a second button that spawns a cone in the same interface.
## Step 8: Spawn a Cone
In this step, you create a new button that spawns a cone.
### Step 8.1: Add a Button
Create a new button below the spawn cube button to spawn a cone:
```python
def on_startup(self, ext_id):
print("[omni.example.spawn_prims] MyExtension startup")
self._window = ui.Window("Spawn Primitives", width=300, height=300)
with self._window.frame:
with ui.VStack():
def on_click():
omni.kit.commands.execute('CreateMeshPrimWithDefaultXform',
prim_type='Cube',
above_ground=True)
ui.Button("Spawn Cube", clicked_fn=on_click)
ui.Button("Spawn Cone", clicked_fn=on_click)
```
### Step 8.2: Save and Review
Save the file, switch back to Omniverse, and test your new button:

Notice that both buttons use the same function and, therefore, both spawn a `Cube`, despite their labels.
### Step 8.3: Create a Cone from the Menu
Using the same *Create* menu in Omniverse, create a Cone (**Create > Mesh > Cone**).
### Step 8.4: Copy the Commands to your Extension
Copy the command in the *Commands* tab with the **Selected Commands** button.
### Step 8.5: Implement Your New Button
Paste the command into `extensions.py` like you did before:

``` python
def on_click():
#Create a Cube
omni.kit.commands.execute('CreateMeshPrimWithDefaultXform',
prim_type='Cube',
above_ground=True)
#Create a Cone
omni.kit.commands.execute('CreateMeshPrimWithDefaultXform',
prim_type='Cone',
above_ground=True)
```
Notice the command is the same, and only the `prim_type` is different:
- To spawn a cube, you pass `'Cube'`
- To spawn a cone, you pass `'Cone'`
### Step 8.6: Accept a Prim Type in `on_click()`
Add a `prim_type` argument to `on_click()`:
``` python
def on_click(prim_type):
```
With this value, you can delete the second `omni.kit.commands.execute()` call. Next, you'll use `prim_type` to determine what shape to create.
### Step 8.7: Use the Prim Type in `on_click()`
Replace `prim_type='Cube'` with `prim_type=prim_type`:
``` python
omni.kit.commands.execute('CreateMeshPrimWithDefaultXform',
prim_type=prim_type,
above_ground=True)
```
`on_click()` should now look like this:
``` python
def on_click(prim_type):
omni.kit.commands.execute('CreateMeshPrimWithDefaultXform',
prim_type=prim_type,
above_ground=True)
```
### Step 8.8: Pass the Prim Type to `on_click()`
Update the `clicked_fn` for both UI Buttons to pass the `prim_type`:
``` python
ui.Button("Spawn Cube", clicked_fn=on_click("Cube"))
ui.Button("Spawn Cone", clicked_fn=on_click("Cone"))
```
### Step 8.9: Save and Test
Save the file, and test the updates to your *Spawn Primitives* Extension:

## Step 9: Conclusion
Great job! You've successfully created a second button that spawns a second mesh, all within the same Extension. This, of course, can be expanded upon.
> **Optional Challenge:** Add a button for every mesh type on your own.
>
> 
>
> Below you can find a completed "cheat sheet" if you need help or just want to copy it for your own use.
>
> <details>
> <summary><b>Click to show the final code</b></summary>
>
> ```
> import omni.ext
> import omni.ui as ui
> import omni.kit.commands
>
> # Functions and vars are available to other extension as usual in python: `example.python_ext some_public_function(x)`
> def some_public_function(x: int):
> print("[my.spawn_prims.ext] some_public_function was called with x: ", x)
> return x ** x
>
> # Any class derived from `omni.ext.IExt` in top level module (defined in `python.modules` of `extension.toml`) will be
> # instantiated when extension gets enabled and `on_startup(ext_id)` will be called. Later when extension gets disabled
> # on_shutdown() is called.
> class MyExtension(omni.ext.IExt):
> # ext_id is current extension id. It can be used with extension manager to query additional information, like where
> # this extension is located on filesystem.
> def on_startup(self, ext_id):
> print("[omni.example.spawn_prims] MyExtension startup")
>
> self._window = ui.Window("Spawn Primitives", width=300, height=300)
> with self._window.frame:
> with ui.VStack():
>
> def on_click(prim_type):
> omni.kit.commands.execute('CreateMeshPrimWithDefaultXform',
> prim_type=prim_type,
> above_ground=True)
>
> ui.Button("Spawn Cube", clicked_fn=on_click("Cube"))
> ui.Button("Spawn Cone", clicked_fn=on_click("Cone"))
> ui.Button("Spawn Cylinder", clicked_fn=on_click("Cylinder"))
> ui.Button("Spawn Disk", clicked_fn=on_click("Disk"))
> ui.Button("Spawn Plane", clicked_fn=on_click("Plane"))
> ui.Button("Spawn Sphere", clicked_fn=on_click("Sphere"))
> ui.Button("Spawn Torus", clicked_fn=on_click("Torus"))
>
> def on_shutdown(self):
> print("[omni.example.spawn_prims] MyExtension shutdown")
> ```
>
> </details> | 21,379 | Markdown | 34.164474 | 356 | 0.683662 |
NVIDIA-Omniverse/kit-extension-sample-spawn-prims/exts/omni.example.spawn_prims/omni/example/spawn_prims/extension.py | # Copyright (c) 2023, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
import omni.ext
import omni.ui as ui
import omni.kit.commands
# Any class derived from `omni.ext.IExt` in top level module (defined in `python.modules` of `extension.toml`) will be
# instantiated when extension gets enabled and `on_startup(ext_id)` will be called. Later when extension gets disabled
# on_shutdown() is called.
class MyExtension(omni.ext.IExt):
# ext_id is current extension id. It can be used with extension manager to query additional information, like where
# this extension is located on filesystem.
def on_startup(self, ext_id):
"""
Called when MyExtension starts.
Args:
ext_id : id of the extension that is
"""
print("[omni.example.spawn_prims] MyExtension startup")
self._window = ui.Window("Spawn Primitives", width=300, height=300)
with self._window.frame:
# VStack which will layout UI elements vertically
with ui.VStack():
def on_click(prim_type):
"""
Creates a mesh primitive of the given type.
Args:
prim_type : The type of primitive to
"""
# omni.kit.commands.execute will execute the given command that is passed followed by the commands arguments
omni.kit.commands.execute('CreateMeshPrimWithDefaultXform',
prim_type=prim_type,
above_ground=True)
# Button UI Elements
ui.Button("Spawn Cube", clicked_fn=lambda: on_click("Cube"))
ui.Button("Spawn Cone", clicked_fn=lambda: on_click("Cone"))
ui.Button("Spawn Cylinder", clicked_fn=lambda: on_click("Cylinder"))
ui.Button("Spawn Disk", clicked_fn=lambda: on_click("Disk"))
ui.Button("Spawn Plane", clicked_fn=lambda: on_click("Plane"))
ui.Button("Spawn Sphere", clicked_fn=lambda: on_click("Sphere"))
ui.Button("Spawn Torus", clicked_fn=lambda: on_click("Torus"))
def on_shutdown(self):
"""
Called when the extension is shutting down.
"""
print("[omni.example.spawn_prims] MyExtension shutdown")
| 2,742 | Python | 46.293103 | 128 | 0.61488 |
NVIDIA-Omniverse/kit-extension-sample-spawn-prims/exts/omni.example.spawn_prims/docs/README.md | # Spawn Primitives (omni.example.spawn_prims)

## Overview
The Spawn Primitives Sample extension creates a new window and has a button for each primitive type. Selecting these buttons will spawn in a primitive corresponding to the label on the button.
See [Adding the Extension](../../../README.md#adding-this-extension) on how to add the extension to your project.
## [Tutorial](../tutorial/tutorial.md)
This extension sample also includes a step-by-step tutorial to accelerate your growth as you learn to build your own
Omniverse Kit extensions. [Get started with the tutorial.](../tutorial/tutorial.md)
## Usage
### Spawn Primitives
* Click on the **Cube**, **Disk**, **Cone**, etc buttons to spawn the corresponding primitive.
| 792 | Markdown | 45.647056 | 193 | 0.756313 |
NVIDIA-Omniverse/mjcf-importer-extension/repo.toml | ########################################################################################################################
# Repo tool base settings
########################################################################################################################
[repo]
# Use the Kit Template repo configuration as a base. Only override things specific to the repo.
import_configs = ["${root}/_repo/deps/repo_kit_tools/kit-template/repo.toml"]
# Repository Name
name = "omniverse-mjcf-importer"
[repo_build.msbuild]
vs_version = "vs2019"
[repo_build]
# List of packman projects to pull (in order)
fetch.packman_host_files_to_pull = [
"${root}/deps/host-deps.packman.xml",
]
fetch.packman_target_files_to_pull = [
"${root}/deps/kit-sdk.packman.xml",
"${root}/deps/rtx-plugins.packman.xml",
"${root}/deps/omni-physics.packman.xml",
"${root}/deps/kit-sdk-deps.packman.xml",
"${root}/deps/omni-usd-resolver.packman.xml",
"${root}/deps/ext-deps.packman.xml",
]
post_build.commands = [
# TODO, fix this?
# ["${root}/repo${shell_ext}", "stubgen", "-c", "${config}"]
]
[repo_docs]
name = "Omniverse MJCF Importer"
project = "omniverse-mjcf-importer"
api_output_directory = "api"
use_fast_doxygen_conversion=false
sphinx_version = "4.5.0.2-py3.10-${platform}"
sphinx_exclude_patterns = [
"_build",
"tools",
"VERSION.md",
"source/extensions/omni.importer.mjcf/PACKAGE-LICENSES",
]
sphinx_conf_py_extra = """
autodoc_mock_imports = ["omni.client", "omni.kit"]
autodoc_member_order = 'bysource'
"""
[repo_package.packages."platform:windows-x86_64".docs]
windows_max_path_length = 0
[repo_publish_exts]
enabled = true
use_packman_to_upload_archive = false
exts.include = [
"omni.importer.mjcf",
]
| 1,768 | TOML | 25.402985 | 120 | 0.582014 |
NVIDIA-Omniverse/mjcf-importer-extension/README.md | # Omniverse MJCF Importer
The MJCF Importer Extension is used to import MuJoCo representations of scenes.
MuJoCo Modeling XML File (MJCF), is an XML format for representing a scene in the MuJoCo simulator.
## Getting Started
1. Clone the GitHub repo to your local machine.
2. Open a command prompt and navigate to the root of your cloned repo.
3. Run `build.bat` to bootstrap your dev environment and build the example extensions.
4. Run `_build\{platform}\release\omni.importer.mjcf.app.bat` to start the Kit application.
5. From the menu, select `Isaac Utils->MJCF Importer` to launch the UI for the MJCF Importer extension.
This extension is enabled by default. If it is ever disabled, it can be re-enabled from the Extension Manager
by searching for `omni.importer.mjcf`.
**Note:** On Linux, replace `.bat` with `.sh` in the instructions above.
## Conventions
Special characters in link or joint names are not supported and will be replaced with an underscore. In the event that the name starts with an underscore due to the replacement, an a is pre-pended. It is recommended to make these name changes in the mjcf directly.
See the [Convention References](https://docs.omniverse.nvidia.com/app_isaacsim/app_isaacsim/reference_conventions.html#isaac-sim-conventions) documentation for a complete list of `Isaac Sim` conventions.
## User Interface

### Configuration Options
* **Fix Base Link**: When checked, every world body will have its base fixed where it is placed in world coordinates.
* **Import Inertia Tensor**: Check to load inertia from mjcf directly. If the mjcf does not specify an inertia tensor, identity will be used and scaled by the scaling factor. If unchecked, Physx will compute it automatically.
* **Stage Units Per Meter**: The default length unit is meters. Here you can set the scaling factor to match the unit used in your MJCF.
* **Link Density**: If a link does not have a given mass, it uses this density (in Kg/m^3) to compute mass based on link volume. A value of 0.0 can be used to tell the physics engine to automatically compute density as well.
* **Clean Stage**: When checked, cleans the stage before loading the new MJCF, otherwise loads it on current open stage at position `(0,0,0)`
* **Self Collision**: Enables self collision between adjacent links. It may cause instability if the collision meshes are intersecting at the joint.
* **Create Physics Scene**: Creates a default physics scene on the stage. Because this physics scene is created outside of the scene asset, it will not be loaded into other scenes composed with the robot asset.
**Note:** It is recommended to set Self Collision to false unless you are certain that links on the robot are not self colliding
## Robot Properties
There might be many properties you want to tune on your robot. These properties can be spread across many different Schemas and APIs.
The general steps of getting and setting a parameter are:
1. Find which API is the parameter under. Most common ones can be found in the [Pixar USD API](https://docs.omniverse.nvidia.com/kit/docs/kit-manual/latest/api/pxr_index.html).
2. Get the prim handle that the API is applied to. For example, Articulation and Drive APIs are applied to joints, and MassAPIs are applied to the rigid bodies.
3. Get the handle to the API. From there on, you can Get or Set the attributes associated with that API.
For example, if we want to set the wheel's drive velocity and the actuators' stiffness, we need to find the DriveAPI:
```python
# get handle to the Drive API for both wheels
left_wheel_drive = UsdPhysics.DriveAPI.Get(stage.GetPrimAtPath("/carter/chassis_link/left_wheel"), "angular")
right_wheel_drive = UsdPhysics.DriveAPI.Get(stage.GetPrimAtPath("/carter/chassis_link/right_wheel"), "angular")
# Set the velocity drive target in degrees/second
left_wheel_drive.GetTargetVelocityAttr().Set(150)
right_wheel_drive.GetTargetVelocityAttr().Set(150)
# Set the drive damping, which controls the strength of the velocity drive
left_wheel_drive.GetDampingAttr().Set(15000)
right_wheel_drive.GetDampingAttr().Set(15000)
# Set the drive stiffness, which controls the strength of the position drive
# In this case because we want to do velocity control this should be set to zero
left_wheel_drive.GetStiffnessAttr().Set(0)
right_wheel_drive.GetStiffnessAttr().Set(0)
```
Alternatively you can use the [Omniverse Commands Tool](https://docs.omniverse.nvidia.com/app_isaacsim/app_isaacsim/ext_omni_kit_commands.html#isaac-sim-command-tool) to change a value in the UI and get the associated Omniverse command that changes the property.
**Note:**
- The drive stiffness parameter should be set when using position control on a joint drive.
- The drive damping parameter should be set when using velocity control on a joint drive.
- A combination of setting stiffness and damping on a drive will result in both targets being applied, this can be useful in position control to reduce vibrations.
| 5,094 | Markdown | 59.654761 | 264 | 0.76914 |
NVIDIA-Omniverse/mjcf-importer-extension/index.rst | Omniverse MJCF Importer
=======================
.. mdinclude:: README.md
Extension Documentation
~~~~~~~~~~~~~~~~~~~~~~~~
.. toctree::
:maxdepth: 1
:glob:
source/extensions/omni.importer.mjcf/docs/index
source/extensions/omni.importer.mjcf/docs/Overview
source/extensions/omni.importer.mjcf/docs/CHANGELOG
| 324 | reStructuredText | 20.666665 | 54 | 0.648148 |
NVIDIA-Omniverse/mjcf-importer-extension/source/extensions/omni.importer.mjcf/python/scripts/style.py | # SPDX-FileCopyrightText: Copyright (c) 2023 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
# SPDX-License-Identifier: Apache-2.0
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import carb.settings
import omni.ui as ui
from omni.kit.window.extensions.common import get_icons_path
# Pilaged from omni.kit.widnow.property style.py
LABEL_WIDTH = 120
BUTTON_WIDTH = 120
HORIZONTAL_SPACING = 4
VERTICAL_SPACING = 5
COLOR_X = 0xFF5555AA
COLOR_Y = 0xFF76A371
COLOR_Z = 0xFFA07D4F
COLOR_W = 0xFFAA5555
def get_style():
icons_path = get_icons_path()
KIT_GREEN = 0xFF8A8777
KIT_GREEN_CHECKBOX = 0xFF9A9A9A
BORDER_RADIUS = 1.5
FONT_SIZE = 14.0
TOOLTIP_STYLE = (
{
"background_color": 0xFFD1F7FF,
"color": 0xFF333333,
"margin_width": 0,
"margin_height": 0,
"padding": 0,
"border_width": 0,
"border_radius": 1.5,
"border_color": 0x0,
},
)
style_settings = carb.settings.get_settings().get("/persistent/app/window/uiStyle")
if not style_settings:
style_settings = "NvidiaDark"
if style_settings == "NvidiaLight":
WINDOW_BACKGROUND_COLOR = 0xFF444444
BUTTON_BACKGROUND_COLOR = 0xFF545454
BUTTON_BACKGROUND_HOVERED_COLOR = 0xFF9E9E9E
BUTTON_BACKGROUND_PRESSED_COLOR = 0xC22A8778
BUTTON_LABEL_DISABLED_COLOR = 0xFF606060
FRAME_TEXT_COLOR = 0xFF545454
FIELD_BACKGROUND = 0xFF545454
FIELD_SECONDARY = 0xFFABABAB
FIELD_TEXT_COLOR = 0xFFD6D6D6
FIELD_TEXT_COLOR_READ_ONLY = 0xFF9C9C9C
FIELD_TEXT_COLOR_HIDDEN = 0x01000000
COLLAPSABLEFRAME_BORDER_COLOR = 0x0
COLLAPSABLEFRAME_BACKGROUND_COLOR = 0x7FD6D6D6
COLLAPSABLEFRAME_TEXT_COLOR = 0xFF545454
COLLAPSABLEFRAME_GROUPFRAME_BACKGROUND_COLOR = 0xFFC9C9C9
COLLAPSABLEFRAME_SUBFRAME_BACKGROUND_COLOR = 0xFFD6D6D6
COLLAPSABLEFRAME_HOVERED_BACKGROUND_COLOR = 0xFFCCCFBF
COLLAPSABLEFRAME_PRESSED_BACKGROUND_COLOR = 0xFF2E2E2B
COLLAPSABLEFRAME_HOVERED_SECONDARY_COLOR = 0xFFD6D6D6
COLLAPSABLEFRAME_PRESSED_SECONDARY_COLOR = 0xFFE6E6E6
LABEL_VECTORLABEL_COLOR = 0xFFDDDDDD
LABEL_MIXED_COLOR = 0xFFD6D6D6
LIGHT_FONT_SIZE = 14.0
LIGHT_BORDER_RADIUS = 3
style = {
"Window": {"background_color": WINDOW_BACKGROUND_COLOR},
"Button": {"background_color": BUTTON_BACKGROUND_COLOR, "margin": 0, "padding": 3, "border_radius": 2},
"Button:hovered": {"background_color": BUTTON_BACKGROUND_HOVERED_COLOR},
"Button:pressed": {"background_color": BUTTON_BACKGROUND_PRESSED_COLOR},
"Button.Label:disabled": {"color": 0xFFD6D6D6},
"Button.Label": {"color": 0xFFD6D6D6},
"Field::models": {
"background_color": FIELD_BACKGROUND,
"font_size": LIGHT_FONT_SIZE,
"color": FIELD_TEXT_COLOR,
"border_radius": LIGHT_BORDER_RADIUS,
"secondary_color": FIELD_SECONDARY,
},
"Field::models_mixed": {
"background_color": FIELD_BACKGROUND,
"font_size": LIGHT_FONT_SIZE,
"color": FIELD_TEXT_COLOR_HIDDEN,
"border_radius": LIGHT_BORDER_RADIUS,
},
"Field::models_readonly": {
"background_color": FIELD_BACKGROUND,
"font_size": LIGHT_FONT_SIZE,
"color": FIELD_TEXT_COLOR_READ_ONLY,
"border_radius": LIGHT_BORDER_RADIUS,
"secondary_color": FIELD_SECONDARY,
},
"Field::models_readonly_mixed": {
"background_color": FIELD_BACKGROUND,
"font_size": LIGHT_FONT_SIZE,
"color": FIELD_TEXT_COLOR_HIDDEN,
"border_radius": LIGHT_BORDER_RADIUS,
},
"Field::models:pressed": {"background_color": 0xFFCECECE},
"Field": {"background_color": 0xFF535354, "color": 0xFFCCCCCC},
"Label": {"font_size": 12, "color": FRAME_TEXT_COLOR},
"Label::label:disabled": {"color": BUTTON_LABEL_DISABLED_COLOR},
"Label::label": {
"font_size": LIGHT_FONT_SIZE,
"background_color": FIELD_BACKGROUND,
"color": FRAME_TEXT_COLOR,
},
"Label::title": {
"font_size": LIGHT_FONT_SIZE,
"background_color": FIELD_BACKGROUND,
"color": FRAME_TEXT_COLOR,
},
"Label::mixed_overlay": {
"font_size": LIGHT_FONT_SIZE,
"background_color": FIELD_BACKGROUND,
"color": FRAME_TEXT_COLOR,
},
"Label::mixed_overlay_normal": {
"font_size": LIGHT_FONT_SIZE,
"background_color": FIELD_BACKGROUND,
"color": FRAME_TEXT_COLOR,
},
"ComboBox::choices": {
"font_size": 12,
"color": 0xFFD6D6D6,
"background_color": FIELD_BACKGROUND,
"secondary_color": FIELD_BACKGROUND,
"border_radius": LIGHT_BORDER_RADIUS * 2,
},
"ComboBox::xform_op": {
"font_size": 10,
"color": 0xFF333333,
"background_color": 0xFF9C9C9C,
"secondary_color": 0x0,
"selected_color": 0xFFACACAF,
"border_radius": LIGHT_BORDER_RADIUS * 2,
},
"ComboBox::xform_op:hovered": {"background_color": 0x0},
"ComboBox::xform_op:selected": {"background_color": 0xFF545454},
"ComboBox": {
"font_size": 10,
"color": 0xFFE6E6E6,
"background_color": 0xFF545454,
"secondary_color": 0xFF545454,
"selected_color": 0xFFACACAF,
"border_radius": LIGHT_BORDER_RADIUS * 2,
},
# "ComboBox": {"background_color": 0xFF535354, "selected_color": 0xFFACACAF, "color": 0xFFD6D6D6},
"ComboBox:hovered": {"background_color": 0xFF545454},
"ComboBox:selected": {"background_color": 0xFF545454},
"ComboBox::choices_mixed": {
"font_size": LIGHT_FONT_SIZE,
"color": 0xFFD6D6D6,
"background_color": FIELD_BACKGROUND,
"secondary_color": FIELD_BACKGROUND,
"secondary_selected_color": FIELD_TEXT_COLOR,
"border_radius": LIGHT_BORDER_RADIUS * 2,
},
"ComboBox:hovered:choices": {"background_color": FIELD_BACKGROUND, "secondary_color": FIELD_BACKGROUND},
"Slider": {
"font_size": LIGHT_FONT_SIZE,
"color": FIELD_TEXT_COLOR,
"border_radius": LIGHT_BORDER_RADIUS,
"background_color": FIELD_BACKGROUND,
"secondary_color": WINDOW_BACKGROUND_COLOR,
"draw_mode": ui.SliderDrawMode.FILLED,
},
"Slider::value": {
"font_size": LIGHT_FONT_SIZE,
"color": FIELD_TEXT_COLOR, # COLLAPSABLEFRAME_TEXT_COLOR
"border_radius": LIGHT_BORDER_RADIUS,
"background_color": FIELD_BACKGROUND,
"secondary_color": KIT_GREEN,
},
"Slider::value_mixed": {
"font_size": LIGHT_FONT_SIZE,
"color": FIELD_TEXT_COLOR_HIDDEN,
"border_radius": LIGHT_BORDER_RADIUS,
"background_color": FIELD_BACKGROUND,
"secondary_color": KIT_GREEN,
},
"Slider::multivalue": {
"font_size": LIGHT_FONT_SIZE,
"color": FIELD_TEXT_COLOR,
"border_radius": LIGHT_BORDER_RADIUS,
"background_color": FIELD_BACKGROUND,
"secondary_color": KIT_GREEN,
"draw_mode": ui.SliderDrawMode.HANDLE,
},
"Slider::multivalue_mixed": {
"font_size": LIGHT_FONT_SIZE,
"color": FIELD_TEXT_COLOR_HIDDEN,
"border_radius": LIGHT_BORDER_RADIUS,
"background_color": FIELD_BACKGROUND,
"secondary_color": KIT_GREEN,
"draw_mode": ui.SliderDrawMode.HANDLE,
},
"Checkbox": {
"margin": 0,
"padding": 0,
"radius": 0,
"font_size": 10,
"background_color": 0xFFA8A8A8,
"background_color": 0xFFA8A8A8,
},
"CheckBox::greenCheck": {"font_size": 10, "background_color": KIT_GREEN, "color": 0xFF23211F},
"CheckBox::greenCheck_mixed": {
"font_size": 10,
"background_color": KIT_GREEN,
"color": FIELD_TEXT_COLOR_HIDDEN,
"border_radius": LIGHT_BORDER_RADIUS,
},
"CollapsableFrame": {
"background_color": COLLAPSABLEFRAME_BACKGROUND_COLOR,
"secondary_color": COLLAPSABLEFRAME_BACKGROUND_COLOR,
"color": COLLAPSABLEFRAME_TEXT_COLOR,
"border_radius": LIGHT_BORDER_RADIUS,
"border_color": 0x0,
"border_width": 1,
"font_size": LIGHT_FONT_SIZE,
"padding": 6,
"Tooltip": TOOLTIP_STYLE,
},
"CollapsableFrame::groupFrame": {
"background_color": COLLAPSABLEFRAME_GROUPFRAME_BACKGROUND_COLOR,
"secondary_color": COLLAPSABLEFRAME_GROUPFRAME_BACKGROUND_COLOR,
"border_radius": BORDER_RADIUS * 2,
"padding": 6,
},
"CollapsableFrame::groupFrame:hovered": {
"background_color": COLLAPSABLEFRAME_GROUPFRAME_BACKGROUND_COLOR,
"secondary_color": COLLAPSABLEFRAME_GROUPFRAME_BACKGROUND_COLOR,
},
"CollapsableFrame::groupFrame:pressed": {
"background_color": COLLAPSABLEFRAME_GROUPFRAME_BACKGROUND_COLOR,
"secondary_color": COLLAPSABLEFRAME_GROUPFRAME_BACKGROUND_COLOR,
},
"CollapsableFrame::subFrame": {
"background_color": COLLAPSABLEFRAME_SUBFRAME_BACKGROUND_COLOR,
"secondary_color": COLLAPSABLEFRAME_SUBFRAME_BACKGROUND_COLOR,
},
"CollapsableFrame::subFrame:hovered": {
"background_color": COLLAPSABLEFRAME_SUBFRAME_BACKGROUND_COLOR,
"secondary_color": COLLAPSABLEFRAME_HOVERED_BACKGROUND_COLOR,
},
"CollapsableFrame::subFrame:pressed": {
"background_color": COLLAPSABLEFRAME_SUBFRAME_BACKGROUND_COLOR,
"secondary_color": COLLAPSABLEFRAME_PRESSED_BACKGROUND_COLOR,
},
"CollapsableFrame.Header": {
"font_size": LIGHT_FONT_SIZE,
"background_color": FRAME_TEXT_COLOR,
"color": FRAME_TEXT_COLOR,
},
"CollapsableFrame:hovered": {"secondary_color": COLLAPSABLEFRAME_HOVERED_SECONDARY_COLOR},
"CollapsableFrame:pressed": {"secondary_color": COLLAPSABLEFRAME_PRESSED_SECONDARY_COLOR},
"ScrollingFrame": {"margin": 0, "padding": 3, "border_radius": LIGHT_BORDER_RADIUS},
"TreeView": {
"background_color": 0xFFE0E0E0,
"background_selected_color": 0x109D905C,
"secondary_color": 0xFFACACAC,
},
"TreeView.ScrollingFrame": {"background_color": 0xFFE0E0E0},
"TreeView.Header": {"color": 0xFFCCCCCC},
"TreeView.Header::background": {
"background_color": 0xFF535354,
"border_color": 0xFF707070,
"border_width": 0.5,
},
"TreeView.Header::columnname": {"margin": 3},
"TreeView.Image::object_icon_grey": {"color": 0x80FFFFFF},
"TreeView.Item": {"color": 0xFF535354, "font_size": 16},
"TreeView.Item::object_name": {"margin": 3},
"TreeView.Item::object_name_grey": {"color": 0xFFACACAC},
"TreeView.Item::object_name_missing": {"color": 0xFF6F72FF},
"TreeView.Item:selected": {"color": 0xFF2A2825},
"TreeView:selected": {"background_color": 0x409D905C},
"Label::vector_label": {"font_size": 14, "color": LABEL_VECTORLABEL_COLOR},
"Rectangle::vector_label": {"border_radius": BORDER_RADIUS * 2, "corner_flag": ui.CornerFlag.LEFT},
"Rectangle::mixed_overlay": {
"border_radius": LIGHT_BORDER_RADIUS,
"background_color": FIELD_BACKGROUND,
"border_width": 3,
},
"Rectangle": {
"border_radius": LIGHT_BORDER_RADIUS,
"color": 0xFFC2C2C2,
"background_color": 0xFFC2C2C2,
}, # FIELD_BACKGROUND},
"Rectangle::xform_op:hovered": {"background_color": 0x0},
"Rectangle::xform_op": {"background_color": 0x0},
# text remove
"Button::remove": {"background_color": FIELD_BACKGROUND, "margin": 0},
"Button::remove:hovered": {"background_color": FIELD_BACKGROUND},
"Button::options": {"background_color": 0x0, "margin": 0},
"Button.Image::options": {"image_url": f"{icons_path}/options.svg", "color": 0xFF989898},
"Button.Image::options:hovered": {"color": 0xFFC2C2C2},
"IconButton": {"margin": 0, "padding": 0, "background_color": 0x0},
"IconButton:hovered": {"background_color": 0x0},
"IconButton:checked": {"background_color": 0x0},
"IconButton:pressed": {"background_color": 0x0},
"IconButton.Image": {"color": 0xFFA8A8A8},
"IconButton.Image:hovered": {"color": 0xFF929292},
"IconButton.Image:pressed": {"color": 0xFFA4A4A4},
"IconButton.Image:checked": {"color": 0xFFFFFFFF},
"IconButton.Tooltip": {"color": 0xFF9E9E9E},
"IconButton.Image::OpenFolder": {
"image_url": f"{icons_path}/open-folder.svg",
"background_color": 0x0,
"color": 0xFFA8A8A8,
"tooltip": TOOLTIP_STYLE,
},
"IconButton.Image::OpenConfig": {
"image_url": f"{icons_path}/open-config.svg",
"background_color": 0x0,
"color": 0xFFA8A8A8,
"tooltip": TOOLTIP_STYLE,
},
"IconButton.Image::OpenLink": {
"image_url": "resources/glyphs/link.svg",
"background_color": 0x0,
"color": 0xFFA8A8A8,
"tooltip": TOOLTIP_STYLE,
},
"IconButton.Image::OpenDocs": {
"image_url": "resources/glyphs/docs.svg",
"background_color": 0x0,
"color": 0xFFA8A8A8,
"tooltip": TOOLTIP_STYLE,
},
"IconButton.Image::CopyToClipboard": {
"image_url": "resources/glyphs/copy.svg",
"background_color": 0x0,
"color": 0xFFA8A8A8,
},
"IconButton.Image::Export": {
"image_url": f"{icons_path}/export.svg",
"background_color": 0x0,
"color": 0xFFA8A8A8,
},
"IconButton.Image::Sync": {
"image_url": "resources/glyphs/sync.svg",
"background_color": 0x0,
"color": 0xFFA8A8A8,
},
"IconButton.Image::Upload": {
"image_url": "resources/glyphs/upload.svg",
"background_color": 0x0,
"color": 0xFFA8A8A8,
},
"IconButton.Image::FolderPicker": {
"image_url": "resources/glyphs/folder.svg",
"background_color": 0x0,
"color": 0xFFA8A8A8,
},
"ItemButton": {"padding": 2, "background_color": 0xFF444444, "border_radius": 4},
"ItemButton.Image::add": {"image_url": f"{icons_path}/plus.svg", "color": 0xFF06C66B},
"ItemButton.Image::remove": {"image_url": f"{icons_path}/trash.svg", "color": 0xFF1010C6},
"ItemButton:hovered": {"background_color": 0xFF333333},
"ItemButton:pressed": {"background_color": 0xFF222222},
"Tooltip": TOOLTIP_STYLE,
}
else:
LABEL_COLOR = 0xFF8F8E86
FIELD_BACKGROUND = 0xFF23211F
FIELD_TEXT_COLOR = 0xFFD5D5D5
FIELD_TEXT_COLOR_READ_ONLY = 0xFF5C5C5C
FIELD_TEXT_COLOR_HIDDEN = 0x01000000
FRAME_TEXT_COLOR = 0xFFCCCCCC
WINDOW_BACKGROUND_COLOR = 0xFF444444
BUTTON_BACKGROUND_COLOR = 0xFF292929
BUTTON_BACKGROUND_HOVERED_COLOR = 0xFF9E9E9E
BUTTON_BACKGROUND_PRESSED_COLOR = 0xC22A8778
BUTTON_LABEL_DISABLED_COLOR = 0xFF606060
LABEL_LABEL_COLOR = 0xFF9E9E9E
LABEL_TITLE_COLOR = 0xFFAAAAAA
LABEL_MIXED_COLOR = 0xFFE6B067
LABEL_VECTORLABEL_COLOR = 0xFFDDDDDD
COLORWIDGET_BORDER_COLOR = 0xFF1E1E1E
COMBOBOX_HOVERED_BACKGROUND_COLOR = 0xFF33312F
COLLAPSABLEFRAME_BORDER_COLOR = 0x0
COLLAPSABLEFRAME_BACKGROUND_COLOR = 0xFF343432
COLLAPSABLEFRAME_GROUPFRAME_BACKGROUND_COLOR = 0xFF23211F
COLLAPSABLEFRAME_SUBFRAME_BACKGROUND_COLOR = 0xFF343432
COLLAPSABLEFRAME_HOVERED_BACKGROUND_COLOR = 0xFF2E2E2B
COLLAPSABLEFRAME_PRESSED_BACKGROUND_COLOR = 0xFF2E2E2B
style = {
"Window": {"background_color": WINDOW_BACKGROUND_COLOR},
"Button": {"background_color": BUTTON_BACKGROUND_COLOR, "margin": 0, "padding": 3, "border_radius": 2},
"Button:hovered": {"background_color": BUTTON_BACKGROUND_HOVERED_COLOR},
"Button:pressed": {"background_color": BUTTON_BACKGROUND_PRESSED_COLOR},
"Button.Label:disabled": {"color": BUTTON_LABEL_DISABLED_COLOR},
"Field::models": {
"background_color": FIELD_BACKGROUND,
"font_size": FONT_SIZE,
"color": FIELD_TEXT_COLOR,
"border_radius": BORDER_RADIUS,
},
"Field::models_mixed": {
"background_color": FIELD_BACKGROUND,
"font_size": FONT_SIZE,
"color": FIELD_TEXT_COLOR_HIDDEN,
"border_radius": BORDER_RADIUS,
},
"Field::models_readonly": {
"background_color": FIELD_BACKGROUND,
"font_size": FONT_SIZE,
"color": FIELD_TEXT_COLOR_READ_ONLY,
"border_radius": BORDER_RADIUS,
},
"Field::models_readonly_mixed": {
"background_color": FIELD_BACKGROUND,
"font_size": FONT_SIZE,
"color": FIELD_TEXT_COLOR_HIDDEN,
"border_radius": BORDER_RADIUS,
},
"Label": {"font_size": FONT_SIZE, "color": LABEL_COLOR},
"Label::label": {"font_size": FONT_SIZE, "color": LABEL_LABEL_COLOR},
"Label::label:disabled": {"color": BUTTON_LABEL_DISABLED_COLOR},
"Label::title": {"font_size": FONT_SIZE, "color": LABEL_TITLE_COLOR},
"Label::mixed_overlay": {"font_size": FONT_SIZE, "color": LABEL_MIXED_COLOR},
"Label::mixed_overlay_normal": {"font_size": FONT_SIZE, "color": FIELD_TEXT_COLOR},
"Label::path_label": {"font_size": FONT_SIZE, "color": LABEL_LABEL_COLOR},
"Label::stage_label": {"font_size": FONT_SIZE, "color": LABEL_LABEL_COLOR},
"ComboBox::choices": {
"font_size": FONT_SIZE,
"color": FIELD_TEXT_COLOR,
"background_color": FIELD_BACKGROUND,
"secondary_color": FIELD_BACKGROUND,
"secondary_selected_color": FIELD_TEXT_COLOR,
"border_radius": BORDER_RADIUS,
},
"ComboBox::choices_mixed": {
"font_size": FONT_SIZE,
"color": FIELD_TEXT_COLOR_HIDDEN,
"background_color": FIELD_BACKGROUND,
"secondary_color": FIELD_BACKGROUND,
"secondary_selected_color": FIELD_TEXT_COLOR,
"border_radius": BORDER_RADIUS,
},
"ComboBox:hovered:choices": {
"background_color": COMBOBOX_HOVERED_BACKGROUND_COLOR,
"secondary_color": COMBOBOX_HOVERED_BACKGROUND_COLOR,
},
"Slider": {
"font_size": FONT_SIZE,
"color": FIELD_TEXT_COLOR,
"border_radius": BORDER_RADIUS,
"background_color": FIELD_BACKGROUND,
"secondary_color": WINDOW_BACKGROUND_COLOR,
"draw_mode": ui.SliderDrawMode.FILLED,
},
"Slider::value": {
"font_size": FONT_SIZE,
"color": FIELD_TEXT_COLOR,
"border_radius": BORDER_RADIUS,
"background_color": FIELD_BACKGROUND,
"secondary_color": WINDOW_BACKGROUND_COLOR,
},
"Slider::value_mixed": {
"font_size": FONT_SIZE,
"color": FIELD_TEXT_COLOR_HIDDEN,
"border_radius": BORDER_RADIUS,
"background_color": FIELD_BACKGROUND,
"secondary_color": WINDOW_BACKGROUND_COLOR,
},
"Slider::multivalue": {
"font_size": FONT_SIZE,
"color": FIELD_TEXT_COLOR,
"border_radius": BORDER_RADIUS,
"background_color": FIELD_BACKGROUND,
"secondary_color": WINDOW_BACKGROUND_COLOR,
"draw_mode": ui.SliderDrawMode.HANDLE,
},
"Slider::multivalue_mixed": {
"font_size": FONT_SIZE,
"color": FIELD_TEXT_COLOR,
"border_radius": BORDER_RADIUS,
"background_color": FIELD_BACKGROUND,
"secondary_color": WINDOW_BACKGROUND_COLOR,
"draw_mode": ui.SliderDrawMode.HANDLE,
},
"CheckBox::greenCheck": {
"font_size": 12,
"background_color": KIT_GREEN_CHECKBOX,
"color": FIELD_BACKGROUND,
"border_radius": BORDER_RADIUS,
},
"CheckBox::greenCheck_mixed": {
"font_size": 12,
"background_color": KIT_GREEN_CHECKBOX,
"color": FIELD_TEXT_COLOR_HIDDEN,
"border_radius": BORDER_RADIUS,
},
"CollapsableFrame": {
"background_color": COLLAPSABLEFRAME_BACKGROUND_COLOR,
"secondary_color": COLLAPSABLEFRAME_BACKGROUND_COLOR,
"border_radius": BORDER_RADIUS * 2,
"border_color": COLLAPSABLEFRAME_BORDER_COLOR,
"border_width": 1,
"padding": 6,
},
"CollapsableFrame::groupFrame": {
"background_color": COLLAPSABLEFRAME_GROUPFRAME_BACKGROUND_COLOR,
"secondary_color": COLLAPSABLEFRAME_GROUPFRAME_BACKGROUND_COLOR,
"border_radius": BORDER_RADIUS * 2,
"padding": 6,
},
"CollapsableFrame::groupFrame:hovered": {
"background_color": COLLAPSABLEFRAME_GROUPFRAME_BACKGROUND_COLOR,
"secondary_color": COLLAPSABLEFRAME_GROUPFRAME_BACKGROUND_COLOR,
},
"CollapsableFrame::groupFrame:pressed": {
"background_color": COLLAPSABLEFRAME_GROUPFRAME_BACKGROUND_COLOR,
"secondary_color": COLLAPSABLEFRAME_GROUPFRAME_BACKGROUND_COLOR,
},
"CollapsableFrame::subFrame": {
"background_color": COLLAPSABLEFRAME_SUBFRAME_BACKGROUND_COLOR,
"secondary_color": COLLAPSABLEFRAME_SUBFRAME_BACKGROUND_COLOR,
},
"CollapsableFrame::subFrame:hovered": {
"background_color": COLLAPSABLEFRAME_SUBFRAME_BACKGROUND_COLOR,
"secondary_color": COLLAPSABLEFRAME_HOVERED_BACKGROUND_COLOR,
},
"CollapsableFrame::subFrame:pressed": {
"background_color": COLLAPSABLEFRAME_SUBFRAME_BACKGROUND_COLOR,
"secondary_color": COLLAPSABLEFRAME_PRESSED_BACKGROUND_COLOR,
},
"CollapsableFrame.Header": {
"font_size": FONT_SIZE,
"background_color": FRAME_TEXT_COLOR,
"color": FRAME_TEXT_COLOR,
},
"CollapsableFrame:hovered": {"secondary_color": COLLAPSABLEFRAME_HOVERED_BACKGROUND_COLOR},
"CollapsableFrame:pressed": {"secondary_color": COLLAPSABLEFRAME_PRESSED_BACKGROUND_COLOR},
"ScrollingFrame": {"margin": 0, "padding": 3, "border_radius": BORDER_RADIUS},
"TreeView": {
"background_color": 0xFF23211F,
"background_selected_color": 0x664F4D43,
"secondary_color": 0xFF403B3B,
},
"TreeView.ScrollingFrame": {"background_color": 0xFF23211F},
"TreeView.Header": {"background_color": 0xFF343432, "color": 0xFFCCCCCC, "font_size": 12},
"TreeView.Image::object_icon_grey": {"color": 0x80FFFFFF},
"TreeView.Image:disabled": {"color": 0x60FFFFFF},
"TreeView.Item": {"color": 0xFF8A8777},
"TreeView.Item:disabled": {"color": 0x608A8777},
"TreeView.Item::object_name_grey": {"color": 0xFF4D4B42},
"TreeView.Item::object_name_missing": {"color": 0xFF6F72FF},
"TreeView.Item:selected": {"color": 0xFF23211F},
"TreeView:selected": {"background_color": 0xFF8A8777},
"ColorWidget": {
"border_radius": BORDER_RADIUS,
"border_color": COLORWIDGET_BORDER_COLOR,
"border_width": 0.5,
},
"Label::vector_label": {"font_size": 16, "color": LABEL_VECTORLABEL_COLOR},
"PlotLabel::X": {"color": 0xFF1515EA, "background_color": 0x0},
"PlotLabel::Y": {"color": 0xFF5FC054, "background_color": 0x0},
"PlotLabel::Z": {"color": 0xFFC5822A, "background_color": 0x0},
"PlotLabel::W": {"color": 0xFFAA5555, "background_color": 0x0},
"Rectangle::vector_label": {"border_radius": BORDER_RADIUS * 2, "corner_flag": ui.CornerFlag.LEFT},
"Rectangle::mixed_overlay": {
"border_radius": BORDER_RADIUS,
"background_color": LABEL_MIXED_COLOR,
"border_width": 3,
},
"Rectangle": {
"border_radius": BORDER_RADIUS,
"background_color": FIELD_TEXT_COLOR_READ_ONLY,
}, # FIELD_BACKGROUND},
"Rectangle::xform_op:hovered": {"background_color": 0xFF444444},
"Rectangle::xform_op": {"background_color": 0xFF333333},
# text remove
"Button::remove": {"background_color": FIELD_BACKGROUND, "margin": 0},
"Button::remove:hovered": {"background_color": FIELD_BACKGROUND},
"Button::options": {"background_color": 0x0, "margin": 0},
"Button.Image::options": {"image_url": f"{icons_path}/options.svg", "color": 0xFF989898},
"Button.Image::options:hovered": {"color": 0xFFC2C2C2},
"IconButton": {"margin": 0, "padding": 0, "background_color": 0x0},
"IconButton:hovered": {"background_color": 0x0},
"IconButton:checked": {"background_color": 0x0},
"IconButton:pressed": {"background_color": 0x0},
"IconButton.Image": {"color": 0xFFA8A8A8},
"IconButton.Image:hovered": {"color": 0xFFC2C2C2},
"IconButton.Image:pressed": {"color": 0xFFA4A4A4},
"IconButton.Image:checked": {"color": 0xFFFFFFFF},
"IconButton.Tooltip": {"color": 0xFF9E9E9E},
"IconButton.Image::OpenFolder": {
"image_url": f"{icons_path}/open-folder.svg",
"background_color": 0x0,
"color": 0xFFA8A8A8,
"tooltip": TOOLTIP_STYLE,
},
"IconButton.Image::OpenConfig": {
"tooltip": TOOLTIP_STYLE,
"image_url": f"{icons_path}/open-config.svg",
"background_color": 0x0,
"color": 0xFFA8A8A8,
},
"IconButton.Image::OpenLink": {
"image_url": "resources/glyphs/link.svg",
"background_color": 0x0,
"color": 0xFFA8A8A8,
"tooltip": TOOLTIP_STYLE,
},
"IconButton.Image::OpenDocs": {
"image_url": "resources/glyphs/docs.svg",
"background_color": 0x0,
"color": 0xFFA8A8A8,
"tooltip": TOOLTIP_STYLE,
},
"IconButton.Image::CopyToClipboard": {
"image_url": "resources/glyphs/copy.svg",
"background_color": 0x0,
"color": 0xFFA8A8A8,
},
"IconButton.Image::Export": {
"image_url": f"{icons_path}/export.svg",
"background_color": 0x0,
"color": 0xFFA8A8A8,
},
"IconButton.Image::Sync": {
"image_url": "resources/glyphs/sync.svg",
"background_color": 0x0,
"color": 0xFFA8A8A8,
},
"IconButton.Image::Upload": {
"image_url": "resources/glyphs/upload.svg",
"background_color": 0x0,
"color": 0xFFA8A8A8,
},
"IconButton.Image::FolderPicker": {
"image_url": "resources/glyphs/folder.svg",
"background_color": 0x0,
"color": 0xFF929292,
},
"ItemButton": {"padding": 2, "background_color": 0xFF444444, "border_radius": 4},
"ItemButton.Image::add": {"image_url": f"{icons_path}/plus.svg", "color": 0xFF06C66B},
"ItemButton.Image::remove": {"image_url": f"{icons_path}/trash.svg", "color": 0xFF1010C6},
"ItemButton:hovered": {"background_color": 0xFF333333},
"ItemButton:pressed": {"background_color": 0xFF222222},
"Tooltip": TOOLTIP_STYLE,
}
return style
| 31,271 | Python | 45.884558 | 116 | 0.53903 |
NVIDIA-Omniverse/mjcf-importer-extension/source/extensions/omni.importer.mjcf/python/scripts/commands.py | # SPDX-FileCopyrightText: Copyright (c) 2023 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
# SPDX-License-Identifier: Apache-2.0
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import os
import omni.client
import omni.kit.commands
# import omni.kit.utils
from omni.client._omniclient import Result
from omni.importer.mjcf import _mjcf
from pxr import Usd
class MJCFCreateImportConfig(omni.kit.commands.Command):
"""
Returns an ImportConfig object that can be used while parsing and importing.
Should be used with the `MJCFCreateAsset` command
Returns:
:obj:`omni.importer.mjcf._mjcf.ImportConfig`: Parsed MJCF stored in an internal structure.
"""
def __init__(self) -> None:
pass
def do(self) -> _mjcf.ImportConfig:
return _mjcf.ImportConfig()
def undo(self) -> None:
pass
class MJCFCreateAsset(omni.kit.commands.Command):
"""
This command parses and imports a given mjcf file.
Args:
arg0 (:obj:`str`): The absolute path the mjcf file
arg1 (:obj:`omni.importer.mjcf._mjcf.ImportConfig`): Import configuration
arg2 (:obj:`str`): Path to the robot on the USD stage
arg3 (:obj:`str`): destination path for robot usd. Default is "" which will load the robot in-memory on the open stage.
"""
def __init__(
self, mjcf_path: str = "", import_config=_mjcf.ImportConfig(), prim_path: str = "", dest_path: str = ""
) -> None:
self.prim_path = prim_path
self.dest_path = dest_path
self._mjcf_path = mjcf_path
self._root_path, self._filename = os.path.split(os.path.abspath(self._mjcf_path))
self._import_config = import_config
self._mjcf_interface = _mjcf.acquire_mjcf_interface()
pass
def do(self) -> str:
# if self.prim_path:
# self.prim_path = self.prim_path.replace(
# "\\", "/"
# ) # Omni client works with both slashes cross platform, making it standard to make it easier later on
if self.dest_path:
self.dest_path = self.dest_path.replace(
"\\", "/"
) # Omni client works with both slashes cross platform, making it standard to make it easier later on
result = omni.client.read_file(self.dest_path)
if result[0] != Result.OK:
stage = Usd.Stage.CreateNew(self.dest_path)
stage.Save()
return self._mjcf_interface.create_asset_mjcf(
self._mjcf_path, self.prim_path, self._import_config, self.dest_path
)
def undo(self) -> None:
pass
omni.kit.commands.register_all_commands_in_module(__name__)
| 3,194 | Python | 31.938144 | 127 | 0.649656 |
NVIDIA-Omniverse/mjcf-importer-extension/source/extensions/omni.importer.mjcf/python/scripts/extension.py | # SPDX-FileCopyrightText: Copyright (c) 2023 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
# SPDX-License-Identifier: Apache-2.0
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import asyncio
import gc
import os
import weakref
import carb
import omni.client
import omni.ext
import omni.ui as ui
from omni.client._omniclient import Result
from omni.importer.mjcf import _mjcf
from omni.kit.menu.utils import MenuItemDescription, add_menu_items, remove_menu_items
from omni.kit.window.filepicker import FilePickerDialog
from pxr import Sdf, Usd, UsdGeom, UsdPhysics
# from omni.isaac.ui.menu import make_menu_item_description
from .ui_utils import (
btn_builder,
cb_builder,
dropdown_builder,
float_builder,
str_builder,
)
EXTENSION_NAME = "MJCF Importer"
import omni.ext
from omni.kit.menu.utils import MenuItemDescription
def make_menu_item_description(ext_id: str, name: str, onclick_fun, action_name: str = "") -> None:
"""Easily replace the onclick_fn with onclick_action when creating a menu description
Args:
ext_id (str): The extension you are adding the menu item to.
name (str): Name of the menu item displayed in UI.
onclick_fun (Function): The function to run when clicking the menu item.
action_name (str): name for the action, in case ext_id+name don't make a unique string
Note:
ext_id + name + action_name must concatenate to a unique identifier.
"""
# TODO, fix errors when reloading extensions
# action_unique = f'{ext_id.replace(" ", "_")}{name.replace(" ", "_")}{action_name.replace(" ", "_")}'
# action_registry = omni.kit.actions.core.get_action_registry()
# action_registry.register_action(ext_id, action_unique, onclick_fun)
return MenuItemDescription(name=name, onclick_fn=onclick_fun)
def is_mjcf_file(path: str):
_, ext = os.path.splitext(path.lower())
return ext == ".xml"
def on_filter_item(item) -> bool:
if not item or item.is_folder:
return not (item.name == "Omniverse" or item.path.startswith("omniverse:"))
return is_mjcf_file(item.path)
class Extension(omni.ext.IExt):
def on_startup(self, ext_id):
self._mjcf_interface = _mjcf.acquire_mjcf_interface()
self._usd_context = omni.usd.get_context()
self._window = omni.ui.Window(
EXTENSION_NAME, width=600, height=400, visible=False, dockPreference=ui.DockPreference.LEFT_BOTTOM
)
self._window.deferred_dock_in("Console", omni.ui.DockPolicy.DO_NOTHING)
self._window.set_visibility_changed_fn(self._on_window)
menu_items = [
make_menu_item_description(ext_id, EXTENSION_NAME, lambda a=weakref.proxy(self): a._menu_callback())
]
self._menu_items = [MenuItemDescription(name="Workflows", sub_menu=menu_items)]
add_menu_items(self._menu_items, "Isaac Utils")
self._models = {}
result, self._config = omni.kit.commands.execute("MJCFCreateImportConfig")
self._filepicker = None
self._last_folder = None
self._content_browser = None
self._extension_path = omni.kit.app.get_app().get_extension_manager().get_extension_path(ext_id)
self._imported_robot = None
# Set defaults
# self._config.set_merge_fixed_joints(False)
# self._config.set_convex_decomp(False)
self._config.set_fix_base(False)
self._config.set_import_inertia_tensor(False)
self._config.set_distance_scale(1.0)
self._config.set_density(0.0)
# self._config.set_default_drive_type(1)
# self._config.set_default_drive_strength(1e7)
# self._config.set_default_position_drive_damping(1e5)
self._config.set_self_collision(False)
self._config.set_make_default_prim(True)
self._config.set_create_physics_scene(True)
self._config.set_import_sites(True)
self._config.set_visualize_collision_geoms(True)
def build_ui(self):
with self._window.frame:
with ui.VStack(spacing=20, height=0):
with ui.HStack(spacing=10):
with ui.VStack(spacing=2, height=0):
# cb_builder(
# label="Merge Fixed Joints",
# tooltip="Check this box to skip adding articulation on fixed joints",
# on_clicked_fn=lambda m, config=self._config: config.set_merge_fixed_joints(m),
# )
cb_builder(
"Fix Base Link",
tooltip="If true, enables the fix base property on the root of the articulation.",
default_val=False,
on_clicked_fn=lambda m, config=self._config: config.set_fix_base(m),
)
cb_builder(
"Import Inertia Tensor",
tooltip="If True, inertia will be loaded from mjcf, if the mjcf does not specify inertia tensor, identity will be used and scaled by the scaling factor. If false physx will compute automatically",
on_clicked_fn=lambda m, config=self._config: config.set_import_inertia_tensor(m),
)
cb_builder(
"Import Sites",
tooltip="If True, sites will be imported from mjcf.",
default_val=True,
on_clicked_fn=lambda m, config=self._config: config.set_import_sites(m),
)
cb_builder(
"Visualize Collision Geoms",
tooltip="If True, collision geoms will also be imported as visual geoms",
default_val=True,
on_clicked_fn=lambda m, config=self._config: config.set_visualize_collision_geoms(m),
)
self._models["scale"] = float_builder(
"Stage Units Per Meter",
default_val=1.0,
tooltip="[1.0 / stage_units] Set the distance units the robot is imported as, default is 1.0 corresponding to m",
)
self._models["scale"].add_value_changed_fn(
lambda m, config=self._config: config.set_distance_scale(m.get_value_as_float())
)
self._models["density"] = float_builder(
"Link Density",
default_val=0.0,
tooltip="[kg/stage_units^3] If a link doesn't have mass, use this density as backup, A density of 0.0 results in the physics engine automatically computing a default density",
)
self._models["density"].add_value_changed_fn(
lambda m, config=self._config: config.set_density(m.get_value_as_float())
)
# dropdown_builder(
# "Joint Drive Type",
# items=["None", "Position", "Velocity"],
# default_val=1,
# on_clicked_fn=lambda i, config=self._config: i,
# #config.set_default_drive_type(0 if i == "None" else (1 if i == "Position" else 2)
# tooltip="Set the default drive configuration, None: stiffness and damping are zero, Position/Velocity: use default specified below.",
# )
# self._models["drive_strength"] = float_builder(
# "Joint Drive Strength",
# default_val=1e7,
# tooltip="Corresponds to stiffness for position or damping for velocity, set to -1 to prevent this value from getting used",
# )
# self._models["drive_strength"].add_value_changed_fn(
# lambda m, config=self._config: m
# # config.set_default_drive_strength(m.get_value_as_float())
# )
# self._models["position_drive_damping"] = float_builder(
# "Joint Position Drive Damping",
# default_val=1e5,
# tooltip="If the drive type is set to position, this will be used as a default damping for the drive, set to -1 to prevent this from getting used",
# )
# self._models["position_drive_damping"].add_value_changed_fn(
# lambda m, config=self._config: m
# #config.set_default_position_drive_damping(m.get_value_as_float()
# )
with ui.VStack(spacing=2, height=0):
self._models["clean_stage"] = cb_builder(
label="Clean Stage", tooltip="Check this box to load MJCF on a clean stage"
)
# cb_builder(
# "Convex Decomposition",
# tooltip="If true, non-convex meshes will be decomposed into convex collision shapes, if false a convex hull will be used.",
# on_clicked_fn=lambda m, config=self._config: config.set_convex_decomp(m),
# )
cb_builder(
"Self Collision",
tooltip="If true, allows self intersection between links in the robot, can cause instability if collision meshes between links are self intersecting",
on_clicked_fn=lambda m, config=self._config: config.set_self_collision(m),
)
cb_builder(
"Create Physics Scene",
tooltip="If true, creates a default physics scene if one does not already exist in the stage",
default_val=True,
on_clicked_fn=lambda m, config=self._config: config.set_create_physics_scene(m),
),
cb_builder(
"Make Default Prim",
tooltip="If true, makes imported robot the default prim for the stage",
default_val=True,
on_clicked_fn=lambda m, config=self._config: config.set_make_default_prim(m),
)
cb_builder(
"Create Instanceable Asset",
tooltip="If true, creates an instanceable version of the asset. Meshes will be saved in a separate USD file",
default_val=False,
on_clicked_fn=lambda m, config=self._config: config.set_make_instanceable(m),
)
self._models["instanceable_usd_path"] = str_builder(
"Instanceable USD Path",
tooltip="USD file to store instanceable meshes in",
default_val="./instanceable_meshes.usd",
use_folder_picker=True,
folder_dialog_title="Select Output File",
folder_button_title="Select File",
)
self._models["instanceable_usd_path"].add_value_changed_fn(
lambda m, config=self._config: config.set_instanceable_usd_path(m.get_value_as_string())
)
with ui.VStack(height=0):
with ui.HStack(spacing=20):
btn_builder("Import MJCF", text="Select and Import", on_clicked_fn=self._parse_mjcf)
def _menu_callback(self):
self._window.visible = not self._window.visible
def _on_window(self, visible):
if self._window.visible:
self.build_ui()
self._events = self._usd_context.get_stage_event_stream()
else:
self._events = None
self._stage_event_sub = None
def _refresh_filebrowser(self):
parent = None
selection_name = None
if len(self._filebrowser.get_selections()):
parent = self._filebrowser.get_selections()[0].parent
selection_name = self._filebrowser.get_selections()[0].name
self._filebrowser.refresh_ui(parent)
if selection_name:
selection = [child for child in parent.children.values() if child.name == selection_name]
if len(selection):
self._filebrowser.select_and_center(selection[0])
def _parse_mjcf(self):
self._filepicker = FilePickerDialog(
"Import MJCF",
allow_multi_selection=False,
apply_button_label="Import",
click_apply_handler=lambda filename, path, c=weakref.proxy(self): c._select_picked_file_callback(
self._filepicker, filename, path
),
click_cancel_handler=lambda a, b, c=weakref.proxy(self): c._filepicker.hide(),
item_filter_fn=on_filter_item,
enable_versioning_pane=True,
)
if self._last_folder:
self._filepicker.set_current_directory(self._last_folder)
self._filepicker.navigate_to(self._last_folder)
self._filepicker.refresh_current_directory()
self._filepicker.toggle_bookmark_from_path("Built In MJCF Files", (self._extension_path + "/data/mjcf"), True)
self._filepicker.show()
def _load_robot(self, path=None):
if path:
base_path = path[: path.rfind("/")]
basename = path[path.rfind("/") + 1 :]
basename = basename[: basename.rfind(".")]
if path.rfind("/") < 0:
base_path = path[: path.rfind("\\")]
basename = path[path.rfind("\\") + 1]
# sanitize basename
if basename[0].isdigit():
basename = "_" + basename
full_path = os.path.abspath(os.path.join(self.root_path, self.filename))
dest_path = "{}/{}/{}.usd".format(base_path, basename, basename)
current_stage = omni.usd.get_context().get_stage()
prim_path = omni.usd.get_stage_next_free_path(current_stage, "/" + basename, False)
omni.kit.commands.execute(
"MJCFCreateAsset",
mjcf_path=full_path,
import_config=self._config,
prim_path=prim_path,
dest_path=dest_path,
)
stage = Usd.Stage.Open(dest_path)
prim_name = str(stage.GetDefaultPrim().GetName())
def add_reference_to_stage():
current_stage = omni.usd.get_context().get_stage()
if current_stage:
prim_path = omni.usd.get_stage_next_free_path(
current_stage, str(current_stage.GetDefaultPrim().GetPath()) + "/" + prim_name, False
)
robot_prim = current_stage.OverridePrim(prim_path)
if "anon:" in current_stage.GetRootLayer().identifier:
robot_prim.GetReferences().AddReference(dest_path)
else:
robot_prim.GetReferences().AddReference(
omni.client.make_relative_url(current_stage.GetRootLayer().identifier, dest_path)
)
if self._config.create_physics_scene:
UsdPhysics.Scene.Define(current_stage, Sdf.Path("/physicsScene"))
async def import_with_clean_stage():
await omni.usd.get_context().new_stage_async()
await omni.kit.app.get_app().next_update_async()
current_stage = omni.usd.get_context().get_stage()
UsdGeom.SetStageUpAxis(current_stage, UsdGeom.Tokens.z)
UsdGeom.SetStageMetersPerUnit(stage, 1)
add_reference_to_stage()
await omni.kit.app.get_app().next_update_async()
if self._models["clean_stage"].get_value_as_bool():
asyncio.ensure_future(import_with_clean_stage())
else:
upAxis = UsdGeom.GetStageUpAxis(current_stage)
if upAxis == "Y":
carb.log_error("The stage Up-Axis must be Z to use the MJCF importer")
add_reference_to_stage()
def _select_picked_file_callback(self, dialog: FilePickerDialog, filename=None, path=None):
if not path.startswith("omniverse://"):
self.root_path = path
self.filename = filename
if path and filename:
self._last_folder = path
self._load_robot(path + "/" + filename)
else:
carb.log_error("path and filename not specified")
else:
carb.log_error("Only Local Paths supported")
dialog.hide()
def on_shutdown(self):
_mjcf.release_mjcf_interface(self._mjcf_interface)
if self._filepicker:
self._filepicker.toggle_bookmark_from_path(
"Built In MJCF Files", (self._extension_path + "/data/mjcf"), False
)
self._filepicker.destroy()
self._filepicker = None
remove_menu_items(self._menu_items, "Isaac Utils")
if self._window:
self._window = None
gc.collect()
| 18,382 | Python | 48.549865 | 224 | 0.543194 |
NVIDIA-Omniverse/mjcf-importer-extension/source/extensions/omni.importer.mjcf/python/scripts/ui_utils.py | # SPDX-FileCopyrightText: Copyright (c) 2023 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
# SPDX-License-Identifier: Apache-2.0
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# str_builder
import asyncio
import os
import subprocess
import sys
from cmath import inf
import carb.settings
import omni.appwindow
import omni.ext
import omni.ui as ui
from omni.kit.window.extensions import SimpleCheckBox
from omni.kit.window.filepicker import FilePickerDialog
from omni.kit.window.property.templates import LABEL_HEIGHT, LABEL_WIDTH
# from .callbacks import on_copy_to_clipboard, on_docs_link_clicked, on_open_folder_clicked, on_open_IDE_clicked
from .style import BUTTON_WIDTH, COLOR_W, COLOR_X, COLOR_Y, COLOR_Z, get_style
def add_line_rect_flourish(draw_line=True):
"""Aesthetic element that adds a Line + Rectangle after all UI elements in the row.
Args:
draw_line (bool, optional): Set false to only draw rectangle. Defaults to True.
"""
if draw_line:
ui.Line(style={"color": 0x338A8777}, width=ui.Fraction(1), alignment=ui.Alignment.CENTER)
ui.Spacer(width=10)
with ui.Frame(width=0):
with ui.VStack():
with ui.Placer(offset_x=0, offset_y=7):
ui.Rectangle(height=5, width=5, alignment=ui.Alignment.CENTER)
ui.Spacer(width=5)
def format_tt(tt):
import string
formated = ""
i = 0
for w in tt.split():
if w.isupper():
formated += w + " "
elif len(w) > 3 or i == 0:
formated += string.capwords(w) + " "
else:
formated += w.lower() + " "
i += 1
return formated
def add_folder_picker_icon(
on_click_fn,
item_filter_fn=None,
bookmark_label=None,
bookmark_path=None,
dialog_title="Select Output Folder",
button_title="Select Folder",
):
def open_file_picker():
def on_selected(filename, path):
on_click_fn(filename, path)
file_picker.hide()
def on_canceled(a, b):
file_picker.hide()
file_picker = FilePickerDialog(
dialog_title,
allow_multi_selection=False,
apply_button_label=button_title,
click_apply_handler=lambda a, b: on_selected(a, b),
click_cancel_handler=lambda a, b: on_canceled(a, b),
item_filter_fn=item_filter_fn,
enable_versioning_pane=True,
)
if bookmark_label and bookmark_path:
file_picker.toggle_bookmark_from_path(bookmark_label, bookmark_path, True)
with ui.Frame(width=0, tooltip=button_title):
ui.Button(
name="IconButton",
width=24,
height=24,
clicked_fn=open_file_picker,
style=get_style()["IconButton.Image::FolderPicker"],
alignment=ui.Alignment.RIGHT_TOP,
)
def btn_builder(label="", type="button", text="button", tooltip="", on_clicked_fn=None):
"""Creates a stylized button.
Args:
label (str, optional): Label to the left of the UI element. Defaults to "".
type (str, optional): Type of UI element. Defaults to "button".
text (str, optional): Text rendered on the button. Defaults to "button".
tooltip (str, optional): Tooltip to display over the Label. Defaults to "".
on_clicked_fn (Callable, optional): Call-back function when clicked. Defaults to None.
Returns:
ui.Button: Button
"""
with ui.HStack():
ui.Label(label, width=LABEL_WIDTH, alignment=ui.Alignment.LEFT_CENTER, tooltip=format_tt(tooltip))
btn = ui.Button(
text.upper(),
name="Button",
width=BUTTON_WIDTH,
clicked_fn=on_clicked_fn,
style=get_style(),
alignment=ui.Alignment.LEFT_CENTER,
)
ui.Spacer(width=5)
add_line_rect_flourish(True)
# ui.Spacer(width=ui.Fraction(1))
# ui.Spacer(width=10)
# with ui.Frame(width=0):
# with ui.VStack():
# with ui.Placer(offset_x=0, offset_y=7):
# ui.Rectangle(height=5, width=5, alignment=ui.Alignment.CENTER)
# ui.Spacer(width=5)
return btn
def cb_builder(label="", type="checkbox", default_val=False, tooltip="", on_clicked_fn=None):
"""Creates a Stylized Checkbox
Args:
label (str, optional): Label to the left of the UI element. Defaults to "".
type (str, optional): Type of UI element. Defaults to "checkbox".
default_val (bool, optional): Checked is True, Unchecked is False. Defaults to False.
tooltip (str, optional): Tooltip to display over the Label. Defaults to "".
on_clicked_fn (Callable, optional): Call-back function when clicked. Defaults to None.
Returns:
ui.SimpleBoolModel: model
"""
with ui.HStack():
ui.Label(label, width=LABEL_WIDTH - 12, alignment=ui.Alignment.LEFT_CENTER, tooltip=format_tt(tooltip))
model = ui.SimpleBoolModel()
callable = on_clicked_fn
if callable is None:
callable = lambda x: None
SimpleCheckBox(default_val, callable, model=model)
add_line_rect_flourish()
return model
def dropdown_builder(
label="", type="dropdown", default_val=0, items=["Option 1", "Option 2", "Option 3"], tooltip="", on_clicked_fn=None
):
"""Creates a Stylized Dropdown Combobox
Args:
label (str, optional): Label to the left of the UI element. Defaults to "".
type (str, optional): Type of UI element. Defaults to "dropdown".
default_val (int, optional): Default index of dropdown items. Defaults to 0.
items (list, optional): List of items for dropdown box. Defaults to ["Option 1", "Option 2", "Option 3"].
tooltip (str, optional): Tooltip to display over the Label. Defaults to "".
on_clicked_fn (Callable, optional): Call-back function when clicked. Defaults to None.
Returns:
AbstractItemModel: model
"""
with ui.HStack():
ui.Label(label, width=LABEL_WIDTH, alignment=ui.Alignment.LEFT_CENTER, tooltip=format_tt(tooltip))
combo_box = ui.ComboBox(
default_val, *items, name="ComboBox", width=ui.Fraction(1), alignment=ui.Alignment.LEFT_CENTER
).model
add_line_rect_flourish(False)
def on_clicked_wrapper(model, val):
on_clicked_fn(items[model.get_item_value_model().as_int])
if on_clicked_fn is not None:
combo_box.add_item_changed_fn(on_clicked_wrapper)
return combo_box
def float_builder(label="", type="floatfield", default_val=0, tooltip="", min=-inf, max=inf, step=0.1, format="%.2f"):
"""Creates a Stylized Floatfield Widget
Args:
label (str, optional): Label to the left of the UI element. Defaults to "".
type (str, optional): Type of UI element. Defaults to "floatfield".
default_val (int, optional): Default Value of UI element. Defaults to 0.
tooltip (str, optional): Tooltip to display over the UI elements. Defaults to "".
Returns:
AbstractValueModel: model
"""
with ui.HStack():
ui.Label(label, width=LABEL_WIDTH, alignment=ui.Alignment.LEFT_CENTER, tooltip=format_tt(tooltip))
float_field = ui.FloatDrag(
name="FloatField",
width=ui.Fraction(1),
height=0,
alignment=ui.Alignment.LEFT_CENTER,
min=min,
max=max,
step=step,
format=format,
).model
float_field.set_value(default_val)
add_line_rect_flourish(False)
return float_field
def str_builder(
label="",
type="stringfield",
default_val=" ",
tooltip="",
on_clicked_fn=None,
use_folder_picker=False,
read_only=False,
item_filter_fn=None,
bookmark_label=None,
bookmark_path=None,
folder_dialog_title="Select Output Folder",
folder_button_title="Select Folder",
):
"""Creates a Stylized Stringfield Widget
Args:
label (str, optional): Label to the left of the UI element. Defaults to "".
type (str, optional): Type of UI element. Defaults to "stringfield".
default_val (str, optional): Text to initialize in Stringfield. Defaults to " ".
tooltip (str, optional): Tooltip to display over the UI elements. Defaults to "".
use_folder_picker (bool, optional): Add a folder picker button to the right. Defaults to False.
read_only (bool, optional): Prevents editing. Defaults to False.
item_filter_fn (Callable, optional): filter function to pass to the FilePicker
bookmark_label (str, optional): bookmark label to pass to the FilePicker
bookmark_path (str, optional): bookmark path to pass to the FilePicker
Returns:
AbstractValueModel: model of Stringfield
"""
with ui.HStack():
ui.Label(label, width=LABEL_WIDTH, alignment=ui.Alignment.LEFT_CENTER, tooltip=format_tt(tooltip))
str_field = ui.StringField(
name="StringField", width=ui.Fraction(1), height=0, alignment=ui.Alignment.LEFT_CENTER, read_only=read_only
).model
str_field.set_value(default_val)
if use_folder_picker:
def update_field(filename, path):
if filename == "":
val = path
elif filename[0] != "/" and path[-1] != "/":
val = path + "/" + filename
elif filename[0] == "/" and path[-1] == "/":
val = path + filename[1:]
else:
val = path + filename
str_field.set_value(val)
add_folder_picker_icon(
update_field,
item_filter_fn,
bookmark_label,
bookmark_path,
dialog_title=folder_dialog_title,
button_title=folder_button_title,
)
else:
add_line_rect_flourish(False)
return str_field
| 10,551 | Python | 35.512111 | 120 | 0.619278 |
NVIDIA-Omniverse/mjcf-importer-extension/source/extensions/omni.importer.mjcf/python/tests/test_mjcf.py | # SPDX-FileCopyrightText: Copyright (c) 2023 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
# SPDX-License-Identifier: Apache-2.0
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import asyncio
import filecmp
import os
import carb
import numpy as np
import omni.kit.commands
# NOTE:
# omni.kit.test - std python's unittest module with additional wrapping to add suport for async/await tests
# For most things refer to unittest docs: https://docs.python.org/3/library/unittest.html
import omni.kit.test
import pxr
from pxr import Gf, PhysicsSchemaTools, Sdf, UsdGeom, UsdPhysics, UsdShade
# Having a test class dervived from omni.kit.test.AsyncTestCase declared on the root of module will make it auto-discoverable by omni.kit.test
class TestMJCF(omni.kit.test.AsyncTestCase):
# Before running each test
async def setUp(self):
self._timeline = omni.timeline.get_timeline_interface()
ext_manager = omni.kit.app.get_app().get_extension_manager()
ext_id = ext_manager.get_enabled_extension_id("omni.importer.mjcf")
self._extension_path = ext_manager.get_extension_path(ext_id)
await omni.usd.get_context().new_stage_async()
await omni.kit.app.get_app().next_update_async()
# After running each test
async def tearDown(self):
while omni.usd.get_context().get_stage_loading_status()[2] > 0:
print("tearDown, assets still loading, waiting to finish...")
await asyncio.sleep(1.0)
await omni.kit.app.get_app().next_update_async()
await omni.usd.get_context().new_stage_async()
async def test_mjcf_ant(self):
stage = omni.usd.get_context().get_stage()
status, import_config = omni.kit.commands.execute("MJCFCreateImportConfig")
import_config.set_fix_base(True)
import_config.set_import_inertia_tensor(True)
omni.kit.commands.execute(
"MJCFCreateAsset",
mjcf_path=self._extension_path + "/data/mjcf/nv_ant.xml",
import_config=import_config,
prim_path="/ant",
)
await omni.kit.app.get_app().next_update_async()
# check if object is there
prim = stage.GetPrimAtPath("/ant")
self.assertNotEqual(prim.GetPath(), Sdf.Path.emptyPath)
# make sure the joints and links exist
front_left_leg_joint = stage.GetPrimAtPath("/ant/torso/joints/hip_1")
self.assertNotEqual(front_left_leg_joint.GetPath(), Sdf.Path.emptyPath)
self.assertEqual(front_left_leg_joint.GetTypeName(), "PhysicsRevoluteJoint")
self.assertAlmostEqual(front_left_leg_joint.GetAttribute("physics:upperLimit").Get(), 40)
self.assertAlmostEqual(front_left_leg_joint.GetAttribute("physics:lowerLimit").Get(), -40)
front_left_leg = stage.GetPrimAtPath("/ant/torso/front_left_leg")
self.assertAlmostEqual(front_left_leg.GetAttribute("physics:diagonalInertia").Get()[0], 0.0)
self.assertAlmostEqual(front_left_leg.GetAttribute("physics:mass").Get(), 0.0)
front_left_foot_joint = stage.GetPrimAtPath("/ant/torso/joints/ankle_1")
self.assertNotEqual(front_left_foot_joint.GetPath(), Sdf.Path.emptyPath)
self.assertEqual(front_left_foot_joint.GetTypeName(), "PhysicsRevoluteJoint")
self.assertAlmostEqual(front_left_foot_joint.GetAttribute("physics:upperLimit").Get(), 100)
self.assertAlmostEqual(front_left_foot_joint.GetAttribute("physics:lowerLimit").Get(), 30)
front_left_foot = stage.GetPrimAtPath("/ant/torso/front_left_foot")
self.assertAlmostEqual(front_left_foot.GetAttribute("physics:diagonalInertia").Get()[0], 0.0)
self.assertAlmostEqual(front_left_foot.GetAttribute("physics:mass").Get(), 0.0)
# Start Simulation and wait
self._timeline.play()
await omni.kit.app.get_app().next_update_async()
await asyncio.sleep(1.0)
# nothing crashes
self._timeline.stop()
self.assertAlmostEqual(UsdGeom.GetStageMetersPerUnit(stage), 1.0)
async def test_mjcf_humanoid(self):
stage = omni.usd.get_context().get_stage()
status, import_config = omni.kit.commands.execute("MJCFCreateImportConfig")
import_config.set_fix_base(True)
import_config.set_import_inertia_tensor(True)
omni.kit.commands.execute(
"MJCFCreateAsset",
mjcf_path=self._extension_path + "/data/mjcf/nv_humanoid.xml",
import_config=import_config,
prim_path="/humanoid",
)
await omni.kit.app.get_app().next_update_async()
# check if object is there
prim = stage.GetPrimAtPath("/humanoid")
self.assertNotEqual(prim.GetPath(), Sdf.Path.emptyPath)
# make sure the joints and link exist
root_joint = stage.GetPrimAtPath("/humanoid/torso/joints/rootJoint_torso")
self.assertNotEqual(root_joint.GetPath(), Sdf.Path.emptyPath)
pelvis_joint = stage.GetPrimAtPath("/humanoid/torso/joints/abdomen_x")
self.assertNotEqual(pelvis_joint.GetPath(), Sdf.Path.emptyPath)
self.assertEqual(pelvis_joint.GetTypeName(), "PhysicsRevoluteJoint")
self.assertAlmostEqual(pelvis_joint.GetAttribute("physics:upperLimit").Get(), 35)
self.assertAlmostEqual(pelvis_joint.GetAttribute("physics:lowerLimit").Get(), -35)
lower_waist_joint = stage.GetPrimAtPath("/humanoid/torso/joints/lower_waist")
self.assertNotEqual(lower_waist_joint.GetPath(), Sdf.Path.emptyPath)
self.assertEqual(lower_waist_joint.GetTypeName(), "PhysicsJoint")
self.assertAlmostEqual(lower_waist_joint.GetAttribute("limit:rotX:physics:high").Get(), 45)
self.assertAlmostEqual(lower_waist_joint.GetAttribute("limit:rotX:physics:low").Get(), -45)
self.assertAlmostEqual(lower_waist_joint.GetAttribute("limit:rotY:physics:high").Get(), 30)
self.assertAlmostEqual(lower_waist_joint.GetAttribute("limit:rotY:physics:low").Get(), -75)
self.assertAlmostEqual(lower_waist_joint.GetAttribute("limit:rotZ:physics:high").Get(), -1)
self.assertAlmostEqual(lower_waist_joint.GetAttribute("limit:rotZ:physics:low").Get(), 1)
left_foot = stage.GetPrimAtPath("/humanoid/torso/left_foot")
self.assertAlmostEqual(left_foot.GetAttribute("physics:diagonalInertia").Get()[0], 0.0)
self.assertAlmostEqual(left_foot.GetAttribute("physics:mass").Get(), 0.0)
# Start Simulation and wait
self._timeline.play()
await omni.kit.app.get_app().next_update_async()
await asyncio.sleep(1.0)
# nothing crashes
self._timeline.stop()
self.assertAlmostEqual(UsdGeom.GetStageMetersPerUnit(stage), 1.0)
# This sample corresponds to the example in the docs, keep this and the version in the docs in sync
async def test_doc_sample(self):
import omni.kit.commands
from pxr import Gf, PhysicsSchemaTools, Sdf, UsdLux, UsdPhysics
# setting up import configuration:
status, import_config = omni.kit.commands.execute("MJCFCreateImportConfig")
import_config.set_fix_base(True)
import_config.set_import_inertia_tensor(True)
# Get path to extension data:
ext_manager = omni.kit.app.get_app().get_extension_manager()
ext_id = ext_manager.get_enabled_extension_id("omni.importer.mjcf")
extension_path = ext_manager.get_extension_path(ext_id)
# import MJCF
omni.kit.commands.execute(
"MJCFCreateAsset",
mjcf_path=extension_path + "/data/mjcf/nv_ant.xml",
import_config=import_config,
prim_path="/ant",
)
# get stage handle
stage = omni.usd.get_context().get_stage()
# enable physics
scene = UsdPhysics.Scene.Define(stage, Sdf.Path("/physicsScene"))
# set gravity
scene.CreateGravityDirectionAttr().Set(Gf.Vec3f(0.0, 0.0, -1.0))
scene.CreateGravityMagnitudeAttr().Set(9.81)
# add lighting
distantLight = UsdLux.DistantLight.Define(stage, Sdf.Path("/DistantLight"))
distantLight.CreateIntensityAttr(500)
async def test_mjcf_scale(self):
stage = omni.usd.get_context().get_stage()
status, import_config = omni.kit.commands.execute("MJCFCreateImportConfig")
import_config.set_distance_scale(100.0)
import_config.set_fix_base(True)
import_config.set_import_inertia_tensor(True)
omni.kit.commands.execute(
"MJCFCreateAsset",
mjcf_path=self._extension_path + "/data/mjcf/nv_ant.xml",
import_config=import_config,
prim_path="/ant",
)
await omni.kit.app.get_app().next_update_async()
# Start Simulation and wait
self._timeline.play()
await omni.kit.app.get_app().next_update_async()
await asyncio.sleep(1.0)
# nothing crashes
self._timeline.stop()
self.assertAlmostEqual(UsdGeom.GetStageMetersPerUnit(stage), 0.01)
async def test_mjcf_self_collision(self):
stage = omni.usd.get_context().get_stage()
status, import_config = omni.kit.commands.execute("MJCFCreateImportConfig")
import_config.set_self_collision(True)
import_config.set_fix_base(True)
import_config.set_import_inertia_tensor(True)
omni.kit.commands.execute(
"MJCFCreateAsset",
mjcf_path=self._extension_path + "/data/mjcf/nv_ant.xml",
import_config=import_config,
prim_path="/ant",
)
await omni.kit.app.get_app().next_update_async()
prim = stage.GetPrimAtPath("/ant/torso")
self.assertNotEqual(prim.GetPath(), Sdf.Path.emptyPath)
self.assertEqual(prim.GetAttribute("physxArticulation:enabledSelfCollisions").Get(), True)
# Start Simulation and wait
self._timeline.play()
await omni.kit.app.get_app().next_update_async()
await asyncio.sleep(1.0)
# nothing crashes
self._timeline.stop()
async def test_mjcf_default_prim(self):
stage = omni.usd.get_context().get_stage()
mjcf_path = os.path.abspath(self._extension_path + "/data/mjcf/nv_ant.xml")
status, import_config = omni.kit.commands.execute("MJCFCreateImportConfig")
import_config.set_fix_base(True)
import_config.set_import_inertia_tensor(True)
import_config.set_make_default_prim(True)
omni.kit.commands.execute(
"MJCFCreateAsset",
mjcf_path=self._extension_path + "/data/mjcf/nv_ant.xml",
import_config=import_config,
prim_path="/ant_1",
)
await omni.kit.app.get_app().next_update_async()
omni.kit.commands.execute(
"MJCFCreateAsset",
mjcf_path=self._extension_path + "/data/mjcf/nv_ant.xml",
import_config=import_config,
prim_path="/ant_2",
)
await omni.kit.app.get_app().next_update_async()
default_prim = stage.GetDefaultPrim()
self.assertNotEqual(default_prim.GetPath(), Sdf.Path.emptyPath)
prim_2 = stage.GetPrimAtPath("/ant_2")
self.assertNotEqual(prim_2.GetPath(), Sdf.Path.emptyPath)
self.assertEqual(default_prim.GetPath(), prim_2.GetPath())
async def test_mjcf_visualize_collision_geom(self):
stage = omni.usd.get_context().get_stage()
status, import_config = omni.kit.commands.execute("MJCFCreateImportConfig")
import_config.set_self_collision(True)
import_config.set_fix_base(True)
import_config.set_import_inertia_tensor(True)
import_config.set_visualize_collision_geoms(False)
omni.kit.commands.execute(
"MJCFCreateAsset",
mjcf_path=self._extension_path + "/data/mjcf/open_ai_assets/hand/manipulate_block.xml",
import_config=import_config,
prim_path="/shadow_hand",
)
await omni.kit.app.get_app().next_update_async()
prim = stage.GetPrimAtPath("/shadow_hand/robot0_hand_mount/robot0_forearm/visuals/robot0_C_forearm")
self.assertNotEqual(prim.GetPath(), Sdf.Path.emptyPath)
imageable = UsdGeom.Imageable(prim)
visibility_attr = imageable.GetVisibilityAttr().Get()
self.assertEqual(visibility_attr, "invisible")
# Start Simulation and wait
self._timeline.play()
await omni.kit.app.get_app().next_update_async()
await asyncio.sleep(1.0)
# nothing crashes
self._timeline.stop()
async def test_mjcf_import_shadow_hand_egg(self):
stage = omni.usd.get_context().get_stage()
status, import_config = omni.kit.commands.execute("MJCFCreateImportConfig")
import_config.set_self_collision(True)
import_config.set_import_inertia_tensor(True)
omni.kit.commands.execute(
"MJCFCreateAsset",
mjcf_path=self._extension_path + "/data/mjcf/open_ai_assets/hand/manipulate_egg_touch_sensors.xml",
import_config=import_config,
prim_path="/shadow_hand",
)
await omni.kit.app.get_app().next_update_async()
prim = stage.GetPrimAtPath("/shadow_hand/robot0_hand_mount")
self.assertNotEqual(prim.GetPath(), Sdf.Path.emptyPath)
prim = stage.GetPrimAtPath("/shadow_hand/object")
self.assertNotEqual(prim.GetPath(), Sdf.Path.emptyPath)
prim = stage.GetPrimAtPath("/shadow_hand/worldBody")
self.assertNotEqual(prim.GetPath(), Sdf.Path.emptyPath)
# Start Simulation and wait
self._timeline.play()
await omni.kit.app.get_app().next_update_async()
await asyncio.sleep(1.0)
# nothing crashes
self._timeline.stop()
async def test_mjcf_import_humanoid_100(self):
stage = omni.usd.get_context().get_stage()
status, import_config = omni.kit.commands.execute("MJCFCreateImportConfig")
import_config.set_self_collision(False)
import_config.set_import_inertia_tensor(True)
omni.kit.commands.execute(
"MJCFCreateAsset",
mjcf_path=self._extension_path + "/data/mjcf/mujoco_sim_assets/humanoid100.xml",
import_config=import_config,
prim_path="/humanoid_100",
)
await omni.kit.app.get_app().next_update_async()
# Start Simulation and wait
self._timeline.play()
await omni.kit.app.get_app().next_update_async()
await asyncio.sleep(1.0)
# nothing crashes
self._timeline.stop()
| 15,081 | Python | 43.753709 | 142 | 0.660898 |
NVIDIA-Omniverse/mjcf-importer-extension/source/extensions/omni.importer.mjcf/bindings/BindingsMjcfPython.cpp | // SPDX-FileCopyrightText: Copyright (c) 2023 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
// SPDX-License-Identifier: Apache-2.0
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include <carb/BindingsPythonUtils.h>
#include "../plugins/Mjcf.h"
CARB_BINDINGS("omni.importer.mjcf.python")
namespace omni {
namespace importer {
namespace mjcf {}
} // namespace importer
} // namespace omni
namespace {
PYBIND11_MODULE(_mjcf, m) {
using namespace carb;
using namespace omni::importer::mjcf;
m.doc() = R"pbdoc(
This extension provides an interface to the MJCF importer.
Example:
Setup the configuration parameters before importing.
Files must be parsed before imported.
::
from omni.importer.mjcf import _mjcf
mjcf_interface = _mjcf.acquire_mjcf_interface()
# setup config params
import_config = _mjcf.ImportConfig()
import_config.fix_base = True
# parse and import file
mjcf_interface.create_asset_mjcf(mjcf_path, prim_path, import_config)
Refer to the sample documentation for more examples and usage
)pbdoc";
py::class_<ImportConfig>(m, "ImportConfig")
.def(py::init<>())
.def_readwrite("merge_fixed_joints", &ImportConfig::mergeFixedJoints,
"Consolidating links that are connected by fixed joints")
.def_readwrite(
"convex_decomp", &ImportConfig::convexDecomp,
"Decompose a convex mesh into smaller pieces for a closer fit")
.def_readwrite("import_inertia_tensor",
&ImportConfig::importInertiaTensor,
"Import inertia tensor from mjcf, if not specified in "
"mjcf it will import as identity")
.def_readwrite("fix_base", &ImportConfig::fixBase,
"Create fix joint for base link")
.def_readwrite("self_collision", &ImportConfig::selfCollision,
"Self collisions between links in the articulation")
.def_readwrite("density", &ImportConfig::density,
"default density used for links")
//.def_readwrite("default_drive_type", &ImportConfig::defaultDriveType,
//"default drive type used for joints")
.def_readwrite("default_drive_strength",
&ImportConfig::defaultDriveStrength,
"default drive stiffness used for joints")
.def_readwrite(
"distance_scale", &ImportConfig::distanceScale,
"Set the unit scaling factor, 1.0 means meters, 100.0 means cm")
//.def_readwrite("up_vector", &ImportConfig::upVector, "Up vector used for
//import")
.def_readwrite("create_physics_scene", &ImportConfig::createPhysicsScene,
"add a physics scene to the stage on import")
.def_readwrite("make_default_prim", &ImportConfig::makeDefaultPrim,
"set imported robot as default prim")
.def_readwrite("create_body_for_fixed_joint",
&ImportConfig::createBodyForFixedJoint,
"creates body for fixed joint")
.def_readwrite("override_com", &ImportConfig::overrideCoM,
"whether to compute the center of mass from geometry and "
"override values given in the original asset")
.def_readwrite("override_inertia_tensor", &ImportConfig::overrideInertia,
"Whether to compute the inertia tensor from geometry and "
"override values given in the original asset")
.def_readwrite("make_instanceable", &ImportConfig::makeInstanceable,
"Creates an instanceable version of the asset. All meshes "
"will be placed in a separate USD file")
.def_readwrite("instanceable_usd_path",
&ImportConfig::instanceableMeshUsdPath,
"USD file to store instanceable mehses in")
// setters for each property
.def("set_merge_fixed_joints",
[](ImportConfig &config, const bool value) {
config.mergeFixedJoints = value;
})
.def("set_convex_decomp",
[](ImportConfig &config, const bool value) {
config.convexDecomp = value;
})
.def("set_import_inertia_tensor",
[](ImportConfig &config, const bool value) {
config.importInertiaTensor = value;
})
.def("set_fix_base", [](ImportConfig &config,
const bool value) { config.fixBase = value; })
.def("set_self_collision",
[](ImportConfig &config, const bool value) {
config.selfCollision = value;
})
.def("set_density", [](ImportConfig &config,
const float value) { config.density = value; })
/* .def("set_default_drive_type",
[](ImportConfig& config, const int value) {
config.defaultDriveType =
static_cast<UrdfJointTargetType>(value);
})*/
.def("set_default_drive_strength",
[](ImportConfig &config, const float value) {
config.defaultDriveStrength = value;
})
.def("set_distance_scale",
[](ImportConfig &config, const float value) {
config.distanceScale = value;
})
/* .def("set_up_vector",
[](ImportConfig& config, const float x, const float y, const
float z) { config.upVector = { x, y, z };
})*/
.def("set_create_physics_scene",
[](ImportConfig &config, const bool value) {
config.createPhysicsScene = value;
})
.def("set_make_default_prim",
[](ImportConfig &config, const bool value) {
config.makeDefaultPrim = value;
})
.def("set_create_body_for_fixed_joint",
[](ImportConfig &config, const bool value) {
config.createBodyForFixedJoint = value;
})
.def("set_override_com",
[](ImportConfig &config, const bool value) {
config.overrideCoM = value;
})
.def("set_override_inertia",
[](ImportConfig &config, const bool value) {
config.overrideInertia = value;
})
.def("set_make_instanceable",
[](ImportConfig &config, const bool value) {
config.makeInstanceable = value;
})
.def("set_instanceable_usd_path",
[](ImportConfig &config, const std::string value) {
config.instanceableMeshUsdPath = value;
})
.def("set_visualize_collision_geoms",
[](ImportConfig &config, const bool value) {
config.visualizeCollisionGeoms = value;
})
.def("set_import_sites", [](ImportConfig &config, const bool value) {
config.importSites = value;
});
defineInterfaceClass<Mjcf>(m, "Mjcf", "acquire_mjcf_interface",
"release_mjcf_interface")
.def("create_asset_mjcf",
wrapInterfaceFunction(&Mjcf::createAssetFromMJCF),
py::arg("fileName"), py::arg("primName"), py::arg("config"),
py::arg("stage_identifier") = std::string(""),
R"pbdoc(
Parse and import MJCF file.
Args:
arg0 (:obj:`str`): The absolute path to the mjcf
arg1 (:obj:`str`): Path to the robot on the USD stage
arg2 (:obj:`omni.importer.mjcf._mjcf.ImportConfig`): Import configuration
arg3 (:obj:`str`): optional: path to stage to use for importing. leaving it empty will import on open stage. If the open stage is a new stage, textures will not load.
)pbdoc");
}
} // namespace
| 8,448 | C++ | 41.671717 | 186 | 0.585701 |
NVIDIA-Omniverse/mjcf-importer-extension/source/extensions/omni.importer.mjcf/config/extension.toml | [core]
reloadable = true
order = 0
[package]
version = "1.1.0"
category = "Simulation"
title = "Omniverse MJCF Importer"
description = "MJCF Importer"
repository="https://github.com/NVIDIA-Omniverse/mjcf-importer-extension"
authors = ["Isaac Sim Team"]
keywords = ["mjcf", "mujoco", "importer", "isaac"]
changelog = "docs/CHANGELOG.md"
readme = "docs/Overview.md"
icon = "data/icon.png"
writeTarget.kit = true
preview_image = "data/preview.png"
[dependencies]
"omni.kit.uiapp" = {}
"omni.kit.window.filepicker" = {}
"omni.kit.window.content_browser" = {}
"omni.kit.pip_archive" = {} # pulls in pillow
"omni.physx" = {}
"omni.kit.commands" = {}
"omni.kit.window.extensions" = {}
"omni.kit.window.property" = {}
[[python.module]]
name = "omni.importer.mjcf"
[[python.module]]
name = "omni.importer.mjcf.tests"
[[native.plugin]]
path = "bin/*.plugin"
recursive = false
[[test]]
# this is to catch issues where our assimp is out of sync with the one that comes with
# asset importer as this can cause segfaults due to binary incompatibility.
dependencies = ["omni.kit.tool.asset_importer"]
stdoutFailPatterns.exclude = [
"*Cannot find material with name*",
"*Neither inertial nor geometries where specified for*",
"*JointSpec type free not yet supported!*",
"*is not a valid usd path*",
"*extension object is still alive, something holds a reference on it*", # exclude warning as failure
]
args = ["--/app/file/ignoreUnsavedOnExit=1"]
[documentation]
pages = [
"docs/Overview.md",
"docs/CHANGELOG.md",
]
| 1,540 | TOML | 23.854838 | 104 | 0.696104 |
NVIDIA-Omniverse/mjcf-importer-extension/source/extensions/omni.importer.mjcf/plugins/MjcfImporter.cpp | // SPDX-FileCopyrightText: Copyright (c) 2023 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
// SPDX-License-Identifier: Apache-2.0
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include "MjcfImporter.h"
#include <pxr/usd/usdGeom/plane.h>
namespace omni {
namespace importer {
namespace mjcf {
MJCFImporter::MJCFImporter(const std::string fullPath, ImportConfig &config) {
defaultClassName = "main";
std::string filePath = fullPath;
char relPathBuffer[2048];
MakeRelativePath(filePath.c_str(), "", relPathBuffer);
baseDirPath = std::string(relPathBuffer);
tinyxml2::XMLDocument doc;
tinyxml2::XMLElement *root = LoadFile(doc, filePath);
if (!root) {
return;
}
// if the mjcf file contains <include file="....">, load the included file as
// well
{
tinyxml2::XMLDocument includeDoc;
tinyxml2::XMLElement *includeElement = root->FirstChildElement("include");
tinyxml2::XMLElement *includeRoot =
LoadInclude(includeDoc, includeElement, baseDirPath);
while (includeRoot) {
LoadGlobals(includeRoot, defaultClassName, baseDirPath, worldBody, bodies,
actuators, tendons, contacts, simulationMeshCache, meshes,
materials, textures, compiler, classes, jointToActuatorIdx,
config);
includeElement = includeElement->NextSiblingElement("include");
includeRoot = LoadInclude(includeDoc, includeElement, baseDirPath);
}
}
LoadGlobals(root, defaultClassName, baseDirPath, worldBody, bodies, actuators,
tendons, contacts, simulationMeshCache, meshes, materials,
textures, compiler, classes, jointToActuatorIdx, config);
for (int i = 0; i < int(bodies.size()); ++i) {
populateBodyLookup(bodies[i]);
}
computeKinematicHierarchy();
if (!createContactGraph()) {
CARB_LOG_ERROR("*** Could not create contact graph to compute collision "
"groups! Are contacts specified properly?\n");
}
// loading is complete if it reaches here
this->isLoaded = true;
}
MJCFImporter::~MJCFImporter() {
for (int i = 0; i < (int)bodies.size(); i++) {
delete bodies[i];
}
for (int i = 0; i < (int)actuators.size(); i++) {
delete actuators[i];
}
for (int i = 0; i < (int)tendons.size(); i++) {
delete tendons[i];
}
for (int i = 0; i < (int)contacts.size(); i++) {
delete contacts[i];
}
}
void MJCFImporter::populateBodyLookup(MJCFBody *body) {
nameToBody[body->name] = body;
for (MJCFGeom *geom : body->geoms) {
// not a visual geom
if (!(geom->contype == 0 && geom->conaffinity == 0)) {
geomNameToIdx[geom->name] = int(collisionGeoms.size());
collisionGeoms.push_back(geom);
}
}
for (MJCFBody *childBody : body->bodies) {
populateBodyLookup(childBody);
}
}
bool MJCFImporter::AddPhysicsEntities(pxr::UsdStageWeakPtr stage,
const Transform trans,
const std::string &rootPrimPath,
const ImportConfig &config) {
this->createBodyForFixedJoint = config.createBodyForFixedJoint;
setStageMetadata(stage, config);
createRoot(stage, trans, rootPrimPath, config);
std::string instanceableUSDPath = config.instanceableMeshUsdPath;
if (config.makeInstanceable) {
if (config.instanceableMeshUsdPath[0] == '.') {
// make relative path relative to output directory
std::string relativePath = config.instanceableMeshUsdPath.substr(1);
std::string curStagePath = stage->GetRootLayer()->GetIdentifier();
std::string directory;
size_t pos = curStagePath.find_last_of("\\/");
directory = (std::string::npos == pos) ? "" : curStagePath.substr(0, pos);
instanceableUSDPath = directory + relativePath;
}
pxr::UsdStageRefPtr instanceableMeshStage =
pxr::UsdStage::CreateNew(instanceableUSDPath);
setStageMetadata(instanceableMeshStage, config);
for (int i = 0; i < (int)bodies.size(); i++) {
std::string rootArtPrimPath =
rootPrimPath + "/" + SanitizeUsdName(bodies[i]->name);
pxr::UsdGeomXform rootArtPrim = pxr::UsdGeomXform::Define(
instanceableMeshStage, pxr::SdfPath(rootArtPrimPath));
CreateInstanceableMeshes(instanceableMeshStage, bodies[i],
rootArtPrimPath, true, config);
}
// create instanceable assets for world body geoms
std::string worldBodyPrimPath = rootPrimPath + "/worldBody";
pxr::UsdGeomXform worldBodyPrim = pxr::UsdGeomXform::Define(
instanceableMeshStage, pxr::SdfPath(worldBodyPrimPath));
for (int i = 0; i < (int)worldBody.geoms.size(); i++) {
std::string bodyPath =
worldBodyPrimPath + "/" + SanitizeUsdName(worldBody.geoms[i]->name);
auto bodyPathSdf =
getNextFreePath(instanceableMeshStage, pxr::SdfPath(bodyPath));
bodyPath = bodyPathSdf.GetString();
std::string uniqueName = bodyPathSdf.GetName();
pxr::UsdPrim bodyLink =
pxr::UsdGeomXform::Define(instanceableMeshStage, bodyPathSdf)
.GetPrim();
bool isVisual = worldBody.geoms[i]->contype == 0 &&
worldBody.geoms[i]->conaffinity == 0;
if (isVisual) {
worldBody.hasVisual = true;
} else {
if (worldBody.geoms[i]->type != MJCFGeom::PLANE) {
std::string geomPath = bodyPath + "/collisions/" + uniqueName;
pxr::UsdPrim prim = createPrimitiveGeom(
instanceableMeshStage, geomPath, worldBody.geoms[i],
simulationMeshCache, config, false, rootPrimPath, true);
// enable collisions on prim
if (prim) {
applyCollisionGeom(instanceableMeshStage, prim, worldBody.geoms[i]);
nameToUsdCollisionPrim[worldBody.geoms[i]->name] = bodyPath;
} else {
CARB_LOG_ERROR("Collision geom %s could not created",
worldBody.geoms[i]->name.c_str());
}
}
}
std::string geomPath = bodyPath + "/visuals/" + uniqueName;
pxr::UsdPrim prim = createPrimitiveGeom(
instanceableMeshStage, geomPath, worldBody.geoms[i],
simulationMeshCache, config, true, rootPrimPath, false);
if (!config.visualizeCollisionGeoms && worldBody.hasVisual && !isVisual) {
// turn off visibility for collision prim
pxr::UsdGeomImageable imageable(prim);
imageable.MakeInvisible();
}
// parse material and texture
if (worldBody.geoms[i]->material != "") {
if (materials.find(worldBody.geoms[i]->material) != materials.end()) {
MJCFMaterial material =
materials.find(worldBody.geoms[i]->material)->second;
MJCFTexture *texture = nullptr;
if (material.texture != "") {
if (textures.find(material.texture) == textures.end()) {
CARB_LOG_ERROR("Cannot find texture with name %s.\n",
material.texture.c_str());
}
texture = &(textures.find(material.texture)->second);
// only MESH type has UV mapping
if (worldBody.geoms[i]->type == MJCFGeom::MESH) {
material.project_uvw = false;
}
}
Vec4 color = Vec4();
createAndBindMaterial(instanceableMeshStage, prim, &material, texture,
color, false);
} else {
CARB_LOG_ERROR("Cannot find material with name %s.\n",
worldBody.geoms[i]->material.c_str());
}
} else if (worldBody.geoms[i]->rgba.x != 0.2 ||
worldBody.geoms[i]->rgba.y != 0.2 ||
worldBody.geoms[i]->rgba.z != 0.2) {
// create material with color only
createAndBindMaterial(instanceableMeshStage, prim, nullptr, nullptr,
worldBody.geoms[i]->rgba, true);
}
geomPrimMap[worldBody.geoms[i]->name] = prim;
geomToBodyPrim[worldBody.geoms[i]->name] = bodyLink;
}
instanceableMeshStage->Export(instanceableUSDPath);
}
for (int i = 0; i < (int)bodies.size(); i++) {
std::string rootArtPrimPath =
rootPrimPath + "/" + SanitizeUsdName(bodies[i]->name);
pxr::UsdGeomXform rootArtPrim =
pxr::UsdGeomXform::Define(stage, pxr::SdfPath(rootArtPrimPath));
CreatePhysicsBodyAndJoint(stage, bodies[i], rootArtPrimPath, trans, true,
rootPrimPath, config, instanceableUSDPath);
}
addWorldGeomsAndSites(stage, rootPrimPath, config, instanceableUSDPath);
AddContactFilters(stage);
AddTendons(stage, rootPrimPath);
return true;
}
bool MJCFImporter::addVisualGeom(pxr::UsdStageWeakPtr stage,
pxr::UsdPrim bodyPrim, MJCFBody *body,
std::string bodyPath,
const ImportConfig &config, bool createGeoms,
const std::string rootPrimPath) {
bool hasVisualGeoms = false;
for (int i = 0; i < (int)body->geoms.size(); i++) {
bool isVisual =
body->geoms[i]->contype == 0 && body->geoms[i]->conaffinity == 0;
if (!config.makeInstanceable || createGeoms) {
std::string geomPath =
bodyPath + "/visuals/" + SanitizeUsdName(body->geoms[i]->name);
pxr::UsdPrim prim = createPrimitiveGeom(stage, geomPath, body->geoms[i],
simulationMeshCache, config, true,
rootPrimPath, false);
if (!config.visualizeCollisionGeoms && body->hasVisual && !isVisual) {
// turn off visibility for prim
pxr::UsdGeomImageable imageable(prim);
imageable.MakeInvisible();
}
// parse material and texture
if (body->geoms[i]->material != "") {
if (materials.find(body->geoms[i]->material) != materials.end()) {
MJCFMaterial material =
materials.find(body->geoms[i]->material)->second;
MJCFTexture *texture = nullptr;
if (material.texture != "") {
if (textures.find(material.texture) == textures.end()) {
CARB_LOG_ERROR("Cannot find texture with name %s.\n",
material.texture.c_str());
}
texture = &(textures.find(material.texture)->second);
// only MESH type has UV mapping
if (body->geoms[i]->type == MJCFGeom::MESH) {
material.project_uvw = false;
}
}
Vec4 color = Vec4();
createAndBindMaterial(stage, prim, &material, texture, color, false);
} else {
CARB_LOG_ERROR("Cannot find material with name %s.\n",
body->geoms[i]->material.c_str());
}
} else if (body->geoms[i]->rgba.x != 0.2 ||
body->geoms[i]->rgba.y != 0.2 ||
body->geoms[i]->rgba.z != 0.2) {
// create material with color only
createAndBindMaterial(stage, prim, nullptr, nullptr,
body->geoms[i]->rgba, true);
}
geomPrimMap[body->geoms[i]->name] = prim;
}
geomToBodyPrim[body->geoms[i]->name] = bodyPrim;
hasVisualGeoms = true;
}
return hasVisualGeoms;
}
void MJCFImporter::addVisualSites(pxr::UsdStageWeakPtr stage,
pxr::UsdPrim bodyPrim, MJCFBody *body,
std::string bodyPath,
const ImportConfig &config) {
for (int i = 0; i < (int)body->sites.size(); i++) {
std::string sitePath =
bodyPath + "/sites/" + SanitizeUsdName(body->sites[i]->name);
pxr::UsdPrim prim;
if (body->sites[i]->hasGeom) {
prim = createPrimitiveGeom(stage, sitePath, body->sites[i], config, true);
// parse material and texture
if (body->sites[i]->material != "") {
if (materials.find(body->sites[i]->material) != materials.end()) {
MJCFMaterial material =
materials.find(body->sites[i]->material)->second;
MJCFTexture *texture = nullptr;
if (material.texture != "") {
if (textures.find(material.texture) == textures.end()) {
CARB_LOG_ERROR("Cannot find texture with name %s.\n",
material.texture.c_str());
}
texture = &(textures.find(material.texture)->second);
}
Vec4 color = Vec4();
createAndBindMaterial(stage, prim, &material, texture, color, false);
} else {
CARB_LOG_ERROR("Cannot find material with name %s.\n",
body->geoms[i]->material.c_str());
}
} else if (body->sites[i]->rgba.x != 0.2 ||
body->sites[i]->rgba.y != 0.2 ||
body->sites[i]->rgba.z != 0.2) {
// create material with color only
createAndBindMaterial(stage, prim, nullptr, nullptr,
body->sites[i]->rgba, true);
}
} else {
prim = pxr::UsdGeomXform::Define(stage, pxr::SdfPath(sitePath)).GetPrim();
}
sitePrimMap[body->sites[i]->name] = prim;
siteToBodyPrim[body->sites[i]->name] = bodyPrim;
}
}
void MJCFImporter::addWorldGeomsAndSites(
pxr::UsdStageWeakPtr stage, std::string rootPath,
const ImportConfig &config, const std::string instanceableUsdPath) {
// we have to create a dummy link to place the sites/geoms defined in the
// world body
std::string dummyPath = rootPath + "/worldBody";
pxr::UsdPrim dummyLink =
pxr::UsdGeomXform::Define(stage, pxr::SdfPath(dummyPath)).GetPrim();
pxr::UsdPhysicsArticulationRootAPI physicsSchema =
pxr::UsdPhysicsArticulationRootAPI::Apply(dummyLink);
pxr::PhysxSchemaPhysxArticulationAPI physxSchema =
pxr::PhysxSchemaPhysxArticulationAPI::Apply(dummyLink);
physxSchema.CreateEnabledSelfCollisionsAttr().Set(config.selfCollision);
for (int i = 0; i < (int)worldBody.geoms.size(); i++) {
std::string bodyPath =
dummyPath + "/" + SanitizeUsdName(worldBody.geoms[i]->name);
auto bodyPathSdf = getNextFreePath(stage, pxr::SdfPath(bodyPath));
bodyPath = bodyPathSdf.GetString();
std::string uniqueName = bodyPathSdf.GetName();
pxr::UsdPrim bodyLink =
pxr::UsdGeomXform::Define(stage, bodyPathSdf).GetPrim();
pxr::UsdPhysicsRigidBodyAPI physicsAPI =
pxr::UsdPhysicsRigidBodyAPI::Apply(bodyLink);
pxr::PhysxSchemaPhysxRigidBodyAPI::Apply(bodyLink);
// createFixedRoot(stage, dummyPath + "/joints/rootJoint_" + uniqueName,
// dummyPath + "/" + uniqueName);
physicsAPI.GetKinematicEnabledAttr().Set(true);
bool hasCollisionGeoms = false;
bool isVisual = worldBody.geoms[i]->contype == 0 &&
worldBody.geoms[i]->conaffinity == 0;
if (isVisual) {
worldBody.hasVisual = true;
} else {
if (worldBody.geoms[i]->type != MJCFGeom::PLANE) {
if (!config.makeInstanceable) {
std::string geomPath = bodyPath + "/collisions/" + uniqueName;
pxr::UsdPrim prim = createPrimitiveGeom(
stage, geomPath, worldBody.geoms[i], simulationMeshCache, config,
false, rootPath, true);
// enable collisions on prim
if (prim) {
applyCollisionGeom(stage, prim, worldBody.geoms[i]);
nameToUsdCollisionPrim[worldBody.geoms[i]->name] = bodyPath;
} else {
CARB_LOG_ERROR("Collision geom %s could not created",
worldBody.geoms[i]->name.c_str());
}
}
} else {
// add collision plane (do not support instanceable asset for the plane)
pxr::SdfPath collisionPlanePath =
pxr::SdfPath(bodyPath + "/collisions/CollisionPlane");
pxr::UsdGeomPlane collisionPlane =
pxr::UsdGeomPlane::Define(stage, collisionPlanePath);
collisionPlane.CreatePurposeAttr().Set(pxr::UsdGeomTokens->guide);
collisionPlane.CreateAxisAttr().Set(pxr::UsdGeomTokens->z);
pxr::UsdPrim collisionPlanePrim = collisionPlane.GetPrim();
pxr::UsdPhysicsCollisionAPI::Apply(collisionPlanePrim);
MJCFGeom *geom = worldBody.geoms[i];
// set transformations for collision plane
pxr::GfMatrix4d mat;
mat.SetIdentity();
mat.SetTranslateOnly(
pxr::GfVec3d(geom->pos.x, geom->pos.y, geom->pos.z));
mat.SetRotateOnly(pxr::GfQuatd(geom->quat.w, geom->quat.x, geom->quat.y,
geom->quat.z));
pxr::GfMatrix4d scale;
scale.SetIdentity();
scale.SetScale(pxr::GfVec3d(config.distanceScale, config.distanceScale,
config.distanceScale));
Vec3 cen = geom->pos;
Quat q = geom->quat;
scale.SetIdentity();
mat.SetTranslateOnly(config.distanceScale *
pxr::GfVec3d(cen.x, cen.y, cen.z));
mat.SetRotateOnly(pxr::GfQuatd(q.w, q.x, q.y, q.z));
pxr::UsdGeomXformable gprim = pxr::UsdGeomXformable(collisionPlanePrim);
gprim.ClearXformOpOrder();
pxr::UsdGeomXformOp transOp = gprim.AddTransformOp();
transOp.Set(scale * mat, pxr::UsdTimeCode::Default());
}
hasCollisionGeoms = true;
}
if (config.makeInstanceable && hasCollisionGeoms &&
worldBody.geoms[i]->type != MJCFGeom::PLANE) {
// make main collisions prim instanceable and reference meshes
pxr::SdfPath collisionsPath = pxr::SdfPath(bodyPath + "/collisions");
pxr::UsdPrim collisionsPrim = stage->DefinePrim(collisionsPath);
collisionsPrim.GetReferences().AddReference(instanceableUsdPath,
collisionsPath);
collisionsPrim.SetInstanceable(true);
}
bool hasVisualGeoms = false;
if (!config.makeInstanceable) {
std::string geomPath = bodyPath + "/visuals/" + uniqueName;
pxr::UsdPrim prim = createPrimitiveGeom(
stage, geomPath, worldBody.geoms[i], simulationMeshCache, config,
true, rootPath, false);
if (!config.visualizeCollisionGeoms && worldBody.hasVisual && !isVisual) {
// turn off visibility for collision prim
pxr::UsdGeomImageable imageable(prim);
imageable.MakeInvisible();
}
// parse material and texture
if (worldBody.geoms[i]->material != "") {
if (materials.find(worldBody.geoms[i]->material) != materials.end()) {
MJCFMaterial material =
materials.find(worldBody.geoms[i]->material)->second;
MJCFTexture *texture = nullptr;
if (material.texture != "") {
if (textures.find(material.texture) == textures.end()) {
CARB_LOG_ERROR("Cannot find texture with name %s.\n",
material.texture.c_str());
}
texture = &(textures.find(material.texture)->second);
// only MESH type has UV mapping
if (worldBody.geoms[i]->type == MJCFGeom::MESH) {
material.project_uvw = false;
}
}
Vec4 color = Vec4();
createAndBindMaterial(stage, prim, &material, texture, color, false);
} else {
CARB_LOG_ERROR("Cannot find material with name %s.\n",
worldBody.geoms[i]->material.c_str());
}
} else if (worldBody.geoms[i]->rgba.x != 0.2 ||
worldBody.geoms[i]->rgba.y != 0.2 ||
worldBody.geoms[i]->rgba.z != 0.2) {
// create material with color only
createAndBindMaterial(stage, prim, nullptr, nullptr,
worldBody.geoms[i]->rgba, true);
}
geomPrimMap[worldBody.geoms[i]->name] = prim;
}
geomToBodyPrim[worldBody.geoms[i]->name] = bodyLink;
hasVisualGeoms = true;
if (config.makeInstanceable && hasVisualGeoms) {
// make main visuals prim instanceable and reference meshes
pxr::SdfPath visualsPath = pxr::SdfPath(bodyPath + "/visuals");
pxr::UsdPrim visualsPrim = stage->DefinePrim(visualsPath);
visualsPrim.GetReferences().AddReference(instanceableUsdPath,
visualsPath);
visualsPrim.SetInstanceable(true);
}
}
addVisualSites(stage, dummyLink, &worldBody, dummyPath, config);
}
void MJCFImporter::AddContactFilters(pxr::UsdStageWeakPtr stage) {
// adding collision filtering pairs
for (int i = 0; i < (int)contactGraph.size(); i++) {
std::string &primPath = nameToUsdCollisionPrim[contactGraph[i]->name];
pxr::UsdPhysicsFilteredPairsAPI filteredPairsAPI =
pxr::UsdPhysicsFilteredPairsAPI::Apply(
stage->GetPrimAtPath(pxr::SdfPath(primPath)));
std::set<int> neighborhood = contactGraph[i]->adjacentNodes;
neighborhood.insert(i);
for (int j = 0; j < (int)contactGraph.size(); j++) {
if (neighborhood.find(j) == neighborhood.end()) {
std::string &filteredPrimPath =
nameToUsdCollisionPrim[contactGraph[j]->name];
filteredPairsAPI.CreateFilteredPairsRel().AddTarget(
pxr::SdfPath(filteredPrimPath));
}
}
}
}
void MJCFImporter::AddTendons(pxr::UsdStageWeakPtr stage,
std::string rootPath) {
// adding tendons
for (const auto &t : tendons) {
if (t->type == MJCFTendon::FIXED) {
// setting the joint with the lowest kinematic hierarchy number as the
// TendonAxisRoot
if (t->fixedJoints.size() != 0) {
MJCFTendon::FixedJoint *rootJoint = t->fixedJoints[0];
for (int i = 0; i < (int)t->fixedJoints.size(); i++) {
if (jointToKinematicHierarchy[t->fixedJoints[i]->joint] <
jointToKinematicHierarchy[rootJoint->joint]) {
rootJoint = t->fixedJoints[i];
}
}
// adding the TendonAxisRoot api to the root joint
pxr::VtArray<float> coef = {rootJoint->coef};
if (revoluteJointsMap.find(rootJoint->joint) !=
revoluteJointsMap.end()) {
pxr::UsdPhysicsRevoluteJoint rootJointPrim =
revoluteJointsMap[rootJoint->joint];
pxr::PhysxSchemaPhysxTendonAxisRootAPI rootAPI =
pxr::PhysxSchemaPhysxTendonAxisRootAPI::Apply(
rootJointPrim.GetPrim(),
pxr::TfToken(SanitizeUsdName(t->name)));
if (t->limited) {
rootAPI.CreateLowerLimitAttr().Set(t->range[0]);
rootAPI.CreateUpperLimitAttr().Set(t->range[1]);
}
if (t->springlength >= 0) {
rootAPI.CreateRestLengthAttr().Set(t->springlength);
}
rootAPI.CreateStiffnessAttr().Set(t->stiffness);
rootAPI.CreateDampingAttr().Set(t->damping);
pxr::PhysxSchemaPhysxTendonAttachmentAPI(rootAPI, rootAPI.GetName())
.CreateGearingAttr()
.Set(coef);
} else if (prismaticJointsMap.find(rootJoint->joint) !=
prismaticJointsMap.end()) {
pxr::UsdPhysicsPrismaticJoint rootJointPrim =
prismaticJointsMap[rootJoint->joint];
pxr::PhysxSchemaPhysxTendonAxisRootAPI rootAPI =
pxr::PhysxSchemaPhysxTendonAxisRootAPI::Apply(
rootJointPrim.GetPrim(),
pxr::TfToken(SanitizeUsdName(t->name)));
if (t->limited) {
rootAPI.CreateLowerLimitAttr().Set(t->range[0]);
rootAPI.CreateUpperLimitAttr().Set(t->range[1]);
}
if (t->springlength >= 0) {
rootAPI.CreateRestLengthAttr().Set(t->springlength);
}
rootAPI.CreateStiffnessAttr().Set(t->stiffness);
rootAPI.CreateDampingAttr().Set(t->damping);
pxr::PhysxSchemaPhysxTendonAttachmentAPI(rootAPI, rootAPI.GetName())
.CreateGearingAttr()
.Set(coef);
} else if (d6JointsMap.find(rootJoint->joint) != d6JointsMap.end()) {
pxr::UsdPhysicsJoint rootJointPrim = d6JointsMap[rootJoint->joint];
pxr::PhysxSchemaPhysxTendonAxisRootAPI rootAPI =
pxr::PhysxSchemaPhysxTendonAxisRootAPI::Apply(
rootJointPrim.GetPrim(),
pxr::TfToken(SanitizeUsdName(t->name)));
if (t->limited) {
rootAPI.CreateLowerLimitAttr().Set(t->range[0]);
rootAPI.CreateUpperLimitAttr().Set(t->range[1]);
}
if (t->springlength >= 0) {
rootAPI.CreateRestLengthAttr().Set(t->springlength);
}
rootAPI.CreateStiffnessAttr().Set(t->stiffness);
rootAPI.CreateDampingAttr().Set(t->damping);
pxr::PhysxSchemaPhysxTendonAttachmentAPI(rootAPI, rootAPI.GetName())
.CreateGearingAttr()
.Set(coef);
} else {
CARB_LOG_ERROR("Joint %s required for tendon %s cannot be found",
rootJoint->joint.c_str(), t->name.c_str());
}
// adding TendonAxis api to the other joints in the tendon
for (int i = 0; i < (int)t->fixedJoints.size(); i++) {
if (t->fixedJoints[i]->joint != rootJoint->joint) {
MJCFTendon::FixedJoint *childJoint = t->fixedJoints[i];
pxr::VtArray<float> coef = {childJoint->coef};
if (revoluteJointsMap.find(childJoint->joint) !=
revoluteJointsMap.end()) {
pxr::UsdPhysicsRevoluteJoint childJointPrim =
revoluteJointsMap[childJoint->joint];
pxr::PhysxSchemaPhysxTendonAxisAPI axisAPI =
pxr::PhysxSchemaPhysxTendonAxisAPI::Apply(
childJointPrim.GetPrim(),
pxr::TfToken(SanitizeUsdName(t->name)));
axisAPI.CreateGearingAttr().Set(coef);
} else if (prismaticJointsMap.find(childJoint->joint) !=
prismaticJointsMap.end()) {
pxr::UsdPhysicsPrismaticJoint childJointPrim =
prismaticJointsMap[childJoint->joint];
pxr::PhysxSchemaPhysxTendonAxisAPI axisAPI =
pxr::PhysxSchemaPhysxTendonAxisAPI::Apply(
childJointPrim.GetPrim(),
pxr::TfToken(SanitizeUsdName(t->name)));
axisAPI.CreateGearingAttr().Set(coef);
} else if (d6JointsMap.find(childJoint->joint) !=
d6JointsMap.end()) {
pxr::UsdPhysicsJoint childJointPrim =
d6JointsMap[childJoint->joint];
pxr::PhysxSchemaPhysxTendonAxisAPI axisAPI =
pxr::PhysxSchemaPhysxTendonAxisAPI::Apply(
childJointPrim.GetPrim(),
pxr::TfToken(SanitizeUsdName(t->name)));
axisAPI.CreateGearingAttr().Set(coef);
} else {
CARB_LOG_ERROR("Joint %s required for tendon %s cannot be found",
childJoint->joint.c_str(), t->name.c_str());
}
}
}
} else {
CARB_LOG_ERROR(
"%s cannot be added since it has no specified joints to attach to.",
t->name.c_str());
}
} else if (t->type == MJCFTendon::SPATIAL) {
std::map<std::string, int> attachmentNames;
bool isFirstAttachment = true;
if (t->spatialAttachments.size() > 0) {
for (auto it = t->spatialBranches.begin();
it != t->spatialBranches.end(); it++) {
std::vector<MJCFTendon::SpatialAttachment *> attachments = it->second;
pxr::UsdPrim parentPrim;
std::string parentName;
for (int i = (int)attachments.size() - 1; i >= 0; --i) {
MJCFTendon::SpatialAttachment *attachment = attachments[i];
std::string name;
pxr::UsdPrim linkPrim;
bool hasLink = false;
if (attachment->type == MJCFTendon::SpatialAttachment::GEOM) {
name = attachment->geom;
if (geomToBodyPrim.find(name) != geomToBodyPrim.end()) {
linkPrim = geomToBodyPrim[name];
hasLink = true;
}
} else if (attachment->type ==
MJCFTendon::SpatialAttachment::SITE) {
name = attachment->site;
if (siteToBodyPrim.find(name) != siteToBodyPrim.end()) {
linkPrim = siteToBodyPrim[name];
hasLink = true;
}
}
if (!hasLink) {
pxr::UsdPrim dummyLink =
stage->GetPrimAtPath(pxr::SdfPath(rootPath + "/worldBody"));
// check if they are part of the world sites/geoms
if (attachment->type == MJCFTendon::SpatialAttachment::GEOM) {
name = attachment->geom;
linkPrim = dummyLink;
geomToBodyPrim[name] = dummyLink;
hasLink = true;
} else if (attachment->type ==
MJCFTendon::SpatialAttachment::SITE) {
name = attachment->site;
linkPrim = dummyLink;
siteToBodyPrim[name] = dummyLink;
hasLink = true;
}
if (!hasLink) {
// we shouldn't be here...
CARB_LOG_ERROR("Error adding attachment %s. Failed to find "
"attached link.\n",
name.c_str());
}
}
// create additional attachments if duplicates are found
if (attachmentNames.find(name) != attachmentNames.end()) {
attachmentNames[name]++;
name = name + "_" + std::to_string(attachmentNames[name] - 1);
} else {
attachmentNames[name] = 0;
}
// setting the first attachment link as the AttachmentRoot
if (isFirstAttachment) {
isFirstAttachment = false;
parentPrim = linkPrim;
parentName = name;
auto rootApi =
pxr::PhysxSchemaPhysxTendonAttachmentRootAPI::Apply(
linkPrim, pxr::TfToken(name));
pxr::GfVec3f localPos = GetLocalPos(*attachment);
pxr::PhysxSchemaPhysxTendonAttachmentAPI(rootApi,
pxr::TfToken(name))
.CreateLocalPosAttr()
.Set(localPos);
rootApi.CreateStiffnessAttr().Set(t->stiffness);
rootApi.CreateDampingAttr().Set(t->damping);
}
// last attachment point
else if (i == 0) {
auto leafApi =
pxr::PhysxSchemaPhysxTendonAttachmentLeafAPI::Apply(
linkPrim, pxr::TfToken(name));
pxr::PhysxSchemaPhysxTendonAttachmentAPI(leafApi,
pxr::TfToken(name))
.CreateParentLinkRel()
.AddTarget(parentPrim.GetPath());
pxr::PhysxSchemaPhysxTendonAttachmentAPI(leafApi,
pxr::TfToken(name))
.CreateParentAttachmentAttr()
.Set(pxr::TfToken(parentName));
pxr::GfVec3f localPos = GetLocalPos(*attachment);
pxr::PhysxSchemaPhysxTendonAttachmentAPI(leafApi,
pxr::TfToken(name))
.CreateLocalPosAttr()
.Set(localPos);
}
// intermediate attachment point
else {
auto attachmentApi =
pxr::PhysxSchemaPhysxTendonAttachmentAPI::Apply(
linkPrim, pxr::TfToken(name));
attachmentApi.CreateParentLinkRel().AddTarget(
parentPrim.GetPath());
attachmentApi.CreateParentAttachmentAttr().Set(
pxr::TfToken(parentName));
pxr::GfVec3f localPos = GetLocalPos(*attachment);
attachmentApi.CreateLocalPosAttr().Set(localPos);
}
// set current body as parent
parentName = name;
parentPrim = linkPrim;
}
}
} else {
CARB_LOG_ERROR("Spatial tendon %s cannot be added since it has no "
"attachments specified.",
t->name.c_str());
}
} else {
CARB_LOG_ERROR("Tendon %s is not a fixed or spatial tendon. Only fixed "
"and spatial tendons are currently supported.",
t->name.c_str());
}
}
}
pxr::GfVec3f
MJCFImporter::GetLocalPos(MJCFTendon::SpatialAttachment attachment) {
pxr::GfVec3f localPos;
if (attachment.type == MJCFTendon::SpatialAttachment::GEOM) {
if (geomToBodyPrim.find(attachment.geom) != geomToBodyPrim.end()) {
const pxr::UsdPrim rootPrim = geomToBodyPrim[attachment.geom];
const pxr::UsdPrim geomPrim = geomPrimMap[attachment.geom];
pxr::GfVec3d geomTranslate =
pxr::UsdGeomXformable(geomPrim)
.ComputeLocalToWorldTransform(pxr::UsdTimeCode::Default())
.ExtractTranslation();
pxr::GfVec3d linkTranslate =
pxr::UsdGeomXformable(rootPrim)
.ComputeLocalToWorldTransform(pxr::UsdTimeCode::Default())
.ExtractTranslation();
localPos = pxr::GfVec3f(geomTranslate - linkTranslate);
}
} else if (attachment.type == MJCFTendon::SpatialAttachment::SITE) {
if (siteToBodyPrim.find(attachment.site) != siteToBodyPrim.end()) {
pxr::UsdPrim rootPrim = siteToBodyPrim[attachment.site];
pxr::UsdPrim sitePrim = sitePrimMap[attachment.site];
pxr::GfVec3d siteTranslate =
pxr::UsdGeomXformable(sitePrim)
.ComputeLocalToWorldTransform(pxr::UsdTimeCode::Default())
.ExtractTranslation();
pxr::GfVec3d linkTranslate =
pxr::UsdGeomXformable(rootPrim)
.ComputeLocalToWorldTransform(pxr::UsdTimeCode::Default())
.ExtractTranslation();
localPos = pxr::GfVec3f(siteTranslate - linkTranslate);
}
}
return localPos;
}
void MJCFImporter::CreateInstanceableMeshes(pxr::UsdStageRefPtr stage,
MJCFBody *body,
const std::string rootPrimPath,
const bool isRoot,
const ImportConfig &config) {
if ((!createBodyForFixedJoint) && ((body->joints.size() == 0) && (!isRoot))) {
CARB_LOG_WARN("RigidBodySpec with no joint will have no geometry for now, "
"to avoid instability of fixed joint!");
} else {
if (!body->inertial && body->geoms.size() == 0) {
CARB_LOG_WARN(
"*** Neither inertial nor geometries where specified for %s",
body->name.c_str());
return;
}
std::string bodyPath = rootPrimPath + "/" + SanitizeUsdName(body->name);
// add collision geoms first to detect whether visuals are available
for (int i = 0; i < (int)body->geoms.size(); i++) {
bool isVisual =
body->geoms[i]->contype == 0 && body->geoms[i]->conaffinity == 0;
if (isVisual) {
body->hasVisual = true;
} else {
std::string geomPath =
bodyPath + "/collisions/" + SanitizeUsdName(body->geoms[i]->name);
pxr::UsdPrim prim = createPrimitiveGeom(stage, geomPath, body->geoms[i],
simulationMeshCache, config,
false, rootPrimPath, true);
// enable collisions on prim
if (prim) {
applyCollisionGeom(stage, prim, body->geoms[i]);
nameToUsdCollisionPrim[body->geoms[i]->name] = bodyPath;
} else {
CARB_LOG_ERROR("Collision geom %s could not be created",
body->geoms[i]->name.c_str());
}
}
}
// add visual geoms
addVisualGeom(stage, pxr::UsdPrim(), body, bodyPath, config, true,
rootPrimPath);
// recursively create children's bodies
for (int i = 0; i < (int)body->bodies.size(); i++) {
CreateInstanceableMeshes(stage, body->bodies[i], rootPrimPath, false,
config);
}
}
}
void MJCFImporter::CreatePhysicsBodyAndJoint(
pxr::UsdStageWeakPtr stage, MJCFBody *body, std::string rootPrimPath,
const Transform trans, const bool isRoot, const std::string parentBodyPath,
const ImportConfig &config, const std::string instanceableUsdPath) {
Transform myTrans;
myTrans = trans * Transform(body->pos, body->quat);
int numJoints = (int)body->joints.size();
if ((!createBodyForFixedJoint) && ((body->joints.size() == 0) && (!isRoot))) {
CARB_LOG_WARN("RigidBodySpec with no joint will have no geometry for now, "
"to avoid instability of fixed joint!");
} else {
if (!body->inertial && body->geoms.size() == 0) {
CARB_LOG_WARN(
"*** Neither inertial nor geometries where specified for %s",
body->name.c_str());
return;
}
std::string bodyPath = rootPrimPath + "/" + SanitizeUsdName(body->name);
pxr::UsdGeomXformable bodyPrim =
createBody(stage, bodyPath, myTrans, config);
// add Rigid Body
if (bodyPrim) {
applyRigidBody(bodyPrim, body, config);
} else {
CARB_LOG_ERROR("Body prim %s could not created", body->name.c_str());
return;
}
if (isRoot) {
pxr::UsdGeomXform rootPrim =
pxr::UsdGeomXform::Define(stage, pxr::SdfPath(rootPrimPath));
applyArticulationAPI(stage, rootPrim, config);
if (config.fixBase || numJoints == 0) {
// enable multiple root joints
createFixedRoot(stage,
rootPrimPath + "/joints/rootJoint_" +
SanitizeUsdName(body->name),
rootPrimPath + "/" + SanitizeUsdName(body->name));
}
}
// add collision geoms first to detect whether visuals are available
bool hasCollisionGeoms = false;
for (int i = 0; i < (int)body->geoms.size(); i++) {
bool isVisual =
body->geoms[i]->contype == 0 && body->geoms[i]->conaffinity == 0;
if (isVisual) {
body->hasVisual = true;
} else {
if (!config.makeInstanceable) {
std::string geomPath =
bodyPath + "/collisions/" + SanitizeUsdName(body->geoms[i]->name);
pxr::UsdPrim prim = createPrimitiveGeom(
stage, geomPath, body->geoms[i], simulationMeshCache, config,
false, rootPrimPath, true);
// enable collisions on prim
if (prim) {
applyCollisionGeom(stage, prim, body->geoms[i]);
nameToUsdCollisionPrim[body->geoms[i]->name] = bodyPath;
} else {
CARB_LOG_ERROR("Collision geom %s could not created",
body->geoms[i]->name.c_str());
}
}
hasCollisionGeoms = true;
}
}
if (config.makeInstanceable && hasCollisionGeoms) {
// make main collisions prim instanceable and reference meshes
pxr::SdfPath collisionsPath = pxr::SdfPath(bodyPath + "/collisions");
pxr::UsdPrim collisionsPrim = stage->DefinePrim(collisionsPath);
collisionsPrim.GetReferences().AddReference(instanceableUsdPath,
collisionsPath);
collisionsPrim.SetInstanceable(true);
}
// add visual geoms
bool hasVisualGeoms = addVisualGeom(stage, bodyPrim.GetPrim(), body,
bodyPath, config, false, rootPrimPath);
if (config.makeInstanceable && hasVisualGeoms) {
// make main visuals prim instanceable and reference meshes
pxr::SdfPath visualsPath = pxr::SdfPath(bodyPath + "/visuals");
pxr::UsdPrim visualsPrim = stage->DefinePrim(visualsPath);
visualsPrim.GetReferences().AddReference(instanceableUsdPath,
visualsPath);
visualsPrim.SetInstanceable(true);
}
// add sites
if (config.importSites) {
addVisualSites(stage, bodyPrim.GetPrim(), body, bodyPath, config);
}
// int numJoints = (int)body->joints.size();
// add joints
// create joint linked to parent
// if the body is a root and there is no joint for the root, do not need to
// go into this if statement to create any joints. However, if the root body
// has joints but the import config has fixBase set to true, also no need to
// create any additional joints.
if (!(isRoot && (numJoints == 0 || config.fixBase))) {
// jointSpec transform
Transform origin;
if (body->joints.size() > 0) {
// origin at last joint (deepest)
origin.p = body->joints[0]->pos;
} else {
origin.p = Vec3(0.0f, 0.0f, 0.0f);
}
// compute joint frame and map joint axes to D6 axes
int axisMap[3] = {0, 1, 2};
computeJointFrame(origin, axisMap, body);
origin = myTrans * origin;
Transform ptran = trans;
Transform mtran = myTrans;
Transform ppose = (Inverse(ptran)) * origin;
Transform cpose = (Inverse(mtran)) * origin;
std::string jointPath =
rootPrimPath + "/joints/" + SanitizeUsdName(body->name);
int numJoints = (int)body->joints.size();
if (numJoints == 0) {
Transform poseJointToParentBody = Transform(body->pos, body->quat);
Transform poseJointToChildBody = Transform();
pxr::UsdPhysicsJoint jointPrim = createFixedJoint(
stage, jointPath, poseJointToParentBody, poseJointToChildBody,
parentBodyPath, bodyPath, config);
} else if (numJoints == 1) {
Transform poseJointToParentBody = Transform(ppose.p, ppose.q);
Transform poseJointToChildBody = Transform(cpose.p, cpose.q);
MJCFJoint *joint = body->joints.front();
std::string jointPath =
rootPrimPath + "/joints/" + SanitizeUsdName(joint->name);
auto actuatorIterator = jointToActuatorIdx.find(joint->name);
int actuatorIdx = actuatorIterator != jointToActuatorIdx.end()
? actuatorIterator->second
: -1;
MJCFActuator *actuator = nullptr;
if (actuatorIdx != -1) {
actuatorIdx = actuatorIterator->second;
actuator = actuators[actuatorIdx];
}
if (joint->type == MJCFJoint::HINGE) {
pxr::UsdPhysicsRevoluteJoint jointPrim =
pxr::UsdPhysicsRevoluteJoint::Define(stage,
pxr::SdfPath(jointPath));
initPhysicsJoint(jointPrim, poseJointToParentBody,
poseJointToChildBody, parentBodyPath, bodyPath,
config.distanceScale);
applyPhysxJoint(jointPrim, joint);
// joint was aligned such that its hinge axis is aligned with local
// x-axis.
jointPrim.CreateAxisAttr().Set(pxr::UsdPhysicsTokens->x);
if (joint->limited) {
jointPrim.CreateLowerLimitAttr().Set(joint->range.x * 180 / kPi);
jointPrim.CreateUpperLimitAttr().Set(joint->range.y * 180 / kPi);
}
pxr::PhysxSchemaPhysxLimitAPI physxLimitAPI =
pxr::PhysxSchemaPhysxLimitAPI::Apply(
jointPrim.GetPrim(), pxr::TfToken(pxr::UsdPhysicsTokens->x));
physxLimitAPI.CreateStiffnessAttr().Set(joint->stiffness);
physxLimitAPI.CreateDampingAttr().Set(joint->damping);
revoluteJointsMap[joint->name] = jointPrim;
createJointDrives(jointPrim, joint, actuator, "X", config);
} else if (joint->type == MJCFJoint::SLIDE) {
pxr::UsdPhysicsPrismaticJoint jointPrim =
pxr::UsdPhysicsPrismaticJoint::Define(stage,
pxr::SdfPath(jointPath));
initPhysicsJoint(jointPrim, poseJointToParentBody,
poseJointToChildBody, parentBodyPath, bodyPath,
config.distanceScale);
applyPhysxJoint(jointPrim, joint);
// joint was aligned such that its hinge axis is aligned with local
// x-axis.
jointPrim.CreateAxisAttr().Set(pxr::UsdPhysicsTokens->x);
if (joint->limited) {
jointPrim.CreateLowerLimitAttr().Set(config.distanceScale *
joint->range.x);
jointPrim.CreateUpperLimitAttr().Set(config.distanceScale *
joint->range.y);
}
pxr::PhysxSchemaPhysxLimitAPI physxLimitAPI =
pxr::PhysxSchemaPhysxLimitAPI::Apply(
jointPrim.GetPrim(), pxr::TfToken(pxr::UsdPhysicsTokens->x));
physxLimitAPI.CreateStiffnessAttr().Set(joint->stiffness);
physxLimitAPI.CreateDampingAttr().Set(joint->damping);
prismaticJointsMap[joint->name] = jointPrim;
createJointDrives(jointPrim, joint, actuator, "X", config);
} else if (joint->type == MJCFJoint::BALL) {
pxr::UsdPhysicsJoint jointPrim = createD6Joint(
stage, jointPath, poseJointToParentBody, poseJointToChildBody,
parentBodyPath, bodyPath, config);
applyPhysxJoint(jointPrim, body->joints[0]);
// lock all translational axes to create a D6 joint.
std::string translationAxes[6] = {"transX", "transY", "transZ"};
for (int i = 0; i < 3; ++i) {
pxr::UsdPhysicsLimitAPI limitAPI = pxr::UsdPhysicsLimitAPI::Apply(
jointPrim.GetPrim(), pxr::TfToken(translationAxes[i]));
limitAPI.CreateLowAttr().Set(1.0f);
limitAPI.CreateHighAttr().Set(-1.0f);
}
d6JointsMap[joint->name] = jointPrim;
} else if (joint->type == MJCFJoint::FREE) {
} else {
CARB_LOG_WARN("*** Only hinge, slide, ball, and free joints are "
"supported by MJCF importer");
}
} else {
Transform poseJointToParentBody = Transform(ppose.p, ppose.q);
Transform poseJointToChildBody = Transform(cpose.p, cpose.q);
pxr::UsdPhysicsJoint jointPrim = createD6Joint(
stage, jointPath, poseJointToParentBody, poseJointToChildBody,
parentBodyPath, bodyPath, config);
applyPhysxJoint(jointPrim, body->joints[0]);
// TODO: this needs to be updated to support all joint types and
// combinations set joint limits
for (int jid = 0; jid < (int)body->joints.size(); jid++) {
// all locked
for (int k = 0; k < 6; ++k) {
body->joints[jid]->velocityLimits[k] = 100.f;
}
if (body->joints[jid]->type != MJCFJoint::HINGE &&
body->joints[jid]->type != MJCFJoint::SLIDE) {
CARB_LOG_WARN("*** Only hinge and slide joints are supported by "
"MJCF importer");
continue;
}
if (body->joints[jid]->ref != 0.0f) {
CARB_LOG_WARN(
"Don't know how to deal with joint with ref != 0 yet");
}
// actuators - TODO: how do we set this part? what do we need to set?
auto actuatorIterator =
jointToActuatorIdx.find(body->joints[jid]->name);
int actuatorIdx = actuatorIterator != jointToActuatorIdx.end()
? actuatorIterator->second
: -1;
MJCFActuator *actuator = nullptr;
if (actuatorIdx != -1) {
actuatorIdx = actuatorIterator->second;
actuator = actuators[actuatorIdx];
}
applyJointLimits(jointPrim, body->joints[jid], actuator, axisMap, jid,
numJoints, config);
d6JointsMap[body->joints[jid]->name] = jointPrim;
}
}
}
// recursively create children's bodies
for (int i = 0; i < (int)body->bodies.size(); i++) {
CreatePhysicsBodyAndJoint(stage, body->bodies[i], rootPrimPath, myTrans,
false, bodyPath, config, instanceableUsdPath);
}
}
}
void MJCFImporter::computeJointFrame(Transform &origin, int *axisMap,
const MJCFBody *body) {
if (body->joints.size() == 0) {
origin.q = Quat();
} else {
if (body->joints.size() == 1) {
// align D6 x-axis with the given axis
origin.q = GetRotationQuat({1.0f, 0.0f, 0.0f}, body->joints[0]->axis);
} else if (body->joints.size() == 2) {
Quat Q = GetRotationQuat(body->joints[0]->axis, {1.0f, 0.0f, 0.0f});
Vec3 a = {1.0f, 0.0f, 0.0f};
Vec3 b = Normalize(Rotate(Q, body->joints[1]->axis));
if (fabs(Dot(a, b)) > 1e-4f) {
CARB_LOG_WARN("*** Non-othogonal joint axes are not supported");
// exit(0);
}
// map third axis to D6 y- or z-axis and compute third axis accordingly
Vec3 c;
if (std::fabs(Dot(b, {0.0f, 1.0f, 0.0f})) >
std::fabs(Dot(b, {0.0f, 0.0f, 1.0f}))) {
axisMap[1] = 1;
c = Normalize(Cross(body->joints[0]->axis, body->joints[1]->axis));
Matrix33 M(Normalize(body->joints[0]->axis),
Normalize(body->joints[1]->axis), c);
origin.q = Quat(M);
} else {
axisMap[1] = 2;
axisMap[2] = 1;
c = Normalize(Cross(body->joints[1]->axis, body->joints[0]->axis));
Matrix33 M(Normalize(body->joints[0]->axis), c,
Normalize(body->joints[1]->axis));
origin.q = Quat(M);
}
} else if (body->joints.size() == 3) {
Quat Q = GetRotationQuat(body->joints[0]->axis, {1.0f, 0.0f, 0.0f});
Vec3 a = {1.0f, 0.0f, 0.0f};
Vec3 b = Normalize(Rotate(Q, body->joints[1]->axis));
Vec3 c = Normalize(Rotate(Q, body->joints[2]->axis));
if (fabs(Dot(a, b)) > 1e-4f || fabs(Dot(a, c)) > 1e-4f ||
fabs(Dot(b, c)) > 1e-4f) {
CARB_LOG_WARN("*** Non-othogonal joint axes are not supported");
// exit(0);
}
if (std::fabs(Dot(b, {0.0f, 1.0f, 0.0f})) >
std::fabs(Dot(b, {0.0f, 0.0f, 1.0f}))) {
axisMap[1] = 1;
axisMap[2] = 2;
Matrix33 M(Normalize(body->joints[0]->axis),
Normalize(body->joints[1]->axis),
Normalize(body->joints[2]->axis));
origin.q = Quat(M);
} else {
axisMap[1] = 2;
axisMap[2] = 1;
Matrix33 M(Normalize(body->joints[0]->axis),
Normalize(body->joints[2]->axis),
Normalize(body->joints[1]->axis));
origin.q = Quat(M);
}
} else {
CARB_LOG_ERROR("*** Don't know how to handle >3 joints per body pair");
exit(0);
}
}
}
bool MJCFImporter::contactBodyExclusion(MJCFBody *body1, MJCFBody *body2) {
// Assumes that contact graph is already set up
// handle current geoms first
for (MJCFGeom *geom1 : body1->geoms) {
if (geom1->conaffinity & geom1->contype) {
for (MJCFGeom *geom2 : body2->geoms) {
if (geom2->conaffinity & geom2->contype) {
auto index1 = geomNameToIdx.find(geom1->name);
auto index2 = geomNameToIdx.find(geom2->name);
if (index1 == geomNameToIdx.end() || index2 == geomNameToIdx.end()) {
return false;
}
int geomIndex1 = index1->second;
int geomIndex2 = index2->second;
contactGraph[geomIndex1]->adjacentNodes.erase(geomIndex2);
contactGraph[geomIndex2]->adjacentNodes.erase(geomIndex1);
}
}
}
}
return true;
}
bool MJCFImporter::createContactGraph() {
contactGraph = std::vector<ContactNode *>();
// initialize nodes with no contacts
for (int i = 0; i < int(collisionGeoms.size()); ++i) {
ContactNode *node = new ContactNode();
node->name = collisionGeoms[i]->name;
contactGraph.push_back(node);
}
// First check pairwise compatability with contype/conaffinity
for (int i = 0; i < int(collisionGeoms.size()) - 1; ++i) {
for (int j = i + 1; j < int(collisionGeoms.size()); ++j) {
MJCFGeom *geom1 = collisionGeoms[i];
MJCFGeom *geom2 = collisionGeoms[j];
if ((geom1->contype & geom2->conaffinity) ||
(geom2->contype && geom1->conaffinity)) {
contactGraph[i]->adjacentNodes.insert(j);
contactGraph[j]->adjacentNodes.insert(i);
}
}
}
// Handle contact specifications
for (auto &contact : contacts) {
if (contact->type == MJCFContact::PAIR) {
auto index1 = geomNameToIdx.find(contact->geom1);
auto index2 = geomNameToIdx.find(contact->geom2);
if (index1 == geomNameToIdx.end() || index2 == geomNameToIdx.end()) {
return false;
}
int geomIndex1 = index1->second;
int geomIndex2 = index2->second;
contactGraph[geomIndex1]->adjacentNodes.insert(geomIndex2);
contactGraph[geomIndex2]->adjacentNodes.insert(geomIndex1);
} else if (contact->type == MJCFContact::EXCLUDE) {
// this is on the level of bodies, not geoms
auto body1 = nameToBody.find(contact->body1);
auto body2 = nameToBody.find(contact->body2);
if (body1 == nameToBody.end() || body2 == nameToBody.end()) {
return false;
}
if (!contactBodyExclusion(body1->second, body2->second)) {
return false;
}
}
}
return true;
}
void MJCFImporter::computeKinematicHierarchy() {
// prepare bodyQueue for breadth-first search
for (int i = 0; i < int(bodies.size()); i++) {
bodyQueue.push(bodies[i]);
}
int level_num = 0;
int num_bodies_at_level;
while (bodyQueue.size() != 0) {
num_bodies_at_level = (int)bodyQueue.size();
for (int i = 0; i < num_bodies_at_level; i++) {
MJCFBody *body = bodyQueue.front();
bodyQueue.pop();
for (MJCFBody *childBody : body->bodies) {
bodyQueue.push(childBody);
}
for (MJCFJoint *joint : body->joints) {
jointToKinematicHierarchy[joint->name] = level_num;
}
}
level_num += 1;
}
}
} // namespace mjcf
} // namespace importer
} // namespace omni
| 55,135 | C++ | 39.932442 | 99 | 0.57887 |
NVIDIA-Omniverse/mjcf-importer-extension/source/extensions/omni.importer.mjcf/plugins/MjcfParser.cpp | // SPDX-FileCopyrightText: Copyright (c) 2023 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
// SPDX-License-Identifier: Apache-2.0
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include "MjcfParser.h"
#include "MeshImporter.h"
#include "MjcfUtils.h"
#include <carb/logging/Log.h>
namespace omni {
namespace importer {
namespace mjcf {
int bodyIdxCount = 0;
int geomIdxCount = 0;
int siteIdxCount = 0;
int jointIdxCount = 0;
tinyxml2::XMLElement *LoadInclude(tinyxml2::XMLDocument &doc,
const tinyxml2::XMLElement *c,
const std::string baseDirPath) {
if (c) {
std::string s;
if ((s = GetAttr(c, "file")) != "") {
std::string fileName(s);
std::string filePath = baseDirPath + fileName;
tinyxml2::XMLElement *root = LoadFile(doc, filePath);
return root;
}
}
return nullptr;
}
void LoadCompiler(tinyxml2::XMLElement *c, MJCFCompiler &compiler) {
if (c) {
std::string s;
if ((s = GetAttr(c, "eulerseq")) != "") {
for (int i = (int)s.length() - 1; i >= 0; i--) {
char axis = s[i];
if (axis == 'X' || axis == 'Y' || axis == 'Z') {
CARB_LOG_ERROR("The MJCF importer currently only supports intrinsic "
"euler rotations!");
}
}
compiler.eulerseq = s;
}
if ((s = GetAttr(c, "angle")) != "") {
compiler.angleInRad = (s == "radian");
}
if ((s = GetAttr(c, "inertiafromgeom")) != "") {
compiler.inertiafromgeom = (s == "true");
}
if ((s = GetAttr(c, "coordinate")) != "") {
compiler.coordinateInLocal = (s == "local");
if (!compiler.coordinateInLocal) {
CARB_LOG_ERROR(
"The global coordinate is no longer supported by MuJoCo!");
}
}
getIfExist(c, "meshdir", compiler.meshDir);
getIfExist(c, "texturedir", compiler.textureDir);
getIfExist(c, "autolimits", compiler.autolimits);
}
}
void LoadInertial(tinyxml2::XMLElement *i, MJCFInertial &inertial) {
if (!i) {
return;
}
getIfExist(i, "mass", inertial.mass);
getIfExist(i, "pos", inertial.pos);
getIfExist(i, "diaginertia", inertial.diaginertia);
float fullInertia[6];
const char *st = i->Attribute("fullinertia");
if (st) {
sscanf(st, "%f %f %f %f %f %f", &fullInertia[0], &fullInertia[1],
&fullInertia[2], &fullInertia[3], &fullInertia[4], &fullInertia[5]);
inertial.hasFullInertia = true;
Matrix33 inertiaMatrix;
inertiaMatrix.cols[0] =
Vec3(fullInertia[0], fullInertia[3], fullInertia[4]);
inertiaMatrix.cols[1] =
Vec3(fullInertia[3], fullInertia[1], fullInertia[5]);
inertiaMatrix.cols[2] =
Vec3(fullInertia[4], fullInertia[5], fullInertia[2]);
Quat principalAxes;
inertial.diaginertia = Diagonalize(inertiaMatrix, principalAxes);
inertial.principalAxes = principalAxes;
}
}
void LoadGeom(tinyxml2::XMLElement *g, MJCFGeom &geom, std::string className,
MJCFCompiler &compiler, std::map<std::string, MJCFClass> &classes,
bool isDefault) {
if (!g) {
return;
}
if (g->Attribute("class"))
className = g->Attribute("class");
geom = classes[className].dgeom;
getIfExist(g, "conaffinity", geom.conaffinity);
getIfExist(g, "condim", geom.condim);
getIfExist(g, "contype", geom.contype);
getIfExist(g, "margin", geom.margin);
getIfExist(g, "friction", geom.friction);
getIfExist(g, "material", geom.material);
getIfExist(g, "rgba", geom.rgba);
getIfExist(g, "solimp", geom.solimp);
getIfExist(g, "solref", geom.solref);
getIfExist(g, "fromto", geom.from, geom.to);
getIfExist(g, "size", geom.size);
getIfExist(g, "name", geom.name);
getIfExist(g, "pos", geom.pos);
getEulerIfExist(g, "euler", geom.quat, compiler.eulerseq,
compiler.angleInRad);
getAngleAxisIfExist(g, "axisangle", geom.quat, compiler.angleInRad);
getZAxisIfExist(g, "zaxis", geom.quat);
getIfExist(g, "quat", geom.quat);
getIfExist(g, "density", geom.density);
getIfExist(g, "mesh", geom.mesh);
if (geom.name == "" && !isDefault) {
geom.name = "_geom_" + std::to_string(geomIdxCount);
geomIdxCount++;
}
if (g->Attribute("fromto")) {
geom.hasFromTo = true;
}
std::string type = "";
getIfExist(g, "type", type);
if (type == "capsule") {
geom.type = MJCFGeom::CAPSULE;
} else if (type == "sphere") {
geom.type = MJCFGeom::SPHERE;
} else if (type == "ellipsoid") {
geom.type = MJCFGeom::ELLIPSOID;
} else if (type == "cylinder") {
geom.type = MJCFGeom::CYLINDER;
} else if (type == "box") {
geom.type = MJCFGeom::BOX;
} else if (type == "mesh") {
geom.type = MJCFGeom::MESH;
} else if (type == "plane") {
geom.type = MJCFGeom::PLANE;
} else if (type != "") {
geom.type = MJCFGeom::OTHER;
std::cout << "Geom type " << type << " not yet supported!" << std::endl;
}
if (!isDefault && geom.name == "") {
geom.name = type;
}
}
void LoadSite(tinyxml2::XMLElement *s, MJCFSite &site, std::string className,
MJCFCompiler &compiler, std::map<std::string, MJCFClass> &classes,
bool isDefault) {
if (!s) {
return;
}
if (s->Attribute("class"))
className = s->Attribute("class");
site = classes[className].dsite;
getIfExist(s, "material", site.material);
getIfExist(s, "rgba", site.rgba);
getIfExist(s, "fromto", site.from, site.to);
getIfExist(s, "size", site.size);
getIfExist(s, "name", site.name);
getIfExist(s, "pos", site.pos);
getEulerIfExist(s, "euler", site.quat, compiler.eulerseq,
compiler.angleInRad);
getAngleAxisIfExist(s, "axisangle", site.quat, compiler.angleInRad);
getZAxisIfExist(s, "zaxis", site.quat);
getIfExist(s, "quat", site.quat);
if (site.name == "" && !isDefault) {
site.name = "_site_" + std::to_string(siteIdxCount);
siteIdxCount++;
}
if (s->Attribute("fromto") || classes[className].dsite.hasFromTo) {
site.hasFromTo = true;
}
if ((!s->Attribute("size") && !classes[className].dsite.hasGeom) &&
!site.hasFromTo) {
site.hasGeom = false;
}
std::string type = "";
getIfExist(s, "type", type);
if (type == "capsule") {
site.type = MJCFSite::CAPSULE;
} else if (type == "sphere") {
site.type = MJCFSite::SPHERE;
} else if (type == "ellipsoid") {
site.type = MJCFSite::ELLIPSOID;
} else if (type == "cylinder") {
site.type = MJCFSite::CYLINDER;
} else if (type == "box") {
site.type = MJCFSite::BOX;
} else if (type != "") {
std::cout << "Site type " << type << " not yet supported!" << std::endl;
}
if (!isDefault && site.name == "") {
site.name = type;
}
}
void LoadMesh(tinyxml2::XMLElement *m, MJCFMesh &mesh, std::string className,
MJCFCompiler &compiler,
std::map<std::string, MJCFClass> &classes) {
if (!m) {
return;
}
if (m->Attribute("class"))
className = m->Attribute("class");
mesh = classes[className].dmesh;
getIfExist(m, "name", mesh.name);
getIfExist(m, "file", mesh.filename);
getIfExist(m, "scale", mesh.scale);
}
void LoadActuator(tinyxml2::XMLElement *g, MJCFActuator &actuator,
std::string className, MJCFActuator::Type type,
std::map<std::string, MJCFClass> &classes) {
if (!g) {
return;
}
if (g->Attribute("class")) {
className = g->Attribute("class");
}
actuator = classes[className].dactuator;
actuator.type = type;
getIfExist(g, "ctrllimited", actuator.ctrllimited);
getIfExist(g, "forcelimited", actuator.forcelimited);
getIfExist(g, "ctrlrange", actuator.ctrlrange);
getIfExist(g, "forcerange", actuator.forcerange);
getIfExist(g, "gear", actuator.gear);
getIfExist(g, "joint", actuator.joint);
getIfExist(g, "name", actuator.name);
// actuator specific attributes
getIfExist(g, "kp", actuator.kp);
getIfExist(g, "kv", actuator.kv);
}
void LoadContact(tinyxml2::XMLElement *g, MJCFContact &contact,
MJCFContact::Type type,
std::map<std::string, MJCFClass> &classes) {
if (!g) {
return;
}
getIfExist(g, "name", contact.name);
if (type == MJCFContact::PAIR) {
getIfExist(g, "geom1", contact.geom1);
getIfExist(g, "geom2", contact.geom2);
getIfExist(g, "condim", contact.condim);
} else if (type == MJCFContact::EXCLUDE) {
getIfExist(g, "body1", contact.body1);
getIfExist(g, "body2", contact.body2);
}
contact.type = type;
}
void LoadTendon(tinyxml2::XMLElement *t, MJCFTendon &tendon,
std::string className, MJCFTendon::Type type,
std::map<std::string, MJCFClass> &classes) {
if (!t) {
return;
}
if (t->Attribute("class"))
className = t->Attribute("class");
tendon = classes[className].dtendon;
tendon.type = type;
// parse tendon parameters:
getIfExist(t, "name", tendon.name);
getIfExist(t, "limited", tendon.limited);
getIfExist(t, "range", tendon.range);
getIfExist(t, "solimplimit", tendon.solimplimit);
getIfExist(t, "solreflimit", tendon.solreflimit);
getIfExist(t, "solimpfriction", tendon.solimpfriction);
getIfExist(t, "solreffriction", tendon.solreffriction);
getIfExist(t, "margin", tendon.margin);
getIfExist(t, "frictionloss", tendon.frictionloss);
getIfExist(t, "width", tendon.width);
getIfExist(t, "material", tendon.material);
getIfExist(t, "rgba", tendon.rgba);
getIfExist(t, "springlength", tendon.springlength);
if (tendon.springlength < 0.0f) {
CARB_LOG_WARN("*** Automatic tendon springlength calculation is not "
"supported (negative springlengths).");
}
getIfExist(t, "stiffness", tendon.stiffness);
getIfExist(t, "damping", tendon.damping);
// and then go through the joints in the fixed tendon:
if (type == MJCFTendon::FIXED) {
tinyxml2::XMLElement *j = t->FirstChildElement("joint");
while (j) {
// parse fixed joint:
if (!j->Attribute("joint")) {
CARB_LOG_FATAL("*** Fixed tendon joint must have a joint attribute.");
}
if (!j->Attribute("coef")) {
CARB_LOG_FATAL("*** Fixed tendon joint must have a coef attribute.");
}
MJCFTendon::FixedJoint *jnt = new MJCFTendon::FixedJoint();
getIfExist(j, "joint", jnt->joint);
getIfExist(j, "coef", jnt->coef);
// if coef nonzero, add:
if (0.0f != jnt->coef) {
tendon.fixedJoints.push_back(jnt);
}
// scan for next joint in tendon:
j = j->NextSiblingElement("joint");
}
}
// attributes for spatial teondon
if (type == MJCFTendon::SPATIAL) {
tinyxml2::XMLElement *x = t->FirstChildElement();
while (x) {
int branch = 0;
if (std::string(x->Value()).compare("geom") == 0) {
MJCFTendon::SpatialAttachment *attachment =
new MJCFTendon::SpatialAttachment();
attachment->type = MJCFTendon::SpatialAttachment::GEOM;
getIfExist(x, "geom", attachment->geom);
getIfExist(x, "sidesite", attachment->sidesite);
attachment->branch = branch;
if (attachment->geom != "") {
tendon.spatialAttachments.push_back(attachment);
tendon.spatialBranches[branch].push_back(attachment);
} else
CARB_LOG_FATAL("*** Spatial tendon geom must be specified.");
} else if (std::string(x->Value()).compare("site") == 0) {
MJCFTendon::SpatialAttachment *attachment =
new MJCFTendon::SpatialAttachment();
attachment->type = MJCFTendon::SpatialAttachment::SITE;
getIfExist(x, "site", attachment->site);
attachment->branch = branch;
if (attachment->site != "") {
tendon.spatialAttachments.push_back(attachment);
tendon.spatialBranches[branch].push_back(attachment);
} else
CARB_LOG_FATAL("*** Spatial tendon site must be specified.");
} else if (std::string(x->Value()).compare("pulley") == 0) {
MJCFTendon::SpatialPulley *pulley = new MJCFTendon::SpatialPulley();
getIfExist(x, "divisor", pulley->divisor);
if (pulley->divisor > 0.0) {
branch++;
pulley->branch = branch;
tendon.spatialPulleys.push_back(pulley);
} else
CARB_LOG_FATAL(
"*** Spatial tendon pulley divisor must be specified.");
} else {
CARB_LOG_WARN("Found unknown tag %s in tendon.\n", x->Value());
}
x = x->NextSiblingElement();
}
}
}
void LoadJoint(tinyxml2::XMLElement *g, MJCFJoint &joint, std::string className,
MJCFCompiler &compiler,
std::map<std::string, MJCFClass> &classes, bool isDefault) {
if (!g) {
return;
}
if (g->Attribute("class"))
className = g->Attribute("class");
joint = classes[className].djoint;
std::string type = "";
getIfExist(g, "type", type);
if (type == "hinge") {
joint.type = MJCFJoint::HINGE;
} else if (type == "slide") {
joint.type = MJCFJoint::SLIDE;
} else if (type == "ball") {
joint.type = MJCFJoint::BALL;
} else if (type == "free") {
joint.type = MJCFJoint::FREE;
} else if (type != "") {
std::cout << "JointSpec type " << type << " not yet supported!"
<< std::endl;
}
getIfExist(g, "ref", joint.ref);
getIfExist(g, "armature", joint.armature);
getIfExist(g, "damping", joint.damping);
getIfExist(g, "limited", joint.limited);
getIfExist(g, "axis", joint.axis);
getIfExist(g, "name", joint.name);
getIfExist(g, "pos", joint.pos);
getIfExist(g, "range", joint.range);
const char *st = g->Attribute("range");
if (st) {
sscanf(st, "%f %f", &joint.range.x, &joint.range.y);
if (compiler.autolimits) {
// set limited to true if a range is specified and autolimits is set to
// true
joint.limited = true;
}
}
if (joint.type != MJCFJoint::Type::SLIDE && !compiler.angleInRad) {
// cout << "Angle in deg" << endl;
joint.range.x = kPi * joint.range.x / 180.0f;
joint.range.y = kPi * joint.range.y / 180.0f;
}
getIfExist(g, "stiffness", joint.stiffness);
joint.axis = Normalize(joint.axis);
if (joint.name == "" && !isDefault) {
joint.name = "_joint_" + std::to_string(jointIdxCount);
jointIdxCount++;
}
}
void LoadFreeJoint(tinyxml2::XMLElement *g, MJCFJoint &joint,
std::string className, MJCFCompiler &compiler,
std::map<std::string, MJCFClass> &classes, bool isDefault) {
if (!g) {
return;
}
if (g->Attribute("class"))
className = g->Attribute("class");
joint = classes[className].djoint;
joint.type = MJCFJoint::FREE;
getIfExist(g, "name", joint.name);
if (joint.name == "" && !isDefault) {
joint.name = "_joint_" + std::to_string(jointIdxCount);
jointIdxCount++;
}
}
void LoadDefault(tinyxml2::XMLElement *e, const std::string className,
MJCFClass &cl, MJCFCompiler &compiler,
std::map<std::string, MJCFClass> &classes) {
LoadJoint(e->FirstChildElement("joint"), cl.djoint, className, compiler,
classes, true);
LoadGeom(e->FirstChildElement("geom"), cl.dgeom, className, compiler, classes,
true);
LoadSite(e->FirstChildElement("site"), cl.dsite, className, compiler, classes,
true);
LoadTendon(e->FirstChildElement("tendon"), cl.dtendon, className,
MJCFTendon::DEFAULT, classes);
LoadMesh(e->FirstChildElement("mesh"), cl.dmesh, className, compiler,
classes);
// a defaults class should have one general actuator element, so only one of
// these should be sucessful
LoadActuator(e->FirstChildElement("motor"), cl.dactuator, className,
MJCFActuator::MOTOR, classes);
LoadActuator(e->FirstChildElement("position"), cl.dactuator, className,
MJCFActuator::POSITION, classes);
LoadActuator(e->FirstChildElement("velocity"), cl.dactuator, className,
MJCFActuator::VELOCITY, classes);
LoadActuator(e->FirstChildElement("general"), cl.dactuator, className,
MJCFActuator::GENERAL, classes);
tinyxml2::XMLElement *d = e->FirstChildElement("default");
// while there is child default
while (d) {
// must have a name
if (!d->Attribute("class")) {
CARB_LOG_ERROR("Non-top level class must have name");
}
std::string name = d->Attribute("class");
classes[name] = cl; // Copy from this class
LoadDefault(d, name, classes[name], compiler,
classes); // Recursively load it
d = d->NextSiblingElement("default");
}
}
void LoadBody(tinyxml2::XMLElement *g, std::vector<MJCFBody *> &bodies,
MJCFBody &body, std::string className, MJCFCompiler &compiler,
std::map<std::string, MJCFClass> &classes,
std::string baseDirPath) {
if (!g) {
return;
}
if (g->Attribute("childclass")) {
className = g->Attribute("childclass");
}
getIfExist(g, "name", body.name);
getIfExist(g, "pos", body.pos);
getEulerIfExist(g, "euler", body.quat, compiler.eulerseq,
compiler.angleInRad);
getAngleAxisIfExist(g, "axisangle", body.quat, compiler.angleInRad);
getZAxisIfExist(g, "zaxis", body.quat);
getIfExist(g, "quat", body.quat);
if (body.name == "") {
body.name = "_body_" + std::to_string(bodyIdxCount);
bodyIdxCount++;
}
// load interial
tinyxml2::XMLElement *c = g->FirstChildElement("inertial");
if (c) {
body.inertial = new MJCFInertial();
LoadInertial(c, *body.inertial);
}
// load geoms
c = g->FirstChildElement("geom");
while (c) {
body.geoms.push_back(new MJCFGeom());
LoadGeom(c, *body.geoms.back(), className, compiler, classes, false);
c = c->NextSiblingElement("geom");
}
// load sites
c = g->FirstChildElement("site");
while (c) {
body.sites.push_back(new MJCFSite());
LoadSite(c, *body.sites.back(), className, compiler, classes, false);
c = c->NextSiblingElement("site");
}
// load joints
c = g->FirstChildElement("joint");
while (c) {
body.joints.push_back(new MJCFJoint());
LoadJoint(c, *body.joints.back(), className, compiler, classes, false);
c = c->NextSiblingElement("joint");
}
// load freejoint
c = g->FirstChildElement("freejoint");
if (c) {
body.joints.push_back(new MJCFJoint());
LoadFreeJoint(c, *body.joints.back(), className, compiler, classes, false);
}
// load imports
c = g->FirstChildElement("include");
while (c) {
tinyxml2::XMLDocument includeDoc;
tinyxml2::XMLElement *includeRoot = LoadInclude(includeDoc, c, baseDirPath);
if (includeRoot) {
tinyxml2::XMLElement *d = includeRoot->FirstChildElement("body");
while (d) {
bodies.push_back(new MJCFBody());
LoadBody(d, bodies, *bodies.back(), className, compiler, classes,
baseDirPath);
d = d->NextSiblingElement("body");
}
}
c = c->NextSiblingElement("include");
}
// load child bodies
c = g->FirstChildElement("body");
while (c) {
body.bodies.push_back(new MJCFBody());
LoadBody(c, bodies, *body.bodies.back(), className, compiler, classes,
baseDirPath);
c = c->NextSiblingElement("body");
}
}
tinyxml2::XMLElement *LoadFile(tinyxml2::XMLDocument &doc,
const std::string filePath) {
if (doc.LoadFile(filePath.c_str()) != tinyxml2::XML_SUCCESS) {
CARB_LOG_ERROR("*** Failed to load '%s'", filePath.c_str());
return nullptr;
}
tinyxml2::XMLElement *root = doc.RootElement();
if (!root) {
CARB_LOG_ERROR("*** Empty document '%s'", filePath.c_str());
}
return root;
}
void LoadAssets(tinyxml2::XMLElement *a, std::string baseDirPath,
MJCFCompiler &compiler,
std::map<std::string, MeshInfo> &simulationMeshCache,
std::map<std::string, MJCFMesh> &meshes,
std::map<std::string, MJCFMaterial> &materials,
std::map<std::string, MJCFTexture> &textures,
std::string className,
std::map<std::string, MJCFClass> &classes,
ImportConfig &config) {
tinyxml2::XMLElement *m = a->FirstChildElement("mesh");
while (m) {
MJCFMesh mMesh = MJCFMesh();
LoadMesh(m, mMesh, className, compiler, classes);
std::string meshName = mMesh.name;
std::string meshFile = mMesh.filename;
Vec3 meshScale = mMesh.scale;
// if (config.meshRootDirectory != "")
// baseDirPath = config.meshRootDirectory;
std::string meshPath = baseDirPath + compiler.meshDir + "/" + meshFile;
if (meshName == "") {
if (meshFile != "") {
size_t lastindex = meshFile.find_last_of(".");
meshName = meshFile.substr(0, lastindex);
} else {
CARB_LOG_ERROR("*** Mesh missing name and file attributes!\n");
}
}
meshes[meshName] = mMesh;
std::map<std::string, MeshInfo>::iterator it =
simulationMeshCache.find(meshName);
Mesh *mesh = nullptr;
if (it == simulationMeshCache.end()) {
Vec3 scale{1.f};
mesh::MeshImporter meshImporter;
mesh = meshImporter.loadMeshAssimp(meshPath.c_str(), scale,
GymMeshNormalMode::eComputePerFace);
if (!mesh) {
CARB_LOG_ERROR("*** Failed to load '%s'!\n", meshPath.c_str());
}
if (meshScale.x != 1.0f || meshScale.y != 1.0f || meshScale.z != 1.0f) {
mesh->Transform(ScaleMatrix(meshScale));
}
mesh->name = meshName;
// use flat normals on collision shapes
mesh->CalculateFaceNormals();
GymMeshHandle gymMeshHandle = -1;
MeshInfo meshInfo;
meshInfo.mesh = mesh;
meshInfo.meshHandle = gymMeshHandle;
simulationMeshCache[meshName] = meshInfo;
} else {
mesh = it->second.mesh;
}
m = m->NextSiblingElement("mesh");
}
tinyxml2::XMLElement *mat = a->FirstChildElement("material");
while (mat) {
std::string matName = "", texture = "";
float matSpecular = 0.5f, matShininess = 0.0f;
Vec4 rgba = Vec4(0.2f, 0.2f, 0.2f, 1.0f);
getIfExist(mat, "name", matName);
getIfExist(mat, "specular", matSpecular);
getIfExist(mat, "shininess", matShininess);
getIfExist(mat, "texture", texture);
getIfExist(mat, "rgba", rgba);
MJCFMaterial material;
material.name = matName;
material.texture = texture;
material.specular = matSpecular;
material.shininess = matShininess;
material.rgba = rgba;
materials[matName] = material;
mat = mat->NextSiblingElement("material");
}
tinyxml2::XMLElement *tex = a->FirstChildElement("texture");
while (tex) {
std::string texName = "", texFile = "", gridsize = "", gridlayout = "",
type = "";
getIfExist(tex, "name", texName);
getIfExist(tex, "file", texFile);
getIfExist(tex, "gridsize", gridsize);
getIfExist(tex, "gridlayout", gridlayout);
getIfExist(tex, "type", type);
if (texFile != "") {
texFile = baseDirPath + compiler.textureDir + "/" + texFile;
}
MJCFTexture texture = MJCFTexture();
texture.name = texName;
texture.filename = texFile;
texture.gridsize = gridsize;
texture.gridlayout = gridlayout;
texture.type = type;
textures[texName] = texture;
tex = tex->NextSiblingElement("texture");
}
}
void LoadGlobals(
tinyxml2::XMLElement *root, std::string &defaultClassName,
std::string baseDirPath, MJCFBody &worldBody,
std::vector<MJCFBody *> &bodies, std::vector<MJCFActuator *> &actuators,
std::vector<MJCFTendon *> &tendons, std::vector<MJCFContact *> &contacts,
std::map<std::string, MeshInfo> &simulationMeshCache,
std::map<std::string, MJCFMesh> &meshes,
std::map<std::string, MJCFMaterial> &materials,
std::map<std::string, MJCFTexture> &textures, MJCFCompiler &compiler,
std::map<std::string, MJCFClass> &classes,
std::map<std::string, int> &jointToActuatorIdx, ImportConfig &config) {
// parses attributes for the MJCF compiler, which defines settings such as
// angle units (rad/deg), mesh directory path, etc.
LoadCompiler(root->FirstChildElement("compiler"), compiler);
// reset counters
bodyIdxCount = 0;
geomIdxCount = 0;
siteIdxCount = 0;
jointIdxCount = 0;
// deal with defaults
tinyxml2::XMLElement *d = root->FirstChildElement("default");
if (!d) {
// if no default, set the defaultClassName to default if it does not exist
// yet. added this condition to avoid overwriting default class parameters
// parsed in a prior call
if (classes.find(defaultClassName) == classes.end()) {
classes[defaultClassName] = MJCFClass();
}
} else {
// only handle one top level default
if (d->Attribute("class"))
defaultClassName = d->Attribute("class");
classes[defaultClassName] = MJCFClass();
LoadDefault(d, defaultClassName, classes[defaultClassName], compiler,
classes);
if (d->NextSiblingElement("default")) {
CARB_LOG_ERROR(
"*** Can only handle one top level default at the moment!");
return;
}
}
tinyxml2::XMLElement *a = root->FirstChildElement("asset");
if (a) {
{
tinyxml2::XMLDocument includeDoc;
tinyxml2::XMLElement *includeRoot =
LoadInclude(includeDoc, a->FirstChildElement("include"), baseDirPath);
if (includeRoot) {
LoadAssets(includeRoot, baseDirPath, compiler, simulationMeshCache,
meshes, materials, textures, defaultClassName, classes,
config);
}
}
LoadAssets(a, baseDirPath, compiler, simulationMeshCache, meshes, materials,
textures, defaultClassName, classes, config);
}
// finds the origin of the world frame within which the rest of the kinematic
// tree is defined
tinyxml2::XMLElement *wb = root->FirstChildElement("worldbody");
if (wb) {
{
tinyxml2::XMLDocument includeDoc;
tinyxml2::XMLElement *includeRoot = LoadInclude(
includeDoc, wb->FirstChildElement("include"), baseDirPath);
if (includeRoot) {
tinyxml2::XMLElement *c = includeRoot->FirstChildElement("body");
while (c) {
bodies.push_back(new MJCFBody());
LoadBody(c, bodies, *bodies.back(), defaultClassName, compiler,
classes, baseDirPath);
c = c->NextSiblingElement("body");
}
}
}
tinyxml2::XMLElement *c = wb->FirstChildElement("body");
while (c) {
bodies.push_back(new MJCFBody());
LoadBody(c, bodies, *bodies.back(), defaultClassName, compiler, classes,
baseDirPath);
c = c->NextSiblingElement("body");
}
worldBody = MJCFBody();
// load sites and geoms
tinyxml2::XMLElement *g = wb->FirstChildElement("geom");
while (g) {
worldBody.geoms.push_back(new MJCFGeom());
LoadGeom(g, *worldBody.geoms.back(), defaultClassName, compiler, classes,
true);
if (worldBody.geoms.back()->type == MJCFGeom::OTHER) {
// don't know how to deal with it - remove it from list
worldBody.geoms.pop_back();
}
g = g->NextSiblingElement("geom");
}
tinyxml2::XMLElement *s = wb->FirstChildElement("site");
while (s) {
worldBody.sites.push_back(new MJCFSite());
LoadSite(wb->FirstChildElement("site"), *worldBody.sites.back(),
defaultClassName, compiler, classes, true);
s = s->NextSiblingElement("site");
}
}
tinyxml2::XMLElement *ac = root->FirstChildElement("actuator");
if (ac) {
tinyxml2::XMLElement *c = ac->FirstChildElement();
while (c) {
MJCFActuator::Type type;
std::string elementName{c->Name()};
if (elementName == "motor") {
type = MJCFActuator::MOTOR;
} else if (elementName == "position") {
type = MJCFActuator::POSITION;
} else if (elementName == "velocity") {
type = MJCFActuator::VELOCITY;
} else if (elementName == "general") {
type = MJCFActuator::GENERAL;
} else {
CARB_LOG_ERROR(
"*** Only motor, position, velocity actuators supported");
c = c->NextSiblingElement();
continue;
}
MJCFActuator *actuator = new MJCFActuator();
LoadActuator(c, *actuator, defaultClassName, type, classes);
jointToActuatorIdx[actuator->joint] = int(actuators.size());
actuators.push_back(actuator);
c = c->NextSiblingElement();
}
}
// load tendons
tinyxml2::XMLElement *tc = root->FirstChildElement("tendon");
if (tc) {
{
// parse fixed tendons first
tinyxml2::XMLElement *c = tc->FirstChildElement("fixed");
while (c) {
MJCFTendon *tendon = new MJCFTendon();
LoadTendon(c, *tendon, defaultClassName, MJCFTendon::FIXED, classes);
tendons.push_back(tendon);
c = c->NextSiblingElement("fixed");
}
}
{
// parse spatial tendons next
tinyxml2::XMLElement *c = tc->FirstChildElement("spatial");
while (c) {
MJCFTendon *tendon = new MJCFTendon();
LoadTendon(c, *tendon, defaultClassName, MJCFTendon::SPATIAL, classes);
tendons.push_back(tendon);
c = c->NextSiblingElement("spatial");
}
}
}
tinyxml2::XMLElement *cc = root->FirstChildElement("contact");
if (cc) {
tinyxml2::XMLElement *c = cc->FirstChildElement();
while (c) {
MJCFContact::Type type;
std::string elementName{c->Name()};
if (elementName == "pair") {
type = MJCFContact::PAIR;
} else if (elementName == "exclude") {
type = MJCFContact::EXCLUDE;
} else {
CARB_LOG_ERROR("*** Invalid contact specification");
c = c->NextSiblingElement();
continue;
}
MJCFContact *contact = new MJCFContact();
LoadContact(c, *contact, type, classes);
contacts.push_back(contact);
c = c->NextSiblingElement();
}
}
}
} // namespace mjcf
} // namespace importer
} // namespace omni
| 30,621 | C++ | 31.926882 | 99 | 0.617909 |
NVIDIA-Omniverse/mjcf-importer-extension/source/extensions/omni.importer.mjcf/plugins/MjcfUsd.h | // SPDX-FileCopyrightText: Copyright (c) 2023 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
// SPDX-License-Identifier: Apache-2.0
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#pragma once
// clang-format off
#include "UsdPCH.h"
// clang-format on
#include "MjcfTypes.h"
#include "MjcfUtils.h"
#include "Mjcf.h"
#include "math/core/maths.h"
#include <physxSchema/jointStateAPI.h>
#include <physxSchema/physxArticulationAPI.h>
#include <physxSchema/physxJointAPI.h>
#include <physxSchema/physxLimitAPI.h>
#include <physxSchema/physxRigidBodyAPI.h>
#include <physxSchema/physxSceneAPI.h>
#include <physxSchema/physxTendonAttachmentAPI.h>
#include <physxSchema/physxTendonAttachmentLeafAPI.h>
#include <physxSchema/physxTendonAttachmentRootAPI.h>
#include <physxSchema/physxTendonAxisAPI.h>
#include <physxSchema/physxTendonAxisRootAPI.h>
#include <pxr/usd/usdPhysics/articulationRootAPI.h>
#include <pxr/usd/usdPhysics/collisionAPI.h>
#include <pxr/usd/usdPhysics/driveAPI.h>
#include <pxr/usd/usdPhysics/filteredPairsAPI.h>
#include <pxr/usd/usdPhysics/fixedJoint.h>
#include <pxr/usd/usdPhysics/joint.h>
#include <pxr/usd/usdPhysics/limitAPI.h>
#include <pxr/usd/usdPhysics/massAPI.h>
#include <pxr/usd/usdPhysics/meshCollisionAPI.h>
#include <pxr/usd/usdPhysics/prismaticJoint.h>
#include <pxr/usd/usdPhysics/revoluteJoint.h>
#include <pxr/usd/usdPhysics/rigidBodyAPI.h>
#include <pxr/usd/usdPhysics/scene.h>
#include <map>
#include <vector>
namespace omni {
namespace importer {
namespace mjcf {
pxr::SdfPath getNextFreePath(pxr::UsdStageWeakPtr stage,
const pxr::SdfPath &primPath);
void setStageMetadata(pxr::UsdStageWeakPtr stage,
const omni::importer::mjcf::ImportConfig config);
void createRoot(pxr::UsdStageWeakPtr stage, Transform trans,
const std::string rootPrimPath,
const omni::importer::mjcf::ImportConfig config);
void createFixedRoot(pxr::UsdStageWeakPtr stage, const std::string jointPath,
const std::string bodyPath);
void applyArticulationAPI(pxr::UsdStageWeakPtr stage,
pxr::UsdGeomXformable prim,
const omni::importer::mjcf::ImportConfig config);
pxr::UsdGeomMesh createMesh(pxr::UsdStageWeakPtr stage, const pxr::SdfPath path,
Mesh *mesh, float scale, bool importMaterials,
bool instanceable);
pxr::UsdGeomMesh createMesh(pxr::UsdStageWeakPtr stage, const pxr::SdfPath path,
const std::vector<pxr::GfVec3f> &points,
const std::vector<pxr::GfVec3f> &normals,
const std::vector<int> &indices,
const std::vector<int> &vertexCounts);
void createAndBindMaterial(pxr::UsdStageWeakPtr stage, pxr::UsdPrim prim,
MJCFMaterial *material, MJCFTexture *texture,
Vec4 &color, bool colorOnly);
pxr::UsdGeomXformable createBody(pxr::UsdStageWeakPtr stage,
const std::string primPath,
const Transform &trans,
const ImportConfig &config);
void applyRigidBody(pxr::UsdGeomXformable bodyPrim, const MJCFBody *body,
const ImportConfig &config);
pxr::UsdPrim
createPrimitiveGeom(pxr::UsdStageWeakPtr stage, const std::string geomPath,
const MJCFGeom *geom,
const std::map<std::string, MeshInfo> &simulationMeshCache,
const ImportConfig &config, bool importMaterials,
const std::string rootPrimPath, bool collisionGeom);
pxr::UsdPrim createPrimitiveGeom(pxr::UsdStageWeakPtr stage,
const std::string geomPath,
const MJCFSite *site,
const ImportConfig &config,
bool importMaterials);
void applyCollisionGeom(pxr::UsdStageWeakPtr stage, pxr::UsdPrim prim,
const MJCFGeom *geom);
pxr::UsdPhysicsJoint createFixedJoint(pxr::UsdStageWeakPtr stage,
const std::string jointPath,
const Transform &poseJointToParentBody,
const Transform &poseJointToChildBody,
const std::string parentBodyPath,
const std::string bodyPath,
const ImportConfig &config);
pxr::UsdPhysicsJoint createD6Joint(pxr::UsdStageWeakPtr stage,
const std::string jointPath,
const Transform &poseJointToParentBody,
const Transform &poseJointToChildBody,
const std::string parentBodyPath,
const std::string bodyPath,
const ImportConfig &config);
void initPhysicsJoint(pxr::UsdPhysicsJoint &jointPrim,
const Transform &poseJointToParentBody,
const Transform &poseJointToChildBody,
const std::string parentBodyPath,
const std::string bodyPath, const float &distanceScale);
void applyPhysxJoint(pxr::UsdPhysicsJoint &jointPrim, const MJCFJoint *joint);
void applyJointLimits(pxr::UsdPhysicsJoint jointPrim, const MJCFJoint *joint,
const MJCFActuator *actuator, const int *axisMap,
const int jointIdx, const int numJoints,
const ImportConfig &config);
void createJointDrives(pxr::UsdPhysicsJoint jointPrim, const MJCFJoint *joint,
const MJCFActuator *actuator, const std::string axis,
const ImportConfig &config);
} // namespace mjcf
} // namespace importer
} // namespace omni
| 6,528 | C | 48.462121 | 99 | 0.633425 |
NVIDIA-Omniverse/mjcf-importer-extension/source/extensions/omni.importer.mjcf/plugins/MjcfUtils.cpp | // SPDX-FileCopyrightText: Copyright (c) 2023 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
// SPDX-License-Identifier: Apache-2.0
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include "MjcfUtils.h"
#include "math/core/maths.h"
namespace omni {
namespace importer {
namespace mjcf {
std::string SanitizeUsdName(const std::string &src) {
if (src.empty()) {
return "_";
}
std::string dst;
if (std::isdigit(src[0])) {
dst.push_back('_');
}
for (auto c : src) {
if (std::isalnum(c) || c == '_') {
dst.push_back(c);
} else {
dst.push_back('_');
}
}
return dst;
}
std::string GetAttr(const tinyxml2::XMLElement *c, const char *name) {
if (c->Attribute(name)) {
return std::string(c->Attribute(name));
} else {
return "";
}
}
void getIfExist(tinyxml2::XMLElement *e, const char *aname, bool &p) {
const char *st = e->Attribute(aname);
if (st) {
std::string s = st;
if (s == "true") {
p = true;
}
if (s == "1") {
p = true;
}
if (s == "false") {
p = false;
}
if (s == "0") {
p = false;
}
}
}
void getIfExist(tinyxml2::XMLElement *e, const char *aname, int &p) {
const char *st = e->Attribute(aname);
if (st) {
sscanf(st, "%d", &p);
}
}
void getIfExist(tinyxml2::XMLElement *e, const char *aname, float &p) {
const char *st = e->Attribute(aname);
if (st) {
sscanf(st, "%f", &p);
}
}
void getIfExist(tinyxml2::XMLElement *e, const char *aname, std::string &s) {
const char *st = e->Attribute(aname);
if (st) {
s = st;
}
}
void getIfExist(tinyxml2::XMLElement *e, const char *aname, Vec2 &p) {
const char *st = e->Attribute(aname);
if (st) {
sscanf(st, "%f %f", &p.x, &p.y);
}
}
void getIfExist(tinyxml2::XMLElement *e, const char *aname, Vec3 &p) {
const char *st = e->Attribute(aname);
if (st) {
sscanf(st, "%f %f %f", &p.x, &p.y, &p.z);
}
}
void getIfExist(tinyxml2::XMLElement *e, const char *aname, Vec3 &from,
Vec3 &to) {
const char *st = e->Attribute(aname);
if (st) {
sscanf(st, "%f %f %f %f %f %f", &from.x, &from.y, &from.z, &to.x, &to.y,
&to.z);
}
}
void getIfExist(tinyxml2::XMLElement *e, const char *aname, Vec4 &p) {
const char *st = e->Attribute(aname);
if (st) {
sscanf(st, "%f %f %f %f", &p.x, &p.y, &p.z, &p.w);
}
}
void getIfExist(tinyxml2::XMLElement *e, const char *aname, Quat &q) {
const char *st = e->Attribute(aname);
if (st) {
sscanf(st, "%f %f %f %f", &q.w, &q.x, &q.y, &q.z);
q = Normalize(q);
}
}
void getEulerIfExist(tinyxml2::XMLElement *e, const char *aname, Quat &q,
std::string eulerseq, bool angleInRad) {
const char *st = e->Attribute(aname);
if (st) {
float a, b, c;
sscanf(st, "%f %f %f", &a, &b, &c);
if (!angleInRad) {
a = kPi * a / 180.0f;
b = kPi * b / 180.0f;
c = kPi * c / 180.0f;
}
float angles[3] = {a, b, c};
q = Quat();
for (int i = (int)eulerseq.length() - 1; i >= 0; i--) {
char axis = eulerseq[i];
Quat new_quat = Quat();
new_quat.w = cos(angles[i] / 2);
if (axis == 'x') {
new_quat.x = sin(angles[i] / 2);
} else if (axis == 'y') {
new_quat.y = sin(angles[i] / 2);
} else if (axis == 'z') {
new_quat.z = sin(angles[i] / 2);
} else {
std::cout << "The MJCF importer currently only supports euler "
"sequences consisting of {x, y, z}"
<< std::endl;
}
q = new_quat * q;
}
}
}
void getAngleAxisIfExist(tinyxml2::XMLElement *e, const char *aname, Quat &q,
bool angleInRad) {
const char *st = e->Attribute(aname);
if (st) {
Vec3 axis;
float angle;
sscanf(st, "%f %f %f %f", &axis.x, &axis.y, &axis.z, &angle);
// convert to quat
if (!angleInRad) {
angle = kPi * angle / 180.0f;
}
q = QuatFromAxisAngle(axis, angle);
}
}
void getZAxisIfExist(tinyxml2::XMLElement *e, const char *aname, Quat &q) {
const char *st = e->Attribute(aname);
if (st) {
Vec3 zaxis;
sscanf(st, "%f %f %f", &zaxis.x, &zaxis.y, &zaxis.z);
Vec3 new_zaxis = zaxis;
new_zaxis = Normalize(new_zaxis);
Vec3 rotVec = Cross(Vec3(0.0f, 0.0f, 1.0f), new_zaxis);
if (Length(rotVec) < 1e-5) {
rotVec = Vec3(0.0f, 0.0f, 1.0f);
} else {
rotVec = Normalize(rotVec);
}
// essentially doing dot product between (0, 0, 1) and the vector and taking
// arccos to obtain the angle between the two vectors
float angle = acos(new_zaxis.z);
q = QuatFromAxisAngle(rotVec, angle);
}
}
void QuatFromZAxis(Vec3 zaxis, Quat &q) {
Vec3 new_zaxis = zaxis;
new_zaxis = Normalize(new_zaxis);
Vec3 rotVec = Cross(Vec3(0.0f, 0.0f, 1.0f), new_zaxis);
if (Length(rotVec) < 1e-5) {
rotVec = Vec3(0.0f, 0.0f, 1.0f);
} else {
rotVec = Normalize(rotVec);
}
// essentially doing dot product between (0, 0, 1) and the vector and taking
// arccos to obtain the angle between the two vectors
float angle = acos(new_zaxis.z);
q = QuatFromAxisAngle(rotVec, angle);
}
Quat indexedRotation(int axis, float s, float c) {
float v[3] = {0, 0, 0};
v[axis] = s;
return Quat(v[0], v[1], v[2], c);
}
Vec3 Diagonalize(const Matrix33 &m, Quat &massFrame) {
const int MAX_ITERS = 24;
Quat q = Quat();
Matrix33 d;
for (int i = 0; i < MAX_ITERS; i++) {
Matrix33 axes;
quat2Mat(q, axes);
d = Transpose(axes) * m * axes;
float d0 = fabs(d(1, 2)), d1 = fabs(d(0, 2)), d2 = fabs(d(0, 1));
// rotation axis index, from largest off-diagonal element
int a = int(d0 > d1 && d0 > d2 ? 0 : d1 > d2 ? 1 : 2);
int a1 = (a + 1 + (a >> 1)) & 3, a2 = (a1 + 1 + (a1 >> 1)) & 3;
if (d(a1, a2) == 0.0f ||
fabs(d(a1, a1) - d(a2, a2)) > 2e6f * fabs(2.0f * d(a1, a2)))
break;
// cot(2 * phi), where phi is the rotation angle
float w = (d(a1, a1) - d(a2, a2)) / (2.0f * d(a1, a2));
float absw = fabs(w);
Quat r;
if (absw > 1000) {
// h will be very close to 1, so use small angle approx instead
r = indexedRotation(a, 1 / (4 * w), 1.f);
} else {
float t = 1 / (absw + Sqrt(w * w + 1)); // absolute value of tan phi
float h = 1 / Sqrt(t * t + 1); // absolute value of cos phi
assert(h != 1); // |w|<1000 guarantees this with typical IEEE754 machine
// eps (approx 6e-8)
r = indexedRotation(a, Sqrt((1 - h) / 2) * Sign(w), Sqrt((1 + h) / 2));
}
q = Normalize(q * r);
}
massFrame = q;
return Vec3(d.cols[0].x, d.cols[1].y, d.cols[2].z);
}
} // namespace mjcf
} // namespace importer
} // namespace omni
| 7,243 | C++ | 25.730627 | 99 | 0.558608 |
NVIDIA-Omniverse/mjcf-importer-extension/source/extensions/omni.importer.mjcf/plugins/MjcfUsd.cpp | // SPDX-FileCopyrightText: Copyright (c) 2023 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
// SPDX-License-Identifier: Apache-2.0
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include <carb/logging/Log.h>
#include "MjcfUsd.h"
#include "utils/Path.h"
namespace omni {
namespace importer {
namespace mjcf {
pxr::SdfPath getNextFreePath(pxr::UsdStageWeakPtr stage,
const pxr::SdfPath &primPath) {
auto uniquePath = primPath;
auto prim = stage->GetPrimAtPath(uniquePath);
const std::string &name = uniquePath.GetName();
int startIndex = 1;
while (prim) {
uniquePath = primPath.ReplaceName(
pxr::TfToken(name + "_" + std::to_string(startIndex)));
prim = stage->GetPrimAtPath(uniquePath);
startIndex++;
}
return uniquePath;
}
std::string makeValidUSDIdentifier(const std::string &name) {
auto validName = pxr::TfMakeValidIdentifier(name);
if (validName[0] == '_') {
validName = "a" + validName;
}
if (pxr::TfIsValidIdentifier(name) == false) {
CARB_LOG_WARN("The path %s is not a valid usd path, modifying to %s",
name.c_str(), validName.c_str());
}
return validName;
}
void setStageMetadata(pxr::UsdStageWeakPtr stage,
const omni::importer::mjcf::ImportConfig config) {
if (config.createPhysicsScene) {
pxr::UsdPhysicsScene scene =
pxr::UsdPhysicsScene::Define(stage, pxr::SdfPath("/physicsScene"));
scene.CreateGravityDirectionAttr().Set(pxr::GfVec3f(0.0f, 0.0f, -1.0));
scene.CreateGravityMagnitudeAttr().Set(9.81f * config.distanceScale);
pxr::PhysxSchemaPhysxSceneAPI physxSceneAPI =
pxr::PhysxSchemaPhysxSceneAPI::Apply(
stage->GetPrimAtPath(pxr::SdfPath("/physicsScene")));
physxSceneAPI.CreateEnableCCDAttr().Set(true);
physxSceneAPI.CreateEnableStabilizationAttr().Set(true);
physxSceneAPI.CreateEnableGPUDynamicsAttr().Set(false);
physxSceneAPI.CreateBroadphaseTypeAttr().Set(pxr::TfToken("MBP"));
physxSceneAPI.CreateSolverTypeAttr().Set(pxr::TfToken("TGS"));
}
pxr::UsdGeomSetStageMetersPerUnit(stage, 1.0f / config.distanceScale);
pxr::UsdGeomSetStageUpAxis(stage, pxr::TfToken("Z"));
}
void createRoot(pxr::UsdStageWeakPtr stage, Transform trans,
const std::string rootPrimPath,
const omni::importer::mjcf::ImportConfig config) {
pxr::UsdGeomXform robotPrim =
pxr::UsdGeomXform::Define(stage, pxr::SdfPath(rootPrimPath));
if (config.makeDefaultPrim) {
stage->SetDefaultPrim(robotPrim.GetPrim());
}
}
void createFixedRoot(pxr::UsdStageWeakPtr stage, const std::string jointPath,
const std::string bodyPath) {
pxr::UsdPhysicsFixedJoint rootJoint =
pxr::UsdPhysicsFixedJoint::Define(stage, pxr::SdfPath(jointPath));
pxr::SdfPathVector val1{pxr::SdfPath(bodyPath)};
rootJoint.CreateBody1Rel().SetTargets(val1);
}
void applyArticulationAPI(pxr::UsdStageWeakPtr stage,
pxr::UsdGeomXformable prim,
const omni::importer::mjcf::ImportConfig config) {
pxr::UsdPhysicsArticulationRootAPI physicsSchema =
pxr::UsdPhysicsArticulationRootAPI::Apply(prim.GetPrim());
pxr::PhysxSchemaPhysxArticulationAPI physxSchema =
pxr::PhysxSchemaPhysxArticulationAPI::Apply(prim.GetPrim());
physxSchema.CreateEnabledSelfCollisionsAttr().Set(config.selfCollision);
}
std::string ReplaceBackwardSlash(std::string in) {
for (auto &c : in) {
if (c == '\\') {
c = '/';
}
}
return in;
}
std::string copyTexture(std::string usdStageIdentifier,
std::string texturePath) {
// switch any windows-style path into linux backwards slash (omniclient
// handles windows paths)
usdStageIdentifier = ReplaceBackwardSlash(usdStageIdentifier);
texturePath = ReplaceBackwardSlash(texturePath);
// Assumes the folder structure has already been created.
int path_idx = (int)usdStageIdentifier.rfind('/');
std::string parent_folder = usdStageIdentifier.substr(0, path_idx);
int basename_idx = (int)texturePath.rfind('/');
std::string textureName = texturePath.substr(basename_idx + 1);
std::string out = (parent_folder + "/materials/" + textureName);
omniClientWait(omniClientCopy(texturePath.c_str(), out.c_str(), {}, {}));
return out;
}
void createMaterial(pxr::UsdStageWeakPtr usdStage, const pxr::SdfPath path,
Mesh *mesh, pxr::UsdGeomMesh usdMesh,
std::map<int, pxr::VtArray<int>> &materialMap) {
std::string prefix_path;
prefix_path = pxr::SdfPath(path)
.GetParentPath()
.GetParentPath()
.GetString(); // Robot root
// for each material, store the face indices and create GeomSubsets
usdStage->DefinePrim(pxr::SdfPath(prefix_path + "/Looks"),
pxr::TfToken("Scope"));
for (auto const &mat : materialMap) {
Material &material = mesh->m_materials[mat.first];
pxr::UsdPrim prim;
pxr::UsdShadeMaterial matPrim;
std::string mat_path(
prefix_path + "/Looks/" +
makeValidUSDIdentifier("material_" + SanitizeUsdName(material.name)));
prim = usdStage->GetPrimAtPath(pxr::SdfPath(mat_path));
int counter = 0;
while (prim) {
mat_path = std::string(
prefix_path + "/Looks/" +
makeValidUSDIdentifier("material_" + SanitizeUsdName(material.name) +
"_" + std::to_string(++counter)));
prim = usdStage->GetPrimAtPath(pxr::SdfPath(mat_path));
}
matPrim = pxr::UsdShadeMaterial::Define(usdStage, pxr::SdfPath(mat_path));
pxr::UsdShadeShader pbrShader = pxr::UsdShadeShader::Define(
usdStage, pxr::SdfPath(mat_path + "/Shader"));
pbrShader.CreateIdAttr(
pxr::VtValue(pxr::UsdImagingTokens->UsdPreviewSurface));
auto shader_out = pbrShader.CreateOutput(pxr::TfToken("out"),
pxr::SdfValueTypeNames->Token);
matPrim.CreateSurfaceOutput(pxr::TfToken("mdl"))
.ConnectToSource(shader_out);
matPrim.CreateVolumeOutput(pxr::TfToken("mdl")).ConnectToSource(shader_out);
matPrim.CreateDisplacementOutput(pxr::TfToken("mdl"))
.ConnectToSource(shader_out);
pbrShader.GetImplementationSourceAttr().Set(
pxr::UsdShadeTokens->sourceAsset);
pbrShader.SetSourceAsset(pxr::SdfAssetPath("OmniPBR.mdl"),
pxr::TfToken("mdl"));
pbrShader.SetSourceAssetSubIdentifier(pxr::TfToken("OmniPBR"),
pxr::TfToken("mdl"));
bool has_emissive_map = false;
// diffuse, normal/bump, metallic, emissive, reflection/shininess
std::string materialMapPaths[5] = {material.mapKd, material.mapBump,
material.mapMetallic, material.mapEnv,
material.mapKs};
std::string materialMapTokens[5] = {
"diffuse_texture", "normalmap_texture", "metallic_texture",
"emissive_mask_texture", "reflectionroughness_texture"};
for (int i = 0; i < 5; i++) {
if (materialMapPaths[i] != "") {
if (!usdStage->GetRootLayer()->IsAnonymous()) {
auto texture_path = copyTexture(
usdStage->GetRootLayer()->GetIdentifier(), materialMapPaths[i]);
int basename_idx = (int)texture_path.rfind('/');
std::string filename = texture_path.substr(basename_idx + 1);
std::string texture_relative_path = "materials/" + filename;
pbrShader
.CreateInput(pxr::TfToken(materialMapTokens[i]),
pxr::SdfValueTypeNames->Asset)
.Set(pxr::SdfAssetPath(texture_relative_path));
if (i == 3) {
pbrShader
.CreateInput(pxr::TfToken("emissive_color"),
pxr::SdfValueTypeNames->Color3f)
.Set(pxr::GfVec3f(1.0f, 1.0f, 1.0f));
pbrShader
.CreateInput(pxr::TfToken("enable_emission"),
pxr::SdfValueTypeNames->Bool)
.Set(true);
pbrShader
.CreateInput(pxr::TfToken("emissive_intensity"),
pxr::SdfValueTypeNames->Float)
.Set(10000.0f);
has_emissive_map = true;
}
} else {
CARB_LOG_WARN(
"Material %s has an image texture, but it won't be imported "
"since the asset is being loaded on memory. Please import it "
"into a destination folder to get all textures.",
material.name.c_str());
}
}
}
if (material.hasDiffuse) {
pbrShader
.CreateInput(pxr::TfToken("diffuse_color_constant"),
pxr::SdfValueTypeNames->Color3f)
.Set(pxr::GfVec3f(material.Ks.x, material.Ks.y, material.Ks.z));
}
if (material.hasMetallic) {
pbrShader
.CreateInput(pxr::TfToken("metallic_constant"),
pxr::SdfValueTypeNames->Float)
.Set(material.metallic);
}
if (material.hasSpecular) {
pbrShader
.CreateInput(pxr::TfToken("specular_level"),
pxr::SdfValueTypeNames->Float)
.Set(material.specular);
}
if (!has_emissive_map && material.hasEmissive) {
pbrShader
.CreateInput(pxr::TfToken("emissive_color"),
pxr::SdfValueTypeNames->Color3f)
.Set(pxr::GfVec3f(material.emissive.x, material.emissive.y,
material.emissive.z));
}
if (materialMap.size() > 1) {
auto geomSubset = pxr::UsdGeomSubset::Define(
usdStage, pxr::SdfPath(usdMesh.GetPath().GetString() + "/material_" +
SanitizeUsdName(material.name)));
geomSubset.CreateElementTypeAttr(pxr::VtValue(pxr::TfToken("face")));
geomSubset.CreateFamilyNameAttr(
pxr::VtValue(pxr::TfToken("materialBind")));
geomSubset.CreateIndicesAttr(pxr::VtValue(mat.second));
if (matPrim) {
pxr::UsdShadeMaterialBindingAPI mbi(geomSubset);
mbi.Bind(matPrim);
// pxr::UsdShadeMaterialBindingAPI::Apply(geomSubset).Bind(matPrim);
}
} else {
if (matPrim) {
pxr::UsdShadeMaterialBindingAPI mbi(usdMesh);
mbi.Bind(matPrim);
// pxr::UsdShadeMaterialBindingAPI::Apply(usdMesh).Bind(matPrim);
}
}
}
}
// convert from internal Gym mesh to USD mesh
pxr::UsdGeomMesh createMesh(pxr::UsdStageWeakPtr stage, const pxr::SdfPath path,
Mesh *mesh, float scale, bool importMaterials) {
// basic mesh data
pxr::VtArray<pxr::VtArray<pxr::GfVec2f>> uvs;
size_t vertexOffset = 0;
std::map<int, pxr::VtArray<int>> materialMap;
for (size_t m = 0; m < mesh->m_usdMeshPrims.size(); m++) {
auto &meshPrim = mesh->m_usdMeshPrims[m];
for (size_t k = 0; k < meshPrim.uvs.size(); k++) {
uvs.push_back(meshPrim.uvs[k]);
}
for (size_t i = vertexOffset;
i < vertexOffset + meshPrim.faceVertexCounts.size(); i++) {
int materialIdx = mesh->m_materialAssignments[m].material;
materialMap[materialIdx].push_back(static_cast<int>(i));
}
vertexOffset = vertexOffset + meshPrim.faceVertexCounts.size();
}
std::vector<pxr::GfVec3f> points(mesh->m_positions.size());
std::vector<pxr::GfVec3f> normals(mesh->m_normals.size());
std::vector<int> indices(mesh->m_indices.size());
std::vector<int> vertexCounts(mesh->GetNumFaces(), 3);
for (size_t i = 0; i < mesh->m_positions.size(); i++) {
Point3 p = scale * mesh->m_positions[i];
points[i].Set(&p.x);
}
for (size_t i = 0; i < mesh->m_normals.size(); i++) {
normals[i].Set(&mesh->m_normals[i].x);
}
for (size_t i = 0; i < mesh->m_indices.size(); i++) {
indices[i] = mesh->m_indices[i];
}
pxr::UsdGeomMesh usdMesh =
createMesh(stage, path, points, normals, indices, vertexCounts);
// texture UV
for (size_t j = 0; j < uvs.size(); j++) {
pxr::TfToken stName;
if (j == 0) {
stName = pxr::TfToken("st");
} else {
stName = pxr::TfToken("st_" + std::to_string(j));
}
pxr::UsdGeomPrimvarsAPI primvarsAPI(usdMesh);
pxr::UsdGeomPrimvar Primvar = primvarsAPI.CreatePrimvar(
stName, pxr::SdfValueTypeNames->TexCoord2fArray,
pxr::UsdGeomTokens->faceVarying);
Primvar.Set(uvs[j]);
}
if (!materialMap.empty() && importMaterials) {
createMaterial(stage, path, mesh, usdMesh, materialMap);
}
return usdMesh;
}
pxr::UsdGeomMesh createMesh(pxr::UsdStageWeakPtr stage, const pxr::SdfPath path,
const std::vector<pxr::GfVec3f> &points,
const std::vector<pxr::GfVec3f> &normals,
const std::vector<int> &indices,
const std::vector<int> &vertexCounts) {
pxr::UsdGeomMesh mesh = pxr::UsdGeomMesh::Define(stage, path);
// fill in VtArrays
pxr::VtArray<int> vertexCountsVt;
vertexCountsVt.assign(vertexCounts.begin(), vertexCounts.end());
pxr::VtArray<int> vertexIndicesVt;
vertexIndicesVt.assign(indices.begin(), indices.end());
pxr::VtArray<pxr::GfVec3f> pointArrayVt;
pointArrayVt.assign(points.begin(), points.end());
pxr::VtArray<pxr::GfVec3f> normalsVt;
normalsVt.assign(normals.begin(), normals.end());
mesh.CreateFaceVertexCountsAttr().Set(vertexCountsVt);
mesh.CreateFaceVertexIndicesAttr().Set(vertexIndicesVt);
mesh.CreatePointsAttr().Set(pointArrayVt);
mesh.CreateDoubleSidedAttr().Set(true);
if (!normals.empty()) {
mesh.CreateNormalsAttr().Set(normalsVt);
mesh.SetNormalsInterpolation(pxr::UsdGeomTokens->faceVarying);
}
return mesh;
}
pxr::UsdGeomXformable createBody(pxr::UsdStageWeakPtr stage,
const std::string primPath,
const Transform &trans,
const ImportConfig &config) {
// translate the prim before xform is created automatically
pxr::UsdGeomXform xform =
pxr::UsdGeomXform::Define(stage, pxr::SdfPath(primPath));
pxr::GfMatrix4d bodyMat;
bodyMat.SetIdentity();
bodyMat.SetTranslateOnly(config.distanceScale *
pxr::GfVec3d(trans.p.x, trans.p.y, trans.p.z));
bodyMat.SetRotateOnly(
pxr::GfQuatd(trans.q.w, trans.q.x, trans.q.y, trans.q.z));
pxr::UsdGeomXformable gprim = pxr::UsdGeomXformable(xform);
gprim.ClearXformOpOrder();
pxr::UsdGeomXformOp transOp = gprim.AddTransformOp();
transOp.Set(bodyMat, pxr::UsdTimeCode::Default());
return gprim;
}
void applyRigidBody(pxr::UsdGeomXformable bodyPrim, const MJCFBody *body,
const ImportConfig &config) {
pxr::UsdPhysicsRigidBodyAPI physicsAPI =
pxr::UsdPhysicsRigidBodyAPI::Apply(bodyPrim.GetPrim());
pxr::PhysxSchemaPhysxRigidBodyAPI::Apply(bodyPrim.GetPrim());
pxr::UsdPhysicsMassAPI massAPI =
pxr::UsdPhysicsMassAPI::Apply(bodyPrim.GetPrim());
// TODO: need to support override computation
if (body->inertial && config.importInertiaTensor) {
massAPI.CreateMassAttr().Set(body->inertial->mass);
if (!config.overrideCoM) {
massAPI.CreateCenterOfMassAttr().Set(config.distanceScale *
pxr::GfVec3f(body->inertial->pos.x,
body->inertial->pos.y,
body->inertial->pos.z));
}
if (!config.overrideInertia) {
massAPI.CreateDiagonalInertiaAttr().Set(
config.distanceScale * config.distanceScale *
pxr::GfVec3f(body->inertial->diaginertia.x,
body->inertial->diaginertia.y,
body->inertial->diaginertia.z));
if (body->inertial->hasFullInertia == true) {
massAPI.CreatePrincipalAxesAttr().Set(pxr::GfQuatf(
body->inertial->principalAxes.w, body->inertial->principalAxes.x,
body->inertial->principalAxes.y, body->inertial->principalAxes.z));
}
}
} else {
massAPI.CreateDensityAttr().Set(config.density / config.distanceScale /
config.distanceScale /
config.distanceScale);
}
}
void createAndBindMaterial(pxr::UsdStageWeakPtr stage, pxr::UsdPrim prim,
MJCFMaterial *material, MJCFTexture *texture,
Vec4 &color, bool colorOnly) {
pxr::SdfPath path = prim.GetPath();
std::string prefix_path;
prefix_path = path.GetParentPath().GetString(); // body category root
stage->DefinePrim(pxr::SdfPath(prefix_path + "/Looks"),
pxr::TfToken("Scope"));
pxr::UsdShadeMaterial matPrim;
std::string materialName =
SanitizeUsdName(material ? material->name : "rgba");
std::string mat_path(prefix_path + "/Looks/" +
makeValidUSDIdentifier("material_" + materialName));
pxr::UsdPrim tmpPrim = stage->GetPrimAtPath(pxr::SdfPath(mat_path));
int counter = 0;
while (tmpPrim) {
mat_path =
std::string(prefix_path + "/Looks/" +
makeValidUSDIdentifier("material_" + materialName + "_" +
std::to_string(++counter)));
tmpPrim = stage->GetPrimAtPath(pxr::SdfPath(mat_path));
}
matPrim = pxr::UsdShadeMaterial::Define(stage, pxr::SdfPath(mat_path));
pxr::UsdShadeShader pbrShader =
pxr::UsdShadeShader::Define(stage, pxr::SdfPath(mat_path + "/Shader"));
pbrShader.CreateIdAttr(
pxr::VtValue(pxr::UsdImagingTokens->UsdPreviewSurface));
auto shader_out = pbrShader.CreateOutput(pxr::TfToken("out"),
pxr::SdfValueTypeNames->Token);
matPrim.CreateSurfaceOutput(pxr::TfToken("mdl")).ConnectToSource(shader_out);
matPrim.CreateVolumeOutput(pxr::TfToken("mdl")).ConnectToSource(shader_out);
matPrim.CreateDisplacementOutput(pxr::TfToken("mdl"))
.ConnectToSource(shader_out);
pbrShader.GetImplementationSourceAttr().Set(pxr::UsdShadeTokens->sourceAsset);
pbrShader.SetSourceAsset(pxr::SdfAssetPath("OmniPBR.mdl"),
pxr::TfToken("mdl"));
pbrShader.SetSourceAssetSubIdentifier(pxr::TfToken("OmniPBR"),
pxr::TfToken("mdl"));
if (colorOnly) {
pbrShader
.CreateInput(pxr::TfToken("diffuse_color_constant"),
pxr::SdfValueTypeNames->Color3f)
.Set(pxr::GfVec3f(color.x, color.y, color.z));
} else {
pbrShader
.CreateInput(pxr::TfToken("diffuse_color_constant"),
pxr::SdfValueTypeNames->Color3f)
.Set(
pxr::GfVec3f(material->rgba.x, material->rgba.y, material->rgba.z));
pbrShader
.CreateInput(pxr::TfToken("metallic_constant"),
pxr::SdfValueTypeNames->Float)
.Set(material->shininess);
pbrShader
.CreateInput(pxr::TfToken("specular_level"),
pxr::SdfValueTypeNames->Float)
.Set(material->specular);
pbrShader
.CreateInput(pxr::TfToken("reflection_roughness_constant"),
pxr::SdfValueTypeNames->Float)
.Set(material->roughness);
}
if (texture) {
if (texture->type == "2d") {
// ensures there is a texture filename to copy
if (texture->filename != "") {
if (!stage->GetRootLayer()->IsAnonymous()) {
auto texture_path = copyTexture(
stage->GetRootLayer()->GetIdentifier(), texture->filename);
int basename_idx = (int)texture_path.rfind('/');
std::string filename = texture_path.substr(basename_idx + 1);
std::string texture_relative_path = "materials/" + filename;
pbrShader
.CreateInput(pxr::TfToken("diffuse_texture"),
pxr::SdfValueTypeNames->Asset)
.Set(pxr::SdfAssetPath(texture_relative_path));
if (material->project_uvw == true) {
pbrShader
.CreateInput(pxr::TfToken("project_uvw"),
pxr::SdfValueTypeNames->Bool)
.Set(true);
}
} else {
CARB_LOG_WARN(
"Material %s has an image texture, but it won't be imported "
"since the asset is being loaded on memory. Please import it "
"into a destination folder to get all textures.",
material->name.c_str());
}
}
} else if (texture->type == "cube") {
// ensures there is a texture filename to copy
if (texture->filename != "") {
if (!stage->GetRootLayer()->IsAnonymous()) {
auto texture_path = copyTexture(
stage->GetRootLayer()->GetIdentifier(), texture->filename);
int basename_idx = (int)texture_path.rfind('/');
std::string filename = texture_path.substr(basename_idx + 1);
std::string texture_relative_path = "materials/" + filename;
pbrShader
.CreateInput(pxr::TfToken("diffuse_texture"),
pxr::SdfValueTypeNames->Asset)
.Set(pxr::SdfAssetPath(texture_relative_path));
} else {
CARB_LOG_WARN(
"Material %s has an image texture, but it won't be imported "
"since the asset is being loaded on memory. Please import it "
"into a destination folder to get all textures.",
material->name.c_str());
}
}
} else {
CARB_LOG_WARN("Only '2d' and 'cube' texture types are supported.\n");
}
}
if (matPrim) {
// pxr::UsdShadeMaterialBindingAPI mbi(prim);
// mbi.Apply(matPrim);
// mbi.Bind(matPrim);
pxr::UsdShadeMaterialBindingAPI::Apply(prim).Bind(matPrim);
}
}
pxr::GfVec3f evalSphereCoord(float u, float v) {
float theta = u * 2.0f * kPi;
float phi = (v - 0.5f) * kPi;
float cos_phi = cos(phi);
float x = cos_phi * cos(theta);
float y = cos_phi * sin(theta);
float z = sin(phi);
return pxr::GfVec3f(x, y, z);
}
int calcSphereIndex(int i, int j, int num_v_verts, int num_u_verts,
std::vector<pxr::GfVec3f> &points) {
if (j == 0) {
return 0;
} else if (j == num_v_verts - 1) {
return (int)points.size() - 1;
} else {
i = (i < num_u_verts) ? i : 0;
return (j - 1) * num_u_verts + i + 1;
}
}
pxr::UsdGeomMesh createSphereMesh(pxr::UsdStageWeakPtr stage,
const pxr::SdfPath path, float scale) {
int u_patches = 32;
int v_patches = 16;
int num_u_verts_scale = 1;
int num_v_verts_scale = 1;
u_patches = u_patches * num_u_verts_scale;
v_patches = v_patches * num_v_verts_scale;
u_patches = (u_patches > 3) ? u_patches : 3;
v_patches = (v_patches > 3) ? v_patches : 2;
float u_delta = 1.0f / (float)u_patches;
float v_delta = 1.0f / (float)v_patches;
int num_u_verts = u_patches;
int num_v_verts = v_patches + 1;
std::vector<pxr::GfVec3f> points;
std::vector<pxr::GfVec3f> normals;
std::vector<int> face_indices;
std::vector<int> face_vertex_counts;
pxr::GfVec3f bottom_point = pxr::GfVec3f(0.0f, 0.0f, -1.0f);
points.push_back(bottom_point);
for (int j = 0; j < num_v_verts - 1; j++) {
float v = (float)j * v_delta;
for (int i = 0; i < num_u_verts; i++) {
float u = (float)i * u_delta;
pxr::GfVec3f point = evalSphereCoord(u, v);
points.push_back(point);
}
}
pxr::GfVec3f top_point = pxr::GfVec3f(0.0f, 0.0f, 1.0f);
points.push_back(top_point);
// generate body
for (int j = 0; j < v_patches; j++) {
for (int i = 0; i < u_patches; i++) {
// index 0 is the bottom hat point
int vindex00 = calcSphereIndex(i, j, num_v_verts, num_u_verts, points);
int vindex10 =
calcSphereIndex(i + 1, j, num_v_verts, num_u_verts, points);
int vindex11 =
calcSphereIndex(i + 1, j + 1, num_v_verts, num_u_verts, points);
int vindex01 =
calcSphereIndex(i, j + 1, num_v_verts, num_u_verts, points);
pxr::GfVec3f p0 = points[vindex00];
pxr::GfVec3f p1 = points[vindex10];
pxr::GfVec3f p2 = points[vindex11];
pxr::GfVec3f p3 = points[vindex01];
if (vindex11 == vindex01) {
face_indices.push_back(vindex00);
face_indices.push_back(vindex10);
face_indices.push_back(vindex01);
face_vertex_counts.push_back(3);
normals.push_back(p0);
normals.push_back(p1);
normals.push_back(p3);
} else if (vindex00 == vindex10) {
face_indices.push_back(vindex00);
face_indices.push_back(vindex11);
face_indices.push_back(vindex01);
face_vertex_counts.push_back(3);
normals.push_back(p0);
normals.push_back(p2);
normals.push_back(p3);
} else {
face_indices.push_back(vindex00);
face_indices.push_back(vindex10);
face_indices.push_back(vindex11);
face_indices.push_back(vindex01);
face_vertex_counts.push_back(4);
normals.push_back(p0);
normals.push_back(p1);
normals.push_back(p2);
normals.push_back(p3);
}
}
}
pxr::UsdGeomMesh usdMesh = createMesh(stage, path, points, normals,
face_indices, face_vertex_counts);
return usdMesh;
}
pxr::UsdPrim
createPrimitiveGeom(pxr::UsdStageWeakPtr stage, const std::string geomPath,
const MJCFGeom *geom,
const std::map<std::string, MeshInfo> &simulationMeshCache,
const ImportConfig &config, bool importMaterials,
const std::string rootPrimPath, bool collisionGeom) {
pxr::SdfPath path = pxr::SdfPath(geomPath);
if (geom->type == MJCFGeom::PLANE) {
// add visual plane
pxr::UsdGeomMesh groundPlane = pxr::UsdGeomMesh::Define(stage, path);
groundPlane.CreateDisplayColorAttr().Set(
pxr::VtArray<pxr::GfVec3f>({pxr::GfVec3f(0.5f, 0.5f, 0.5f)}));
pxr::VtIntArray faceVertexCounts({4});
pxr::VtIntArray faceVertexIndices({0, 1, 2, 3});
pxr::GfVec3f normalsBase[] = {
pxr::GfVec3f(0.0f, 0.0f, 1.0f), pxr::GfVec3f(0.0f, 0.0f, 1.0f),
pxr::GfVec3f(0.0f, 0.0f, 1.0f), pxr::GfVec3f(0.0f, 0.0f, 1.0f)};
const size_t normalCount = sizeof(normalsBase) / sizeof(normalsBase[0]);
pxr::VtVec3fArray normals;
normals.resize(normalCount);
for (uint32_t i = 0; i < normalCount; i++) {
const pxr::GfVec3f &pointSrc = normalsBase[i];
pxr::GfVec3f &pointDst = normals[i];
pointDst[0] = pointSrc[0];
pointDst[1] = pointSrc[1];
pointDst[2] = pointSrc[2];
}
float planeSize[] = {geom->size.x, geom->size.y};
pxr::GfVec3f pointsBase[] = {
pxr::GfVec3f(-planeSize[0], -planeSize[1], 0.0f) * config.distanceScale,
pxr::GfVec3f(-planeSize[0], planeSize[1], 0.0f) * config.distanceScale,
pxr::GfVec3f(planeSize[0], planeSize[1], 0.0f) * config.distanceScale,
pxr::GfVec3f(planeSize[0], -planeSize[1], 0.0f) * config.distanceScale,
};
const size_t pointCount = sizeof(pointsBase) / sizeof(pointsBase[0]);
pxr::VtVec3fArray points;
points.resize(pointCount);
for (uint32_t i = 0; i < pointCount; i++) {
const pxr::GfVec3f &pointSrc = pointsBase[i];
pxr::GfVec3f &pointDst = points[i];
pointDst[0] = pointSrc[0];
pointDst[1] = pointSrc[1];
pointDst[2] = pointSrc[2];
}
groundPlane.CreateFaceVertexCountsAttr().Set(faceVertexCounts);
groundPlane.CreateFaceVertexIndicesAttr().Set(faceVertexIndices);
groundPlane.CreateNormalsAttr().Set(normals);
groundPlane.CreatePointsAttr().Set(points);
} else if (geom->type == MJCFGeom::SPHERE) {
pxr::UsdGeomSphere spherePrim = pxr::UsdGeomSphere::Define(stage, path);
pxr::VtVec3fArray extentArray(2);
spherePrim.ComputeExtent(geom->size.x, &extentArray);
spherePrim.GetRadiusAttr().Set(double(geom->size.x));
spherePrim.GetExtentAttr().Set(extentArray);
} else if (geom->type == MJCFGeom::ELLIPSOID) {
if (collisionGeom) {
// use mesh for collision, or else collision mesh does not work properly
createSphereMesh(stage, path, config.distanceScale);
} else {
// use shape prim for visual
pxr::UsdGeomSphere ellipsePrim = pxr::UsdGeomSphere::Define(stage, path);
pxr::VtVec3fArray extentArray(2);
ellipsePrim.ComputeExtent(geom->size.x, &extentArray);
ellipsePrim.GetExtentAttr().Set(extentArray);
}
} else if (geom->type == MJCFGeom::CAPSULE) {
pxr::UsdGeomCapsule capsulePrim = pxr::UsdGeomCapsule::Define(stage, path);
pxr::VtVec3fArray extentArray(4);
pxr::TfToken axis = pxr::TfToken("X");
float height;
if (geom->hasFromTo) {
Vec3 dif = geom->to - geom->from;
height = Length(dif);
} else {
// half length
height = 2.0f * geom->size.y;
}
capsulePrim.GetRadiusAttr().Set(double(geom->size.x));
capsulePrim.GetHeightAttr().Set(double(height));
capsulePrim.GetAxisAttr().Set(axis);
capsulePrim.ComputeExtent(double(height), double(geom->size.x), axis,
&extentArray);
capsulePrim.GetExtentAttr().Set(extentArray);
} else if (geom->type == MJCFGeom::CYLINDER) {
pxr::UsdGeomCylinder cylinderPrim =
pxr::UsdGeomCylinder::Define(stage, path);
pxr::VtVec3fArray extentArray(2);
float height;
if (geom->hasFromTo) {
Vec3 dif = geom->to - geom->from;
height = Length(dif);
} else {
height = 2.0f * geom->size.y;
}
pxr::TfToken axis = pxr::TfToken("X");
cylinderPrim.ComputeExtent(double(height), double(geom->size.x), axis,
&extentArray);
cylinderPrim.GetAxisAttr().Set(pxr::UsdGeomTokens->z);
cylinderPrim.GetExtentAttr().Set(extentArray);
cylinderPrim.GetHeightAttr().Set(double(height));
cylinderPrim.GetRadiusAttr().Set(double(geom->size.x));
} else if (geom->type == MJCFGeom::BOX) {
pxr::UsdGeomCube boxPrim = pxr::UsdGeomCube::Define(stage, path);
pxr::VtVec3fArray extentArray(2);
extentArray[1] = pxr::GfVec3f(geom->size.x, geom->size.y, geom->size.z);
extentArray[0] = -extentArray[1];
boxPrim.GetExtentAttr().Set(extentArray);
} else if (geom->type == MJCFGeom::MESH) {
MeshInfo meshInfo = simulationMeshCache.find(geom->mesh)->second;
createMesh(stage, path, meshInfo.mesh, config.distanceScale,
importMaterials);
}
pxr::UsdPrim prim = stage->GetPrimAtPath(path);
if (prim) {
// set the transformations first
pxr::GfMatrix4d mat;
mat.SetIdentity();
mat.SetTranslateOnly(pxr::GfVec3d(geom->pos.x, geom->pos.y, geom->pos.z));
mat.SetRotateOnly(
pxr::GfQuatd(geom->quat.w, geom->quat.x, geom->quat.y, geom->quat.z));
pxr::GfMatrix4d scale;
scale.SetIdentity();
scale.SetScale(pxr::GfVec3d(config.distanceScale, config.distanceScale,
config.distanceScale));
if (geom->type == MJCFGeom::ELLIPSOID) {
scale.SetScale(config.distanceScale *
pxr::GfVec3d(geom->size.x, geom->size.y, geom->size.z));
} else if (geom->type == MJCFGeom::SPHERE) {
Vec3 s = geom->size;
Vec3 cen = geom->pos;
Quat q = geom->quat;
// scale.SetIdentity();
mat.SetTranslateOnly(config.distanceScale *
pxr::GfVec3d(cen.x, cen.y, cen.z));
mat.SetRotateOnly(pxr::GfQuatd(q.w, q.x, q.y, q.z));
} else if (geom->type == MJCFGeom::CAPSULE) {
Vec3 cen;
Quat q;
if (geom->hasFromTo) {
Vec3 diff = geom->to - geom->from;
diff = Normalize(diff);
Vec3 rotVec = Cross(Vec3(1.0f, 0.0f, 0.0f), diff);
if (Length(rotVec) < 1e-5) {
rotVec = Vec3(0.0f, 1.0f, 0.0f); // default rotation about y-axis
} else {
rotVec = Normalize(rotVec); // z axis
}
float angle = acos(diff.x);
cen = 0.5f * (geom->from + geom->to);
q = QuatFromAxisAngle(rotVec, angle);
} else {
cen = geom->pos;
q = geom->quat * QuatFromAxisAngle(Vec3(0.0f, 1.0f, 0.0f), -kPi * 0.5f);
}
mat.SetTranslateOnly(config.distanceScale *
pxr::GfVec3d(cen.x, cen.y, cen.z));
mat.SetRotateOnly(pxr::GfQuatd(q.w, q.x, q.y, q.z));
} else if (geom->type == MJCFGeom::CYLINDER) {
Vec3 cen;
Quat q;
if (geom->hasFromTo) {
cen = 0.5f * (geom->from + geom->to);
Vec3 axis = geom->to - geom->from;
q = GetRotationQuat(Vec3(0.0f, 0.0f, 1.0f), Normalize(axis));
} else {
cen = geom->pos;
q = geom->quat;
}
mat.SetRotateOnly(pxr::GfQuatd(q.w, q.x, q.y, q.z));
mat.SetTranslateOnly(config.distanceScale *
pxr::GfVec3d(cen.x, cen.y, cen.z));
} else if (geom->type == MJCFGeom::BOX) {
Vec3 s = geom->size;
Vec3 cen = geom->pos;
Quat q = geom->quat;
scale.SetScale(config.distanceScale * pxr::GfVec3d(s.x, s.y, s.z));
mat.SetTranslateOnly(config.distanceScale *
pxr::GfVec3d(cen.x, cen.y, cen.z));
mat.SetRotateOnly(pxr::GfQuatd(q.w, q.x, q.y, q.z));
} else if (geom->type == MJCFGeom::MESH) {
Vec3 cen = geom->pos;
Quat q = geom->quat;
scale.SetIdentity();
mat.SetTranslateOnly(config.distanceScale *
pxr::GfVec3d(cen.x, cen.y, cen.z));
mat.SetRotateOnly(pxr::GfQuatd(q.w, q.x, q.y, q.z));
} else if (geom->type == MJCFGeom::PLANE) {
Vec3 cen = geom->pos;
Quat q = geom->quat;
scale.SetIdentity();
mat.SetTranslateOnly(config.distanceScale *
pxr::GfVec3d(cen.x, cen.y, cen.z));
mat.SetRotateOnly(pxr::GfQuatd(q.w, q.x, q.y, q.z));
}
pxr::UsdGeomXformable gprim = pxr::UsdGeomXformable(prim);
gprim.ClearXformOpOrder();
pxr::UsdGeomXformOp transOp = gprim.AddTransformOp();
transOp.Set(scale * mat, pxr::UsdTimeCode::Default());
}
return prim;
}
pxr::UsdPrim createPrimitiveGeom(pxr::UsdStageWeakPtr stage,
const std::string geomPath,
const MJCFSite *site,
const ImportConfig &config,
bool importMaterials) {
pxr::SdfPath path = pxr::SdfPath(geomPath);
if (site->type == MJCFSite::SPHERE) {
pxr::UsdGeomSphere spherePrim = pxr::UsdGeomSphere::Define(stage, path);
pxr::VtVec3fArray extentArray(2);
spherePrim.ComputeExtent(site->size.x, &extentArray);
spherePrim.GetRadiusAttr().Set(double(site->size.x));
spherePrim.GetExtentAttr().Set(extentArray);
} else if (site->type == MJCFSite::ELLIPSOID) {
pxr::UsdGeomSphere ellipsePrim = pxr::UsdGeomSphere::Define(stage, path);
pxr::VtVec3fArray extentArray(2);
ellipsePrim.ComputeExtent(site->size.x, &extentArray);
ellipsePrim.GetExtentAttr().Set(extentArray);
} else if (site->type == MJCFSite::CAPSULE) {
pxr::UsdGeomCapsule capsulePrim = pxr::UsdGeomCapsule::Define(stage, path);
pxr::VtVec3fArray extentArray(4);
pxr::TfToken axis = pxr::TfToken("X");
float height;
if (site->hasFromTo) {
Vec3 dif = site->to - site->from;
height = Length(dif);
} else {
// half length
height = 2.0f * site->size.y;
}
capsulePrim.GetRadiusAttr().Set(double(site->size.x));
capsulePrim.GetHeightAttr().Set(double(height));
capsulePrim.GetAxisAttr().Set(axis);
capsulePrim.ComputeExtent(double(height), double(site->size.x), axis,
&extentArray);
capsulePrim.GetExtentAttr().Set(extentArray);
} else if (site->type == MJCFSite::CYLINDER) {
pxr::UsdGeomCylinder cylinderPrim =
pxr::UsdGeomCylinder::Define(stage, path);
pxr::VtVec3fArray extentArray(2);
float height;
if (site->hasFromTo) {
Vec3 dif = site->to - site->from;
height = Length(dif);
} else {
height = 2.0f * site->size.y;
}
pxr::TfToken axis = pxr::TfToken("X");
cylinderPrim.ComputeExtent(double(height), double(site->size.x), axis,
&extentArray);
cylinderPrim.GetAxisAttr().Set(pxr::UsdGeomTokens->z);
cylinderPrim.GetExtentAttr().Set(extentArray);
cylinderPrim.GetHeightAttr().Set(double(height));
cylinderPrim.GetRadiusAttr().Set(double(site->size.x));
} else if (site->type == MJCFSite::BOX) {
pxr::UsdGeomCube boxPrim = pxr::UsdGeomCube::Define(stage, path);
pxr::VtVec3fArray extentArray(2);
extentArray[1] = pxr::GfVec3f(site->size.x, site->size.y, site->size.z);
extentArray[0] = -extentArray[1];
boxPrim.GetExtentAttr().Set(extentArray);
}
pxr::UsdPrim prim = stage->GetPrimAtPath(path);
if (prim) {
// set the transformations first
pxr::GfMatrix4d mat;
mat.SetIdentity();
mat.SetTranslateOnly(pxr::GfVec3d(site->pos.x, site->pos.y, site->pos.z));
mat.SetRotateOnly(
pxr::GfQuatd(site->quat.w, site->quat.x, site->quat.y, site->quat.z));
pxr::GfMatrix4d scale;
scale.SetIdentity();
scale.SetScale(pxr::GfVec3d(config.distanceScale, config.distanceScale,
config.distanceScale));
if (site->type == MJCFSite::ELLIPSOID) {
scale.SetScale(config.distanceScale *
pxr::GfVec3d(site->size.x, site->size.y, site->size.z));
} else if (site->type == MJCFSite::CAPSULE) {
Vec3 cen;
Quat q;
if (site->hasFromTo) {
Vec3 diff = site->to - site->from;
diff = Normalize(diff);
Vec3 rotVec = Cross(Vec3(1.0f, 0.0f, 0.0f), diff);
if (Length(rotVec) < 1e-5) {
rotVec = Vec3(0.0f, 1.0f, 0.0f); // default rotation about y-axis
} else {
rotVec = Normalize(rotVec); // z axis
}
float angle = acos(diff.x);
cen = 0.5f * (site->from + site->to);
q = QuatFromAxisAngle(rotVec, angle);
} else {
cen = site->pos;
q = site->quat * QuatFromAxisAngle(Vec3(0.0f, 1.0f, 0.0f), -kPi * 0.5f);
}
mat.SetTranslateOnly(config.distanceScale *
pxr::GfVec3d(cen.x, cen.y, cen.z));
mat.SetRotateOnly(pxr::GfQuatd(q.w, q.x, q.y, q.z));
} else if (site->type == MJCFSite::CYLINDER) {
Vec3 cen;
Quat q;
if (site->hasFromTo) {
cen = 0.5f * (site->from + site->to);
Vec3 axis = site->to - site->from;
q = GetRotationQuat(Vec3(0.0f, 0.0f, 1.0f), Normalize(axis));
} else {
cen = site->pos;
q = site->quat;
}
mat.SetRotateOnly(pxr::GfQuatd(q.w, q.x, q.y, q.z));
mat.SetTranslateOnly(pxr::GfVec3d(cen.x, cen.y, cen.z));
} else if (site->type == MJCFSite::BOX) {
Vec3 s = site->size;
Vec3 cen = site->pos;
Quat q = site->quat;
scale.SetScale(config.distanceScale * pxr::GfVec3d(s.x, s.y, s.z));
mat.SetTranslateOnly(config.distanceScale *
pxr::GfVec3d(cen.x, cen.y, cen.z));
mat.SetRotateOnly(pxr::GfQuatd(q.w, q.x, q.y, q.z));
}
pxr::UsdGeomXformable gprim = pxr::UsdGeomXformable(prim);
gprim.ClearXformOpOrder();
pxr::UsdGeomXformOp transOp = gprim.AddTransformOp();
transOp.Set(scale * mat, pxr::UsdTimeCode::Default());
}
return prim;
}
void applyCollisionGeom(pxr::UsdStageWeakPtr stage, pxr::UsdPrim prim,
const MJCFGeom *geom) {
if (geom->type == MJCFGeom::PLANE) {
} else {
pxr::UsdPhysicsCollisionAPI::Apply(prim);
pxr::UsdPhysicsMeshCollisionAPI physicsMeshAPI =
pxr::UsdPhysicsMeshCollisionAPI::Apply(prim);
if (geom->type == MJCFGeom::SPHERE) {
physicsMeshAPI.CreateApproximationAttr().Set(
pxr::UsdPhysicsTokens.Get()->boundingSphere);
} else if (geom->type == MJCFGeom::BOX) {
physicsMeshAPI.CreateApproximationAttr().Set(
pxr::UsdPhysicsTokens.Get()->boundingCube);
} else {
physicsMeshAPI.CreateApproximationAttr().Set(
pxr::UsdPhysicsTokens.Get()->convexHull);
}
pxr::UsdGeomMesh(prim).CreatePurposeAttr().Set(pxr::UsdGeomTokens->guide);
}
}
pxr::UsdPhysicsJoint createFixedJoint(pxr::UsdStageWeakPtr stage,
const std::string jointPath,
const Transform &poseJointToParentBody,
const Transform &poseJointToChildBody,
const std::string parentBodyPath,
const std::string bodyPath,
const ImportConfig &config) {
pxr::UsdPhysicsJoint jointPrim =
pxr::UsdPhysicsFixedJoint::Define(stage, pxr::SdfPath(jointPath));
pxr::GfVec3f localPos0 =
config.distanceScale * pxr::GfVec3f(poseJointToParentBody.p.x,
poseJointToParentBody.p.y,
poseJointToParentBody.p.z);
pxr::GfQuatf localRot0 =
pxr::GfQuatf(poseJointToParentBody.q.w, poseJointToParentBody.q.x,
poseJointToParentBody.q.y, poseJointToParentBody.q.z);
pxr::GfVec3f localPos1 =
config.distanceScale * pxr::GfVec3f(poseJointToChildBody.p.x,
poseJointToChildBody.p.y,
poseJointToChildBody.p.z);
pxr::GfQuatf localRot1 =
pxr::GfQuatf(poseJointToChildBody.q.w, poseJointToChildBody.q.x,
poseJointToChildBody.q.y, poseJointToChildBody.q.z);
pxr::SdfPathVector val0{pxr::SdfPath(parentBodyPath)};
pxr::SdfPathVector val1{pxr::SdfPath(bodyPath)};
jointPrim.CreateBody0Rel().SetTargets(val0);
jointPrim.CreateLocalPos0Attr().Set(localPos0);
jointPrim.CreateLocalRot0Attr().Set(localRot0);
jointPrim.CreateBody1Rel().SetTargets(val1);
jointPrim.CreateLocalPos1Attr().Set(localPos1);
jointPrim.CreateLocalRot1Attr().Set(localRot1);
jointPrim.CreateBreakForceAttr().Set(FLT_MAX);
jointPrim.CreateBreakTorqueAttr().Set(FLT_MAX);
return jointPrim;
}
pxr::UsdPhysicsJoint createD6Joint(pxr::UsdStageWeakPtr stage,
const std::string jointPath,
const Transform &poseJointToParentBody,
const Transform &poseJointToChildBody,
const std::string parentBodyPath,
const std::string bodyPath,
const ImportConfig &config) {
pxr::UsdPhysicsJoint jointPrim =
pxr::UsdPhysicsJoint::Define(stage, pxr::SdfPath(jointPath));
pxr::GfVec3f localPos0 =
config.distanceScale * pxr::GfVec3f(poseJointToParentBody.p.x,
poseJointToParentBody.p.y,
poseJointToParentBody.p.z);
pxr::GfQuatf localRot0 =
pxr::GfQuatf(poseJointToParentBody.q.w, poseJointToParentBody.q.x,
poseJointToParentBody.q.y, poseJointToParentBody.q.z);
pxr::GfVec3f localPos1 =
config.distanceScale * pxr::GfVec3f(poseJointToChildBody.p.x,
poseJointToChildBody.p.y,
poseJointToChildBody.p.z);
pxr::GfQuatf localRot1 =
pxr::GfQuatf(poseJointToChildBody.q.w, poseJointToChildBody.q.x,
poseJointToChildBody.q.y, poseJointToChildBody.q.z);
pxr::SdfPathVector val0{pxr::SdfPath(parentBodyPath)};
pxr::SdfPathVector val1{pxr::SdfPath(bodyPath)};
jointPrim.CreateBody0Rel().SetTargets(val0);
jointPrim.CreateLocalPos0Attr().Set(localPos0);
jointPrim.CreateLocalRot0Attr().Set(localRot0);
jointPrim.CreateBody1Rel().SetTargets(val1);
jointPrim.CreateLocalPos1Attr().Set(localPos1);
jointPrim.CreateLocalRot1Attr().Set(localRot1);
jointPrim.CreateBreakForceAttr().Set(FLT_MAX);
jointPrim.CreateBreakTorqueAttr().Set(FLT_MAX);
return jointPrim;
}
void initPhysicsJoint(pxr::UsdPhysicsJoint &jointPrim,
const Transform &poseJointToParentBody,
const Transform &poseJointToChildBody,
const std::string parentBodyPath,
const std::string bodyPath, const float &distanceScale) {
pxr::GfVec3f localPos0 =
distanceScale * pxr::GfVec3f(poseJointToParentBody.p.x,
poseJointToParentBody.p.y,
poseJointToParentBody.p.z);
pxr::GfQuatf localRot0 =
pxr::GfQuatf(poseJointToParentBody.q.w, poseJointToParentBody.q.x,
poseJointToParentBody.q.y, poseJointToParentBody.q.z);
pxr::GfVec3f localPos1 =
distanceScale * pxr::GfVec3f(poseJointToChildBody.p.x,
poseJointToChildBody.p.y,
poseJointToChildBody.p.z);
pxr::GfQuatf localRot1 =
pxr::GfQuatf(poseJointToChildBody.q.w, poseJointToChildBody.q.x,
poseJointToChildBody.q.y, poseJointToChildBody.q.z);
pxr::SdfPathVector val0{pxr::SdfPath(parentBodyPath)};
pxr::SdfPathVector val1{pxr::SdfPath(bodyPath)};
jointPrim.CreateBody0Rel().SetTargets(val0);
jointPrim.CreateLocalPos0Attr().Set(localPos0);
jointPrim.CreateLocalRot0Attr().Set(localRot0);
jointPrim.CreateBody1Rel().SetTargets(val1);
jointPrim.CreateLocalPos1Attr().Set(localPos1);
jointPrim.CreateLocalRot1Attr().Set(localRot1);
jointPrim.CreateBreakForceAttr().Set(FLT_MAX);
jointPrim.CreateBreakTorqueAttr().Set(FLT_MAX);
}
void applyPhysxJoint(pxr::UsdPhysicsJoint &jointPrim, const MJCFJoint *joint) {
pxr::PhysxSchemaPhysxJointAPI physxJoint =
pxr::PhysxSchemaPhysxJointAPI::Apply(jointPrim.GetPrim());
physxJoint.CreateArmatureAttr().Set(joint->armature);
}
void applyJointLimits(pxr::UsdPhysicsJoint jointPrim, const MJCFJoint *joint,
const MJCFActuator *actuator, const int *axisMap,
const int jointIdx, const int numJoints,
const ImportConfig &config) {
// enable limits if set
JointAxis axisHinge[3] = {eJointAxisTwist, eJointAxisSwing1,
eJointAxisSwing2};
JointAxis axisSlide[3] = {eJointAxisX, eJointAxisY, eJointAxisZ};
std::string d6Axes[6] = {"transX", "transY", "transZ",
"rotX", "rotY", "rotZ"};
int axis = -1;
std::string limitAttr = "";
// assume we can only have one of slide or hinge per d6 joint
if (joint->type == MJCFJoint::SLIDE) {
// lock all rotation axes
for (int i = 3; i < 6; ++i) {
pxr::UsdPhysicsLimitAPI limitAPI = pxr::UsdPhysicsLimitAPI::Apply(
jointPrim.GetPrim(), pxr::TfToken(d6Axes[i]));
limitAPI.CreateLowAttr().Set(1.0f);
limitAPI.CreateHighAttr().Set(-1.0f);
}
axis = int(axisSlide[axisMap[jointIdx]]);
if (joint->limited) {
pxr::UsdPhysicsLimitAPI limitAPI = pxr::UsdPhysicsLimitAPI::Apply(
jointPrim.GetPrim(), pxr::TfToken(d6Axes[axis]));
limitAPI.CreateLowAttr().Set(config.distanceScale * joint->range.x);
limitAPI.CreateHighAttr().Set(config.distanceScale * joint->range.y);
}
pxr::PhysxSchemaPhysxLimitAPI physxLimitAPI =
pxr::PhysxSchemaPhysxLimitAPI::Apply(jointPrim.GetPrim(),
pxr::TfToken(d6Axes[axis]));
pxr::PhysxSchemaJointStateAPI::Apply(jointPrim.GetPrim(),
pxr::TfToken("linear"));
physxLimitAPI.CreateStiffnessAttr().Set(joint->stiffness);
physxLimitAPI.CreateDampingAttr().Set(joint->damping);
} else if (joint->type == MJCFJoint::HINGE) {
// lock all translation axes
for (int i = 0; i < 3; ++i) {
pxr::UsdPhysicsLimitAPI limitAPI = pxr::UsdPhysicsLimitAPI::Apply(
jointPrim.GetPrim(), pxr::TfToken(d6Axes[i]));
limitAPI.CreateLowAttr().Set(1.0f);
limitAPI.CreateHighAttr().Set(-1.0f);
}
// TODO: locking all axes at the beginning doesn't work?
if (numJoints == 1) {
pxr::UsdPhysicsLimitAPI limitAPI = pxr::UsdPhysicsLimitAPI::Apply(
jointPrim.GetPrim(), pxr::TfToken(d6Axes[axisHinge[axisMap[1]]]));
limitAPI.CreateLowAttr().Set(1.0f);
limitAPI.CreateHighAttr().Set(-1.0f);
limitAPI = pxr::UsdPhysicsLimitAPI::Apply(
jointPrim.GetPrim(), pxr::TfToken(d6Axes[axisHinge[axisMap[2]]]));
limitAPI.CreateLowAttr().Set(1.0f);
limitAPI.CreateHighAttr().Set(-1.0f);
} else if (numJoints == 2) {
pxr::UsdPhysicsLimitAPI limitAPI = pxr::UsdPhysicsLimitAPI::Apply(
jointPrim.GetPrim(), pxr::TfToken(d6Axes[axisHinge[axisMap[2]]]));
limitAPI.CreateLowAttr().Set(1.0f);
limitAPI.CreateHighAttr().Set(-1.0f);
}
axis = int(axisHinge[axisMap[jointIdx]]);
if (joint->limited) {
pxr::UsdPhysicsLimitAPI limitAPI = pxr::UsdPhysicsLimitAPI::Apply(
jointPrim.GetPrim(), pxr::TfToken(d6Axes[axis]));
limitAPI.CreateLowAttr().Set(joint->range.x * 180 / kPi);
limitAPI.CreateHighAttr().Set(joint->range.y * 180 / kPi);
pxr::PhysxSchemaPhysxLimitAPI physxLimitAPI =
pxr::PhysxSchemaPhysxLimitAPI::Apply(jointPrim.GetPrim(),
pxr::TfToken(d6Axes[axis]));
physxLimitAPI.CreateStiffnessAttr().Set(joint->stiffness);
physxLimitAPI.CreateDampingAttr().Set(joint->damping);
}
pxr::PhysxSchemaJointStateAPI::Apply(jointPrim.GetPrim(),
pxr::TfToken("angular"));
}
jointPrim.GetPrim()
.CreateAttribute(pxr::TfToken("mjcf:" + d6Axes[axis] + ":name"),
pxr::SdfValueTypeNames->Token)
.Set(pxr::TfToken(SanitizeUsdName(joint->name)));
createJointDrives(jointPrim, joint, actuator, d6Axes[axis], config);
}
void createJointDrives(pxr::UsdPhysicsJoint jointPrim, const MJCFJoint *joint,
const MJCFActuator *actuator, const std::string axis,
const ImportConfig &config) {
pxr::UsdPhysicsDriveAPI driveAPI =
pxr::UsdPhysicsDriveAPI::Apply(jointPrim.GetPrim(), pxr::TfToken(axis));
driveAPI =
pxr::UsdPhysicsDriveAPI::Apply(jointPrim.GetPrim(), pxr::TfToken(axis));
driveAPI.CreateTypeAttr().Set(
pxr::TfToken("force")); // TODO: when will this be acceleration?
driveAPI.CreateDampingAttr().Set(joint->damping);
driveAPI.CreateStiffnessAttr().Set(joint->stiffness);
if (actuator) {
MJCFActuator::Type actuatorType = actuator->type;
if (actuatorType == MJCFActuator::MOTOR ||
actuatorType == MJCFActuator::GENERAL) {
// nothing special
} else if (actuatorType == MJCFActuator::POSITION) {
driveAPI.CreateStiffnessAttr().Set(actuator->kp);
} else if (actuatorType == MJCFActuator::VELOCITY) {
driveAPI.CreateStiffnessAttr().Set(actuator->kv);
}
const Vec2 &forcerange = actuator->forcerange;
float maxForce = std::max(abs(forcerange.x), abs(forcerange.y));
driveAPI.CreateMaxForceAttr().Set(maxForce);
}
}
} // namespace mjcf
} // namespace importer
} // namespace omni
| 52,024 | C++ | 38.98847 | 99 | 0.613967 |
NVIDIA-Omniverse/mjcf-importer-extension/source/extensions/omni.importer.mjcf/plugins/Mjcf.h | // SPDX-FileCopyrightText: Copyright (c) 2023 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
// SPDX-License-Identifier: Apache-2.0
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
#pragma once
#include <carb/Defines.h>
#include <pybind11/pybind11.h>
#include <stdint.h>
namespace omni {
namespace importer {
namespace mjcf {
struct ImportConfig {
bool mergeFixedJoints = false;
bool convexDecomp = false;
bool importInertiaTensor = false;
bool fixBase = true;
bool selfCollision = false;
float density = 1000; // default density used for objects without mass/inertia
// UrdfJointTargetType defaultDriveType = UrdfJointTargetType::POSITION;
float defaultDriveStrength = 100000;
float distanceScale = 1.0f;
// UrdfAxis upVector = { 0, 0, 1 };
bool createPhysicsScene = true;
bool makeDefaultPrim = true;
bool createBodyForFixedJoint = true;
bool overrideCoM = false;
bool overrideInertia = false;
bool visualizeCollisionGeoms = false;
bool importSites = true;
bool makeInstanceable = false;
std::string instanceableMeshUsdPath = "./instanceable_meshes.usd";
};
struct Mjcf {
CARB_PLUGIN_INTERFACE("omni::importer::mjcf::Mjcf", 0, 1);
void(CARB_ABI *createAssetFromMJCF)(const char *fileName,
const char *primName,
ImportConfig &config,
const std::string &stage_identifier);
};
} // namespace mjcf
} // namespace importer
} // namespace omni
| 2,021 | C | 30.59375 | 99 | 0.700643 |
NVIDIA-Omniverse/mjcf-importer-extension/source/extensions/omni.importer.mjcf/plugins/MjcfImporter.h | // SPDX-FileCopyrightText: Copyright (c) 2023 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
// SPDX-License-Identifier: Apache-2.0
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#pragma once
// clang-format off
#include "UsdPCH.h"
// clang-format on
#include "MjcfParser.h"
#include "MjcfTypes.h"
#include "MjcfUsd.h"
#include "MjcfUtils.h"
#include "core/mesh.h"
#include <carb/logging/Log.h>
#include "Mjcf.h"
#include "math/core/maths.h"
#include <pxr/usd/usdGeom/imageable.h>
#include <iostream>
#include <iterator>
#include <map>
#include <queue>
#include <set>
#include <string>
#include <tinyxml2.h>
#include <vector>
namespace omni {
namespace importer {
namespace mjcf {
class MJCFImporter {
public:
std::string baseDirPath;
std::string defaultClassName;
std::map<std::string, MJCFClass> classes;
MJCFCompiler compiler;
std::vector<MJCFBody *> bodies;
std::vector<MJCFGeom *> collisionGeoms;
std::vector<MJCFActuator *> actuators;
std::vector<MJCFTendon *> tendons;
std::vector<MJCFContact *> contacts;
MJCFBody worldBody;
std::map<std::string, pxr::UsdPhysicsRevoluteJoint> revoluteJointsMap;
std::map<std::string, pxr::UsdPhysicsPrismaticJoint> prismaticJointsMap;
std::map<std::string, pxr::UsdPhysicsJoint> d6JointsMap;
std::map<std::string, pxr::UsdPrim> geomPrimMap;
std::map<std::string, pxr::UsdPrim> sitePrimMap;
std::map<std::string, pxr::UsdPrim> siteToBodyPrim;
std::map<std::string, pxr::UsdPrim> geomToBodyPrim;
std::queue<MJCFBody *> bodyQueue;
std::map<std::string, int> jointToKinematicHierarchy;
std::map<std::string, int> jointToActuatorIdx;
std::map<std::string, MeshInfo> simulationMeshCache;
std::map<std::string, MJCFMesh> meshes;
std::map<std::string, MJCFMaterial> materials;
std::map<std::string, MJCFTexture> textures;
std::vector<ContactNode *> contactGraph;
std::map<std::string, MJCFBody *> nameToBody;
std::map<std::string, int> geomNameToIdx;
std::map<std::string, std::string> nameToUsdCollisionPrim;
bool createBodyForFixedJoint;
bool isLoaded = false;
MJCFImporter(const std::string fullPath, ImportConfig &config);
~MJCFImporter();
void populateBodyLookup(MJCFBody *body);
bool AddPhysicsEntities(pxr::UsdStageWeakPtr stage, const Transform trans,
const std::string &rootPrimPath,
const ImportConfig &config);
void CreateInstanceableMeshes(pxr::UsdStageRefPtr stage, MJCFBody *body,
const std::string rootPrimPath,
const bool isRoot, const ImportConfig &config);
void CreatePhysicsBodyAndJoint(pxr::UsdStageWeakPtr stage, MJCFBody *body,
std::string rootPrimPath,
const Transform trans, const bool isRoot,
const std::string parentBodyPath,
const ImportConfig &config,
const std::string instanceableUsdPath);
void computeJointFrame(Transform &origin, int *axisMap, const MJCFBody *body);
bool contactBodyExclusion(MJCFBody *body1, MJCFBody *body2);
bool createContactGraph();
void computeKinematicHierarchy();
void addWorldGeomsAndSites(pxr::UsdStageWeakPtr stage, std::string rootPath,
const ImportConfig &config,
const std::string instanceableUsdPath);
bool addVisualGeom(pxr::UsdStageWeakPtr stage, pxr::UsdPrim bodyPrim,
MJCFBody *body, std::string bodyPath,
const ImportConfig &config, bool createGeoms,
const std::string rootPrimPath);
void addVisualSites(pxr::UsdStageWeakPtr stage, pxr::UsdPrim bodyPrim,
MJCFBody *body, std::string bodyPath,
const ImportConfig &config);
void AddContactFilters(pxr::UsdStageWeakPtr stage);
void AddTendons(pxr::UsdStageWeakPtr stage, std::string rootPath);
pxr::GfVec3f GetLocalPos(MJCFTendon::SpatialAttachment attachment);
};
} // namespace mjcf
} // namespace importer
} // namespace omni
| 4,659 | C | 33.518518 | 99 | 0.68534 |
NVIDIA-Omniverse/mjcf-importer-extension/source/extensions/omni.importer.mjcf/plugins/UsdPCH.h | // SPDX-FileCopyrightText: Copyright (c) 2023 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
// SPDX-License-Identifier: Apache-2.0
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#pragma once
// !!! DO NOT INCLUDE THIS FILE IN A HEADER !!!
// When you include this file in a cpp file, add the file name to premake5.lua's
// pchFiles list!
// The usd headers drag in heavy dependencies and are very slow to build.
// Make it PCH to speed up building time.
#ifdef _MSC_VER
#pragma warning(push)
#pragma warning( \
disable : 4244) // = Conversion from double to float / int to float
#pragma warning(disable : 4267) // conversion from size_t to int
#pragma warning(disable : 4305) // argument truncation from double to float
#pragma warning(disable : 4800) // int to bool
#pragma warning( \
disable : 4996) // call to std::copy with parameters that may be unsafe
#define NOMINMAX // Make sure nobody #defines min or max
#include <Windows.h> // Include this here so we can curate
#undef small // defined in rpcndr.h
#elif defined(__GNUC__)
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wdeprecated-declarations"
#pragma GCC diagnostic ignored "-Wunused-local-typedefs"
#pragma GCC diagnostic ignored "-Wunused-function"
// This suppresses deprecated header warnings, which is impossible with pragmas.
// Alternative is to specify -Wno-deprecated build option, but that disables
// other useful warnings too.
#ifdef __DEPRECATED
#define OMNI_USD_SUPPRESS_DEPRECATION_WARNINGS
#undef __DEPRECATED
#endif
#endif
#define BOOST_PYTHON_STATIC_LIB
// Include cstdio here so that vsnprintf is properly declared. This is necessary
// because pyerrors.h has #define vsnprintf _vsnprintf which later causes
// <cstdio> to declare std::_vsnprintf instead of the correct and proper
// std::vsnprintf. By doing it here before everything else, we avoid this
// nonsense.
#include <cstdio>
// Python must be included first because it monkeys with macros that cause
// TBB to fail to compile in debug mode if TBB is included before Python
#include <boost/python/object.hpp>
#include <pxr/base/arch/stackTrace.h>
#include <pxr/base/arch/threads.h>
#include <pxr/base/gf/api.h>
#include <pxr/base/gf/camera.h>
#include <pxr/base/gf/frustum.h>
#include <pxr/base/gf/matrix3f.h>
#include <pxr/base/gf/matrix4d.h>
#include <pxr/base/gf/matrix4f.h>
#include <pxr/base/gf/quaternion.h>
#include <pxr/base/gf/rotation.h>
#include <pxr/base/gf/transform.h>
#include <pxr/base/gf/vec2f.h>
#include <pxr/base/plug/notice.h>
#include <pxr/base/plug/plugin.h>
#include <pxr/base/tf/hashmap.h>
#include <pxr/base/tf/staticTokens.h>
#include <pxr/base/tf/token.h>
#include <pxr/base/trace/reporter.h>
#include <pxr/base/trace/trace.h>
#include <pxr/base/vt/value.h>
#include <pxr/base/work/loops.h>
#include <pxr/base/work/threadLimits.h>
#include <pxr/imaging/hd/basisCurves.h>
#include <pxr/imaging/hd/camera.h>
#include <pxr/imaging/hd/engine.h>
#include <pxr/imaging/hd/extComputation.h>
#include <pxr/imaging/hd/flatNormals.h>
#include <pxr/imaging/hd/instancer.h>
#include <pxr/imaging/hd/light.h>
#include <pxr/imaging/hd/material.h>
#include <pxr/imaging/hd/mesh.h>
#include <pxr/imaging/hd/meshUtil.h>
#include <pxr/imaging/hd/points.h>
#include <pxr/imaging/hd/renderBuffer.h>
#include <pxr/imaging/hd/renderIndex.h>
#include <pxr/imaging/hd/renderPass.h>
#include <pxr/imaging/hd/renderPassState.h>
#include <pxr/imaging/hd/rendererPluginRegistry.h>
#include <pxr/imaging/hd/resourceRegistry.h>
#include <pxr/imaging/hd/rprim.h>
#include <pxr/imaging/hd/smoothNormals.h>
#include <pxr/imaging/hd/sprim.h>
#include <pxr/imaging/hd/vertexAdjacency.h>
#include <pxr/imaging/hdx/tokens.h>
#include <pxr/imaging/pxOsd/tokens.h>
#include <pxr/usd/ar/resolver.h>
#include <pxr/usd/ar/resolverContext.h>
#include <pxr/usd/ar/resolverContextBinder.h>
#include <pxr/usd/ar/resolverScopedCache.h>
#include <pxr/usd/kind/registry.h>
#include <pxr/usd/pcp/layerStack.h>
#include <pxr/usd/pcp/site.h>
#include <pxr/usd/sdf/attributeSpec.h>
#include <pxr/usd/sdf/changeList.h>
#include <pxr/usd/sdf/copyUtils.h>
#include <pxr/usd/sdf/fileFormat.h>
#include <pxr/usd/sdf/layerStateDelegate.h>
#include <pxr/usd/sdf/layerUtils.h>
#include <pxr/usd/sdf/relationshipSpec.h>
#include <pxr/usd/usd/attribute.h>
#include <pxr/usd/usd/editContext.h>
#include <pxr/usd/usd/modelAPI.h>
#include <pxr/usd/usd/notice.h>
#include <pxr/usd/usd/primRange.h>
#include <pxr/usd/usd/relationship.h>
#include <pxr/usd/usd/stage.h>
#include <pxr/usd/usd/stageCache.h>
#include <pxr/usd/usd/usdFileFormat.h>
#include <pxr/usd/usdGeom/basisCurves.h>
#include <pxr/usd/usdGeom/camera.h>
#include <pxr/usd/usdGeom/capsule.h>
#include <pxr/usd/usdGeom/cone.h>
#include <pxr/usd/usdGeom/cube.h>
#include <pxr/usd/usdGeom/cylinder.h>
#include <pxr/usd/usdGeom/mesh.h>
#include <pxr/usd/usdGeom/metrics.h>
#include <pxr/usd/usdGeom/points.h>
#include <pxr/usd/usdGeom/primvarsAPI.h>
#include <pxr/usd/usdGeom/scope.h>
#include <pxr/usd/usdGeom/sphere.h>
#include <pxr/usd/usdGeom/subset.h>
#include <pxr/usd/usdGeom/xform.h>
#include <pxr/usd/usdGeom/xformCommonAPI.h>
#include <pxr/usd/usdLux/cylinderLight.h>
#include <pxr/usd/usdLux/diskLight.h>
#include <pxr/usd/usdLux/distantLight.h>
#include <pxr/usd/usdLux/domeLight.h>
#include <pxr/usd/usdLux/rectLight.h>
#include <pxr/usd/usdLux/sphereLight.h>
#include <pxr/usd/usdLux/tokens.h>
#include <pxr/usd/usdShade/tokens.h>
#include <pxr/usd/usdSkel/animation.h>
#include <pxr/usd/usdSkel/root.h>
#include <pxr/usd/usdSkel/skeleton.h>
#include <pxr/usd/usdSkel/tokens.h>
#include <pxr/usd/usdUtils/stageCache.h>
#include <pxr/usdImaging/usdImaging/delegate.h>
// -- Hydra
#include <pxr/imaging/hd/renderDelegate.h>
#include <pxr/imaging/hd/renderIndex.h>
#include <pxr/imaging/hd/rendererPlugin.h>
#include <pxr/imaging/hd/sceneDelegate.h>
#include <pxr/imaging/hd/tokens.h>
#include <pxr/imaging/hdx/taskController.h>
#include <pxr/usdImaging/usdImaging/gprimAdapter.h>
#include <pxr/usdImaging/usdImaging/indexProxy.h>
#include <pxr/usdImaging/usdImaging/tokens.h>
// -- nv extensions
//#include <audioSchema/sound.h>
// -- omni.usd
#include <omni/usd/UsdContextIncludes.h>
#include <omni/usd/UtilsIncludes.h>
#ifdef _MSC_VER
#pragma warning(pop)
#elif defined(__GNUC__)
#pragma GCC diagnostic pop
#ifdef OMNI_USD_SUPPRESS_DEPRECATION_WARNINGS
#define __DEPRECATED
#undef OMNI_USD_SUPPRESS_DEPRECATION_WARNINGS
#endif
#endif
| 7,098 | C | 36.560846 | 99 | 0.742181 |
NVIDIA-Omniverse/mjcf-importer-extension/source/extensions/omni.importer.mjcf/plugins/Mjcf.cpp | // SPDX-FileCopyrightText: Copyright (c) 2023 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
// SPDX-License-Identifier: Apache-2.0
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#define CARB_EXPORTS
// clang-format off
#include "UsdPCH.h"
// clang-format on
#include "MjcfImporter.h"
#include "stdio.h"
#include <carb/PluginUtils.h>
#include <carb/logging/Log.h>
#include "Mjcf.h"
#include <omni/ext/IExt.h>
#include <omni/kit/IApp.h>
#include <omni/kit/IStageUpdate.h>
#define EXTENSION_NAME "omni.importer.mjcf.plugin"
using namespace carb;
const struct carb::PluginImplDesc kPluginImpl = {
EXTENSION_NAME, "MJCF Utilities", "NVIDIA", carb::PluginHotReload::eEnabled,
"dev"};
CARB_PLUGIN_IMPL(kPluginImpl, omni::importer::mjcf::Mjcf)
CARB_PLUGIN_IMPL_DEPS(omni::kit::IApp, carb::logging::ILogging)
namespace {
// passed in from python
void createAssetFromMJCF(const char *fileName, const char *primName,
omni::importer::mjcf::ImportConfig &config,
const std::string &stage_identifier = "") {
omni::importer::mjcf::MJCFImporter mjcf(fileName, config);
if (!mjcf.isLoaded) {
printf("cannot load mjcf xml file\n");
}
Transform trans = Transform();
bool save_stage = true;
pxr::UsdStageRefPtr _stage;
if (stage_identifier != "" &&
pxr::UsdStage::IsSupportedFile(stage_identifier)) {
_stage = pxr::UsdStage::Open(stage_identifier);
if (!_stage) {
CARB_LOG_INFO("Creating Stage: %s", stage_identifier.c_str());
_stage = pxr::UsdStage::CreateNew(stage_identifier);
} else {
for (const auto &p :
_stage->GetPrimAtPath(pxr::SdfPath("/")).GetChildren()) {
_stage->RemovePrim(p.GetPath());
}
}
config.makeDefaultPrim = true;
pxr::UsdGeomSetStageUpAxis(_stage, pxr::UsdGeomTokens->z);
}
if (!_stage) // If all else fails, import on current stage
{
CARB_LOG_INFO("Importing URDF to Current Stage");
// Get the 'active' USD stage from the USD stage cache.
const std::vector<pxr::UsdStageRefPtr> allStages =
pxr::UsdUtilsStageCache::Get().GetAllStages();
if (allStages.size() != 1) {
CARB_LOG_ERROR("Cannot determine the 'active' USD stage (%zu stages "
"present in the USD stage cache).",
allStages.size());
return;
}
_stage = allStages[0];
save_stage = false;
}
std::string result = "";
if (_stage) {
pxr::UsdGeomSetStageMetersPerUnit(_stage, 1.0 / config.distanceScale);
if (!mjcf.AddPhysicsEntities(_stage, trans, primName, config)) {
printf("no physics entities found!\n");
}
// CARB_LOG_WARN("Import Done, saving");
if (save_stage) {
// CARB_LOG_WARN("Saving Stage %s",
// _stage->GetRootLayer()->GetIdentifier().c_str());
_stage->Save();
}
}
}
} // namespace
CARB_EXPORT void carbOnPluginStartup() {
CARB_LOG_INFO("Startup MJCF Extension");
}
CARB_EXPORT void carbOnPluginShutdown() {}
void fillInterface(omni::importer::mjcf::Mjcf &iface) {
using namespace omni::importer::mjcf;
memset(&iface, 0, sizeof(iface));
// iface.helloWorld = helloWorld;
iface.createAssetFromMJCF = createAssetFromMJCF;
// iface.importRobot = importRobot;
}
| 3,775 | C++ | 30.466666 | 99 | 0.666225 |
NVIDIA-Omniverse/mjcf-importer-extension/source/extensions/omni.importer.mjcf/plugins/MeshImporter.h | // SPDX-FileCopyrightText: Copyright (c) 2023 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
// SPDX-License-Identifier: Apache-2.0
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#pragma once
#include "core/mesh.h"
#include <fstream>
namespace mesh {
class MeshImporter {
private:
// std::map<std::string, std::pair<Mesh*, carb::gym::GymMeshHandle>>
// gymGraphicsMeshCache; std::map<std::pair<float, float>,
// carb::gym::TriangleMeshHandle> cylinderCache; std::map<std::string, Mesh*>
// simulationMeshCache;
public:
MeshImporter() {}
std::string resolveMeshPath(const std::string &filePath) {
// noop for now
return filePath;
}
Mesh *loadMeshAssimp(std::string relativeMeshPath, const Vec3 &scale,
GymMeshNormalMode normalMode, bool flip = false) {
std::string meshPath = resolveMeshPath(relativeMeshPath);
Mesh *mesh = ImportMeshAssimp(meshPath.c_str());
if (mesh == nullptr) {
return nullptr;
}
if (mesh->m_positions.size() == 0) {
return nullptr;
}
if (normalMode == GymMeshNormalMode::eFromAsset) {
// asset normals should already be in the mesh
if (mesh->m_normals.size() != mesh->m_positions.size()) {
// fall back to vertex norms
mesh->CalculateNormals();
}
} else if (normalMode == GymMeshNormalMode::eComputePerVertex) {
mesh->CalculateNormals();
} else if (normalMode == GymMeshNormalMode::eComputePerFace) {
mesh->CalculateFaceNormals();
}
// Use normals to generate missing texcoords
for (unsigned int i = 0; i < mesh->m_texcoords.size(); ++i) {
Vector2 &uv = mesh->m_texcoords[i];
if (uv.x < 0 && uv.y < 0) {
Vector3 &n = mesh->m_normals[i];
uv.x = std::atan2(n.z, n.x) / k2Pi;
uv.y = std::atan2(std::sqrt(n.x * n.x + n.z * n.z), n.y) / kPi;
}
}
if (flip) {
Matrix44 flip;
flip(0, 0) = 1.0f;
flip(2, 1) = 1.0f;
flip(1, 2) = -1.0f;
flip(3, 3) = 1.0f;
mesh->Transform(flip);
}
mesh->Transform(ScaleMatrix(scale));
return mesh;
}
Mesh *loadMeshFromObj(std::string relativeMeshPath, const Vec3 &scale,
bool flip = false) {
std::string meshPath = resolveMeshPath(relativeMeshPath);
size_t extensionPosition = meshPath.find_last_of(".");
meshPath.replace(extensionPosition, std::string::npos, ".obj");
Mesh *mesh = ImportMeshFromObj(meshPath.c_str());
if (mesh == nullptr) {
return nullptr;
}
if (mesh->m_positions.size() == 0) {
// Memory leak? `Mesh` has no `delete` mechanism
return nullptr;
}
if (flip) {
Matrix44 flip;
flip(0, 0) = 1.0f;
flip(2, 1) = 1.0f;
flip(1, 2) = -1.0f;
flip(3, 3) = 1.0f;
mesh->Transform(flip);
}
mesh->Transform(ScaleMatrix(scale));
// use flat normals on collision shapes
mesh->CalculateFaceNormals();
return mesh;
}
Mesh *loadMeshFromWrl(std::string relativeMeshPath, const Vec3 &scale) {
std::string meshPath = resolveMeshPath(relativeMeshPath);
size_t extensionPosition = meshPath.find_last_of(".");
meshPath.replace(extensionPosition, std::string::npos, ".wrl");
std::ifstream inf(meshPath);
if (!inf) {
printf("File %s not found!\n", meshPath.c_str());
return nullptr;
}
// TODO Avoid!
Mesh *mesh = new Mesh();
std::string str;
while (inf >> str) {
if (str == "point") {
std::vector<Vec3> points;
std::string tmp;
inf >> tmp;
while (tmp != "]") {
float x, y, z;
std::string ss;
inf >> ss;
if (ss == "]") {
break;
}
x = (float)atof(ss.c_str());
inf >> y >> z;
points.push_back(Vec3(x * scale.x, y * scale.y, z * scale.z));
inf >> tmp;
}
while (inf >> str) {
if (str == "coordIndex") {
std::vector<int> indices;
inf >> tmp;
inf >> tmp;
while (tmp != "]") {
int i0, i1, i2;
if (tmp == "]") {
break;
}
sscanf(tmp.c_str(), "%d", &i0);
std::string s1, s2, s3;
inf >> s1 >> s2 >> s3;
sscanf(s1.c_str(), "%d", &i1);
sscanf(s2.c_str(), "%d", &i2);
indices.push_back(i0);
indices.push_back(i1);
indices.push_back(i2);
inf >> tmp;
}
// Now found triangles too, create convex
mesh->m_positions.resize(points.size());
mesh->m_indices.resize(indices.size());
for (size_t i = 0; i < points.size(); i++) {
mesh->m_positions[i].x = points[i].x;
mesh->m_positions[i].y = points[i].y;
mesh->m_positions[i].z = points[i].z;
}
memcpy(&mesh->m_indices[0], &indices[0],
sizeof(int) * indices.size());
mesh->CalculateNormals();
break;
}
}
}
}
inf.close();
return mesh;
}
};
} // namespace mesh
| 5,716 | C | 27.02451 | 99 | 0.55021 |
NVIDIA-Omniverse/mjcf-importer-extension/source/extensions/omni.importer.mjcf/plugins/MjcfUtils.h | // SPDX-FileCopyrightText: Copyright (c) 2023 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
// SPDX-License-Identifier: Apache-2.0
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#pragma once
#include "math/core/maths.h"
#include <tinyxml2.h>
namespace omni {
namespace importer {
namespace mjcf {
std::string SanitizeUsdName(const std::string &src);
std::string GetAttr(const tinyxml2::XMLElement *c, const char *name);
void getIfExist(tinyxml2::XMLElement *e, const char *aname, bool &p);
void getIfExist(tinyxml2::XMLElement *e, const char *aname, int &p);
void getIfExist(tinyxml2::XMLElement *e, const char *aname, float &p);
void getIfExist(tinyxml2::XMLElement *e, const char *aname, std::string &s);
void getIfExist(tinyxml2::XMLElement *e, const char *aname, Vec2 &p);
void getIfExist(tinyxml2::XMLElement *e, const char *aname, Vec3 &p);
void getIfExist(tinyxml2::XMLElement *e, const char *aname, Vec3 &from,
Vec3 &to);
void getIfExist(tinyxml2::XMLElement *e, const char *aname, Vec4 &p);
void getIfExist(tinyxml2::XMLElement *e, const char *aname, Quat &q);
void getEulerIfExist(tinyxml2::XMLElement *e, const char *aname, Quat &q,
std::string eulerseq, bool angleInRad);
void getZAxisIfExist(tinyxml2::XMLElement *e, const char *aname, Quat &q);
void getAngleAxisIfExist(tinyxml2::XMLElement *e, const char *aname, Quat &q,
bool angleInRad);
Quat indexedRotation(int axis, float s, float c);
Vec3 Diagonalize(const Matrix33 &m, Quat &massFrame);
} // namespace mjcf
} // namespace importer
} // namespace omni
| 2,105 | C | 42.874999 | 99 | 0.728266 |
NVIDIA-Omniverse/mjcf-importer-extension/source/extensions/omni.importer.mjcf/plugins/MjcfTypes.h | // SPDX-FileCopyrightText: Copyright (c) 2023 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
// SPDX-License-Identifier: Apache-2.0
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#pragma once
#include "core/mesh.h"
#include "math/core/maths.h"
#include <set>
#include <vector>
namespace omni {
namespace importer {
namespace mjcf {
typedef unsigned int TriangleMeshHandle;
typedef int64_t GymMeshHandle;
struct MeshInfo {
Mesh *mesh = nullptr;
TriangleMeshHandle meshId = -1;
GymMeshHandle meshHandle = -1;
};
struct ContactNode {
std::string name;
std::set<int> adjacentNodes;
};
class MJCFJoint {
public:
enum Type {
HINGE,
SLIDE,
BALL,
FREE,
};
std::string name;
Type type;
bool limited;
float armature;
// dynamics
float stiffness;
float damping;
float friction;
// axis
Vec3 axis;
float ref;
Vec3 pos; // aka origin's position: origin is {position, quat}
// limits
Vec2 range; // lower to upper joint limit
float velocityLimits[6];
float initVal;
MJCFJoint() {
armature = 0.0f;
damping = 0.0f;
limited = false;
axis = Vec3(1.0f, 0.0f, 0.0f);
name = "";
pos = Vec3(0.0f, 0.0f, 0.0f);
range = Vec2(0.0f, 0.0f);
stiffness = 0.0f;
friction = 0.0f;
type = HINGE;
ref = 0.0f;
initVal = 0.0f;
}
};
class MJCFGeom {
public:
enum Type { CAPSULE, SPHERE, ELLIPSOID, CYLINDER, BOX, MESH, PLANE, OTHER };
float density;
int conaffinity;
int condim;
int contype;
float margin;
// sliding, torsion, rolling frictions
Vec3 friction;
std::string material;
Vec4 rgba;
Vec3 solimp;
Vec2 solref;
Vec3 from;
Vec3 to;
Vec3 size;
std::string name;
Vec3 pos;
Type type;
Quat quat;
Vec4 axisangle;
Vec3 zaxis;
std::string mesh;
bool hasFromTo;
MJCFGeom() {
conaffinity = 1;
condim = 3;
contype = 1;
margin = 0.0f;
friction = Vec3(1.0f, 0.005f, 0.0001f);
material = "";
rgba = Vec4(0.5f, 0.5f, 0.5f, 1.0f);
solimp = Vec3(0.9f, 0.95f, 0.001f);
solref = Vec2(0.02f, 1.0f);
from = Vec3(0.0f, 0.0f, 0.0f);
to = Vec3(0.0f, 0.0f, 0.0f);
size = Vec3(1.0f, 1.0f, 1.0f);
name = "";
pos = Vec3(0.0f, 0.0f, 0.0f);
type = SPHERE;
density = 1000.0f;
quat = Quat();
hasFromTo = false;
}
};
class MJCFSite {
public:
enum Type { CAPSULE, SPHERE, ELLIPSOID, CYLINDER, BOX };
int group;
// sliding, torsion, rolling frictions
Vec3 friction;
std::string material;
Vec4 rgba;
Vec3 from;
Vec3 to;
Vec3 size;
bool hasFromTo;
std::string name;
Vec3 pos;
Type type;
Quat quat;
Vec3 zaxis;
bool hasGeom;
MJCFSite() {
group = 0;
material = "";
rgba = Vec4(0.5f, 0.5f, 0.5f, 1.0f);
from = Vec3(0.0f, 0.0f, 0.0f);
to = Vec3(0.0f, 0.0f, 0.0f);
size = Vec3(0.005f, 0.005f, 0.005f);
hasFromTo = false;
name = "";
pos = Vec3(0.0f, 0.0f, 0.0f);
type = SPHERE;
quat = Quat();
hasGeom = true;
}
};
class MJCFInertial {
public:
float mass;
Vec3 pos;
Vec3 diaginertia;
Quat principalAxes;
bool hasFullInertia;
MJCFInertial() {
mass = -1.0f;
pos = Vec3(0.0f, 0.0f, 0.0f);
diaginertia = Vec3(0.0f, 0.0f, 0.0f);
principalAxes = Quat();
hasFullInertia = false;
}
};
enum JointAxis {
eJointAxisX, //!< Corresponds to translation around the body0 x-axis
eJointAxisY, //!< Corresponds to translation around the body0 y-axis
eJointAxisZ, //!< Corresponds to translation around the body0 z-axis
eJointAxisTwist, //!< Corresponds to rotation around the body0 x-axis
eJointAxisSwing1, //!< Corresponds to rotation around the body0 y-axis
eJointAxisSwing2, //!< Corresponds to rotation around the body0 z-axis
};
class MJCFBody {
public:
std::string name;
Vec3 pos;
Quat quat;
Vec3 zaxis;
MJCFInertial *inertial;
std::vector<MJCFGeom *> geoms;
std::vector<MJCFJoint *> joints;
std::vector<MJCFBody *> bodies;
std::vector<MJCFSite *> sites;
bool hasVisual;
MJCFBody() {
name = "";
pos = Vec3(0.0f, 0.0f, 0.0f);
quat = Quat();
inertial = nullptr;
geoms.clear();
joints.clear();
bodies.clear();
hasVisual = false;
}
~MJCFBody() {
if (inertial) {
delete inertial;
}
for (int i = 0; i < (int)geoms.size(); i++) {
delete geoms[i];
}
for (int i = 0; i < (int)joints.size(); i++) {
delete joints[i];
}
for (int i = 0; i < (int)bodies.size(); i++) {
delete bodies[i];
}
for (int i = 0; i < (int)sites.size(); i++) {
delete sites[i];
}
}
};
class MJCFCompiler {
public:
bool angleInRad;
bool inertiafromgeom;
bool coordinateInLocal;
bool autolimits;
std::string eulerseq;
std::string meshDir;
std::string textureDir;
MJCFCompiler() {
eulerseq = "xyz";
angleInRad = false;
inertiafromgeom = true;
coordinateInLocal = true;
autolimits = false;
}
};
class MJCFContact {
public:
enum Type { PAIR, EXCLUDE, DEFAULT };
Type type;
std::string name;
std::string geom1, geom2;
int condim;
std::string body1, body2;
MJCFContact() {
type = DEFAULT;
name = "";
geom1 = "";
geom2 = "";
body1 = "";
body2 = "";
}
};
class MJCFActuator {
public:
enum Type { MOTOR, POSITION, VELOCITY, GENERAL, DEFAULT };
Type type;
bool ctrllimited;
bool forcelimited;
Vec2 ctrlrange;
Vec2 forcerange;
float gear;
std::string joint;
std::string name;
float kp, kv;
MJCFActuator() {
type = DEFAULT;
ctrllimited = false;
forcelimited = false;
ctrlrange = Vec2(-1.0f, 1.0f);
forcerange = Vec2(-FLT_MAX, FLT_MAX);
gear = 0.0f;
name = "";
joint = "";
kp = 0.f;
kv = 0.f;
}
};
class MJCFTendon {
public:
enum Type {
SPATIAL = 0,
FIXED,
DEFAULT // flag for default tendon
};
struct FixedJoint {
std::string joint;
float coef;
};
struct SpatialAttachment {
enum Type { GEOM, SITE };
std::string geom;
std::string sidesite = "";
std::string site;
Type type;
int branch;
};
struct SpatialPulley {
float divisor = 0.0;
int branch;
};
Type type;
std::string name;
bool limited;
Vec2 range;
// limit and friction solver params:
Vec3 solimplimit;
Vec2 solreflimit;
Vec3 solimpfriction;
Vec2 solreffriction;
float margin;
float frictionloss;
float width;
std::string material;
Vec4 rgba;
float springlength;
float stiffness;
float damping;
// fixed
std::vector<FixedJoint *> fixedJoints;
// spatial
std::vector<SpatialAttachment *> spatialAttachments;
std::vector<SpatialPulley *> spatialPulleys;
std::map<int, std::vector<SpatialAttachment *>> spatialBranches;
MJCFTendon() {
type = FIXED;
limited = false;
range = Vec2(0.0f, 0.0f);
solimplimit = Vec3(0.9f, 0.95f, 0.001f);
solreflimit = Vec2(0.02f, 1.0f);
solimpfriction = Vec3(0.9f, 0.95f, 0.001f);
solreffriction = Vec2(0.02f, 1.0f);
margin = 0.0f;
frictionloss = 0.0f;
width = 0.003f;
material = "";
rgba = Vec4(0.5f, 0.5f, 0.5f, 1.0f);
}
~MJCFTendon() {
for (int i = 0; i < (int)fixedJoints.size(); i++) {
delete fixedJoints[i];
}
for (int i = 0; i < (int)spatialAttachments.size(); i++) {
delete spatialAttachments[i];
}
for (int i = 0; i < (int)spatialPulleys.size(); i++) {
delete spatialPulleys[i];
}
}
};
class MJCFMesh {
public:
std::string name;
std::string filename;
Vec3 scale;
MJCFMesh() {
name = "";
filename = "";
scale = Vec3(1.0f);
}
};
class MJCFTexture {
public:
std::string name;
std::string filename;
std::string gridsize;
std::string gridlayout;
std::string type;
MJCFTexture() {
name = "";
filename = "";
gridsize = "";
gridlayout = "";
type = "cube";
}
};
class MJCFMaterial {
public:
std::string name;
std::string texture;
float specular;
float roughness;
float shininess;
Vec4 rgba;
bool project_uvw;
MJCFMaterial() {
name = "";
texture = "";
specular = 0.5f;
roughness = 0.5f;
shininess = 0.0f; // metallic
rgba = Vec4(0.2f, 0.2f, 0.2f, 1.0f);
project_uvw = true;
}
};
class MJCFClass {
public:
// a class that defines default values for the following entities
MJCFJoint djoint;
MJCFGeom dgeom;
MJCFActuator dactuator;
MJCFTendon dtendon;
MJCFMesh dmesh;
MJCFMaterial dmaterial;
MJCFSite dsite;
std::string name;
};
} // namespace mjcf
} // namespace importer
} // namespace omni
| 9,135 | C | 17.055336 | 99 | 0.614888 |
NVIDIA-Omniverse/mjcf-importer-extension/source/extensions/omni.importer.mjcf/plugins/MjcfParser.h | // SPDX-FileCopyrightText: Copyright (c) 2023 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
// SPDX-License-Identifier: Apache-2.0
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#pragma once
#include "Mjcf.h"
#include "MjcfTypes.h"
#include "math/core/maths.h"
#include <map>
#include <tinyxml2.h>
namespace omni {
namespace importer {
namespace mjcf {
tinyxml2::XMLElement *LoadInclude(tinyxml2::XMLDocument &doc,
const tinyxml2::XMLElement *c,
const std::string baseDirPath);
void LoadCompiler(tinyxml2::XMLElement *c, MJCFCompiler &compiler);
void LoadInertial(tinyxml2::XMLElement *i, MJCFInertial &inertial);
void LoadGeom(tinyxml2::XMLElement *g, MJCFGeom &geom, std::string className,
MJCFCompiler &compiler, std::map<std::string, MJCFClass> &classes,
bool isDefault);
void LoadSite(tinyxml2::XMLElement *s, MJCFSite &site, std::string className,
MJCFCompiler &compiler, std::map<std::string, MJCFClass> &classes,
bool isDefault);
void LoadMesh(tinyxml2::XMLElement *m, MJCFMesh &mesh, std::string className,
MJCFCompiler &compiler,
std::map<std::string, MJCFClass> &classes);
void LoadActuator(tinyxml2::XMLElement *g, MJCFActuator &actuator,
std::string className, MJCFActuator::Type type,
std::map<std::string, MJCFClass> &classes);
void LoadContact(tinyxml2::XMLElement *g, MJCFContact &contact,
MJCFContact::Type type,
std::map<std::string, MJCFClass> &classes);
void LoadTendon(tinyxml2::XMLElement *t, MJCFTendon &tendon,
std::string className, MJCFTendon::Type type,
std::map<std::string, MJCFClass> &classes);
void LoadJoint(tinyxml2::XMLElement *g, MJCFJoint &joint, std::string className,
MJCFCompiler &compiler,
std::map<std::string, MJCFClass> &classes, bool isDefault);
void LoadFreeJoint(tinyxml2::XMLElement *g, MJCFJoint &joint,
std::string className, MJCFCompiler &compiler,
std::map<std::string, MJCFClass> &classes, bool isDefault);
void LoadDefault(tinyxml2::XMLElement *e, const std::string className,
MJCFClass &cl, MJCFCompiler &compiler,
std::map<std::string, MJCFClass> &classes);
void LoadBody(tinyxml2::XMLElement *g, std::vector<MJCFBody *> &bodies,
MJCFBody &body, std::string className, MJCFCompiler &compiler,
std::map<std::string, MJCFClass> &classes,
std::string baseDirPath);
tinyxml2::XMLElement *LoadFile(tinyxml2::XMLDocument &doc,
const std::string filePath);
void LoadAssets(tinyxml2::XMLElement *a, std::string baseDirPath,
MJCFCompiler &compiler,
std::map<std::string, MeshInfo> &simulationMeshCache,
std::map<std::string, MJCFMesh> &meshes,
std::map<std::string, MJCFMaterial> &materials,
std::map<std::string, MJCFTexture> &textures,
std::string className,
std::map<std::string, MJCFClass> &classes,
ImportConfig &config);
void LoadGlobals(
tinyxml2::XMLElement *root, std::string &defaultClassName,
std::string baseDirPath, MJCFBody &worldBody,
std::vector<MJCFBody *> &bodies, std::vector<MJCFActuator *> &actuators,
std::vector<MJCFTendon *> &tendons, std::vector<MJCFContact *> &contacts,
std::map<std::string, MeshInfo> &simulationMeshCache,
std::map<std::string, MJCFMesh> &meshes,
std::map<std::string, MJCFMaterial> &materials,
std::map<std::string, MJCFTexture> &textures, MJCFCompiler &compiler,
std::map<std::string, MJCFClass> &classes,
std::map<std::string, int> &jointToActuatorIdx, ImportConfig &config);
} // namespace mjcf
} // namespace importer
} // namespace omni
| 4,453 | C | 47.945054 | 99 | 0.661801 |
NVIDIA-Omniverse/mjcf-importer-extension/source/extensions/omni.importer.mjcf/plugins/math/core/mat33.h | // SPDX-FileCopyrightText: Copyright (c) 2023 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
// SPDX-License-Identifier: Apache-2.0
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#pragma once
#include "common_math.h"
#include "quat.h"
#include "vec3.h"
struct Matrix33 {
CUDA_CALLABLE Matrix33() {}
CUDA_CALLABLE Matrix33(const float *ptr) {
cols[0].x = ptr[0];
cols[0].y = ptr[1];
cols[0].z = ptr[2];
cols[1].x = ptr[3];
cols[1].y = ptr[4];
cols[1].z = ptr[5];
cols[2].x = ptr[6];
cols[2].y = ptr[7];
cols[2].z = ptr[8];
}
CUDA_CALLABLE Matrix33(const Vec3 &c1, const Vec3 &c2, const Vec3 &c3) {
cols[0] = c1;
cols[1] = c2;
cols[2] = c3;
}
CUDA_CALLABLE Matrix33(const Quat &q) {
cols[0] = Rotate(q, Vec3(1.0f, 0.0f, 0.0f));
cols[1] = Rotate(q, Vec3(0.0f, 1.0f, 0.0f));
cols[2] = Rotate(q, Vec3(0.0f, 0.0f, 1.0f));
}
CUDA_CALLABLE float operator()(int i, int j) const {
return static_cast<const float *>(cols[j])[i];
}
CUDA_CALLABLE float &operator()(int i, int j) {
return static_cast<float *>(cols[j])[i];
}
Vec3 cols[3];
CUDA_CALLABLE static inline Matrix33 Identity() {
const Matrix33 sIdentity(Vec3(1.0f, 0.0f, 0.0f), Vec3(0.0f, 1.0f, 0.0f),
Vec3(0.0f, 0.0f, 1.0f));
return sIdentity;
}
};
CUDA_CALLABLE inline Matrix33 Multiply(float s, const Matrix33 &m) {
Matrix33 r = m;
r.cols[0] *= s;
r.cols[1] *= s;
r.cols[2] *= s;
return r;
}
CUDA_CALLABLE inline Vec3 Multiply(const Matrix33 &a, const Vec3 &x) {
return a.cols[0] * x.x + a.cols[1] * x.y + a.cols[2] * x.z;
}
CUDA_CALLABLE inline Vec3 operator*(const Matrix33 &a, const Vec3 &x) {
return Multiply(a, x);
}
CUDA_CALLABLE inline Matrix33 Multiply(const Matrix33 &a, const Matrix33 &b) {
Matrix33 r;
r.cols[0] = a * b.cols[0];
r.cols[1] = a * b.cols[1];
r.cols[2] = a * b.cols[2];
return r;
}
CUDA_CALLABLE inline Matrix33 Add(const Matrix33 &a, const Matrix33 &b) {
return Matrix33(a.cols[0] + b.cols[0], a.cols[1] + b.cols[1],
a.cols[2] + b.cols[2]);
}
CUDA_CALLABLE inline float Determinant(const Matrix33 &m) {
return Dot(m.cols[0], Cross(m.cols[1], m.cols[2]));
}
CUDA_CALLABLE inline Matrix33 Transpose(const Matrix33 &a) {
Matrix33 r;
for (uint32_t i = 0; i < 3; ++i)
for (uint32_t j = 0; j < 3; ++j)
r(i, j) = a(j, i);
return r;
}
CUDA_CALLABLE inline float Trace(const Matrix33 &a) {
return a(0, 0) + a(1, 1) + a(2, 2);
}
CUDA_CALLABLE inline Matrix33 Outer(const Vec3 &a, const Vec3 &b) {
return Matrix33(a * b.x, a * b.y, a * b.z);
}
CUDA_CALLABLE inline Matrix33 Inverse(const Matrix33 &a, bool &success) {
float s = Determinant(a);
const float eps = 0.0f;
if (fabsf(s) > eps) {
Matrix33 b;
b(0, 0) = a(1, 1) * a(2, 2) - a(1, 2) * a(2, 1);
b(0, 1) = a(0, 2) * a(2, 1) - a(0, 1) * a(2, 2);
b(0, 2) = a(0, 1) * a(1, 2) - a(0, 2) * a(1, 1);
b(1, 0) = a(1, 2) * a(2, 0) - a(1, 0) * a(2, 2);
b(1, 1) = a(0, 0) * a(2, 2) - a(0, 2) * a(2, 0);
b(1, 2) = a(0, 2) * a(1, 0) - a(0, 0) * a(1, 2);
b(2, 0) = a(1, 0) * a(2, 1) - a(1, 1) * a(2, 0);
b(2, 1) = a(0, 1) * a(2, 0) - a(0, 0) * a(2, 1);
b(2, 2) = a(0, 0) * a(1, 1) - a(0, 1) * a(1, 0);
success = true;
return Multiply(1.0f / s, b);
} else {
success = false;
return Matrix33();
}
}
CUDA_CALLABLE inline Matrix33 InverseDouble(const Matrix33 &a, bool &success) {
double m[3][3];
for (int i = 0; i < 3; ++i)
for (int j = 0; j < 3; ++j)
m[i][j] = a(i, j);
double det = m[0][0] * (m[2][2] * m[1][1] - m[2][1] * m[1][2]) -
m[1][0] * (m[2][2] * m[0][1] - m[2][1] * m[0][2]) +
m[2][0] * (m[1][2] * m[0][1] - m[1][1] * m[0][2]);
const double eps = 0.0f;
if (fabs(det) > eps) {
double b[3][3];
b[0][0] = m[1][1] * m[2][2] - m[1][2] * m[2][1];
b[0][1] = m[0][2] * m[2][1] - m[0][1] * m[2][2];
b[0][2] = m[0][1] * m[1][2] - m[0][2] * m[1][1];
b[1][0] = m[1][2] * m[2][0] - m[1][0] * m[2][2];
b[1][1] = m[0][0] * m[2][2] - m[0][2] * m[2][0];
b[1][2] = m[0][2] * m[1][0] - m[0][0] * m[1][2];
b[2][0] = m[1][0] * m[2][1] - m[1][1] * m[2][0];
b[2][1] = m[0][1] * m[2][0] - m[0][0] * m[2][1];
b[2][2] = m[0][0] * m[1][1] - m[0][1] * m[1][0];
success = true;
double invDet = 1.0 / det;
Matrix33 out;
for (int i = 0; i < 3; ++i)
for (int j = 0; j < 3; ++j)
out(i, j) = (float)(b[i][j] * invDet);
return out;
} else {
success = false;
Matrix33 out;
for (int i = 0; i < 3; ++i)
for (int j = 0; j < 3; ++j)
out(i, j) = 0.0f;
return out;
}
}
CUDA_CALLABLE inline Matrix33 operator*(float s, const Matrix33 &a) {
return Multiply(s, a);
}
CUDA_CALLABLE inline Matrix33 operator*(const Matrix33 &a, float s) {
return Multiply(s, a);
}
CUDA_CALLABLE inline Matrix33 operator*(const Matrix33 &a, const Matrix33 &b) {
return Multiply(a, b);
}
CUDA_CALLABLE inline Matrix33 operator+(const Matrix33 &a, const Matrix33 &b) {
return Add(a, b);
}
CUDA_CALLABLE inline Matrix33 operator-(const Matrix33 &a, const Matrix33 &b) {
return Add(a, -1.0f * b);
}
CUDA_CALLABLE inline Matrix33 &operator+=(Matrix33 &a, const Matrix33 &b) {
a = a + b;
return a;
}
CUDA_CALLABLE inline Matrix33 &operator-=(Matrix33 &a, const Matrix33 &b) {
a = a - b;
return a;
}
CUDA_CALLABLE inline Matrix33 &operator*=(Matrix33 &a, float s) {
a.cols[0] *= s;
a.cols[1] *= s;
a.cols[2] *= s;
return a;
}
CUDA_CALLABLE inline Matrix33 Skew(const Vec3 &v) {
return Matrix33(Vec3(0.0f, v.z, -v.y), Vec3(-v.z, 0.0f, v.x),
Vec3(v.y, -v.x, 0.0f));
}
template <typename T> CUDA_CALLABLE inline XQuat<T>::XQuat(const Matrix33 &m) {
float tr = m(0, 0) + m(1, 1) + m(2, 2), h;
if (tr >= 0) {
h = sqrtf(tr + 1);
w = 0.5f * h;
h = 0.5f / h;
x = (m(2, 1) - m(1, 2)) * h;
y = (m(0, 2) - m(2, 0)) * h;
z = (m(1, 0) - m(0, 1)) * h;
} else {
unsigned int i = 0;
if (m(1, 1) > m(0, 0))
i = 1;
if (m(2, 2) > m(i, i))
i = 2;
switch (i) {
case 0:
h = sqrtf((m(0, 0) - (m(1, 1) + m(2, 2))) + 1);
x = 0.5f * h;
h = 0.5f / h;
y = (m(0, 1) + m(1, 0)) * h;
z = (m(2, 0) + m(0, 2)) * h;
w = (m(2, 1) - m(1, 2)) * h;
break;
case 1:
h = sqrtf((m(1, 1) - (m(2, 2) + m(0, 0))) + 1);
y = 0.5f * h;
h = 0.5f / h;
z = (m(1, 2) + m(2, 1)) * h;
x = (m(0, 1) + m(1, 0)) * h;
w = (m(0, 2) - m(2, 0)) * h;
break;
case 2:
h = sqrtf((m(2, 2) - (m(0, 0) + m(1, 1))) + 1);
z = 0.5f * h;
h = 0.5f / h;
x = (m(2, 0) + m(0, 2)) * h;
y = (m(1, 2) + m(2, 1)) * h;
w = (m(1, 0) - m(0, 1)) * h;
break;
default: // Make compiler happy
x = y = z = w = 0;
break;
}
}
*this = Normalize(*this);
}
CUDA_CALLABLE inline void quat2Mat(const XQuat<float> &q, Matrix33 &m) {
float sqx = q.x * q.x;
float sqy = q.y * q.y;
float sqz = q.z * q.z;
float squ = q.w * q.w;
float s = 1.f / (sqx + sqy + sqz + squ);
m(0, 0) = 1.f - 2.f * s * (sqy + sqz);
m(0, 1) = 2.f * s * (q.x * q.y - q.z * q.w);
m(0, 2) = 2.f * s * (q.x * q.z + q.y * q.w);
m(1, 0) = 2.f * s * (q.x * q.y + q.z * q.w);
m(1, 1) = 1.f - 2.f * s * (sqx + sqz);
m(1, 2) = 2.f * s * (q.y * q.z - q.x * q.w);
m(2, 0) = 2.f * s * (q.x * q.z - q.y * q.w);
m(2, 1) = 2.f * s * (q.y * q.z + q.x * q.w);
m(2, 2) = 1.f - 2.f * s * (sqx + sqy);
}
// rotation is using new rotation axis
// rotation: Rx(X)*Ry(Y)*Rz(Z)
CUDA_CALLABLE inline void getEulerXYZ(const XQuat<float> &q, float &X, float &Y,
float &Z) {
Matrix33 rot;
quat2Mat(q, rot);
float cy = sqrtf(rot(2, 2) * rot(2, 2) + rot(1, 2) * rot(1, 2));
if (cy > 1e-6f) {
Z = -atan2(rot(0, 1), rot(0, 0));
Y = -atan2(-rot(0, 2), cy);
X = -atan2(rot(1, 2), rot(2, 2));
} else {
Z = -atan2(-rot(1, 0), rot(1, 1));
Y = -atan2(-rot(0, 2), cy);
X = 0.0f;
}
}
| 8,613 | C | 26.433121 | 99 | 0.500639 |
NVIDIA-Omniverse/mjcf-importer-extension/source/extensions/omni.importer.mjcf/plugins/math/core/mat22.h | // SPDX-FileCopyrightText: Copyright (c) 2023 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
// SPDX-License-Identifier: Apache-2.0
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#pragma once
#include "common_math.h"
#include "vec2.h"
struct Matrix22 {
CUDA_CALLABLE Matrix22() {}
CUDA_CALLABLE Matrix22(float a, float b, float c, float d) {
cols[0] = Vec2(a, c);
cols[1] = Vec2(b, d);
}
CUDA_CALLABLE Matrix22(const Vec2 &c1, const Vec2 &c2) {
cols[0] = c1;
cols[1] = c2;
}
CUDA_CALLABLE float operator()(int i, int j) const {
return static_cast<const float *>(cols[j])[i];
}
CUDA_CALLABLE float &operator()(int i, int j) {
return static_cast<float *>(cols[j])[i];
}
Vec2 cols[2];
static inline Matrix22 Identity() {
static const Matrix22 sIdentity(Vec2(1.0f, 0.0f), Vec2(0.0f, 1.0f));
return sIdentity;
}
};
CUDA_CALLABLE inline Matrix22 Multiply(float s, const Matrix22 &m) {
Matrix22 r = m;
r.cols[0] *= s;
r.cols[1] *= s;
return r;
}
CUDA_CALLABLE inline Matrix22 Multiply(const Matrix22 &a, const Matrix22 &b) {
Matrix22 r;
r.cols[0] = a.cols[0] * b.cols[0].x + a.cols[1] * b.cols[0].y;
r.cols[1] = a.cols[0] * b.cols[1].x + a.cols[1] * b.cols[1].y;
return r;
}
CUDA_CALLABLE inline Matrix22 Add(const Matrix22 &a, const Matrix22 &b) {
return Matrix22(a.cols[0] + b.cols[0], a.cols[1] + b.cols[1]);
}
CUDA_CALLABLE inline Vec2 Multiply(const Matrix22 &a, const Vec2 &x) {
return a.cols[0] * x.x + a.cols[1] * x.y;
}
CUDA_CALLABLE inline Matrix22 operator*(float s, const Matrix22 &a) {
return Multiply(s, a);
}
CUDA_CALLABLE inline Matrix22 operator*(const Matrix22 &a, float s) {
return Multiply(s, a);
}
CUDA_CALLABLE inline Matrix22 operator*(const Matrix22 &a, const Matrix22 &b) {
return Multiply(a, b);
}
CUDA_CALLABLE inline Matrix22 operator+(const Matrix22 &a, const Matrix22 &b) {
return Add(a, b);
}
CUDA_CALLABLE inline Matrix22 operator-(const Matrix22 &a, const Matrix22 &b) {
return Add(a, -1.0f * b);
}
CUDA_CALLABLE inline Matrix22 &operator+=(Matrix22 &a, const Matrix22 &b) {
a = a + b;
return a;
}
CUDA_CALLABLE inline Matrix22 &operator-=(Matrix22 &a, const Matrix22 &b) {
a = a - b;
return a;
}
CUDA_CALLABLE inline Matrix22 &operator*=(Matrix22 &a, float s) {
a = a * s;
return a;
}
CUDA_CALLABLE inline Vec2 operator*(const Matrix22 &a, const Vec2 &x) {
return Multiply(a, x);
}
CUDA_CALLABLE inline float Determinant(const Matrix22 &m) {
return m(0, 0) * m(1, 1) - m(1, 0) * m(0, 1);
}
CUDA_CALLABLE inline Matrix22 Inverse(const Matrix22 &m, float &det) {
det = Determinant(m);
if (fabsf(det) > FLT_EPSILON) {
Matrix22 inv;
inv(0, 0) = m(1, 1);
inv(1, 1) = m(0, 0);
inv(0, 1) = -m(0, 1);
inv(1, 0) = -m(1, 0);
return Multiply(1.0f / det, inv);
} else {
det = 0.0f;
return m;
}
}
CUDA_CALLABLE inline Matrix22 Transpose(const Matrix22 &a) {
Matrix22 r;
r(0, 0) = a(0, 0);
r(0, 1) = a(1, 0);
r(1, 0) = a(0, 1);
r(1, 1) = a(1, 1);
return r;
}
CUDA_CALLABLE inline float Trace(const Matrix22 &a) {
return a(0, 0) + a(1, 1);
}
CUDA_CALLABLE inline Matrix22 RotationMatrix(float theta) {
return Matrix22(Vec2(cosf(theta), sinf(theta)),
Vec2(-sinf(theta), cosf(theta)));
}
// outer product of a and b, b is considered a row vector
CUDA_CALLABLE inline Matrix22 Outer(const Vec2 &a, const Vec2 &b) {
return Matrix22(a * b.x, a * b.y);
}
CUDA_CALLABLE inline Matrix22 QRDecomposition(const Matrix22 &m) {
Vec2 a = Normalize(m.cols[0]);
Matrix22 q(a, PerpCCW(a));
return q;
}
CUDA_CALLABLE inline Matrix22 PolarDecomposition(const Matrix22 &m) {
/*
//iterative method
float det;
Matrix22 q = m;
for (int i=0; i < 4; ++i)
{
q = 0.5f*(q + Inverse(Transpose(q), det));
}
*/
Matrix22 q = m + Matrix22(m(1, 1), -m(1, 0), -m(0, 1), m(0, 0));
float s = Length(q.cols[0]);
q.cols[0] /= s;
q.cols[1] /= s;
return q;
}
| 4,489 | C | 24.953757 | 99 | 0.6409 |
NVIDIA-Omniverse/mjcf-importer-extension/source/extensions/omni.importer.mjcf/plugins/math/core/vec2.h | // SPDX-FileCopyrightText: Copyright (c) 2023 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
// SPDX-License-Identifier: Apache-2.0
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#pragma once
#include "common_math.h"
#if defined(_WIN32) && !defined(__CUDACC__)
#if defined(_DEBUG)
#define VEC2_VALIDATE() \
{ \
assert(_finite(x)); \
assert(!_isnan(x)); \
\
assert(_finite(y)); \
assert(!_isnan(y)); \
}
#else
#define VEC2_VALIDATE() \
{ \
assert(isfinite(x)); \
assert(isfinite(y)); \
}
#endif // _WIN32
#else
#define VEC2_VALIDATE()
#endif
#ifdef _DEBUG
#define FLOAT_VALIDATE(f) \
{ \
assert(_finite(f)); \
assert(!_isnan(f)); \
}
#else
#define FLOAT_VALIDATE(f)
#endif
// vec2
template <typename T> class XVector2 {
public:
typedef T value_type;
CUDA_CALLABLE XVector2() : x(0.0f), y(0.0f) { VEC2_VALIDATE(); }
CUDA_CALLABLE XVector2(T _x) : x(_x), y(_x) { VEC2_VALIDATE(); }
CUDA_CALLABLE XVector2(T _x, T _y) : x(_x), y(_y) { VEC2_VALIDATE(); }
CUDA_CALLABLE XVector2(const T *p) : x(p[0]), y(p[1]) {}
template <typename U>
CUDA_CALLABLE explicit XVector2(const XVector2<U> &v) : x(v.x), y(v.y) {}
CUDA_CALLABLE operator T *() { return &x; }
CUDA_CALLABLE operator const T *() const { return &x; };
CUDA_CALLABLE void Set(T x_, T y_) {
VEC2_VALIDATE();
x = x_;
y = y_;
}
CUDA_CALLABLE XVector2<T> operator*(T scale) const {
XVector2<T> r(*this);
r *= scale;
VEC2_VALIDATE();
return r;
}
CUDA_CALLABLE XVector2<T> operator/(T scale) const {
XVector2<T> r(*this);
r /= scale;
VEC2_VALIDATE();
return r;
}
CUDA_CALLABLE XVector2<T> operator+(const XVector2<T> &v) const {
XVector2<T> r(*this);
r += v;
VEC2_VALIDATE();
return r;
}
CUDA_CALLABLE XVector2<T> operator-(const XVector2<T> &v) const {
XVector2<T> r(*this);
r -= v;
VEC2_VALIDATE();
return r;
}
CUDA_CALLABLE XVector2<T> &operator*=(T scale) {
x *= scale;
y *= scale;
VEC2_VALIDATE();
return *this;
}
CUDA_CALLABLE XVector2<T> &operator/=(T scale) {
T s(1.0f / scale);
x *= s;
y *= s;
VEC2_VALIDATE();
return *this;
}
CUDA_CALLABLE XVector2<T> &operator+=(const XVector2<T> &v) {
x += v.x;
y += v.y;
VEC2_VALIDATE();
return *this;
}
CUDA_CALLABLE XVector2<T> &operator-=(const XVector2<T> &v) {
x -= v.x;
y -= v.y;
VEC2_VALIDATE();
return *this;
}
CUDA_CALLABLE XVector2<T> &operator*=(const XVector2<T> &scale) {
x *= scale.x;
y *= scale.y;
VEC2_VALIDATE();
return *this;
}
// negate
CUDA_CALLABLE XVector2<T> operator-() const {
VEC2_VALIDATE();
return XVector2<T>(-x, -y);
}
T x;
T y;
};
typedef XVector2<float> Vec2;
typedef XVector2<float> Vector2;
// lhs scalar scale
template <typename T>
CUDA_CALLABLE XVector2<T> operator*(T lhs, const XVector2<T> &rhs) {
XVector2<T> r(rhs);
r *= lhs;
return r;
}
template <typename T>
CUDA_CALLABLE XVector2<T> operator*(const XVector2<T> &lhs,
const XVector2<T> &rhs) {
XVector2<T> r(lhs);
r *= rhs;
return r;
}
template <typename T>
CUDA_CALLABLE bool operator==(const XVector2<T> &lhs, const XVector2<T> &rhs) {
return (lhs.x == rhs.x && lhs.y == rhs.y);
}
template <typename T>
CUDA_CALLABLE T Dot(const XVector2<T> &v1, const XVector2<T> &v2) {
return v1.x * v2.x + v1.y * v2.y;
}
// returns the ccw perpendicular vector
template <typename T> CUDA_CALLABLE XVector2<T> PerpCCW(const XVector2<T> &v) {
return XVector2<T>(-v.y, v.x);
}
template <typename T> CUDA_CALLABLE XVector2<T> PerpCW(const XVector2<T> &v) {
return XVector2<T>(v.y, -v.x);
}
// component wise min max functions
template <typename T>
CUDA_CALLABLE XVector2<T> Max(const XVector2<T> &a, const XVector2<T> &b) {
return XVector2<T>(Max(a.x, b.x), Max(a.y, b.y));
}
template <typename T>
CUDA_CALLABLE XVector2<T> Min(const XVector2<T> &a, const XVector2<T> &b) {
return XVector2<T>(Min(a.x, b.x), Min(a.y, b.y));
}
// 2d cross product, treat as if a and b are in the xy plane and return
// magnitude of z
template <typename T>
CUDA_CALLABLE T Cross(const XVector2<T> &a, const XVector2<T> &b) {
return (a.x * b.y - a.y * b.x);
}
| 5,697 | C | 27.49 | 99 | 0.523082 |
NVIDIA-Omniverse/mjcf-importer-extension/source/extensions/omni.importer.mjcf/plugins/math/core/point3.h | // SPDX-FileCopyrightText: Copyright (c) 2023 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
// SPDX-License-Identifier: Apache-2.0
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#pragma once
#include "vec4.h"
#include <ostream>
class Point3 {
public:
CUDA_CALLABLE Point3() : x(0), y(0), z(0) {}
CUDA_CALLABLE Point3(float a) : x(a), y(a), z(a) {}
CUDA_CALLABLE Point3(const float *p) : x(p[0]), y(p[1]), z(p[2]) {}
CUDA_CALLABLE Point3(float x_, float y_, float z_) : x(x_), y(y_), z(z_) {
Validate();
}
CUDA_CALLABLE explicit Point3(const Vec3 &v) : x(v.x), y(v.y), z(v.z) {}
CUDA_CALLABLE operator float *() { return &x; }
CUDA_CALLABLE operator const float *() const { return &x; };
CUDA_CALLABLE operator Vec4() const { return Vec4(x, y, z, 1.0f); }
CUDA_CALLABLE void Set(float x_, float y_, float z_) {
Validate();
x = x_;
y = y_;
z = z_;
}
CUDA_CALLABLE Point3 operator*(float scale) const {
Point3 r(*this);
r *= scale;
Validate();
return r;
}
CUDA_CALLABLE Point3 operator/(float scale) const {
Point3 r(*this);
r /= scale;
Validate();
return r;
}
CUDA_CALLABLE Point3 operator+(const Vec3 &v) const {
Point3 r(*this);
r += v;
Validate();
return r;
}
CUDA_CALLABLE Point3 operator-(const Vec3 &v) const {
Point3 r(*this);
r -= v;
Validate();
return r;
}
CUDA_CALLABLE Point3 &operator*=(float scale) {
x *= scale;
y *= scale;
z *= scale;
Validate();
return *this;
}
CUDA_CALLABLE Point3 &operator/=(float scale) {
float s(1.0f / scale);
x *= s;
y *= s;
z *= s;
Validate();
return *this;
}
CUDA_CALLABLE Point3 &operator+=(const Vec3 &v) {
x += v.x;
y += v.y;
z += v.z;
Validate();
return *this;
}
CUDA_CALLABLE Point3 &operator-=(const Vec3 &v) {
x -= v.x;
y -= v.y;
z -= v.z;
Validate();
return *this;
}
CUDA_CALLABLE Point3 &operator=(const Vec3 &v) {
x = v.x;
y = v.y;
z = v.z;
return *this;
}
CUDA_CALLABLE bool operator!=(const Point3 &v) const {
return (x != v.x || y != v.y || z != v.z);
}
// negate
CUDA_CALLABLE Point3 operator-() const {
Validate();
return Point3(-x, -y, -z);
}
float x, y, z;
CUDA_CALLABLE void Validate() const {}
};
// lhs scalar scale
CUDA_CALLABLE inline Point3 operator*(float lhs, const Point3 &rhs) {
Point3 r(rhs);
r *= lhs;
return r;
}
CUDA_CALLABLE inline Vec3 operator-(const Point3 &lhs, const Point3 &rhs) {
return Vec3(lhs.x - rhs.x, lhs.y - rhs.y, lhs.z - rhs.z);
}
CUDA_CALLABLE inline Point3 operator+(const Point3 &lhs, const Point3 &rhs) {
return Point3(lhs.x + rhs.x, lhs.y + rhs.y, lhs.z + rhs.z);
}
CUDA_CALLABLE inline bool operator==(const Point3 &lhs, const Point3 &rhs) {
return (lhs.x == rhs.x && lhs.y == rhs.y && lhs.z == rhs.z);
}
// component wise min max functions
CUDA_CALLABLE inline Point3 Max(const Point3 &a, const Point3 &b) {
return Point3(Max(a.x, b.x), Max(a.y, b.y), Max(a.z, b.z));
}
CUDA_CALLABLE inline Point3 Min(const Point3 &a, const Point3 &b) {
return Point3(Min(a.x, b.x), Min(a.y, b.y), Min(a.z, b.z));
}
| 3,714 | C | 24.101351 | 99 | 0.608239 |
NVIDIA-Omniverse/mjcf-importer-extension/source/extensions/omni.importer.mjcf/plugins/math/core/quat.h | // SPDX-FileCopyrightText: Copyright (c) 2023 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
// SPDX-License-Identifier: Apache-2.0
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#pragma once
#include "vec3.h"
#include <cassert>
struct Matrix33;
template <typename T> class XQuat {
public:
typedef T value_type;
CUDA_CALLABLE XQuat() : x(0), y(0), z(0), w(1.0) {}
CUDA_CALLABLE XQuat(const T *p) : x(p[0]), y(p[1]), z(p[2]), w(p[3]) {}
CUDA_CALLABLE XQuat(T x_, T y_, T z_, T w_) : x(x_), y(y_), z(z_), w(w_) {}
CUDA_CALLABLE XQuat(const Vec3 &v, float w) : x(v.x), y(v.y), z(v.z), w(w) {}
CUDA_CALLABLE explicit XQuat(const Matrix33 &m);
CUDA_CALLABLE operator T *() { return &x; }
CUDA_CALLABLE operator const T *() const { return &x; };
CUDA_CALLABLE void Set(T x_, T y_, T z_, T w_) {
x = x_;
y = y_;
z = z_;
w = w_;
}
CUDA_CALLABLE XQuat<T> operator*(T scale) const {
XQuat<T> r(*this);
r *= scale;
return r;
}
CUDA_CALLABLE XQuat<T> operator/(T scale) const {
XQuat<T> r(*this);
r /= scale;
return r;
}
CUDA_CALLABLE XQuat<T> operator+(const XQuat<T> &v) const {
XQuat<T> r(*this);
r += v;
return r;
}
CUDA_CALLABLE XQuat<T> operator-(const XQuat<T> &v) const {
XQuat<T> r(*this);
r -= v;
return r;
}
CUDA_CALLABLE XQuat<T> operator*(XQuat<T> q) const {
// quaternion multiplication
return XQuat<T>(w * q.x + q.w * x + y * q.z - q.y * z,
w * q.y + q.w * y + z * q.x - q.z * x,
w * q.z + q.w * z + x * q.y - q.x * y,
w * q.w - x * q.x - y * q.y - z * q.z);
}
CUDA_CALLABLE XQuat<T> &operator*=(T scale) {
x *= scale;
y *= scale;
z *= scale;
w *= scale;
return *this;
}
CUDA_CALLABLE XQuat<T> &operator/=(T scale) {
T s(1.0f / scale);
x *= s;
y *= s;
z *= s;
w *= s;
return *this;
}
CUDA_CALLABLE XQuat<T> &operator+=(const XQuat<T> &v) {
x += v.x;
y += v.y;
z += v.z;
w += v.w;
return *this;
}
CUDA_CALLABLE XQuat<T> &operator-=(const XQuat<T> &v) {
x -= v.x;
y -= v.y;
z -= v.z;
w -= v.w;
return *this;
}
CUDA_CALLABLE bool operator!=(const XQuat<T> &v) const {
return (x != v.x || y != v.y || z != v.z || w != v.w);
}
// negate
CUDA_CALLABLE XQuat<T> operator-() const { return XQuat<T>(-x, -y, -z, -w); }
CUDA_CALLABLE XVector3<T> GetAxis() const { return XVector3<T>(x, y, z); }
T x, y, z, w;
};
typedef XQuat<float> Quat;
// lhs scalar scale
template <typename T>
CUDA_CALLABLE XQuat<T> operator*(T lhs, const XQuat<T> &rhs) {
XQuat<T> r(rhs);
r *= lhs;
return r;
}
template <typename T>
CUDA_CALLABLE bool operator==(const XQuat<T> &lhs, const XQuat<T> &rhs) {
return (lhs.x == rhs.x && lhs.y == rhs.y && lhs.z == rhs.z && lhs.w == rhs.w);
}
template <typename T>
CUDA_CALLABLE inline XQuat<T> QuatFromAxisAngle(const Vec3 &axis, float angle) {
Vec3 v = Normalize(axis);
float half = angle * 0.5f;
float w = cosf(half);
const float sin_theta_over_two = sinf(half);
v *= sin_theta_over_two;
return XQuat<T>(v.x, v.y, v.z, w);
}
CUDA_CALLABLE inline float Dot(const Quat &a, const Quat &b) {
return a.x * b.x + a.y * b.y + a.z * b.z + a.w * b.w;
}
CUDA_CALLABLE inline float Length(const Quat &a) { return sqrtf(Dot(a, a)); }
CUDA_CALLABLE inline Quat QuatFromEulerZYX(float rotx, float roty, float rotz) {
Quat q;
// Abbreviations for the various angular functions
float cy = cos(rotz * 0.5f);
float sy = sin(rotz * 0.5f);
float cr = cos(rotx * 0.5f);
float sr = sin(rotx * 0.5f);
float cp = cos(roty * 0.5f);
float sp = sin(roty * 0.5f);
q.w = (float)(cy * cr * cp + sy * sr * sp);
q.x = (float)(cy * sr * cp - sy * cr * sp);
q.y = (float)(cy * cr * sp + sy * sr * cp);
q.z = (float)(sy * cr * cp - cy * sr * sp);
return q;
}
CUDA_CALLABLE inline void EulerFromQuatZYX(const Quat &q, float &rotx,
float &roty, float &rotz) {
float x = q.x, y = q.y, z = q.z, w = q.w;
float t0 = x * x - z * z;
float t1 = w * w - y * y;
float xx = 0.5f * (t0 + t1); // 1/2 x of x'
float xy = x * y + w * z; // 1/2 y of x'
float xz = w * y - x * z; // 1/2 z of x'
float t = xx * xx + xy * xy; // cos(theta)^2
float yz = 2.0f * (y * z + w * x); // z of y'
rotz = atan2(xy, xx); // yaw (psi)
roty = atan(xz / sqrt(t)); // pitch (theta)
// todo: doublecheck!
if (fabsf(t) > 1e-6f) {
rotx = (float)atan2(yz, t1 - t0);
} else {
rotx = (float)(2.0f * atan2(x, w) - copysignf(1.0f, xz) * rotz);
}
}
// converts Euler angles to quaternion performing an intrinsic rotation in yaw
// then pitch then roll order i.e. first rotate by yaw around z, then rotate by
// pitch around the rotated y axis, then rotate around roll around the twice (by
// yaw and pitch) rotated x axis
CUDA_CALLABLE inline Quat rpy2quat(const float roll, const float pitch,
const float yaw) {
Quat q;
// Abbreviations for the various angular functions
float cy = cos(yaw * 0.5f);
float sy = sin(yaw * 0.5f);
float cr = cos(roll * 0.5f);
float sr = sin(roll * 0.5f);
float cp = cos(pitch * 0.5f);
float sp = sin(pitch * 0.5f);
q.w = (float)(cy * cr * cp + sy * sr * sp);
q.x = (float)(cy * sr * cp - sy * cr * sp);
q.y = (float)(cy * cr * sp + sy * sr * cp);
q.z = (float)(sy * cr * cp - cy * sr * sp);
return q;
}
// converts Euler angles to quaternion performing an intrinsic rotation in x
// then y then z order i.e. first rotate by x_rot around x, then rotate by y_rot
// around the rotated y axis, then rotate by z_rot around the twice (by roll and
// pitch) rotated z axis
CUDA_CALLABLE inline Quat euler_xyz2quat(const float x_rot, const float y_rot,
const float z_rot) {
Quat q;
// Abbreviations for the various angular functions
float cy = std::cos(z_rot * 0.5f);
float sy = std::sin(z_rot * 0.5f);
float cr = std::cos(x_rot * 0.5f);
float sr = std::sin(x_rot * 0.5f);
float cp = std::cos(y_rot * 0.5f);
float sp = std::sin(y_rot * 0.5f);
q.w = (float)(cy * cr * cp - sy * sr * sp);
q.x = (float)(cy * sr * cp + sy * cr * sp);
q.y = (float)(cy * cr * sp - sy * sr * cp);
q.z = (float)(sy * cr * cp + cy * sr * sp);
return q;
}
// !!! preist@ This function produces euler angles according to this convention:
// https://www.euclideanspace.com/maths/standards/index.htm Heading = rotation
// about y axis Attitude = rotation about z axis Bank = rotation about x axis
// Order: Heading (y) -> Attitude (z) -> Bank (x), and applied intrinsically
CUDA_CALLABLE inline void quat2rpy(const Quat &q1, float &bank, float &attitude,
float &heading) {
float sqw = q1.w * q1.w;
float sqx = q1.x * q1.x;
float sqy = q1.y * q1.y;
float sqz = q1.z * q1.z;
float unit = sqx + sqy + sqz +
sqw; // if normalised is one, otherwise is correction factor
float test = q1.x * q1.y + q1.z * q1.w;
if (test > 0.499f * unit) { // singularity at north pole
heading = 2.f * atan2(q1.x, q1.w);
attitude = kPi / 2.f;
bank = 0.f;
return;
}
if (test < -0.499f * unit) { // singularity at south pole
heading = -2.f * atan2(q1.x, q1.w);
attitude = -kPi / 2.f;
bank = 0.f;
return;
}
heading = atan2(2.f * q1.x * q1.y + 2.f * q1.w * q1.z, sqx - sqy - sqz + sqw);
attitude = asin(-2.f * q1.x * q1.z + 2.f * q1.y * q1.w);
bank = atan2(2.f * q1.y * q1.z + 2.f * q1.x * q1.w, -sqx - sqy + sqz + sqw);
}
// preist@:
// The Euler angles correspond to an extrinsic x-y-z i.e. intrinsic z-y-x
// rotation and this function does not guard against gimbal lock
CUDA_CALLABLE inline void zUpQuat2rpy(const Quat &q1, float &roll, float &pitch,
float &yaw) {
// roll (x-axis rotation)
float sinr_cosp = 2.0f * (q1.w * q1.x + q1.y * q1.z);
float cosr_cosp = 1.0f - 2.0f * (q1.x * q1.x + q1.y * q1.y);
roll = atan2(sinr_cosp, cosr_cosp);
// pitch (y-axis rotation)
float sinp = 2.0f * (q1.w * q1.y - q1.z * q1.x);
if (fabs(sinp) > 0.999f)
pitch = (float)copysign(kPi / 2.0f, sinp);
else
pitch = asin(sinp);
// yaw (z-axis rotation)
float siny_cosp = 2.0f * (q1.w * q1.z + q1.x * q1.y);
float cosy_cosp = 1.0f - 2.0f * (q1.y * q1.y + q1.z * q1.z);
yaw = atan2(siny_cosp, cosy_cosp);
}
CUDA_CALLABLE inline void getEulerZYX(const Quat &q, float &yawZ, float &pitchY,
float &rollX) {
float squ;
float sqx;
float sqy;
float sqz;
float sarg;
sqx = q.x * q.x;
sqy = q.y * q.y;
sqz = q.z * q.z;
squ = q.w * q.w;
rollX = atan2(2 * (q.y * q.z + q.w * q.x), squ - sqx - sqy + sqz);
sarg = (-2.0f) * (q.x * q.z - q.w * q.y);
pitchY = sarg <= (-1.0f) ? (-0.5f) * kPi
: (sarg >= (1.0f) ? (0.5f) * kPi : asinf(sarg));
yawZ = atan2(2 * (q.x * q.y + q.w * q.z), squ + sqx - sqy - sqz);
}
// rotate vector by quaternion (q, w)
CUDA_CALLABLE inline Vec3 Rotate(const Quat &q, const Vec3 &x) {
return x * (2.0f * q.w * q.w - 1.0f) + Cross(Vec3(q), x) * q.w * 2.0f +
Vec3(q) * Dot(Vec3(q), x) * 2.0f;
}
CUDA_CALLABLE inline Vec3 operator*(const Quat &q, const Vec3 &v) {
return Rotate(q, v);
}
CUDA_CALLABLE inline Vec3 GetBasisVector0(const Quat &q) {
return Rotate(q, Vec3(1.0f, 0.0f, 0.0f));
}
CUDA_CALLABLE inline Vec3 GetBasisVector1(const Quat &q) {
return Rotate(q, Vec3(0.0f, 1.0f, 0.0f));
}
CUDA_CALLABLE inline Vec3 GetBasisVector2(const Quat &q) {
return Rotate(q, Vec3(0.0f, 0.0f, 1.0f));
}
// rotate vector by inverse transform in (q, w)
CUDA_CALLABLE inline Vec3 RotateInv(const Quat &q, const Vec3 &x) {
return x * (2.0f * q.w * q.w - 1.0f) - Cross(Vec3(q), x) * q.w * 2.0f +
Vec3(q) * Dot(Vec3(q), x) * 2.0f;
}
CUDA_CALLABLE inline Quat Inverse(const Quat &q) {
return Quat(-q.x, -q.y, -q.z, q.w);
}
CUDA_CALLABLE inline Quat Normalize(const Quat &q) {
float lSq = q.x * q.x + q.y * q.y + q.z * q.z + q.w * q.w;
if (lSq > 0.0f) {
float invL = 1.0f / sqrtf(lSq);
return q * invL;
} else
return Quat();
}
//
// given two quaternions and a time-step returns the corresponding angular
// velocity vector
//
CUDA_CALLABLE inline Vec3 DifferentiateQuat(const Quat &q1, const Quat &q0,
float invdt) {
Quat dq = q1 * Inverse(q0);
float sinHalfTheta = Length(dq.GetAxis());
float theta = asinf(sinHalfTheta) * 2.0f;
if (fabsf(theta) < 0.001f) {
// use linear approximation approx for small angles
Quat dqdt = (q1 - q0) * invdt;
Quat omega = dqdt * Inverse(q0);
return Vec3(omega.x, omega.y, omega.z) * 2.0f;
} else {
// use inverse exponential map
Vec3 axis = Normalize(dq.GetAxis());
return axis * theta * invdt;
}
}
CUDA_CALLABLE inline Quat IntegrateQuat(const Vec3 &omega, const Quat &q0,
float dt) {
Vec3 axis;
float w = Length(omega);
if (w * dt < 0.001f) {
// sinc approx for small angles
axis = omega * (0.5f * dt - (dt * dt * dt) / 48.0f * w * w);
} else {
axis = omega * (sinf(0.5f * w * dt) / w);
}
Quat dq;
dq.x = axis.x;
dq.y = axis.y;
dq.z = axis.z;
dq.w = cosf(w * dt * 0.5f);
Quat q1 = dq * q0;
// explicit re-normalization here otherwise we do some see energy drift
return Normalize(q1);
}
| 12,042 | C | 29.258794 | 99 | 0.566185 |
NVIDIA-Omniverse/mjcf-importer-extension/source/extensions/omni.importer.mjcf/plugins/math/core/vec3.h | // SPDX-FileCopyrightText: Copyright (c) 2023 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
// SPDX-License-Identifier: Apache-2.0
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#pragma once
#include "common_math.h"
#if 0 //_DEBUG
#define VEC3_VALIDATE() \
{ \
assert(_finite(x)); \
assert(!_isnan(x)); \
\
assert(_finite(y)); \
assert(!_isnan(y)); \
\
assert(_finite(z)); \
assert(!_isnan(z)); \
}
#else
#define VEC3_VALIDATE()
#endif
template <typename T = float> class XVector3 {
public:
typedef T value_type;
CUDA_CALLABLE inline XVector3() : x(0.0f), y(0.0f), z(0.0f) {}
CUDA_CALLABLE inline XVector3(T a) : x(a), y(a), z(a) {}
CUDA_CALLABLE inline XVector3(const T *p) : x(p[0]), y(p[1]), z(p[2]) {}
CUDA_CALLABLE inline XVector3(T x_, T y_, T z_) : x(x_), y(y_), z(z_) {
VEC3_VALIDATE();
}
CUDA_CALLABLE inline operator T *() { return &x; }
CUDA_CALLABLE inline operator const T *() const { return &x; };
CUDA_CALLABLE inline void Set(T x_, T y_, T z_) {
VEC3_VALIDATE();
x = x_;
y = y_;
z = z_;
}
CUDA_CALLABLE inline XVector3<T> operator*(T scale) const {
XVector3<T> r(*this);
r *= scale;
return r;
VEC3_VALIDATE();
}
CUDA_CALLABLE inline XVector3<T> operator/(T scale) const {
XVector3<T> r(*this);
r /= scale;
return r;
VEC3_VALIDATE();
}
CUDA_CALLABLE inline XVector3<T> operator+(const XVector3<T> &v) const {
XVector3<T> r(*this);
r += v;
return r;
VEC3_VALIDATE();
}
CUDA_CALLABLE inline XVector3<T> operator-(const XVector3<T> &v) const {
XVector3<T> r(*this);
r -= v;
return r;
VEC3_VALIDATE();
}
CUDA_CALLABLE inline XVector3<T> operator/(const XVector3<T> &v) const {
XVector3<T> r(*this);
r /= v;
return r;
VEC3_VALIDATE();
}
CUDA_CALLABLE inline XVector3<T> operator*(const XVector3<T> &v) const {
XVector3<T> r(*this);
r *= v;
return r;
VEC3_VALIDATE();
}
CUDA_CALLABLE inline XVector3<T> &operator*=(T scale) {
x *= scale;
y *= scale;
z *= scale;
VEC3_VALIDATE();
return *this;
}
CUDA_CALLABLE inline XVector3<T> &operator/=(T scale) {
T s(1.0f / scale);
x *= s;
y *= s;
z *= s;
VEC3_VALIDATE();
return *this;
}
CUDA_CALLABLE inline XVector3<T> &operator+=(const XVector3<T> &v) {
x += v.x;
y += v.y;
z += v.z;
VEC3_VALIDATE();
return *this;
}
CUDA_CALLABLE inline XVector3<T> &operator-=(const XVector3<T> &v) {
x -= v.x;
y -= v.y;
z -= v.z;
VEC3_VALIDATE();
return *this;
}
CUDA_CALLABLE inline XVector3<T> &operator/=(const XVector3<T> &v) {
x /= v.x;
y /= v.y;
z /= v.z;
VEC3_VALIDATE();
return *this;
}
CUDA_CALLABLE inline XVector3<T> &operator*=(const XVector3<T> &v) {
x *= v.x;
y *= v.y;
z *= v.z;
VEC3_VALIDATE();
return *this;
}
CUDA_CALLABLE inline bool operator!=(const XVector3<T> &v) const {
return (x != v.x || y != v.y || z != v.z);
}
// negate
CUDA_CALLABLE inline XVector3<T> operator-() const {
VEC3_VALIDATE();
return XVector3<T>(-x, -y, -z);
}
CUDA_CALLABLE void Validate() { VEC3_VALIDATE(); }
T x, y, z;
};
typedef XVector3<float> Vec3;
typedef XVector3<float> Vector3;
// lhs scalar scale
template <typename T>
CUDA_CALLABLE XVector3<T> operator*(T lhs, const XVector3<T> &rhs) {
XVector3<T> r(rhs);
r *= lhs;
return r;
}
template <typename T>
CUDA_CALLABLE bool operator==(const XVector3<T> &lhs, const XVector3<T> &rhs) {
return (lhs.x == rhs.x && lhs.y == rhs.y && lhs.z == rhs.z);
}
template <typename T>
CUDA_CALLABLE typename T::value_type Dot3(const T &v1, const T &v2) {
return v1.x * v2.x + v1.y * v2.y + v1.z * v2.z;
}
CUDA_CALLABLE inline float Dot3(const float *v1, const float *v2) {
return v1[0] * v2[0] + v1[1] * v2[1] + v1[2] * v2[2];
}
template <typename T>
CUDA_CALLABLE inline T Dot(const XVector3<T> &v1, const XVector3<T> &v2) {
return v1.x * v2.x + v1.y * v2.y + v1.z * v2.z;
}
CUDA_CALLABLE inline Vec3 Cross(const Vec3 &b, const Vec3 &c) {
return Vec3(b.y * c.z - b.z * c.y, b.z * c.x - b.x * c.z,
b.x * c.y - b.y * c.x);
}
// component wise min max functions
template <typename T>
CUDA_CALLABLE inline XVector3<T> Max(const XVector3<T> &a,
const XVector3<T> &b) {
return XVector3<T>(Max(a.x, b.x), Max(a.y, b.y), Max(a.z, b.z));
}
template <typename T>
CUDA_CALLABLE inline XVector3<T> Min(const XVector3<T> &a,
const XVector3<T> &b) {
return XVector3<T>(Min(a.x, b.x), Min(a.y, b.y), Min(a.z, b.z));
}
| 5,802 | C | 28.015 | 99 | 0.531024 |
NVIDIA-Omniverse/mjcf-importer-extension/source/extensions/omni.importer.mjcf/plugins/math/core/matnn.h | // SPDX-FileCopyrightText: Copyright (c) 2023 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
// SPDX-License-Identifier: Apache-2.0
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#pragma once
template <int m, int n, typename T = double> class XMatrix {
public:
XMatrix() { memset(data, 0, sizeof(*this)); }
XMatrix(const XMatrix<m, n> &a) { memcpy(data, a.data, sizeof(*this)); }
template <typename OtherT> XMatrix(const OtherT *ptr) {
for (int j = 0; j < n; ++j)
for (int i = 0; i < m; ++i)
data[j][i] = *(ptr++);
}
const XMatrix<m, n> &operator=(const XMatrix<m, n> &a) {
memcpy(data, a.data, sizeof(*this));
return *this;
}
template <typename OtherT>
void SetCol(int j, const XMatrix<m, 1, OtherT> &c) {
for (int i = 0; i < m; ++i)
data[j][i] = c(i, 0);
}
template <typename OtherT>
void SetRow(int i, const XMatrix<1, n, OtherT> &r) {
for (int j = 0; j < m; ++j)
data[j][i] = r(0, j);
}
T &operator()(int row, int col) { return data[col][row]; }
const T &operator()(int row, int col) const { return data[col][row]; }
void SetIdentity() {
for (int i = 0; i < m; ++i) {
for (int j = 0; j < n; ++j) {
if (i == j)
data[i][j] = 1.0;
else
data[i][j] = 0.0;
}
}
}
// column major storage
T data[n][m];
};
template <int m, int n, typename T>
XMatrix<m, n, T> operator-(const XMatrix<m, n, T> &lhs,
const XMatrix<m, n, T> &rhs) {
XMatrix<m, n> d;
for (int i = 0; i < m; ++i)
for (int j = 0; j < n; ++j)
d(i, j) = lhs(i, j) - rhs(i, j);
return d;
}
template <int m, int n, typename T>
XMatrix<m, n, T> operator+(const XMatrix<m, n, T> &lhs,
const XMatrix<m, n, T> &rhs) {
XMatrix<m, n> d;
for (int i = 0; i < m; ++i)
for (int j = 0; j < n; ++j)
d(i, j) = lhs(i, j) + rhs(i, j);
return d;
}
template <int m, int n, int o, typename T>
XMatrix<m, o> Multiply(const XMatrix<m, n, T> &lhs,
const XMatrix<n, o, T> &rhs) {
XMatrix<m, o> ret;
for (int i = 0; i < m; ++i) {
for (int j = 0; j < o; ++j) {
T sum = 0.0f;
for (int k = 0; k < n; ++k) {
sum += lhs(i, k) * rhs(k, j);
}
ret(i, j) = sum;
}
}
return ret;
}
template <int m, int n> XMatrix<n, m> Transpose(const XMatrix<m, n> &a) {
XMatrix<n, m> ret;
for (int i = 0; i < m; ++i) {
for (int j = 0; j < n; ++j) {
ret(j, i) = a(i, j);
}
}
return ret;
}
// matrix to swap row i and j when multiplied on the right
template <int n> XMatrix<n, n> Permutation(int i, int j) {
XMatrix<n, n> m;
m.SetIdentity();
m(i, i) = 0.0;
m(i, j) = 1.0;
m(j, j) = 0.0;
m(j, i) = 1.0;
return m;
}
template <int m, int n> void PrintMatrix(const char *name, XMatrix<m, n> a) {
printf("%s = [\n", name);
for (int i = 0; i < m; ++i) {
printf("[ ");
for (int j = 0; j < n; ++j) {
printf("% .4f", float(a(i, j)));
if (j < n - 1)
printf(" ");
}
printf(" ]\n");
}
printf("]\n");
}
template <int n, typename T>
XMatrix<n, n, T> LU(const XMatrix<n, n, T> &m, XMatrix<n, n, T> &L) {
XMatrix<n, n> U = m;
L.SetIdentity();
// for each row
for (int j = 0; j < n; ++j) {
XMatrix<n, n> Li, LiInv;
Li.SetIdentity();
LiInv.SetIdentity();
T pivot = U(j, j);
if (pivot == 0.0)
return U;
assert(pivot != 0.0);
// zero our all entries below pivot
for (int i = j + 1; i < n; ++i) {
T l = -U(i, j) / pivot;
Li(i, j) = l;
// create inverse of L1..Ln as we go (this is L)
L(i, j) = -l;
}
U = Multiply(Li, U);
}
return U;
}
template <int m, typename T>
XMatrix<m, 1, T> Solve(const XMatrix<m, m, T> &L, const XMatrix<m, m, T> &U,
const XMatrix<m, 1, T> &b) {
XMatrix<m, 1> y;
XMatrix<m, 1> x;
// Ly = b (forward substitution)
for (int i = 0; i < m; ++i) {
T sum = 0.0;
for (int j = 0; j < i; ++j) {
sum += y(j, 0) * L(i, j);
}
assert(L(i, i) != 0.0);
y(i, 0) = (b(i, 0) - sum) / L(i, i);
}
// Ux = y (back substitution)
for (int i = m - 1; i >= 0; --i) {
T sum = 0.0;
for (int j = i + 1; j < m; ++j) {
sum += x(j, 0) * U(i, j);
}
assert(U(i, i) != 0.0);
x(i, 0) = (y(i, 0) - sum) / U(i, i);
}
return x;
}
template <int n, typename T>
T Determinant(const XMatrix<n, n, T> &A, XMatrix<n, n, T> &L,
XMatrix<n, n, T> &U) {
U = LU(A, L);
// determinant is the product of diagonal entries of U (assume L has 1s on
// diagonal)
T det = 1.0;
for (int i = 0; i < n; ++i)
det *= U(i, i);
return det;
}
template <int n, typename T>
XMatrix<n, n, T> Inverse(const XMatrix<n, n, T> &A, T &det) {
XMatrix<n, n> L, U;
det = Determinant(A, L, U);
XMatrix<n, n> Inv;
if (det != 0.0f) {
for (int i = 0; i < n; ++i) {
// solve for each column of the identity matrix
XMatrix<n, 1> I;
I(i, 0) = 1.0;
XMatrix<n, 1> x = Solve(L, U, I);
Inv.SetCol(i, x);
}
}
return Inv;
}
template <int m, int n, typename T> T FrobeniusNorm(const XMatrix<m, n, T> &A) {
T sum = 0.0;
for (int i = 0; i < m; ++i)
for (int j = 0; j < n; ++j)
sum += A(i, j) * A(i, j);
return sqrt(sum);
}
| 5,862 | C | 20.958801 | 99 | 0.507847 |
NVIDIA-Omniverse/mjcf-importer-extension/source/extensions/omni.importer.mjcf/plugins/math/core/vec4.h | // SPDX-FileCopyrightText: Copyright (c) 2023 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
// SPDX-License-Identifier: Apache-2.0
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#pragma once
#include "common_math.h"
#include "vec3.h"
#include <cassert>
#if 0 // defined(_DEBUG) && defined(_WIN32)
#define VEC4_VALIDATE() \
{ \
assert(_finite(x)); \
assert(!_isnan(x)); \
\
assert(_finite(y)); \
assert(!_isnan(y)); \
\
assert(_finite(z)); \
assert(!_isnan(z)); \
\
assert(_finite(w)); \
assert(!_isnan(w)); \
}
#else
#define VEC4_VALIDATE()
#endif
template <typename T> class XVector4 {
public:
typedef T value_type;
CUDA_CALLABLE XVector4() : x(0), y(0), z(0), w(0) {}
CUDA_CALLABLE XVector4(T a) : x(a), y(a), z(a), w(a) {}
CUDA_CALLABLE XVector4(const T *p) : x(p[0]), y(p[1]), z(p[2]), w(p[3]) {}
CUDA_CALLABLE XVector4(T x_, T y_, T z_, T w_ = 1.0f)
: x(x_), y(y_), z(z_), w(w_) {
VEC4_VALIDATE();
}
CUDA_CALLABLE XVector4(const Vec3 &v, float w)
: x(v.x), y(v.y), z(v.z), w(w) {}
CUDA_CALLABLE operator T *() { return &x; }
CUDA_CALLABLE operator const T *() const { return &x; };
CUDA_CALLABLE void Set(T x_, T y_, T z_, T w_) {
VEC4_VALIDATE();
x = x_;
y = y_;
z = z_;
w = w_;
}
CUDA_CALLABLE XVector4<T> operator*(T scale) const {
XVector4<T> r(*this);
r *= scale;
VEC4_VALIDATE();
return r;
}
CUDA_CALLABLE XVector4<T> operator/(T scale) const {
XVector4<T> r(*this);
r /= scale;
VEC4_VALIDATE();
return r;
}
CUDA_CALLABLE XVector4<T> operator+(const XVector4<T> &v) const {
XVector4<T> r(*this);
r += v;
VEC4_VALIDATE();
return r;
}
CUDA_CALLABLE XVector4<T> operator-(const XVector4<T> &v) const {
XVector4<T> r(*this);
r -= v;
VEC4_VALIDATE();
return r;
}
CUDA_CALLABLE XVector4<T> operator*(XVector4<T> scale) const {
XVector4<T> r(*this);
r *= scale;
VEC4_VALIDATE();
return r;
}
CUDA_CALLABLE XVector4<T> &operator*=(T scale) {
x *= scale;
y *= scale;
z *= scale;
w *= scale;
VEC4_VALIDATE();
return *this;
}
CUDA_CALLABLE XVector4<T> &operator/=(T scale) {
T s(1.0f / scale);
x *= s;
y *= s;
z *= s;
w *= s;
VEC4_VALIDATE();
return *this;
}
CUDA_CALLABLE XVector4<T> &operator+=(const XVector4<T> &v) {
x += v.x;
y += v.y;
z += v.z;
w += v.w;
VEC4_VALIDATE();
return *this;
}
CUDA_CALLABLE XVector4<T> &operator-=(const XVector4<T> &v) {
x -= v.x;
y -= v.y;
z -= v.z;
w -= v.w;
VEC4_VALIDATE();
return *this;
}
CUDA_CALLABLE XVector4<T> &operator*=(const XVector4<T> &v) {
x *= v.x;
y *= v.y;
z *= v.z;
w *= v.w;
VEC4_VALIDATE();
return *this;
}
CUDA_CALLABLE bool operator!=(const XVector4<T> &v) const {
return (x != v.x || y != v.y || z != v.z || w != v.w);
}
// negate
CUDA_CALLABLE XVector4<T> operator-() const {
VEC4_VALIDATE();
return XVector4<T>(-x, -y, -z, -w);
}
T x, y, z, w;
};
typedef XVector4<float> Vector4;
typedef XVector4<float> Vec4;
// lhs scalar scale
template <typename T>
CUDA_CALLABLE XVector4<T> operator*(T lhs, const XVector4<T> &rhs) {
XVector4<T> r(rhs);
r *= lhs;
return r;
}
template <typename T>
CUDA_CALLABLE bool operator==(const XVector4<T> &lhs, const XVector4<T> &rhs) {
return (lhs.x == rhs.x && lhs.y == rhs.y && lhs.z == rhs.z && lhs.w == rhs.w);
}
| 4,815 | C | 27.666667 | 99 | 0.482035 |
NVIDIA-Omniverse/mjcf-importer-extension/source/extensions/omni.importer.mjcf/plugins/math/core/mat44.h | // SPDX-FileCopyrightText: Copyright (c) 2023 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
// SPDX-License-Identifier: Apache-2.0
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#pragma once
#include "common_math.h"
#include "point3.h"
#include "vec4.h"
// stores column vectors in column major order
template <typename T> class XMatrix44 {
public:
CUDA_CALLABLE XMatrix44() { memset(columns, 0, sizeof(columns)); }
CUDA_CALLABLE XMatrix44(const T *d) {
assert(d);
memcpy(columns, d, sizeof(*this));
}
CUDA_CALLABLE XMatrix44(T c11, T c21, T c31, T c41, T c12, T c22, T c32,
T c42, T c13, T c23, T c33, T c43, T c14, T c24,
T c34, T c44) {
columns[0][0] = c11;
columns[0][1] = c21;
columns[0][2] = c31;
columns[0][3] = c41;
columns[1][0] = c12;
columns[1][1] = c22;
columns[1][2] = c32;
columns[1][3] = c42;
columns[2][0] = c13;
columns[2][1] = c23;
columns[2][2] = c33;
columns[2][3] = c43;
columns[3][0] = c14;
columns[3][1] = c24;
columns[3][2] = c34;
columns[3][3] = c44;
}
CUDA_CALLABLE XMatrix44(const Vec4 &c1, const Vec4 &c2, const Vec4 &c3,
const Vec4 &c4) {
columns[0][0] = c1.x;
columns[0][1] = c1.y;
columns[0][2] = c1.z;
columns[0][3] = c1.w;
columns[1][0] = c2.x;
columns[1][1] = c2.y;
columns[1][2] = c2.z;
columns[1][3] = c2.w;
columns[2][0] = c3.x;
columns[2][1] = c3.y;
columns[2][2] = c3.z;
columns[2][3] = c3.w;
columns[3][0] = c4.x;
columns[3][1] = c4.y;
columns[3][2] = c4.z;
columns[3][3] = c4.w;
}
CUDA_CALLABLE operator T *() { return &columns[0][0]; }
CUDA_CALLABLE operator const T *() const { return &columns[0][0]; }
// right multiply
CUDA_CALLABLE XMatrix44<T> operator*(const XMatrix44<T> &rhs) const {
XMatrix44<T> r;
MatrixMultiply(*this, rhs, r);
return r;
}
// right multiply
CUDA_CALLABLE XMatrix44<T> &operator*=(const XMatrix44<T> &rhs) {
XMatrix44<T> r;
MatrixMultiply(*this, rhs, r);
*this = r;
return *this;
}
CUDA_CALLABLE float operator()(int row, int col) const {
return columns[col][row];
}
CUDA_CALLABLE float &operator()(int row, int col) {
return columns[col][row];
}
// scalar multiplication
CUDA_CALLABLE XMatrix44<T> &operator*=(const T &s) {
for (int c = 0; c < 4; ++c) {
for (int r = 0; r < 4; ++r) {
columns[c][r] *= s;
}
}
return *this;
}
CUDA_CALLABLE void MatrixMultiply(const T *__restrict lhs,
const T *__restrict rhs,
T *__restrict result) const {
assert(lhs != rhs);
assert(lhs != result);
assert(rhs != result);
for (int i = 0; i < 4; ++i) {
for (int j = 0; j < 4; ++j) {
result[j * 4 + i] = rhs[j * 4 + 0] * lhs[i + 0];
result[j * 4 + i] += rhs[j * 4 + 1] * lhs[i + 4];
result[j * 4 + i] += rhs[j * 4 + 2] * lhs[i + 8];
result[j * 4 + i] += rhs[j * 4 + 3] * lhs[i + 12];
}
}
}
CUDA_CALLABLE void SetCol(int index, const Vec4 &c) {
columns[index][0] = c.x;
columns[index][1] = c.y;
columns[index][2] = c.z;
columns[index][3] = c.w;
}
// convenience overloads
CUDA_CALLABLE void SetAxis(uint32_t index, const XVector3<T> &a) {
columns[index][0] = a.x;
columns[index][1] = a.y;
columns[index][2] = a.z;
columns[index][3] = 0.0f;
}
CUDA_CALLABLE void SetTranslation(const Point3 &p) {
columns[3][0] = p.x;
columns[3][1] = p.y;
columns[3][2] = p.z;
columns[3][3] = 1.0f;
}
CUDA_CALLABLE const Vec3 &GetAxis(int i) const {
return *reinterpret_cast<const Vec3 *>(&columns[i]);
}
CUDA_CALLABLE const Vec4 &GetCol(int i) const {
return *reinterpret_cast<const Vec4 *>(&columns[i]);
}
CUDA_CALLABLE const Point3 &GetTranslation() const {
return *reinterpret_cast<const Point3 *>(&columns[3]);
}
CUDA_CALLABLE Vec4 GetRow(int i) const {
return Vec4(columns[0][i], columns[1][i], columns[2][i], columns[3][i]);
}
CUDA_CALLABLE static inline XMatrix44 Identity() {
const XMatrix44 sIdentity(
Vec4(1.0f, 0.0f, 0.0f, 0.0f), Vec4(0.0f, 1.0f, 0.0f, 0.0f),
Vec4(0.0f, 0.0f, 1.0f, 0.0f), Vec4(0.0f, 0.0f, 0.0f, 1.0f));
return sIdentity;
}
float columns[4][4];
};
// right multiply a point assumes w of 1
template <typename T>
CUDA_CALLABLE Point3 Multiply(const XMatrix44<T> &mat, const Point3 &v) {
Point3 r;
r.x = v.x * mat[0] + v.y * mat[4] + v.z * mat[8] + mat[12];
r.y = v.x * mat[1] + v.y * mat[5] + v.z * mat[9] + mat[13];
r.z = v.x * mat[2] + v.y * mat[6] + v.z * mat[10] + mat[14];
return r;
}
// right multiply a vector3 assumes a w of 0
template <typename T>
CUDA_CALLABLE XVector3<T> Multiply(const XMatrix44<T> &mat,
const XVector3<T> &v) {
XVector3<T> r;
r.x = v.x * mat[0] + v.y * mat[4] + v.z * mat[8];
r.y = v.x * mat[1] + v.y * mat[5] + v.z * mat[9];
r.z = v.x * mat[2] + v.y * mat[6] + v.z * mat[10];
return r;
}
// right multiply a vector4
template <typename T>
CUDA_CALLABLE XVector4<T> Multiply(const XMatrix44<T> &mat,
const XVector4<T> &v) {
XVector4<T> r;
r.x = v.x * mat[0] + v.y * mat[4] + v.z * mat[8] + v.w * mat[12];
r.y = v.x * mat[1] + v.y * mat[5] + v.z * mat[9] + v.w * mat[13];
r.z = v.x * mat[2] + v.y * mat[6] + v.z * mat[10] + v.w * mat[14];
r.w = v.x * mat[3] + v.y * mat[7] + v.z * mat[11] + v.w * mat[15];
return r;
}
template <typename T>
CUDA_CALLABLE Point3 operator*(const XMatrix44<T> &mat, const Point3 &v) {
return Multiply(mat, v);
}
template <typename T>
CUDA_CALLABLE XVector4<T> operator*(const XMatrix44<T> &mat,
const XVector4<T> &v) {
return Multiply(mat, v);
}
template <typename T>
CUDA_CALLABLE XVector3<T> operator*(const XMatrix44<T> &mat,
const XVector3<T> &v) {
return Multiply(mat, v);
}
template <typename T>
CUDA_CALLABLE inline XMatrix44<T> Transpose(const XMatrix44<T> &m) {
XMatrix44<float> inv;
// transpose
for (uint32_t c = 0; c < 4; ++c) {
for (uint32_t r = 0; r < 4; ++r) {
inv.columns[c][r] = m.columns[r][c];
}
}
return inv;
}
template <typename T>
CUDA_CALLABLE XMatrix44<T> AffineInverse(const XMatrix44<T> &m) {
XMatrix44<T> inv;
// transpose upper 3x3
for (int c = 0; c < 3; ++c) {
for (int r = 0; r < 3; ++r) {
inv.columns[c][r] = m.columns[r][c];
}
}
// multiply -translation by upper 3x3 transpose
inv.columns[3][0] = -Dot3(m.columns[3], m.columns[0]);
inv.columns[3][1] = -Dot3(m.columns[3], m.columns[1]);
inv.columns[3][2] = -Dot3(m.columns[3], m.columns[2]);
inv.columns[3][3] = 1.0f;
return inv;
}
CUDA_CALLABLE inline XMatrix44<float> Outer(const Vec4 &a, const Vec4 &b) {
return XMatrix44<float>(a * b.x, a * b.y, a * b.z, a * b.w);
}
// convenience
typedef XMatrix44<float> Mat44;
typedef XMatrix44<float> Matrix44;
| 7,639 | C | 27.191882 | 99 | 0.566959 |
NVIDIA-Omniverse/mjcf-importer-extension/source/extensions/omni.importer.mjcf/plugins/math/core/maths.h | // SPDX-FileCopyrightText: Copyright (c) 2023 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
// SPDX-License-Identifier: Apache-2.0
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#pragma once
#include "common_math.h"
#include "core.h"
#include "mat22.h"
#include "mat33.h"
#include "mat44.h"
#include "matnn.h"
#include "point3.h"
#include "quat.h"
#include "types.h"
#include "vec2.h"
#include "vec3.h"
#include "vec4.h"
#include <cassert>
#include <cmath>
#include <cstdlib>
#include <float.h>
#include <string.h>
struct Transform {
// transform
CUDA_CALLABLE Transform() : p(0.0) {}
CUDA_CALLABLE Transform(const Vec3 &v, const Quat &q = Quat()) : p(v), q(q) {}
CUDA_CALLABLE Transform operator*(const Transform &rhs) const {
return Transform(Rotate(q, rhs.p) + p, q * rhs.q);
}
Vec3 p;
Quat q;
};
CUDA_CALLABLE inline Transform Inverse(const Transform &transform) {
Transform t;
t.q = Inverse(transform.q);
t.p = -Rotate(t.q, transform.p);
return t;
}
CUDA_CALLABLE inline Vec3 TransformVector(const Transform &t, const Vec3 &v) {
return t.q * v;
}
CUDA_CALLABLE inline Vec3 TransformPoint(const Transform &t, const Vec3 &v) {
return t.q * v + t.p;
}
CUDA_CALLABLE inline Vec3 InverseTransformVector(const Transform &t,
const Vec3 &v) {
return Inverse(t.q) * v;
}
CUDA_CALLABLE inline Vec3 InverseTransformPoint(const Transform &t,
const Vec3 &v) {
return Inverse(t.q) * (v - t.p);
}
// represents a plane in the form ax + by + cz - d = 0
class Plane : public Vec4 {
public:
CUDA_CALLABLE inline Plane() {}
CUDA_CALLABLE inline Plane(float x, float y, float z, float w)
: Vec4(x, y, z, w) {}
CUDA_CALLABLE inline Plane(const Vec3 &p, const Vector3 &n) {
x = n.x;
y = n.y;
z = n.z;
w = -Dot3(p, n);
}
CUDA_CALLABLE inline Vec3 GetNormal() const { return Vec3(x, y, z); }
CUDA_CALLABLE inline Vec3 GetPoint() const {
return Vec3(x * -w, y * -w, z * -w);
}
CUDA_CALLABLE inline Plane(const Vec3 &v) : Vec4(v.x, v.y, v.z, 1.0f) {}
CUDA_CALLABLE inline Plane(const Vec4 &v) : Vec4(v) {}
};
template <typename T>
CUDA_CALLABLE inline T Dot(const XVector4<T> &v1, const XVector4<T> &v2) {
return v1.x * v2.x + v1.y * v2.y + v1.z * v2.z + v1.w * v2.w;
}
// helper function that assumes a w of 0
CUDA_CALLABLE inline float Dot(const Plane &p, const Vector3 &v) {
return p.x * v.x + p.y * v.y + p.z * v.z;
}
CUDA_CALLABLE inline float Dot(const Vector3 &v, const Plane &p) {
return Dot(p, v);
}
// helper function that assumes a w of 1
CUDA_CALLABLE inline float Dot(const Plane &p, const Point3 &v) {
return p.x * v.x + p.y * v.y + p.z * v.z + p.w;
}
// ensures that the normal component of the plane is unit magnitude
CUDA_CALLABLE inline Vec4 NormalizePlane(const Vec4 &p) {
float l = Length(Vec3(p));
return (1.0f / l) * p;
}
//----------------------------------------------------------------------------
inline float RandomUnit() {
float r = (float)rand();
r /= RAND_MAX;
return r;
}
// Random number in range [-1,1]
inline float RandomSignedUnit() {
float r = (float)rand();
r /= RAND_MAX;
r = 2.0f * r - 1.0f;
return r;
}
inline float Random(float lo, float hi) {
float r = (float)rand();
r /= RAND_MAX;
r = (hi - lo) * r + lo;
return r;
}
inline void RandInit(uint32_t seed = 315645664) {
std::srand(static_cast<unsigned>(seed));
}
// random number generator
inline uint32_t Rand() { return static_cast<uint32_t>(std::rand()); }
// returns a random number in the range [min, max)
inline uint32_t Rand(uint32_t min, uint32_t max) {
return min + Rand() % (max - min);
}
// returns random number between 0-1
inline float Randf() {
uint32_t value = Rand();
uint32_t limit = 0xffffffff;
return (float)value * (1.0f / (float)limit);
}
// returns random number between min and max
inline float Randf(float min, float max) {
// return Lerp(min, max, ParticleRandf());
float t = Randf();
return (1.0f - t) * min + t * (max);
}
// returns random number between 0-max
inline float Randf(float max) { return Randf() * max; }
// returns a random unit vector (also can add an offset to generate around an
// off axis vector)
inline Vec3 RandomUnitVector() {
float phi = Randf(kPi * 2.0f);
float theta = Randf(kPi * 2.0f);
float cosTheta = Cos(theta);
float sinTheta = Sin(theta);
float cosPhi = Cos(phi);
float sinPhi = Sin(phi);
return Vec3(cosTheta * sinPhi, cosPhi, sinTheta * sinPhi);
}
inline Vec3 RandVec3() {
return Vec3(Randf(-1.0f, 1.0f), Randf(-1.0f, 1.0f), Randf(-1.0f, 1.0f));
}
// uniformly sample volume of a sphere using dart throwing
inline Vec3 UniformSampleSphereVolume() {
for (;;) {
Vec3 v = RandVec3();
if (Dot(v, v) < 1.0f)
return v;
}
}
inline Vec3 UniformSampleSphere() {
float u1 = Randf(0.0f, 1.0f);
float u2 = Randf(0.0f, 1.0f);
float z = 1.f - 2.f * u1;
float r = sqrtf(Max(0.f, 1.f - z * z));
float phi = 2.f * kPi * u2;
float x = r * cosf(phi);
float y = r * sinf(phi);
return Vector3(x, y, z);
}
inline Vec3 UniformSampleHemisphere() {
// generate a random z value
float z = Randf(0.0f, 1.0f);
float w = Sqrt(1.0f - z * z);
float phi = k2Pi * Randf(0.0f, 1.0f);
float x = Cos(phi) * w;
float y = Sin(phi) * w;
return Vec3(x, y, z);
}
inline Vec2 UniformSampleDisc() {
float r = Sqrt(Randf(0.0f, 1.0f));
float theta = k2Pi * Randf(0.0f, 1.0f);
return Vec2(r * Cos(theta), r * Sin(theta));
}
inline void UniformSampleTriangle(float &u, float &v) {
float r = Sqrt(Randf());
u = 1.0f - r;
v = Randf() * r;
}
inline Vec3 CosineSampleHemisphere() {
Vec2 s = UniformSampleDisc();
float z = Sqrt(Max(0.0f, 1.0f - s.x * s.x - s.y * s.y));
return Vec3(s.x, s.y, z);
}
inline Vec3 SphericalToXYZ(float theta, float phi) {
float cosTheta = cos(theta);
float sinTheta = sin(theta);
return Vec3(sin(phi) * sinTheta, cosTheta, cos(phi) * sinTheta);
}
// returns random vector between -range and range
inline Vec4 Randf(const Vec4 &range) {
return Vec4(Randf(-range.x, range.x), Randf(-range.y, range.y),
Randf(-range.z, range.z), Randf(-range.w, range.w));
}
// generates a transform matrix with v as the z axis, taken from PBRT
CUDA_CALLABLE inline void BasisFromVector(const Vec3 &w, Vec3 *u, Vec3 *v) {
if (fabsf(w.x) > fabsf(w.y)) {
float invLen = 1.0f / sqrtf(w.x * w.x + w.z * w.z);
*u = Vec3(-w.z * invLen, 0.0f, w.x * invLen);
} else {
float invLen = 1.0f / sqrtf(w.y * w.y + w.z * w.z);
*u = Vec3(0.0f, w.z * invLen, -w.y * invLen);
}
*v = Cross(w, *u);
// assert(fabsf(Length(*u)-1.0f) < 0.01f);
// assert(fabsf(Length(*v)-1.0f) < 0.01f);
}
// same as above but returns a matrix
inline Mat44 TransformFromVector(const Vec3 &w,
const Point3 &t = Point3(0.0f, 0.0f, 0.0f)) {
Mat44 m = Mat44::Identity();
m.SetCol(2, Vec4(w.x, w.y, w.z, 0.0));
m.SetCol(3, Vec4(t.x, t.y, t.z, 1.0f));
BasisFromVector(w, (Vec3 *)m.columns[0], (Vec3 *)m.columns[1]);
return m;
}
// todo: sort out rotations
inline Mat44 ViewMatrix(const Point3 &pos) {
float view[4][4] = {{1.0f, 0.0f, 0.0f, 0.0f},
{0.0f, 1.0f, 0.0f, 0.0f},
{0.0f, 0.0f, 1.0f, 0.0f},
{-pos.x, -pos.y, -pos.z, 1.0f}};
return Mat44(&view[0][0]);
}
inline Mat44 LookAtMatrix(const Point3 &viewer, const Point3 &target) {
// create a basis from viewer to target (OpenGL convention looking down -z)
Vec3 forward = -Normalize(target - viewer);
Vec3 up(0.0f, 1.0f, 0.0f);
Vec3 left = Normalize(Cross(up, forward));
up = Cross(forward, left);
float xform[4][4] = {{left.x, left.y, left.z, 0.0f},
{up.x, up.y, up.z, 0.0f},
{forward.x, forward.y, forward.z, 0.0f},
{viewer.x, viewer.y, viewer.z, 1.0f}};
return AffineInverse(Mat44(&xform[0][0]));
}
// generate a rotation matrix around an axis, from PBRT p74
inline Mat44 RotationMatrix(float angle, const Vec3 &axis) {
Vec3 a = Normalize(axis);
float s = sinf(angle);
float c = cosf(angle);
float m[4][4];
m[0][0] = a.x * a.x + (1.0f - a.x * a.x) * c;
m[0][1] = a.x * a.y * (1.0f - c) + a.z * s;
m[0][2] = a.x * a.z * (1.0f - c) - a.y * s;
m[0][3] = 0.0f;
m[1][0] = a.x * a.y * (1.0f - c) - a.z * s;
m[1][1] = a.y * a.y + (1.0f - a.y * a.y) * c;
m[1][2] = a.y * a.z * (1.0f - c) + a.x * s;
m[1][3] = 0.0f;
m[2][0] = a.x * a.z * (1.0f - c) + a.y * s;
m[2][1] = a.y * a.z * (1.0f - c) - a.x * s;
m[2][2] = a.z * a.z + (1.0f - a.z * a.z) * c;
m[2][3] = 0.0f;
m[3][0] = 0.0f;
m[3][1] = 0.0f;
m[3][2] = 0.0f;
m[3][3] = 1.0f;
return Mat44(&m[0][0]);
}
inline Mat44 RotationMatrix(const Quat &q) {
Matrix33 rotation(q);
Matrix44 m;
m.SetAxis(0, rotation.cols[0]);
m.SetAxis(1, rotation.cols[1]);
m.SetAxis(2, rotation.cols[2]);
m.SetTranslation(Point3(0.0f));
return m;
}
inline Mat44 TranslationMatrix(const Point3 &t) {
Mat44 m(Mat44::Identity());
m.SetTranslation(t);
return m;
}
inline Mat44 TransformMatrix(const Transform &t) {
return TranslationMatrix(Point3(t.p)) * RotationMatrix(t.q);
}
inline Mat44 OrthographicMatrix(float left, float right, float bottom,
float top, float n, float f) {
float m[4][4] = {{2.0f / (right - left), 0.0f, 0.0f, 0.0f},
{0.0f, 2.0f / (top - bottom), 0.0f, 0.0f},
{0.0f, 0.0f, -2.0f / (f - n), 0.0f},
{-(right + left) / (right - left),
-(top + bottom) / (top - bottom), -(f + n) / (f - n),
1.0f}};
return Mat44(&m[0][0]);
}
// this is designed as a drop in replacement for gluPerspective
inline Mat44 ProjectionMatrix(float fov, float aspect, float znear,
float zfar) {
float f = 1.0f / tanf(DegToRad(fov * 0.5f));
float zd = znear - zfar;
float view[4][4] = {{f / aspect, 0.0f, 0.0f, 0.0f},
{0.0f, f, 0.0f, 0.0f},
{0.0f, 0.0f, (zfar + znear) / zd, -1.0f},
{0.0f, 0.0f, (2.0f * znear * zfar) / zd, 0.0f}};
return Mat44(&view[0][0]);
}
// encapsulates an orientation encoded in Euler angles, not the sexiest
// representation but it is convenient when manipulating objects from script
class Rotation {
public:
Rotation() : yaw(0), pitch(0), roll(0) {}
Rotation(float inYaw, float inPitch, float inRoll)
: yaw(inYaw), pitch(inPitch), roll(inRoll) {}
Rotation &operator+=(const Rotation &rhs) {
yaw += rhs.yaw;
pitch += rhs.pitch;
roll += rhs.roll;
return *this;
}
Rotation &operator-=(const Rotation &rhs) {
yaw -= rhs.yaw;
pitch -= rhs.pitch;
roll -= rhs.roll;
return *this;
}
Rotation operator+(const Rotation &rhs) const {
Rotation lhs(*this);
lhs += rhs;
return lhs;
}
Rotation operator-(const Rotation &rhs) const {
Rotation lhs(*this);
lhs -= rhs;
return lhs;
}
// all members are in degrees (easy editing)
float yaw;
float pitch;
float roll;
};
inline Mat44 ScaleMatrix(const Vector3 &s) {
float m[4][4] = {{s.x, 0.0f, 0.0f, 0.0f},
{0.0f, s.y, 0.0f, 0.0f},
{0.0f, 0.0f, s.z, 0.0f},
{0.0f, 0.0f, 0.0f, 1.0f}};
return Mat44(&m[0][0]);
}
// assumes yaw on y, then pitch on z, then roll on x
inline Mat44 TransformMatrix(const Rotation &r, const Point3 &p) {
const float yaw = DegToRad(r.yaw);
const float pitch = DegToRad(r.pitch);
const float roll = DegToRad(r.roll);
const float s1 = Sin(roll);
const float c1 = Cos(roll);
const float s2 = Sin(pitch);
const float c2 = Cos(pitch);
const float s3 = Sin(yaw);
const float c3 = Cos(yaw);
// interprets the angles as yaw around world-y, pitch around new z, roll
// around new x
float mr[4][4] = {
{c2 * c3, s2, -c2 * s3, 0.0f},
{s1 * s3 - c1 * c3 * s2, c1 * c2, c3 * s1 + c1 * s2 * s3, 0.0f},
{c3 * s1 * s2 + c1 * s3, -c2 * s1, c1 * c3 - s1 * s2 * s3, 0.0f},
{p.x, p.y, p.z, 1.0f}};
Mat44 m1(&mr[0][0]);
return m1; // m2 * m1;
}
// aligns the z axis along the vector
inline Rotation AlignToVector(const Vec3 &vector) {
// todo: fix, see spherical->cartesian coordinates wikipedia
return Rotation(0.0f, RadToDeg(atan2(vector.y, vector.x)), 0.0f);
}
// creates a vector given an angle measured clockwise from horizontal (1,0)
inline Vec2 AngleToVector(float a) { return Vec2(Cos(a), Sin(a)); }
inline float VectorToAngle(const Vec2 &v) { return atan2f(v.y, v.x); }
CUDA_CALLABLE inline float SmoothStep(float a, float b, float t) {
t = Clamp(t - a / (b - a), 0.0f, 1.0f);
return t * t * (3.0f - 2.0f * t);
}
// hermite spline interpolation
template <typename T>
T HermiteInterpolate(const T &a, const T &b, const T &t1, const T &t2,
float t) {
// blending weights
const float w1 = 1.0f - 3 * t * t + 2 * t * t * t;
const float w2 = t * t * (3.0f - 2.0f * t);
const float w3 = t * t * t - 2 * t * t + t;
const float w4 = t * t * (t - 1.0f);
// return weighted combination
return a * w1 + b * w2 + t1 * w3 + t2 * w4;
}
template <typename T>
T HermiteTangent(const T &a, const T &b, const T &t1, const T &t2, float t) {
// first derivative blend weights
const float w1 = 6.0f * t * t - 6 * t;
const float w2 = -6.0f * t * t + 6 * t;
const float w3 = 3 * t * t - 4 * t + 1;
const float w4 = 3 * t * t - 2 * t;
// weighted combination
return a * w1 + b * w2 + t1 * w3 + t2 * w4;
}
template <typename T>
T HermiteSecondDerivative(const T &a, const T &b, const T &t1, const T &t2,
float t) {
// first derivative blend weights
const float w1 = 12 * t - 6.0f;
const float w2 = -12.0f * t + 6;
const float w3 = 6 * t - 4.0f;
const float w4 = 6 * t - 2.0f;
// weighted combination
return a * w1 + b * w2 + t1 * w3 + t2 * w4;
}
inline float Log(float base, float x) {
// calculate the log of a value for an arbitary base, only use if you can't
// use the standard bases (10, e)
return logf(x) / logf(base);
}
inline int Log2(int x) {
int n = 0;
while (x >= 2) {
++n;
x /= 2;
}
return n;
}
// function which maps a value to a range
template <typename T> T RangeMap(T value, T lower, T upper) {
assert(upper >= lower);
return (value - lower) / (upper - lower);
}
// simple colour class
class Colour {
public:
enum Preset { kRed, kGreen, kBlue, kWhite, kBlack };
Colour(float r_ = 0.0f, float g_ = 0.0f, float b_ = 0.0f, float a_ = 1.0f)
: r(r_), g(g_), b(b_), a(a_) {}
Colour(float *p) : r(p[0]), g(p[1]), b(p[2]), a(p[3]) {}
Colour(uint32_t rgba) {
a = ((rgba)&0xff) / 255.0f;
r = ((rgba >> 24) & 0xff) / 255.0f;
g = ((rgba >> 16) & 0xff) / 255.0f;
b = ((rgba >> 8) & 0xff) / 255.0f;
}
Colour(Preset p) {
switch (p) {
case kRed:
*this = Colour(1.0f, 0.0f, 0.0f);
break;
case kGreen:
*this = Colour(0.0f, 1.0f, 0.0f);
break;
case kBlue:
*this = Colour(0.0f, 0.0f, 1.0f);
break;
case kWhite:
*this = Colour(1.0f, 1.0f, 1.0f);
break;
case kBlack:
*this = Colour(0.0f, 0.0f, 0.0f);
break;
};
}
// cast operator
operator const float *() const { return &r; }
operator float *() { return &r; }
Colour operator*(float scale) const {
Colour r(*this);
r *= scale;
return r;
}
Colour operator/(float scale) const {
Colour r(*this);
r /= scale;
return r;
}
Colour operator+(const Colour &v) const {
Colour r(*this);
r += v;
return r;
}
Colour operator-(const Colour &v) const {
Colour r(*this);
r -= v;
return r;
}
Colour operator*(const Colour &scale) const {
Colour r(*this);
r *= scale;
return r;
}
Colour &operator*=(float scale) {
r *= scale;
g *= scale;
b *= scale;
a *= scale;
return *this;
}
Colour &operator/=(float scale) {
float s(1.0f / scale);
r *= s;
g *= s;
b *= s;
a *= s;
return *this;
}
Colour &operator+=(const Colour &v) {
r += v.r;
g += v.g;
b += v.b;
a += v.a;
return *this;
}
Colour &operator-=(const Colour &v) {
r -= v.r;
g -= v.g;
b -= v.b;
a -= v.a;
return *this;
}
Colour &operator*=(const Colour &v) {
r *= v.r;
g *= v.g;
b *= v.b;
a *= v.a;
return *this;
}
float r, g, b, a;
};
inline bool operator==(const Colour &lhs, const Colour &rhs) {
return lhs.r == rhs.r && lhs.g == rhs.g && lhs.b == rhs.b && lhs.a == rhs.a;
}
inline bool operator!=(const Colour &lhs, const Colour &rhs) {
return !(lhs == rhs);
}
inline Colour ToneMap(const Colour &s) {
// return Colour(s.r / (s.r+1.0f), s.g / (s.g+1.0f), s.b /
// (s.b+1.0f), 1.0f);
float Y = 0.3333f * (s.r + s.g + s.b);
return s / (1.0f + Y);
}
// lhs scalar scale
inline Colour operator*(float lhs, const Colour &rhs) {
Colour r(rhs);
r *= lhs;
return r;
}
inline Colour YxyToXYZ(float Y, float x, float y) {
float X = x * (Y / y);
float Z = (1.0f - x - y) * Y / y;
return Colour(X, Y, Z, 1.0f);
}
inline Colour HSVToRGB(float h, float s, float v) {
float r, g, b;
int i;
float f, p, q, t;
if (s == 0) {
// achromatic (grey)
r = g = b = v;
} else {
h *= 6.0f; // sector 0 to 5
i = int(floor(h));
f = h - i; // factorial part of h
p = v * (1 - s);
q = v * (1 - s * f);
t = v * (1 - s * (1 - f));
switch (i) {
case 0:
r = v;
g = t;
b = p;
break;
case 1:
r = q;
g = v;
b = p;
break;
case 2:
r = p;
g = v;
b = t;
break;
case 3:
r = p;
g = q;
b = v;
break;
case 4:
r = t;
g = p;
b = v;
break;
default: // case 5:
r = v;
g = p;
b = q;
break;
};
}
return Colour(r, g, b);
}
inline Colour XYZToLinear(float x, float y, float z) {
float c[4];
c[0] = 3.240479f * x + -1.537150f * y + -0.498535f * z;
c[1] = -0.969256f * x + 1.875991f * y + 0.041556f * z;
c[2] = 0.055648f * x + -0.204043f * y + 1.057311f * z;
c[3] = 1.0f;
return Colour(c);
}
inline uint32_t ColourToRGBA8(const Colour &c) {
union SmallColor {
uint8_t u8[4];
uint32_t u32;
};
SmallColor s;
s.u8[0] = (uint8_t)(Clamp(c.r, 0.0f, 1.0f) * 255);
s.u8[1] = (uint8_t)(Clamp(c.g, 0.0f, 1.0f) * 255);
s.u8[2] = (uint8_t)(Clamp(c.b, 0.0f, 1.0f) * 255);
s.u8[3] = (uint8_t)(Clamp(c.a, 0.0f, 1.0f) * 255);
return s.u32;
}
inline Colour LinearToSrgb(const Colour &c) {
const float kInvGamma = 1.0f / 2.2f;
return Colour(powf(c.r, kInvGamma), powf(c.g, kInvGamma),
powf(c.b, kInvGamma), c.a);
}
inline Colour SrgbToLinear(const Colour &c) {
const float kInvGamma = 2.2f;
return Colour(powf(c.r, kInvGamma), powf(c.g, kInvGamma),
powf(c.b, kInvGamma), c.a);
}
inline float SpecularRoughnessToExponent(float roughness,
float maxExponent = 2048.0f) {
return powf(maxExponent, 1.0f - roughness);
}
inline float SpecularExponentToRoughness(float exponent,
float maxExponent = 2048.0f) {
if (exponent <= 1.0f)
return 1.0f;
else
return 1.0f - logf(exponent) / logf(maxExponent);
}
inline Colour JetColorMap(float low, float high, float x) {
float t = (x - low) / (high - low);
return HSVToRGB(t, 1.0f, 1.0f);
}
inline Colour BourkeColorMap(float low, float high, float v) {
Colour c(1.0f, 1.0f, 1.0f); // white
float dv;
if (v < low)
v = low;
if (v > high)
v = high;
dv = high - low;
if (v < (low + 0.25f * dv)) {
c.r = 0.f;
c.g = 4.f * (v - low) / dv;
} else if (v < (low + 0.5f * dv)) {
c.r = 0.f;
c.b = 1.f + 4.f * (low + 0.25f * dv - v) / dv;
} else if (v < (low + 0.75f * dv)) {
c.r = 4.f * (v - low - 0.5f * dv) / dv;
c.b = 0.f;
} else {
c.g = 1.f + 4.f * (low + 0.75f * dv - v) / dv;
c.b = 0.f;
}
return (c);
}
// intersection routines
inline bool IntersectRaySphere(const Point3 &sphereOrigin, float sphereRadius,
const Point3 &rayOrigin, const Vec3 &rayDir,
float &t, Vec3 *hitNormal = nullptr) {
Vec3 d(sphereOrigin - rayOrigin);
float deltaSq = LengthSq(d);
float radiusSq = sphereRadius * sphereRadius;
// if the origin is inside the sphere return no intersection
if (deltaSq > radiusSq) {
float dprojr = Dot(d, rayDir);
// if ray pointing away from sphere no intersection
if (dprojr < 0.0f)
return false;
// bit of Pythagoras to get closest point on ray
float dSq = deltaSq - dprojr * dprojr;
if (dSq > radiusSq)
return false;
else {
// length of the half cord
float thc = sqrt(radiusSq - dSq);
// closest intersection
t = dprojr - thc;
// calculate normal if requested
if (hitNormal)
*hitNormal = Normalize((rayOrigin + rayDir * t) - sphereOrigin);
return true;
}
} else {
return false;
}
}
template <typename T>
CUDA_CALLABLE inline bool SolveQuadratic(T a, T b, T c, T &minT, T &maxT) {
if (a == 0.0f && b == 0.0f) {
minT = maxT = 0.0f;
return true;
}
T discriminant = b * b - T(4.0) * a * c;
if (discriminant < 0.0f) {
return false;
}
// numerical receipes 5.6 (this method ensures numerical accuracy is
// preserved)
T t = T(-0.5) * (b + Sign(b) * Sqrt(discriminant));
minT = t / a;
maxT = c / t;
if (minT > maxT) {
Swap(minT, maxT);
}
return true;
}
// alternative ray sphere intersect, returns closest and furthest t values
inline bool IntersectRaySphere(const Point3 &sphereOrigin, float sphereRadius,
const Point3 &rayOrigin, const Vector3 &rayDir,
float &minT, float &maxT,
Vec3 *hitNormal = nullptr) {
Vector3 q = rayOrigin - sphereOrigin;
float a = 1.0f;
float b = 2.0f * Dot(q, rayDir);
float c = Dot(q, q) - (sphereRadius * sphereRadius);
bool r = SolveQuadratic(a, b, c, minT, maxT);
if (minT < 0.0)
minT = 0.0f;
// calculate the normal of the closest hit
if (hitNormal && r) {
*hitNormal = Normalize((rayOrigin + rayDir * minT) - sphereOrigin);
}
return r;
}
CUDA_CALLABLE inline bool IntersectRayPlane(const Point3 &p, const Vector3 &dir,
const Plane &plane, float &t) {
float d = Dot(plane, dir);
if (d == 0.0f) {
return false;
} else {
t = -Dot(plane, p) / d;
}
return (t > 0.0f);
}
CUDA_CALLABLE inline bool IntersectLineSegmentPlane(const Vec3 &start,
const Vec3 &end,
const Plane &plane,
Vec3 &out) {
Vec3 u(end - start);
float dist = -Dot(plane, start) / Dot(plane, u);
if (dist > 0.0f && dist < 1.0f) {
out = (start + u * dist);
return true;
} else
return false;
}
// Moller and Trumbore's method
CUDA_CALLABLE inline bool
IntersectRayTriTwoSided(const Vec3 &p, const Vec3 &dir, const Vec3 &a,
const Vec3 &b, const Vec3 &c, float &t, float &u,
float &v, float &w, float &sign, Vec3 *normal) {
Vector3 ab = b - a;
Vector3 ac = c - a;
Vector3 n = Cross(ab, ac);
float d = Dot(-dir, n);
float ood = 1.0f / d; // No need to check for division by zero here as
// infinity aritmetic will save us...
Vector3 ap = p - a;
t = Dot(ap, n) * ood;
if (t < 0.0f)
return false;
Vector3 e = Cross(-dir, ap);
v = Dot(ac, e) * ood;
if (v < 0.0f || v > 1.0f) // ...here...
return false;
w = -Dot(ab, e) * ood;
if (w < 0.0f || v + w > 1.0f) // ...and here
return false;
u = 1.0f - v - w;
if (normal)
*normal = n;
sign = d;
return true;
}
// mostly taken from Real Time Collision Detection - p192
inline bool IntersectRayTri(const Point3 &p, const Vec3 &dir, const Point3 &a,
const Point3 &b, const Point3 &c, float &t,
float &u, float &v, float &w, Vec3 *normal) {
const Vec3 ab = b - a;
const Vec3 ac = c - a;
// calculate normal
Vec3 n = Cross(ab, ac);
// need to solve a system of three equations to give t, u, v
float d = Dot(-dir, n);
// if dir is parallel to triangle plane or points away from triangle
if (d <= 0.0f)
return false;
Vec3 ap = p - a;
t = Dot(ap, n);
// ignores tris behind
if (t < 0.0f)
return false;
// compute barycentric coordinates
Vec3 e = Cross(-dir, ap);
v = Dot(ac, e);
if (v < 0.0f || v > d)
return false;
w = -Dot(ab, e);
if (w < 0.0f || v + w > d)
return false;
float ood = 1.0f / d;
t *= ood;
v *= ood;
w *= ood;
u = 1.0f - v - w;
// optionally write out normal (todo: this branch is a performance concern,
// should probably remove)
if (normal)
*normal = n;
return true;
}
// mostly taken from Real Time Collision Detection - p192
CUDA_CALLABLE inline bool IntersectSegmentTri(const Vec3 &p, const Vec3 &q,
const Vec3 &a, const Vec3 &b,
const Vec3 &c, float &t, float &u,
float &v, float &w,
Vec3 *normal) {
const Vec3 ab = b - a;
const Vec3 ac = c - a;
const Vec3 qp = p - q;
// calculate normal
Vec3 n = Cross(ab, ac);
// need to solve a system of three equations to give t, u, v
float d = Dot(qp, n);
// if dir is parallel to triangle plane or points away from triangle
// if (d <= 0.0f)
// return false;
Vec3 ap = p - a;
t = Dot(ap, n);
// ignores tris behind
if (t < 0.0f)
return false;
// ignores tris beyond segment
if (t > d)
return false;
// compute barycentric coordinates
Vec3 e = Cross(qp, ap);
v = Dot(ac, e);
if (v < 0.0f || v > d)
return false;
w = -Dot(ab, e);
if (w < 0.0f || v + w > d)
return false;
float ood = 1.0f / d;
t *= ood;
v *= ood;
w *= ood;
u = 1.0f - v - w;
// optionally write out normal (todo: this branch is a performance concern,
// should probably remove)
if (normal)
*normal = n;
return true;
}
CUDA_CALLABLE inline float ScalarTriple(const Vec3 &a, const Vec3 &b,
const Vec3 &c) {
return Dot(Cross(a, b), c);
}
// intersects a line (through points p and q, against a triangle a, b, c -
// mostly taken from Real Time Collision Detection - p186
CUDA_CALLABLE inline bool
IntersectLineTri(const Vec3 &p, const Vec3 &q, const Vec3 &a, const Vec3 &b,
const Vec3 &c) //, float& t, float& u, float& v, float&
// w, Vec3* normal, float expand)
{
const Vec3 pq = q - p;
const Vec3 pa = a - p;
const Vec3 pb = b - p;
const Vec3 pc = c - p;
Vec3 m = Cross(pq, pc);
float u = Dot(pb, m);
if (u < 0.0f)
return false;
float v = -Dot(pa, m);
if (v < 0.0f)
return false;
float w = ScalarTriple(pq, pb, pa);
if (w < 0.0f)
return false;
return true;
}
CUDA_CALLABLE inline Vec3 ClosestPointToAABB(const Vec3 &p, const Vec3 &lower,
const Vec3 &upper) {
Vec3 c;
for (int i = 0; i < 3; ++i) {
float v = p[i];
if (v < lower[i])
v = lower[i];
if (v > upper[i])
v = upper[i];
c[i] = v;
}
return c;
}
// RTCD 5.1.5, page 142
CUDA_CALLABLE inline Vec3 ClosestPointOnTriangle(const Vec3 &a, const Vec3 &b,
const Vec3 &c, const Vec3 &p,
float &v, float &w) {
Vec3 ab = b - a;
Vec3 ac = c - a;
Vec3 ap = p - a;
float d1 = Dot(ab, ap);
float d2 = Dot(ac, ap);
if (d1 <= 0.0f && d2 <= 0.0f) {
v = 0.0f;
w = 0.0f;
return a;
}
Vec3 bp = p - b;
float d3 = Dot(ab, bp);
float d4 = Dot(ac, bp);
if (d3 >= 0.0f && d4 <= d3) {
v = 1.0f;
w = 0.0f;
return b;
}
float vc = d1 * d4 - d3 * d2;
if (vc <= 0.0f && d1 >= 0.0f && d3 <= 0.0f) {
v = d1 / (d1 - d3);
w = 0.0f;
return a + v * ab;
}
Vec3 cp = p - c;
float d5 = Dot(ab, cp);
float d6 = Dot(ac, cp);
if (d6 >= 0.0f && d5 <= d6) {
v = 0.0f;
w = 1.0f;
return c;
}
float vb = d5 * d2 - d1 * d6;
if (vb <= 0.0f && d2 >= 0.0f && d6 <= 0.0f) {
v = 0.0f;
w = d2 / (d2 - d6);
return a + w * ac;
}
float va = d3 * d6 - d5 * d4;
if (va <= 0.0f && (d4 - d3) >= 0.0f && (d5 - d6) >= 0.0f) {
w = (d4 - d3) / ((d4 - d3) + (d5 - d6));
v = 1.0f - w;
return b + w * (c - b);
}
float denom = 1.0f / (va + vb + vc);
v = vb * denom;
w = vc * denom;
return a + ab * v + ac * w;
}
CUDA_CALLABLE inline Vec3
ClosestPointOnFatTriangle(const Vec3 &a, const Vec3 &b, const Vec3 &c,
const Vec3 &p, const float thickness, float &v,
float &w) {
const Vec3 x = ClosestPointOnTriangle(a, b, c, p, v, w);
const Vec3 d = SafeNormalize(p - x);
// apply thickness along delta dir
return x + d * thickness;
}
// computes intersection between a ray and a triangle expanded by a constant
// thickness, also works for ray-sphere and ray-capsule this is an iterative
// method similar to sphere tracing but for convex objects, see
// http://dtecta.com/papers/jgt04raycast.pdf
CUDA_CALLABLE inline bool
IntersectRayFatTriangle(const Vec3 &p, const Vec3 &dir, const Vec3 &a,
const Vec3 &b, const Vec3 &c, float thickness,
float threshold, float maxT, float &t, float &u,
float &v, float &w, Vec3 *normal) {
t = 0.0f;
Vec3 x = p;
Vec3 n;
float distSq;
const float thresholdSq = threshold * threshold;
const int maxIterations = 20;
for (int i = 0; i < maxIterations; ++i) {
const Vec3 closestPoint =
ClosestPointOnFatTriangle(a, b, c, x, thickness, v, w);
n = x - closestPoint;
distSq = LengthSq(n);
// early out
if (distSq <= thresholdSq)
break;
float ndir = Dot(n, dir);
// we've gone past the convex
if (ndir >= 0.0f)
return false;
// we've exceeded max ray length
if (t > maxT)
return false;
t = t - distSq / ndir;
x = p + t * dir;
}
// calculate normal based on unexpanded geometry to avoid precision issues
Vec3 cp = ClosestPointOnTriangle(a, b, c, x, v, w);
n = x - cp;
// if n faces away due to numerical issues flip it to face ray dir
if (Dot(n, dir) > 0.0f)
n *= -1.0f;
u = 1.0f - v - w;
*normal = SafeNormalize(n);
return true;
}
CUDA_CALLABLE inline float SqDistPointSegment(Vec3 a, Vec3 b, Vec3 c) {
Vec3 ab = b - a, ac = c - a, bc = c - b;
float e = Dot(ac, ab);
if (e <= 0.0f)
return Dot(ac, ac);
float f = Dot(ab, ab);
if (e >= f)
return Dot(bc, bc);
return Dot(ac, ac) - e * e / f;
}
CUDA_CALLABLE inline bool PointInTriangle(Vec3 a, Vec3 b, Vec3 c, Vec3 p) {
a -= p;
b -= p;
c -= p;
/*
float eps = 0.0f;
float ab = Dot(a, b);
float ac = Dot(a, c);
float bc = Dot(b, c);
float cc = Dot(c, c);
if (bc *ac - cc * ab <= eps)
return false;
float bb = Dot(b, b);
if (ab * bc - ac*bb <= eps)
return false;
return true;
*/
Vec3 u = Cross(b, c);
Vec3 v = Cross(c, a);
if (Dot(u, v) <= 0.0f)
return false;
Vec3 w = Cross(a, b);
if (Dot(u, w) <= 0.0f)
return false;
return true;
}
CUDA_CALLABLE inline void
ClosestPointBetweenLineSegments(const Vec3 &p, const Vec3 &q, const Vec3 &r,
const Vec3 &s, float &u, float &v) {
Vec3 d1 = q - p;
Vec3 d2 = s - r;
Vec3 rp = p - r;
float a = Dot(d1, d1);
float c = Dot(d1, rp);
float e = Dot(d2, d2);
float f = Dot(d2, rp);
float b = Dot(d1, d2);
float denom = a * e - b * b;
if (denom != 0.0f)
u = Clamp((b * f - c * e) / denom, 0.0f, 1.0f);
else {
u = 0.0f;
}
v = (b * u + f) / e;
if (v < 0.0f) {
v = 0.0f;
u = Clamp(-c / a, 0.0f, 1.0f);
} else if (v > 1.0f) {
v = 1.0f;
u = Clamp((b - c) / a, 0.0f, 1.0f);
}
}
CUDA_CALLABLE inline float ClosestPointBetweenLineSegmentAndTri(
const Vec3 &p, const Vec3 &q, const Vec3 &a, const Vec3 &b, const Vec3 &c,
float &outT, float &outV, float &outW) {
float minDsq = FLT_MAX;
float minT, minV, minW;
float t, u, v, w, dSq;
Vec3 r, s;
// test if line segment intersects tri
if (IntersectSegmentTri(p, q, a, b, c, t, u, v, w, nullptr)) {
outT = t;
outV = v;
outW = w;
return 0.0f;
}
// edge ab
ClosestPointBetweenLineSegments(p, q, a, b, t, v);
r = p + (q - p) * t;
s = a + (b - a) * v;
dSq = LengthSq(r - s);
if (dSq < minDsq) {
minDsq = dSq;
minT = u;
// minU = 1.0f-v
minV = v;
minW = 0.0f;
}
// edge bc
ClosestPointBetweenLineSegments(p, q, b, c, t, w);
r = p + (q - p) * t;
s = b + (c - b) * w;
dSq = LengthSq(r - s);
if (dSq < minDsq) {
minDsq = dSq;
minT = t;
// minU = 0.0f;
minV = 1.0f - w;
minW = w;
}
// edge ca
ClosestPointBetweenLineSegments(p, q, c, a, t, u);
r = p + (q - p) * t;
s = c + (a - c) * u;
dSq = LengthSq(r - s);
if (dSq < minDsq) {
minDsq = dSq;
minT = t;
// minU = u;
minV = 0.0f;
minW = 1.0f - u;
}
// end point p
ClosestPointOnTriangle(a, b, c, p, v, w);
s = a * (1.0f - v - w) + b * v + c * w;
dSq = LengthSq(s - p);
if (dSq < minDsq) {
minDsq = dSq;
minT = 0.0f;
minV = v;
minW = w;
}
// end point q
ClosestPointOnTriangle(a, b, c, q, v, w);
s = a * (1.0f - v - w) + b * v + c * w;
dSq = LengthSq(s - q);
if (dSq < minDsq) {
minDsq = dSq;
minT = 1.0f;
minV = v;
minW = w;
}
// write mins
outT = minT;
outV = minV;
outW = minW;
return sqrtf(minDsq);
}
CUDA_CALLABLE inline float minf(const float a, const float b) {
return a < b ? a : b;
}
CUDA_CALLABLE inline float maxf(const float a, const float b) {
return a > b ? a : b;
}
CUDA_CALLABLE inline bool IntersectRayAABBFast(const Vec3 &pos,
const Vector3 &rcp_dir,
const Vector3 &min,
const Vector3 &max, float &t) {
float l1 = (min.x - pos.x) * rcp_dir.x, l2 = (max.x - pos.x) * rcp_dir.x,
lmin = minf(l1, l2), lmax = maxf(l1, l2);
l1 = (min.y - pos.y) * rcp_dir.y;
l2 = (max.y - pos.y) * rcp_dir.y;
lmin = maxf(minf(l1, l2), lmin);
lmax = minf(maxf(l1, l2), lmax);
l1 = (min.z - pos.z) * rcp_dir.z;
l2 = (max.z - pos.z) * rcp_dir.z;
lmin = maxf(minf(l1, l2), lmin);
lmax = minf(maxf(l1, l2), lmax);
// return ((lmax > 0.f) & (lmax >= lmin));
// return ((lmax > 0.f) & (lmax > lmin));
bool hit = ((lmax >= 0.f) & (lmax >= lmin));
if (hit)
t = lmin;
return hit;
}
CUDA_CALLABLE inline bool
IntersectRayAABB(const Vec3 &start, const Vector3 &dir, const Vector3 &min,
const Vector3 &max, float &t, Vector3 *normal) {
//! calculate candidate plane on each axis
float tx = -1.0f, ty = -1.0f, tz = -1.0f;
bool inside = true;
//! use unrolled loops
//! x
if (start.x < min.x) {
if (dir.x != 0.0f)
tx = (min.x - start.x) / dir.x;
inside = false;
} else if (start.x > max.x) {
if (dir.x != 0.0f)
tx = (max.x - start.x) / dir.x;
inside = false;
}
//! y
if (start.y < min.y) {
if (dir.y != 0.0f)
ty = (min.y - start.y) / dir.y;
inside = false;
} else if (start.y > max.y) {
if (dir.y != 0.0f)
ty = (max.y - start.y) / dir.y;
inside = false;
}
//! z
if (start.z < min.z) {
if (dir.z != 0.0f)
tz = (min.z - start.z) / dir.z;
inside = false;
} else if (start.z > max.z) {
if (dir.z != 0.0f)
tz = (max.z - start.z) / dir.z;
inside = false;
}
//! if point inside all planes
if (inside) {
t = 0.0f;
return true;
}
//! we now have t values for each of possible intersection planes
//! find the maximum to get the intersection point
float tmax = tx;
int taxis = 0;
if (ty > tmax) {
tmax = ty;
taxis = 1;
}
if (tz > tmax) {
tmax = tz;
taxis = 2;
}
if (tmax < 0.0f)
return false;
//! check that the intersection point lies on the plane we picked
//! we don't test the axis of closest intersection for precision reasons
//! no eps for now
float eps = 0.0f;
Vec3 hit = start + dir * tmax;
if ((hit.x < min.x - eps || hit.x > max.x + eps) && taxis != 0)
return false;
if ((hit.y < min.y - eps || hit.y > max.y + eps) && taxis != 1)
return false;
if ((hit.z < min.z - eps || hit.z > max.z + eps) && taxis != 2)
return false;
//! output results
t = tmax;
return true;
}
// construct a plane equation such that ax + by + cz + dw = 0
CUDA_CALLABLE inline Vec4 PlaneFromPoints(const Vec3 &p, const Vec3 &q,
const Vec3 &r) {
Vec3 e0 = q - p;
Vec3 e1 = r - p;
Vec3 n = SafeNormalize(Cross(e0, e1));
return Vec4(n.x, n.y, n.z, -Dot(p, n));
}
CUDA_CALLABLE inline bool
IntersectPlaneAABB(const Vec4 &plane, const Vec3 ¢er, const Vec3 &extents) {
float radius = Abs(extents.x * plane.x) + Abs(extents.y * plane.y) +
Abs(extents.z * plane.z);
float delta = Dot(center, Vec3(plane)) + plane.w;
return Abs(delta) <= radius;
}
// 2d rectangle class
class Rect {
public:
Rect() : m_left(0), m_right(0), m_top(0), m_bottom(0) {}
Rect(uint32_t left, uint32_t right, uint32_t top, uint32_t bottom)
: m_left(left), m_right(right), m_top(top), m_bottom(bottom) {
assert(left <= right);
assert(top <= bottom);
}
uint32_t Width() const { return m_right - m_left; }
uint32_t Height() const { return m_bottom - m_top; }
// expand rect x units in each direction
void Expand(uint32_t x) {
m_left -= x;
m_right += x;
m_top -= x;
m_bottom += x;
}
uint32_t Left() const { return m_left; }
uint32_t Right() const { return m_right; }
uint32_t Top() const { return m_top; }
uint32_t Bottom() const { return m_bottom; }
bool Contains(uint32_t x, uint32_t y) const {
return (x >= m_left) && (x <= m_right) && (y >= m_top) && (y <= m_bottom);
}
uint32_t m_left;
uint32_t m_right;
uint32_t m_top;
uint32_t m_bottom;
};
// doesn't really belong here but efficient (and I believe correct) in place
// random shuffle based on the Fisher-Yates / Knuth algorithm
template <typename T> void RandomShuffle(T begin, T end) {
assert(end > begin);
uint32_t n = distance(begin, end);
for (uint32_t i = 0; i < n; ++i) {
// pick a random number between 0 and n-1
uint32_t r = Rand() % (n - i);
// swap that location with the current randomly selected position
swap(*(begin + i), *(begin + (i + r)));
}
}
CUDA_CALLABLE inline Quat QuatFromAxisAngle(const Vec3 &axis, float angle) {
Vec3 v = Normalize(axis);
float half = angle * 0.5f;
float w = cosf(half);
const float sin_theta_over_two = sinf(half);
v *= sin_theta_over_two;
return Quat(v.x, v.y, v.z, w);
}
// rotate by quaternion (q, w)
CUDA_CALLABLE inline Vec3 rotate(const Vec3 &q, float w, const Vec3 &x) {
return 2.0f * (x * (w * w - 0.5f) + Cross(q, x) * w + q * Dot(q, x));
}
// rotate x by inverse transform in (q, w)
CUDA_CALLABLE inline Vec3 rotateInv(const Vec3 &q, float w, const Vec3 &x) {
return 2.0f * (x * (w * w - 0.5f) - Cross(q, x) * w + q * Dot(q, x));
}
// get rotation from u to v
CUDA_CALLABLE inline Quat GetRotationQuat(const Vec3 &_u, const Vec3 &_v) {
Vec3 u = Normalize(_u);
Vec3 v = Normalize(_v);
// check for aligned vectors
float d = Dot(u, v);
if (d > 1.0f - 1e-6f) {
// vectors are colinear, return identity
return Quat();
} else if (d < 1e-6f - 1.0f) {
// vectors are opposite, return a 180 degree rotation
Vec3 axis = Cross({1.0f, 0.0f, 0.0f}, u);
if (LengthSq(axis) < 1e-6f) {
axis = Cross({0.0f, 1.0f, 0.0f}, u);
}
return QuatFromAxisAngle(Normalize(axis), kPi);
} else {
Vec3 c = Cross(u, v);
float s = sqrtf((1.0f + d) * 2.0f);
float invs = 1.0f / s;
Quat q(invs * c.x, invs * c.y, invs * c.z, 0.5f * s);
return Normalize(q);
}
}
CUDA_CALLABLE inline void TransformBounds(const Quat &q, Vec3 extents,
Vec3 &newExtents) {
Matrix33 transform(q);
transform.cols[0] *= extents.x;
transform.cols[1] *= extents.y;
transform.cols[2] *= extents.z;
float ex = fabsf(transform.cols[0].x) + fabsf(transform.cols[1].x) +
fabsf(transform.cols[2].x);
float ey = fabsf(transform.cols[0].y) + fabsf(transform.cols[1].y) +
fabsf(transform.cols[2].y);
float ez = fabsf(transform.cols[0].z) + fabsf(transform.cols[1].z) +
fabsf(transform.cols[2].z);
newExtents = Vec3(ex, ey, ez);
}
CUDA_CALLABLE inline void TransformBounds(const Vec3 &localLower,
const Vec3 &localUpper,
const Vec3 &translation,
const Quat &rotation, float scale,
Vec3 &lower, Vec3 &upper) {
Matrix33 transform(rotation);
Vec3 extents = (localUpper - localLower) * scale;
transform.cols[0] *= extents.x;
transform.cols[1] *= extents.y;
transform.cols[2] *= extents.z;
float ex = fabsf(transform.cols[0].x) + fabsf(transform.cols[1].x) +
fabsf(transform.cols[2].x);
float ey = fabsf(transform.cols[0].y) + fabsf(transform.cols[1].y) +
fabsf(transform.cols[2].y);
float ez = fabsf(transform.cols[0].z) + fabsf(transform.cols[1].z) +
fabsf(transform.cols[2].z);
Vec3 center = (localUpper + localLower) * 0.5f * scale;
lower = rotation * center + translation - Vec3(ex, ey, ez) * 0.5f;
upper = rotation * center + translation + Vec3(ex, ey, ez) * 0.5f;
}
// Poisson sample the volume of a sphere with given separation
inline int PoissonSample3D(float radius, float separation, Vec3 *points,
int maxPoints, int maxAttempts) {
// naive O(n^2) dart throwing algorithm to generate a Poisson distribution
int c = 0;
while (c < maxPoints) {
int a = 0;
while (a < maxAttempts) {
const Vec3 p = UniformSampleSphereVolume() * radius;
// test against points already generated
int i = 0;
for (; i < c; ++i) {
Vec3 d = p - points[i];
// reject if closer than separation
if (LengthSq(d) < separation * separation)
break;
}
// sample passed all tests, accept
if (i == c) {
points[c] = p;
++c;
break;
}
++a;
}
// exit if we reached the max attempts and didn't manage to add a point
if (a == maxAttempts)
break;
}
return c;
}
inline int PoissonSampleBox3D(Vec3 lower, Vec3 upper, float separation,
Vec3 *points, int maxPoints, int maxAttempts) {
// naive O(n^2) dart throwing algorithm to generate a Poisson distribution
int c = 0;
while (c < maxPoints) {
int a = 0;
while (a < maxAttempts) {
const Vec3 p = Vec3(Randf(lower.x, upper.x), Randf(lower.y, upper.y),
Randf(lower.z, upper.z));
// test against points already generated
int i = 0;
for (; i < c; ++i) {
Vec3 d = p - points[i];
// reject if closer than separation
if (LengthSq(d) < separation * separation)
break;
}
// sample passed all tests, accept
if (i == c) {
points[c] = p;
++c;
break;
}
++a;
}
// exit if we reached the max attempts and didn't manage to add a point
if (a == maxAttempts)
break;
}
return c;
}
// Generates an optimally dense sphere packing at the origin (implicit sphere at
// the origin)
inline int TightPack3D(float radius, float separation, Vec3 *points,
int maxPoints) {
int dim = int(ceilf(radius / separation));
int c = 0;
for (int z = -dim; z <= dim; ++z) {
for (int y = -dim; y <= dim; ++y) {
for (int x = -dim; x <= dim; ++x) {
float xpos =
x * separation + (((y + z) & 1) ? separation * 0.5f : 0.0f);
float ypos = y * sqrtf(0.75f) * separation;
float zpos = z * sqrtf(0.75f) * separation;
Vec3 p(xpos, ypos, zpos);
// skip center
if (LengthSq(p) == 0.0f)
continue;
if (c < maxPoints && Length(p) <= radius) {
points[c] = p;
++c;
}
}
}
}
return c;
}
struct Bounds {
CUDA_CALLABLE inline Bounds() : lower(FLT_MAX), upper(-FLT_MAX) {}
CUDA_CALLABLE inline Bounds(const Vec3 &lower, const Vec3 &upper)
: lower(lower), upper(upper) {}
CUDA_CALLABLE inline Vec3 GetCenter() const { return 0.5f * (lower + upper); }
CUDA_CALLABLE inline Vec3 GetEdges() const { return upper - lower; }
CUDA_CALLABLE inline void Expand(float r) {
lower -= Vec3(r);
upper += Vec3(r);
}
CUDA_CALLABLE inline void Expand(const Vec3 &r) {
lower -= r;
upper += r;
}
CUDA_CALLABLE inline bool Empty() const {
return lower.x >= upper.x || lower.y >= upper.y || lower.z >= upper.z;
}
CUDA_CALLABLE inline bool Overlaps(const Vec3 &p) const {
if (p.x < lower.x || p.y < lower.y || p.z < lower.z || p.x > upper.x ||
p.y > upper.y || p.z > upper.z) {
return false;
} else {
return true;
}
}
CUDA_CALLABLE inline bool Overlaps(const Bounds &b) const {
if (lower.x > b.upper.x || lower.y > b.upper.y || lower.z > b.upper.z ||
upper.x < b.lower.x || upper.y < b.lower.y || upper.z < b.lower.z) {
return false;
} else {
return true;
}
}
Vec3 lower;
Vec3 upper;
};
CUDA_CALLABLE inline Bounds Union(const Bounds &a, const Vec3 &b) {
return Bounds(Min(a.lower, b), Max(a.upper, b));
}
CUDA_CALLABLE inline Bounds Union(const Bounds &a, const Bounds &b) {
return Bounds(Min(a.lower, b.lower), Max(a.upper, b.upper));
}
CUDA_CALLABLE inline Bounds Intersection(const Bounds &a, const Bounds &b) {
return Bounds(Max(a.lower, b.lower), Min(a.upper, b.upper));
}
CUDA_CALLABLE inline float SurfaceArea(const Bounds &b) {
Vec3 e = b.upper - b.lower;
return 2.0f * (e.x * e.y + e.x * e.z + e.y * e.z);
}
inline void ExtractFrustumPlanes(const Matrix44 &m, Plane *planes) {
// Based on Fast Extraction of Viewing Frustum Planes from the
// WorldView-Projection Matrix, Gill Grib, Klaus Hartmann
// Left clipping plane
planes[0].x = m(3, 0) + m(0, 0);
planes[0].y = m(3, 1) + m(0, 1);
planes[0].z = m(3, 2) + m(0, 2);
planes[0].w = m(3, 3) + m(0, 3);
// Right clipping plane
planes[1].x = m(3, 0) - m(0, 0);
planes[1].y = m(3, 1) - m(0, 1);
planes[1].z = m(3, 2) - m(0, 2);
planes[1].w = m(3, 3) - m(0, 3);
// Top clipping plane
planes[2].x = m(3, 0) - m(1, 0);
planes[2].y = m(3, 1) - m(1, 1);
planes[2].z = m(3, 2) - m(1, 2);
planes[2].w = m(3, 3) - m(1, 3);
// Bottom clipping plane
planes[3].x = m(3, 0) + m(1, 0);
planes[3].y = m(3, 1) + m(1, 1);
planes[3].z = m(3, 2) + m(1, 2);
planes[3].w = m(3, 3) + m(1, 3);
// Near clipping plane
planes[4].x = m(3, 0) + m(2, 0);
planes[4].y = m(3, 1) + m(2, 1);
planes[4].z = m(3, 2) + m(2, 2);
planes[4].w = m(3, 3) + m(2, 3);
// Far clipping plane
planes[5].x = m(3, 0) - m(2, 0);
planes[5].y = m(3, 1) - m(2, 1);
planes[5].z = m(3, 2) - m(2, 2);
planes[5].w = m(3, 3) - m(2, 3);
NormalizePlane(planes[0]);
NormalizePlane(planes[1]);
NormalizePlane(planes[2]);
NormalizePlane(planes[3]);
NormalizePlane(planes[4]);
NormalizePlane(planes[5]);
}
inline bool TestSphereAgainstFrustum(const Plane *planes, Vec3 center,
float radius) {
for (int i = 0; i < 6; ++i) {
float d = -Dot(planes[i], Point3(center)) - radius;
if (d > 0.0f)
return false;
}
return true;
}
| 49,107 | C | 24.352607 | 99 | 0.549372 |
NVIDIA-Omniverse/mjcf-importer-extension/source/extensions/omni.importer.mjcf/plugins/math/core/common_math.h | // SPDX-FileCopyrightText: Copyright (c) 2023 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
// SPDX-License-Identifier: Apache-2.0
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#pragma once
#include "core.h"
#include "types.h"
#include <cassert>
#include <cmath>
#include <float.h>
#include <string.h>
#ifdef __CUDACC__
#define CUDA_CALLABLE __host__ __device__
#else
#define CUDA_CALLABLE
#endif
#define kPi 3.141592653589f
const float k2Pi = 2.0f * kPi;
const float kInvPi = 1.0f / kPi;
const float kInv2Pi = 0.5f / kPi;
const float kDegToRad = kPi / 180.0f;
const float kRadToDeg = 180.0f / kPi;
CUDA_CALLABLE inline float DegToRad(float t) { return t * kDegToRad; }
CUDA_CALLABLE inline float RadToDeg(float t) { return t * kRadToDeg; }
CUDA_CALLABLE inline float Sin(float theta) { return sinf(theta); }
CUDA_CALLABLE inline float Cos(float theta) { return cosf(theta); }
CUDA_CALLABLE inline void SinCos(float theta, float &s, float &c) {
// no optimizations yet
s = sinf(theta);
c = cosf(theta);
}
CUDA_CALLABLE inline float Tan(float theta) { return tanf(theta); }
CUDA_CALLABLE inline float Sqrt(float x) { return sqrtf(x); }
CUDA_CALLABLE inline double Sqrt(double x) { return sqrt(x); }
CUDA_CALLABLE inline float ASin(float theta) { return asinf(theta); }
CUDA_CALLABLE inline float ACos(float theta) { return acosf(theta); }
CUDA_CALLABLE inline float ATan(float theta) { return atanf(theta); }
CUDA_CALLABLE inline float ATan2(float x, float y) { return atan2f(x, y); }
CUDA_CALLABLE inline float Abs(float x) { return fabsf(x); }
CUDA_CALLABLE inline float Pow(float b, float e) { return powf(b, e); }
CUDA_CALLABLE inline float Sgn(float x) { return (x < 0.0f ? -1.0f : 1.0f); }
CUDA_CALLABLE inline float Sign(float x) { return x < 0.0f ? -1.0f : 1.0f; }
CUDA_CALLABLE inline double Sign(double x) { return x < 0.0f ? -1.0f : 1.0f; }
CUDA_CALLABLE inline float Mod(float x, float y) { return fmod(x, y); }
template <typename T> CUDA_CALLABLE inline T Min(T a, T b) {
return a < b ? a : b;
}
template <typename T> CUDA_CALLABLE inline T Max(T a, T b) {
return a > b ? a : b;
}
template <typename T> CUDA_CALLABLE inline void Swap(T &a, T &b) {
T tmp = a;
a = b;
b = tmp;
}
template <typename T> CUDA_CALLABLE inline T Clamp(T a, T low, T high) {
if (low > high)
Swap(low, high);
return Max(low, Min(a, high));
}
template <typename V, typename T>
CUDA_CALLABLE inline V Lerp(const V &start, const V &end, const T &t) {
return start + (end - start) * t;
}
CUDA_CALLABLE inline float InvSqrt(float x) { return 1.0f / sqrtf(x); }
// round towards +infinity
CUDA_CALLABLE inline int Round(float f) { return int(f + 0.5f); }
template <typename T> CUDA_CALLABLE T Normalize(const T &v) {
T a(v);
a /= Length(v);
return a;
}
template <typename T>
CUDA_CALLABLE inline typename T::value_type LengthSq(const T v) {
return Dot(v, v);
}
template <typename T>
CUDA_CALLABLE inline typename T::value_type Length(const T &v) {
typename T::value_type lSq = LengthSq(v);
if (lSq)
return Sqrt(LengthSq(v));
else
return 0.0f;
}
// this is mainly a helper function used by script
template <typename T>
CUDA_CALLABLE inline typename T::value_type Distance(const T &v1, const T &v2) {
return Length(v1 - v2);
}
template <typename T>
CUDA_CALLABLE inline T SafeNormalize(const T &v, const T &fallback = T()) {
float l = LengthSq(v);
if (l > 0.0f) {
return v * InvSqrt(l);
} else
return fallback;
}
template <typename T> CUDA_CALLABLE inline T Sqr(T x) { return x * x; }
template <typename T> CUDA_CALLABLE inline T Cube(T x) { return x * x * x; }
| 4,158 | C | 27.101351 | 99 | 0.688793 |
NVIDIA-Omniverse/mjcf-importer-extension/source/extensions/omni.importer.mjcf/plugins/math/core/core.h | // SPDX-FileCopyrightText: Copyright (c) 2023 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
// SPDX-License-Identifier: Apache-2.0
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#pragma once
#define ENABLE_VERBOSE_OUTPUT 0
#define ENABLE_APIC_CAPTURE 0
#define ENABLE_PERFALYZE_CAPTURE 0
#if ENABLE_VERBOSE_OUTPUT
#define VERBOSE(a) a##;
#else
#define VERBOSE(a)
#endif
//#define Super __super
// basically just a collection of macros and types
#ifndef UNUSED
#define UNUSED(x) (void)x;
#endif
#define NOMINMAX
#if !PLATFORM_OPENCL
#include <cassert>
#endif
#include "types.h"
#if !PLATFORM_SPU && !PLATFORM_OPENCL
#include <algorithm>
#include <fstream>
#include <functional>
#include <iostream>
#include <string>
#endif
#include <string.h>
// disable some warnings
#if _WIN32
#pragma warning(disable : 4996) // secure io
#pragma warning(disable : 4100) // unreferenced param
#pragma warning( \
disable : 4324) // structure was padded due to __declspec(align())
#endif
// alignment helpers
#define DEFAULT_ALIGNMENT 16
#if PLATFORM_LINUX
#define ALIGN_N(x)
#define ENDALIGN_N(x) __attribute__((aligned(x)))
#else
#define ALIGN_N(x) __declspec(align(x))
#define END_ALIGN_N(x)
#endif
#define ALIGN ALIGN_N(DEFAULT_ALIGNMENT)
#define END_ALIGN END_ALIGN_N(DEFAULT_ALIGNMENT)
inline bool IsPowerOfTwo(int n) { return (n & (n - 1)) == 0; }
// align a ptr to a power of tow
template <typename T> inline T *AlignPtr(T *p, uint32_t alignment) {
assert(IsPowerOfTwo(alignment));
// cast to safe ptr type
uintptr_t up = reinterpret_cast<uintptr_t>(p);
return (T *)((up + (alignment - 1)) & ~(alignment - 1));
}
// align an unsigned value to a power of two
inline uint32_t Align(uint32_t val, uint32_t alignment) {
assert(IsPowerOfTwo(alignment));
return (val + (alignment - 1)) & ~(alignment - 1);
}
inline bool IsAligned(void *p, uint32_t alignment) {
return (((uintptr_t)p) & (alignment - 1)) == 0;
}
template <typename To, typename From> To UnionCast(From in) {
union {
To t;
From f;
};
f = in;
return t;
}
// Endian helpers
template <typename T> T ByteSwap(const T &val) {
T copy = val;
uint8_t *p = reinterpret_cast<uint8_t *>(©);
std::reverse(p, p + sizeof(T));
return copy;
}
#ifndef LITTLE_ENDIAN
#define LITTLE_ENDIAN WIN32
#endif
#ifndef BIG_ENDIAN
#define BIG_ENDIAN PLATFORM_PS3 || PLATFORM_SPU
#endif
#if BIG_ENDIAN
#define ToLittleEndian(x) ByteSwap(x)
#else
#define ToLittleEndian(x) x
#endif
//#include "platform.h"
//#define sizeof_array(x) (sizeof(x)/sizeof(*x))
template <typename T, size_t N> size_t sizeof_array(const T (&)[N]) {
return N;
}
// unary_function depricated in c++11
// functor designed for use in the stl
// template <typename T>
// class free_ptr : public std::unary_function<T*, void>
//{
// public:
// void operator()(const T* ptr)
// {
// delete ptr;
// }
//};
// given the path of one file it strips the filename and appends the relative
// path onto it
inline void MakeRelativePath(const char *filePath, const char *fileRelativePath,
char *fullPath) {
// get base path of file
const char *lastSlash = nullptr;
if (!lastSlash)
lastSlash = strrchr(filePath, '\\');
if (!lastSlash)
lastSlash = strrchr(filePath, '/');
int baseLength = 0;
if (lastSlash) {
baseLength = int(lastSlash - filePath) + 1;
// copy base path (including slash to relative path)
memcpy(fullPath, filePath, baseLength);
}
// if (fileRelativePath[0] == '.')
//++fileRelativePath;
if (fileRelativePath[0] == '\\' || fileRelativePath[0] == '/')
++fileRelativePath;
// append mesh filename
strcpy(fullPath + baseLength, fileRelativePath);
}
| 4,296 | C | 22.872222 | 99 | 0.674348 |
NVIDIA-Omniverse/mjcf-importer-extension/source/extensions/omni.importer.mjcf/plugins/core/mesh.h | // SPDX-FileCopyrightText: Copyright (c) 2023 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
// SPDX-License-Identifier: Apache-2.0
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#pragma once
// clang-format off
#include "../UsdPCH.h"
// clang-format on
#include "assimp/scene.h"
#include "../math/core/core.h"
#include "../math/core/maths.h"
#include <string>
#include <vector>
struct TextureData {
int width; // width of texture - if height == 0, then width will be the same
// as buffer.size()
int height; // height of textur - if height == 0, then the buffer represents a
// compressed image with file type corresponding to format
std::vector<uint8_t> buffer; // r8g8b8a8 if not compressed
std::string
format; // format of the data in buffer if compressed (i.e. png, jpg, bmp)
};
// direct representation of .obj style material
struct Material {
std::string name;
Vec3 Ka;
Vec3 Kd;
Vec3 Ks;
Vec3 emissive;
float Ns = 50.0f; // specular exponent
float metallic = 0.0f;
float specular = 0.0f;
std::string mapKd = ""; // diffuse
std::string mapKs = ""; // shininess
std::string mapBump = ""; // normal
std::string mapEnv = ""; // emissive
std::string mapMetallic = "";
bool hasDiffuse = false;
bool hasSpecular = false;
bool hasMetallic = false;
bool hasEmissive = false;
bool hasShininess = false;
};
struct MaterialAssignment {
int startTri;
int endTri;
int startIndices;
int endIndices;
int material;
};
struct UVInfo {
std::vector<std::vector<Vector2>> uvs;
std::vector<unsigned int> uvStartIndices;
};
/// Used when loading meshes to determine how to load normals
enum GymMeshNormalMode {
eFromAsset, // try to load normals from the mesh
eComputePerVertex, // compute per-vertex normals
eComputePerFace, // compute per-face normals
};
struct USDMesh {
std::string name;
pxr::VtArray<pxr::GfVec3f> points;
pxr::VtArray<int> faceVertexCounts;
pxr::VtArray<int> faceVertexIndices;
pxr::VtArray<pxr::GfVec3f> normals; // Face varing normals
pxr::VtArray<pxr::VtArray<pxr::GfVec2f>> uvs; // Face varing uvs
pxr::VtArray<pxr::VtArray<pxr::GfVec3f>> colors; // Face varing colors
};
struct Mesh {
void AddMesh(const Mesh &m);
uint32_t GetNumVertices() const { return uint32_t(m_positions.size()); }
uint32_t GetNumFaces() const { return uint32_t(m_indices.size()) / 3; }
void DuplicateVertex(uint32_t i);
void CalculateFaceNormals(); // splits mesh at vertices to calculate faceted
// normals (changes topology)
void CalculateNormals();
void Transform(const Matrix44 &m);
void Normalize(float s = 1.0f); // scale so bounds in any dimension equals s
// and lower bound = (0,0,0)
void Flip();
void GetBounds(Vector3 &minExtents, Vector3 &maxExtents) const;
std::string name; // optional
std::vector<Point3> m_positions;
std::vector<Vector3> m_normals;
std::vector<Vector2> m_texcoords;
std::vector<Colour> m_colours;
std::vector<uint32_t> m_indices;
std::vector<Material> m_materials;
std::vector<MaterialAssignment> m_materialAssignments;
std::vector<USDMesh> m_usdMeshPrims;
};
// Create mesh from Assimp import
void addAssimpNodeToMesh(const aiScene *scene, const aiNode *node,
aiMatrix4x4 xform, UVInfo &uvInfo, Mesh *mesh);
Mesh *ImportMeshAssimp(const char *path);
// create mesh from file
Mesh *ImportMeshFromObj(const char *path);
Mesh *ImportMeshFromPly(const char *path);
Mesh *ImportMeshFromBin(const char *path);
Mesh *ImportMeshFromStl(const char *path);
// just switches on filename
Mesh *ImportMesh(const char *path);
// save a mesh in a flat binary format
void ExportMeshToBin(const char *path, const Mesh *m);
// create procedural primitives
Mesh *CreateTriMesh(float size, float y = 0.0f);
Mesh *CreateCubeMesh();
Mesh *CreateQuadMesh(float sizex, float sizez, int gridx, int gridz);
Mesh *CreateDiscMesh(float radius, uint32_t segments);
Mesh *CreateTetrahedron(float ground = 0.0f,
float height = 1.0f); // fixed but not used
Mesh *CreateSphere(int slices, int segments, float radius = 1.0f);
Mesh *CreateEllipsoid(int slices, int segments, Vec3 radiis);
Mesh *CreateCapsule(int slices, int segments, float radius = 1.0f,
float halfHeight = 1.0f);
Mesh *CreateCylinder(int slices, float radius, float halfHeight,
bool cap = false);
| 5,029 | C | 30.63522 | 99 | 0.690595 |
NVIDIA-Omniverse/mjcf-importer-extension/source/extensions/omni.importer.mjcf/plugins/core/mesh.cpp | // SPDX-FileCopyrightText: Copyright (c) 2023 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
// SPDX-License-Identifier: Apache-2.0
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include "mesh.h"
#include "assimp/Importer.hpp"
#include "assimp/postprocess.h"
#include "assimp/scene.h"
//#include "platform.h"
#include <fstream>
#include <iostream>
#include <map>
using namespace std;
void Mesh::DuplicateVertex(uint32_t i) {
assert(m_positions.size() > i);
m_positions.push_back(m_positions[i]);
if (m_normals.size() > i)
m_normals.push_back(m_normals[i]);
if (m_colours.size() > i)
m_colours.push_back(m_colours[i]);
if (m_texcoords.size() > i)
m_texcoords.push_back(m_texcoords[i]);
}
void Mesh::Normalize(float s) {
Vec3 lower, upper;
GetBounds(lower, upper);
Vec3 edges = upper - lower;
Transform(TranslationMatrix(Point3(-lower)));
float maxEdge = max(edges.x, max(edges.y, edges.z));
Transform(ScaleMatrix(s / maxEdge));
}
void Mesh::CalculateFaceNormals() {
Mesh m;
int numTris = int(GetNumFaces());
for (int i = 0; i < numTris; ++i) {
int a = m_indices[i * 3 + 0];
int b = m_indices[i * 3 + 1];
int c = m_indices[i * 3 + 2];
int start = int(m.m_positions.size());
m.m_positions.push_back(m_positions[a]);
m.m_positions.push_back(m_positions[b]);
m.m_positions.push_back(m_positions[c]);
if (!m_texcoords.empty()) {
m.m_texcoords.push_back(m_texcoords[a]);
m.m_texcoords.push_back(m_texcoords[b]);
m.m_texcoords.push_back(m_texcoords[c]);
}
if (!m_colours.empty()) {
m.m_colours.push_back(m_colours[a]);
m.m_colours.push_back(m_colours[b]);
m.m_colours.push_back(m_colours[c]);
}
m.m_indices.push_back(start + 0);
m.m_indices.push_back(start + 1);
m.m_indices.push_back(start + 2);
}
m.CalculateNormals();
m.m_materials = this->m_materials;
m.m_materialAssignments = this->m_materialAssignments;
m.m_usdMeshPrims = this->m_usdMeshPrims;
*this = m;
}
void Mesh::CalculateNormals() {
m_normals.resize(0);
m_normals.resize(m_positions.size());
int numTris = int(GetNumFaces());
for (int i = 0; i < numTris; ++i) {
int a = m_indices[i * 3 + 0];
int b = m_indices[i * 3 + 1];
int c = m_indices[i * 3 + 2];
Vec3 n =
Cross(m_positions[b] - m_positions[a], m_positions[c] - m_positions[a]);
m_normals[a] += n;
m_normals[b] += n;
m_normals[c] += n;
}
int numVertices = int(GetNumVertices());
for (int i = 0; i < numVertices; ++i)
m_normals[i] = ::Normalize(m_normals[i]);
}
namespace {
enum PlyFormat { eAscii, eBinaryBigEndian };
template <typename T> T PlyRead(ifstream &s, PlyFormat format) {
T data = eAscii;
switch (format) {
case eAscii: {
s >> data;
break;
}
case eBinaryBigEndian: {
char c[sizeof(T)];
s.read(c, sizeof(T));
reverse(c, c + sizeof(T));
data = *(T *)c;
break;
}
default:
assert(0);
}
return data;
}
} // namespace
static pxr::GfVec3f AiVector3dToGfVector3f(const aiVector3D &vector) {
return pxr::GfVec3f(vector.x, vector.y, vector.z);
}
static pxr::GfVec2f AiVector3dToGfVector2f(const aiVector3D &vector) {
return pxr::GfVec2f(vector.x, vector.y);
}
pxr::GfVec3f AiColor4DToGfVector3f(const aiColor4D &color) {
return pxr::GfVec3f(color.r, color.g, color.b);
}
void addAssimpNodeToMesh(const aiScene *scene, const aiNode *node,
aiMatrix4x4 xform, UVInfo &uvInfo, Mesh *mesh) {
unsigned int triOffset =
static_cast<unsigned int>(mesh->m_indices.size() / 3);
unsigned int pointOffset =
static_cast<unsigned int>(mesh->m_positions.size());
unsigned int nodeTriOffset = 0;
unsigned int nodePointOffset = 0;
for (unsigned int m = 0; m < node->mNumMeshes; ++m) {
const aiMesh *assimpMesh = scene->mMeshes[node->mMeshes[m]];
USDMesh usdmesh;
for (unsigned int j = 0; j < assimpMesh->mNumVertices; ++j) {
const aiVector3D &p = xform * assimpMesh->mVertices[j];
mesh->m_positions.push_back(Point3{p.x, p.y, p.z});
usdmesh.points.push_back(AiVector3dToGfVector3f(p));
}
unsigned int numColourChannels = assimpMesh->GetNumColorChannels();
usdmesh.colors.resize(numColourChannels);
if (numColourChannels > 0) {
if (numColourChannels > 1) {
std::cout
<< "Multiple colour channels not supported. Using first channel."
<< std::endl;
}
unsigned int colourChannel = 0;
for (; colourChannel < AI_MAX_NUMBER_OF_COLOR_SETS; ++colourChannel) {
if (assimpMesh->HasVertexColors(colourChannel))
break;
}
for (unsigned int j = 0; j < assimpMesh->mNumVertices; ++j) {
const aiColor4D &c = assimpMesh->mColors[colourChannel][j];
mesh->m_colours.push_back(Colour{c.r, c.g, c.b, c.a});
}
}
unsigned int numUVChannels = assimpMesh->GetNumUVChannels();
usdmesh.uvs.resize(numUVChannels);
if (numUVChannels > 0) {
if (numUVChannels > 1) {
std::cout << "Multiple UV channels not supported. Using first channel."
<< std::endl;
}
unsigned int UVChannel = 0;
for (; UVChannel < AI_MAX_NUMBER_OF_TEXTURECOORDS; ++UVChannel) {
if (assimpMesh->HasTextureCoords(UVChannel) &&
assimpMesh->mNumUVComponents[UVChannel] <= 2)
break;
}
uvInfo.uvs.emplace_back();
auto ¤tUV = uvInfo.uvs.back();
uvInfo.uvStartIndices.push_back(pointOffset + nodePointOffset);
for (unsigned int j = 0; j < assimpMesh->mNumVertices; ++j) {
const aiVector3D &uv = assimpMesh->mTextureCoords[UVChannel][j];
mesh->m_texcoords.push_back(Vector2{uv.x, uv.y});
currentUV.push_back(Vector2{uv.x, uv.y});
}
}
for (size_t j = 0; j < assimpMesh->mNumFaces; j++) {
const aiFace &face = assimpMesh->mFaces[j];
if (face.mNumIndices >= 3) {
for (size_t k = 0; k < face.mNumIndices; k++) {
if (assimpMesh->mNormals) {
usdmesh.normals.push_back(
AiVector3dToGfVector3f(assimpMesh->mNormals[face.mIndices[k]]));
}
for (size_t m = 0; m < usdmesh.uvs.size(); m++) {
usdmesh.uvs[m].push_back(AiVector3dToGfVector2f(
assimpMesh->mTextureCoords[m][face.mIndices[k]]));
}
for (size_t m = 0; m < usdmesh.colors.size(); m++) {
usdmesh.colors[m].push_back(AiColor4DToGfVector3f(
assimpMesh->mColors[m][face.mIndices[k]]));
}
}
usdmesh.faceVertexCounts.push_back(face.mNumIndices);
}
}
unsigned int indexOffset = pointOffset + nodePointOffset;
for (unsigned int j = 0; j < assimpMesh->mNumFaces; ++j) {
const aiFace &f = assimpMesh->mFaces[j];
if (f.mNumIndices >= 3) {
for (size_t k = 0; k < f.mNumIndices; k++) {
usdmesh.faceVertexIndices.push_back(f.mIndices[k]);
}
}
// assert(f.mNumIndices > 0 && f.mNumIndices <= 3); // importer should
// triangluate mesh
if (f.mNumIndices == 1) {
mesh->m_indices.push_back(f.mIndices[0] + indexOffset);
mesh->m_indices.push_back(f.mIndices[0] + indexOffset);
mesh->m_indices.push_back(f.mIndices[0] + indexOffset);
} else if (f.mNumIndices == 2) {
mesh->m_indices.push_back(f.mIndices[0] + indexOffset);
mesh->m_indices.push_back(f.mIndices[1] + indexOffset);
mesh->m_indices.push_back(f.mIndices[1] + indexOffset);
} else if (f.mNumIndices == 3) {
mesh->m_indices.push_back(f.mIndices[0] + indexOffset);
mesh->m_indices.push_back(f.mIndices[1] + indexOffset);
mesh->m_indices.push_back(f.mIndices[2] + indexOffset);
}
}
if (assimpMesh->HasNormals()) {
for (unsigned int j = 0; j < assimpMesh->mNumVertices; ++j) {
const aiVector3D &n = xform * assimpMesh->mNormals[j];
mesh->m_normals.push_back(SafeNormalize(Vector3{n.x, n.y, n.z}));
}
}
MaterialAssignment matAssign;
matAssign.startTri = triOffset + nodeTriOffset;
matAssign.endTri = triOffset + nodeTriOffset + assimpMesh->mNumFaces;
matAssign.material = static_cast<int>(assimpMesh->mMaterialIndex);
mesh->m_materialAssignments.push_back(matAssign);
nodeTriOffset += assimpMesh->mNumFaces;
nodePointOffset += assimpMesh->mNumVertices;
mesh->m_usdMeshPrims.push_back(usdmesh);
}
}
Mesh *ImportMeshAssimp(const char *path) {
Assimp::Importer importer;
const aiScene *scene =
importer.ReadFile(std::string(path), aiProcess_Triangulate |
aiProcess_JoinIdenticalVertices);
if (!scene) {
return nullptr;
}
Mesh *mesh = new Mesh;
for (unsigned int i = 0; i < scene->mNumMaterials; ++i) {
aiMaterial *assimpMaterial = scene->mMaterials[i];
Material mat;
mat.name = std::string{assimpMaterial->GetName().C_Str()};
aiColor3D Ka;
if (assimpMaterial->Get(AI_MATKEY_COLOR_AMBIENT, Ka) == AI_SUCCESS) {
mat.Ka = Vec3{Ka.r, Ka.g, Ka.b};
}
aiColor3D Kd;
if (assimpMaterial->Get(AI_MATKEY_COLOR_DIFFUSE, Kd) == AI_SUCCESS) {
mat.Kd = Vec3{Kd.r, Kd.g, Kd.b};
mat.hasDiffuse = true;
}
aiColor3D Ks;
if (assimpMaterial->Get(AI_MATKEY_COLOR_SPECULAR, Ks) == AI_SUCCESS) {
mat.Ks = Vec3{Ks.r, Ks.g, Ks.b};
}
float specular;
if (assimpMaterial->Get(AI_MATKEY_SPECULAR_FACTOR, specular) ==
AI_SUCCESS) {
mat.specular = specular;
mat.hasSpecular = true;
}
float Ns;
if (assimpMaterial->Get(AI_MATKEY_SHININESS, Ns) == AI_SUCCESS) {
mat.Ns = Ns;
mat.hasShininess = true;
}
float metallic;
if (assimpMaterial->Get(AI_MATKEY_METALLIC_FACTOR, metallic) ==
AI_SUCCESS) {
mat.metallic = metallic;
mat.hasMetallic = true;
}
aiColor3D emissive;
if (assimpMaterial->Get(AI_MATKEY_COLOR_EMISSIVE, emissive) == AI_SUCCESS) {
mat.emissive = Vec3{emissive.r, emissive.g, emissive.b};
mat.hasEmissive = true;
}
aiString path;
if (assimpMaterial->GetTexture(aiTextureType_DIFFUSE, 0, &path) ==
aiReturn_SUCCESS) {
mat.mapKd = std::string(path.C_Str());
}
if (assimpMaterial->GetTexture(aiTextureType_HEIGHT, 0, &path) ==
aiReturn_SUCCESS) {
mat.mapBump = std::string(path.C_Str());
}
if (assimpMaterial->GetTexture(aiTextureType_REFLECTION, 0, &path) ==
aiReturn_SUCCESS) {
mat.mapMetallic = std::string(path.C_Str());
}
if (assimpMaterial->GetTexture(aiTextureType_EMISSIVE, 0, &path) ==
aiReturn_SUCCESS) {
mat.mapEnv = std::string(path.C_Str());
}
if (assimpMaterial->GetTexture(aiTextureType_SHININESS, 0, &path) ==
aiReturn_SUCCESS) {
mat.mapKs = std::string(path.C_Str());
}
mesh->m_materials.push_back(mat);
}
UVInfo uvInfo;
std::vector<std::pair<const aiNode *, aiMatrix4x4>> nodeStack;
const aiNode *root = scene->mRootNode;
nodeStack.push_back(std::make_pair(root, root->mTransformation));
while (!nodeStack.empty()) {
auto nodeAndTransform = nodeStack.back();
const aiNode *node = nodeAndTransform.first;
aiMatrix4x4 xform = nodeAndTransform.second;
nodeStack.pop_back();
addAssimpNodeToMesh(scene, node, xform, uvInfo, mesh);
for (unsigned int c = 0; c < node->mNumChildren; ++c) {
const aiNode *child = node->mChildren[c];
nodeStack.push_back(
std::make_pair(child, xform * child->mTransformation));
}
}
return mesh;
}
string GetExtension(const char *path) {
const char *s = strrchr(path, '.');
if (s) {
return string(s + 1);
} else {
return "";
}
}
Mesh *ImportMesh(const char *path) {
std::string ext = GetExtension(path);
Mesh *mesh = nullptr;
if (ext == "ply")
mesh = ImportMeshFromPly(path);
else if (ext == "obj")
mesh = ImportMeshFromObj(path);
else if (ext == "stl")
mesh = ImportMeshFromStl(path);
return mesh;
}
Mesh *ImportMeshFromBin(const char *path) {
// double start = GetSeconds();
FILE *f = fopen(path, "rb");
if (f) {
int numVertices;
int numIndices;
size_t len;
len = fread(&numVertices, sizeof(numVertices), 1, f);
len = fread(&numIndices, sizeof(numIndices), 1, f);
Mesh *m = new Mesh();
m->m_positions.resize(numVertices);
m->m_normals.resize(numVertices);
m->m_indices.resize(numIndices);
len = fread(&m->m_positions[0], sizeof(Vec3) * numVertices, 1, f);
len = fread(&m->m_normals[0], sizeof(Vec3) * numVertices, 1, f);
len = fread(&m->m_indices[0], sizeof(int) * numIndices, 1, f);
(void)len;
fclose(f);
// double end = GetSeconds();
// printf("Imported mesh %s in %f ms\n", path, (end - start) * 1000.0f);
return m;
}
return nullptr;
}
void ExportMeshToBin(const char *path, const Mesh *m) {
FILE *f = fopen(path, "wb");
if (f) {
int numVertices = int(m->m_positions.size());
int numIndices = int(m->m_indices.size());
fwrite(&numVertices, sizeof(numVertices), 1, f);
fwrite(&numIndices, sizeof(numIndices), 1, f);
// write data blocks
fwrite(&m->m_positions[0], sizeof(Vec3) * numVertices, 1, f);
fwrite(&m->m_normals[0], sizeof(Vec3) * numVertices, 1, f);
fwrite(&m->m_indices[0], sizeof(int) * numIndices, 1, f);
fclose(f);
}
}
Mesh *ImportMeshFromPly(const char *path) {
ifstream file(path, ios_base::in | ios_base::binary);
if (!file)
return nullptr;
// some scratch memory
const uint32_t kMaxLineLength = 1024;
char buffer[kMaxLineLength];
// double startTime = GetSeconds();
file >> buffer;
if (strcmp(buffer, "ply") != 0)
return nullptr;
PlyFormat format = eAscii;
uint32_t numFaces = 0;
uint32_t numVertices = 0;
const uint32_t kMaxProperties = 16;
uint32_t numProperties = 0;
float properties[kMaxProperties];
bool vertexElement = false;
while (file) {
file >> buffer;
if (strcmp(buffer, "element") == 0) {
file >> buffer;
if (strcmp(buffer, "face") == 0) {
vertexElement = false;
file >> numFaces;
}
else if (strcmp(buffer, "vertex") == 0) {
vertexElement = true;
file >> numVertices;
}
} else if (strcmp(buffer, "format") == 0) {
file >> buffer;
if (strcmp(buffer, "ascii") == 0) {
format = eAscii;
} else if (strcmp(buffer, "binary_big_endian") == 0) {
format = eBinaryBigEndian;
} else {
printf("Ply: unknown format\n");
return nullptr;
}
} else if (strcmp(buffer, "property") == 0) {
if (vertexElement)
++numProperties;
} else if (strcmp(buffer, "end_header") == 0) {
break;
}
}
// eat newline
char nl;
file.read(&nl, 1);
// debug
#if ENABLE_VERBOSE_OUTPUT
printf("Loaded mesh: %s numFaces: %d numVertices: %d format: %d "
"numProperties: %d\n",
path, numFaces, numVertices, format, numProperties);
#endif
Mesh *mesh = new Mesh;
mesh->m_positions.resize(numVertices);
mesh->m_normals.resize(numVertices);
mesh->m_colours.resize(numVertices, Colour(1.0f, 1.0f, 1.0f, 1.0f));
mesh->m_indices.reserve(numFaces * 3);
// read vertices
for (uint32_t v = 0; v < numVertices; ++v) {
for (uint32_t i = 0; i < numProperties; ++i) {
properties[i] = PlyRead<float>(file, format);
}
mesh->m_positions[v] = Point3(properties[0], properties[1], properties[2]);
mesh->m_normals[v] = Vector3(0.0f, 0.0f, 0.0f);
}
// read indices
for (uint32_t f = 0; f < numFaces; ++f) {
uint32_t numIndices = (format == eAscii) ? PlyRead<uint32_t>(file, format)
: PlyRead<uint8_t>(file, format);
uint32_t indices[4];
for (uint32_t i = 0; i < numIndices; ++i) {
indices[i] = PlyRead<uint32_t>(file, format);
}
switch (numIndices) {
case 3:
mesh->m_indices.push_back(indices[0]);
mesh->m_indices.push_back(indices[1]);
mesh->m_indices.push_back(indices[2]);
break;
case 4:
mesh->m_indices.push_back(indices[0]);
mesh->m_indices.push_back(indices[1]);
mesh->m_indices.push_back(indices[2]);
mesh->m_indices.push_back(indices[2]);
mesh->m_indices.push_back(indices[3]);
mesh->m_indices.push_back(indices[0]);
break;
default:
assert(!"invalid number of indices, only support tris and quads");
break;
};
// calculate vertex normals as we go
Point3 &v0 = mesh->m_positions[indices[0]];
Point3 &v1 = mesh->m_positions[indices[1]];
Point3 &v2 = mesh->m_positions[indices[2]];
Vector3 n =
SafeNormalize(Cross(v1 - v0, v2 - v0), Vector3(0.0f, 1.0f, 0.0f));
for (uint32_t i = 0; i < numIndices; ++i) {
mesh->m_normals[indices[i]] += n;
}
}
for (uint32_t i = 0; i < numVertices; ++i) {
mesh->m_normals[i] =
SafeNormalize(mesh->m_normals[i], Vector3(0.0f, 1.0f, 0.0f));
}
// cout << "Imported mesh " << path << " in " <<
// (GetSeconds()-startTime)*1000.f << "ms" << endl;
return mesh;
}
// map of Material name to Material
struct VertexKey {
VertexKey() : v(0), vt(0), vn(0) {}
uint32_t v, vt, vn;
bool operator==(const VertexKey &rhs) const {
return v == rhs.v && vt == rhs.vt && vn == rhs.vn;
}
bool operator<(const VertexKey &rhs) const {
if (v != rhs.v)
return v < rhs.v;
else if (vt != rhs.vt)
return vt < rhs.vt;
else
return vn < rhs.vn;
}
};
void ImportFromMtlLib(const char *path, std::vector<Material> &materials) {
FILE *f = fopen(path, "r");
const int kMaxLineLength = 1024;
if (f) {
char line[kMaxLineLength];
while (fgets(line, kMaxLineLength, f)) {
char name[kMaxLineLength];
if (sscanf(line, " newmtl %s", name) == 1) {
Material mat;
mat.name = name;
materials.push_back(mat);
}
if (materials.size()) {
Material &mat = materials.back();
sscanf(line, " Ka %f %f %f", &mat.Ka.x, &mat.Ka.y, &mat.Ka.z);
sscanf(line, " Kd %f %f %f", &mat.Kd.x, &mat.Kd.y, &mat.Kd.z);
sscanf(line, " Ks %f %f %f", &mat.Ks.x, &mat.Ks.y, &mat.Ks.z);
sscanf(line, " Ns %f", &mat.Ns);
sscanf(line, " metallic %f", &mat.metallic);
char map[kMaxLineLength];
if (sscanf(line, " map_Kd %s", map) == 1)
mat.mapKd = map;
if (sscanf(line, " map_Ks %s", map) == 1)
mat.mapKs = map;
if (sscanf(line, " map_bump %s", map) == 1)
mat.mapBump = map;
if (sscanf(line, " map_env %s", map) == 1)
mat.mapEnv = map;
}
}
fclose(f);
}
}
Mesh *ImportMeshFromObj(const char *meshPath) {
ifstream file(meshPath);
if (!file)
return nullptr;
Mesh *m = new Mesh();
vector<Point3> positions;
vector<Vector3> normals;
vector<Vector2> texcoords;
vector<Vector3> colors;
vector<uint32_t> &indices = m->m_indices;
// typedef unordered_map<VertexKey, uint32_t, MemoryHash<VertexKey> >
// VertexMap;
typedef map<VertexKey, uint32_t> VertexMap;
VertexMap vertexLookup;
// some scratch memory
const uint32_t kMaxLineLength = 1024;
char buffer[kMaxLineLength];
// double startTime = GetSeconds();
file >> buffer;
while (!file.eof()) {
if (strcmp(buffer, "vn") == 0) {
// normals
float x, y, z;
file >> x >> y >> z;
normals.push_back(Vector3(x, y, z));
} else if (strcmp(buffer, "vt") == 0) {
// texture coords
float u, v;
file >> u >> v;
texcoords.push_back(Vector2(u, v));
} else if (buffer[0] == 'v') {
// positions
float x, y, z;
file >> x >> y >> z;
positions.push_back(Point3(x, y, z));
} else if (buffer[0] == 's' || buffer[0] == 'g' || buffer[0] == 'o') {
// ignore smoothing groups, groups and objects
char linebuf[256];
file.getline(linebuf, 256);
} else if (strcmp(buffer, "mtllib") == 0) {
std::string materialFile;
file >> materialFile;
char materialPath[2048];
MakeRelativePath(meshPath, materialFile.c_str(), materialPath);
ImportFromMtlLib(materialPath, m->m_materials);
} else if (strcmp(buffer, "usemtl") == 0) {
// read Material name, ignored right now
std::string materialName;
file >> materialName;
// if there was a previous assignment then close it
if (m->m_materialAssignments.size())
m->m_materialAssignments.back().endTri = int(indices.size() / 3);
// generate assignment
MaterialAssignment batch;
batch.startTri = int(indices.size() / 3);
batch.material = -1;
for (int i = 0; i < (int)m->m_materials.size(); ++i) {
if (m->m_materials[i].name == materialName) {
batch.material = i;
break;
}
}
if (batch.material == -1)
printf(".obj references material not found in .mtl library, %s\n",
materialName.c_str());
else {
// push back assignment
m->m_materialAssignments.push_back(batch);
}
} else if (buffer[0] == 'f') {
// faces
uint32_t faceIndices[4];
uint32_t faceIndexCount = 0;
for (int i = 0; i < 4; ++i) {
VertexKey key;
file >> key.v;
// failed to read another index continue on
if (file.fail()) {
file.clear();
break;
}
if (file.peek() == '/') {
file.ignore();
if (file.peek() != '/') {
file >> key.vt;
}
if (file.peek() == '/') {
file.ignore();
file >> key.vn;
}
}
// find / add vertex, index
VertexMap::iterator iter = vertexLookup.find(key);
if (iter != vertexLookup.end()) {
faceIndices[faceIndexCount++] = iter->second;
} else {
// add vertex
uint32_t newIndex = uint32_t(m->m_positions.size());
faceIndices[faceIndexCount++] = newIndex;
vertexLookup.insert(make_pair(key, newIndex));
// push back vertex data
assert(key.v > 0);
m->m_positions.push_back(positions[key.v - 1]);
// obj format doesn't support mesh colours so add default value
m->m_colours.push_back(Colour(1.0f, 1.0f, 1.0f));
// normal
if (key.vn) {
m->m_normals.push_back(normals[key.vn - 1]);
} else {
m->m_normals.push_back(0.0f);
}
// texcoord
if (key.vt) {
m->m_texcoords.push_back(texcoords[key.vt - 1]);
} else {
m->m_texcoords.push_back(0.0f);
}
}
}
if (faceIndexCount < 3) {
cout << "File contains face(s) with less than 3 vertices" << endl;
} else if (faceIndexCount == 3) {
// a triangle
indices.insert(indices.end(), faceIndices, faceIndices + 3);
} else if (faceIndexCount == 4) {
// a quad, triangulate clockwise
indices.insert(indices.end(), faceIndices, faceIndices + 3);
indices.push_back(faceIndices[2]);
indices.push_back(faceIndices[3]);
indices.push_back(faceIndices[0]);
} else {
cout << "Face with more than 4 vertices are not supported" << endl;
}
} else if (buffer[0] == '#') {
// comment
char linebuf[256];
file.getline(linebuf, 256);
}
file >> buffer;
}
// calculate normals if none specified in file
m->m_normals.resize(m->m_positions.size());
const uint32_t numFaces = uint32_t(indices.size()) / 3;
for (uint32_t i = 0; i < numFaces; ++i) {
uint32_t a = indices[i * 3 + 0];
uint32_t b = indices[i * 3 + 1];
uint32_t c = indices[i * 3 + 2];
Point3 &v0 = m->m_positions[a];
Point3 &v1 = m->m_positions[b];
Point3 &v2 = m->m_positions[c];
Vector3 n =
SafeNormalize(Cross(v1 - v0, v2 - v0), Vector3(0.0f, 1.0f, 0.0f));
m->m_normals[a] += n;
m->m_normals[b] += n;
m->m_normals[c] += n;
}
for (uint32_t i = 0; i < m->m_normals.size(); ++i) {
m->m_normals[i] = SafeNormalize(m->m_normals[i], Vector3(0.0f, 1.0f, 0.0f));
}
// close final material assignment
if (m->m_materialAssignments.size())
m->m_materialAssignments.back().endTri = int(indices.size()) / 3;
// cout << "Imported mesh " << meshPath << " in " <<
// (GetSeconds()-startTime)*1000.f << "ms" << endl;
return m;
}
void ExportToObj(const char *path, const Mesh &m) {
ofstream file(path);
if (!file)
return;
file << "# positions" << endl;
for (uint32_t i = 0; i < m.m_positions.size(); ++i) {
Point3 v = m.m_positions[i];
file << "v " << v.x << " " << v.y << " " << v.z << endl;
}
file << "# texcoords" << endl;
for (uint32_t i = 0; i < m.m_texcoords.size(); ++i) {
Vec2 t = m.m_texcoords[0][i];
file << "vt " << t.x << " " << t.y << endl;
}
file << "# normals" << endl;
for (uint32_t i = 0; i < m.m_normals.size(); ++i) {
Vec3 n = m.m_normals[0][i];
file << "vn " << n.x << " " << n.y << " " << n.z << endl;
}
file << "# faces" << endl;
for (uint32_t i = 0; i < m.m_indices.size() / 3; ++i) {
// uint32_t j = i+1;
// no sharing, assumes there is a unique position, texcoord and normal for
// each vertex
file << "f " << m.m_indices[i * 3] + 1 << " " << m.m_indices[i * 3 + 1] + 1
<< " " << m.m_indices[i * 3 + 2] + 1 << endl;
}
}
Mesh *ImportMeshFromStl(const char *path) {
// double start = GetSeconds();
FILE *f = fopen(path, "rb");
if (f) {
char header[80];
fread(header, 80, 1, f);
int numTriangles;
fread(&numTriangles, sizeof(int), 1, f);
Mesh *m = new Mesh();
m->m_positions.resize(numTriangles * 3);
m->m_normals.resize(numTriangles * 3);
m->m_indices.resize(numTriangles * 3);
Point3 *vertexPtr = m->m_positions.data();
Vector3 *normalPtr = m->m_normals.data();
uint32_t *indexPtr = m->m_indices.data();
for (int t = 0; t < numTriangles; ++t) {
Vector3 n;
Point3 v0, v1, v2;
uint16_t attributeByteCount;
fread(&n, sizeof(Vector3), 1, f);
fread(&v0, sizeof(Point3), 1, f);
fread(&v1, sizeof(Point3), 1, f);
fread(&v2, sizeof(Point3), 1, f);
fread(&attributeByteCount, sizeof(uint16_t), 1, f);
*(normalPtr++) = n;
*(normalPtr++) = n;
*(normalPtr++) = n;
*(vertexPtr++) = v0;
*(vertexPtr++) = v1;
*(vertexPtr++) = v2;
*(indexPtr++) = t * 3 + 0;
*(indexPtr++) = t * 3 + 1;
*(indexPtr++) = t * 3 + 2;
}
fclose(f);
// double end = GetSeconds();
// printf("Imported mesh %s in %f ms\n", path, (end - start) * 1000.0f);
return m;
}
return nullptr;
}
void Mesh::AddMesh(const Mesh &m) {
uint32_t offset = uint32_t(m_positions.size());
// add new vertices
m_positions.insert(m_positions.end(), m.m_positions.begin(),
m.m_positions.end());
m_normals.insert(m_normals.end(), m.m_normals.begin(), m.m_normals.end());
m_colours.insert(m_colours.end(), m.m_colours.begin(), m.m_colours.end());
// add new indices with offset
for (uint32_t i = 0; i < m.m_indices.size(); ++i) {
m_indices.push_back(m.m_indices[i] + offset);
}
}
void Mesh::Flip() {
for (int i = 0; i < int(GetNumFaces()); ++i) {
swap(m_indices[i * 3 + 0], m_indices[i * 3 + 1]);
}
for (int i = 0; i < (int)m_normals.size(); ++i)
m_normals[i] *= -1.0f;
}
void Mesh::Transform(const Matrix44 &m) {
for (uint32_t i = 0; i < m_positions.size(); ++i) {
m_positions[i] = m * m_positions[i];
m_normals[i] = m * m_normals[i];
}
}
void Mesh::GetBounds(Vector3 &outMinExtents, Vector3 &outMaxExtents) const {
Point3 minExtents(FLT_MAX);
Point3 maxExtents(-FLT_MAX);
// calculate face bounds
for (uint32_t i = 0; i < m_positions.size(); ++i) {
const Point3 &a = m_positions[i];
minExtents = Min(a, minExtents);
maxExtents = Max(a, maxExtents);
}
outMinExtents = Vector3(minExtents);
outMaxExtents = Vector3(maxExtents);
}
Mesh *CreateTriMesh(float size, float y) {
uint32_t indices[] = {0, 1, 2};
Point3 positions[3];
Vector3 normals[3];
positions[0] = Point3(-size, y, size);
positions[1] = Point3(size, y, size);
positions[2] = Point3(size, y, -size);
normals[0] = Vector3(0.0f, 1.0f, 0.0f);
normals[1] = Vector3(0.0f, 1.0f, 0.0f);
normals[2] = Vector3(0.0f, 1.0f, 0.0f);
Mesh *m = new Mesh();
m->m_indices.insert(m->m_indices.begin(), indices, indices + 3);
m->m_positions.insert(m->m_positions.begin(), positions, positions + 3);
m->m_normals.insert(m->m_normals.begin(), normals, normals + 3);
return m;
}
Mesh *CreateCubeMesh() {
const Point3 vertices[24] = {
Point3(0.5, 0.5, 0.5), Point3(-0.5, 0.5, 0.5),
Point3(0.5, -0.5, 0.5), Point3(-0.5, -0.5, 0.5),
Point3(0.5, 0.5, -0.5), Point3(-0.5, 0.5, -0.5),
Point3(0.5, -0.5, -0.5), Point3(-0.5, -0.5, -0.5),
Point3(0.5, 0.5, 0.5), Point3(0.5, -0.5, 0.5),
Point3(0.5, 0.5, 0.5), Point3(0.5, 0.5, -0.5),
Point3(-0.5, 0.5, 0.5), Point3(-0.5, 0.5, -0.5),
Point3(0.5, -0.5, -0.5), Point3(0.5, 0.5, -0.5),
Point3(-0.5, -0.5, -0.5), Point3(0.5, -0.5, -0.5),
Point3(-0.5, -0.5, 0.5), Point3(0.5, -0.5, 0.5),
Point3(-0.5, -0.5, -0.5), Point3(-0.5, -0.5, 0.5),
Point3(-0.5, 0.5, -0.5), Point3(-0.5, 0.5, 0.5)};
const Vec3 normals[24] = {Vec3(0.0f, 0.0f, 1.0f), Vec3(0.0f, 0.0f, 1.0f),
Vec3(0.0f, 0.0f, 1.0f), Vec3(0.0f, 0.0f, 1.0f),
Vec3(1.0f, 0.0f, 0.0f), Vec3(0.0f, 1.0f, 0.0f),
Vec3(1.0f, 0.0f, 0.0f), Vec3(0.0f, 0.0f, -1.0f),
Vec3(1.0f, 0.0f, 0.0f), Vec3(1.0f, 0.0f, 0.0f),
Vec3(0.0f, 1.0f, 0.0f), Vec3(0.0f, 1.0f, 0.0f),
Vec3(0.0f, 1.0f, 0.0f), Vec3(0.0f, 0.0f, -1.0f),
Vec3(0.0f, 0.0f, -1.0f), Vec3(-0.0f, -0.0f, -1.0f),
Vec3(0.0f, -1.0f, 0.0f), Vec3(0.0f, -1.0f, 0.0f),
Vec3(0.0f, -1.0f, 0.0f), Vec3(-0.0f, -1.0f, -0.0f),
Vec3(-1.0f, 0.0f, 0.0f), Vec3(-1.0f, 0.0f, 0.0f),
Vec3(-1.0f, 0.0f, 0.0f), Vec3(-1.0f, -0.0f, -0.0f)};
const int indices[36] = {0, 1, 2, 3, 2, 1, 8, 9, 4, 6, 4, 9,
10, 11, 12, 5, 12, 11, 7, 13, 14, 15, 14, 13,
16, 17, 18, 19, 18, 17, 20, 21, 22, 23, 22, 21};
Mesh *m = new Mesh();
m->m_positions.assign(vertices, vertices + 24);
m->m_normals.assign(normals, normals + 24);
m->m_indices.assign(indices, indices + 36);
return m;
}
Mesh *CreateQuadMesh(float sizex, float sizez, int gridx, int gridz) {
Mesh *m = new Mesh();
float cellx = sizex / gridz;
float cellz = sizez / gridz;
Vec3 start = Vec3(-sizex, 0.0f, sizez) * 0.5f;
for (int z = 0; z <= gridz; ++z) {
for (int x = 0; x <= gridx; ++x) {
Point3 p = Point3(cellx * x, 0.0f, -cellz * z) + start;
m->m_positions.push_back(p);
m->m_normals.push_back(Vec3(0.0f, 1.0f, 0.0f));
m->m_texcoords.push_back(Vec2(float(x) / gridx, float(z) / gridz));
if (z > 0 && x > 0) {
int index = int(m->m_positions.size()) - 1;
m->m_indices.push_back(index);
m->m_indices.push_back(index - 1);
m->m_indices.push_back(index - gridx - 1);
m->m_indices.push_back(index - 1);
m->m_indices.push_back(index - 1 - gridx - 1);
m->m_indices.push_back(index - gridx - 1);
}
}
}
return m;
}
Mesh *CreateDiscMesh(float radius, uint32_t segments) {
const uint32_t numVerts = 1 + segments;
Mesh *m = new Mesh();
m->m_positions.resize(numVerts);
m->m_normals.resize(numVerts, Vec3(0.0f, 1.0f, 0.0f));
m->m_positions[0] = Point3(0.0f);
m->m_positions[1] = Point3(0.0f, 0.0f, radius);
for (uint32_t i = 1; i <= segments; ++i) {
uint32_t nextVert = (i + 1) % numVerts;
if (nextVert == 0)
nextVert = 1;
m->m_positions[nextVert] =
Point3(radius * Sin((float(i) / segments) * k2Pi), 0.0f,
radius * Cos((float(i) / segments) * k2Pi));
m->m_indices.push_back(0);
m->m_indices.push_back(i);
m->m_indices.push_back(nextVert);
}
return m;
}
Mesh *CreateTetrahedron(float ground, float height) {
Mesh *m = new Mesh();
const float dimValue = 1.0f / sqrtf(2.0f);
const Point3 vertices[4] = {
Point3(-1.0f, ground, -dimValue), Point3(1.0f, ground, -dimValue),
Point3(0.0f, ground + height, dimValue), Point3(0.0f, ground, dimValue)};
const int indices[12] = {// winding order is counter-clockwise
0, 2, 1, 2, 3, 1, 2, 0, 3, 3, 0, 1};
m->m_positions.assign(vertices, vertices + 4);
m->m_indices.assign(indices, indices + 12);
m->CalculateNormals();
return m;
}
Mesh *CreateCylinder(int slices, float radius, float halfHeight, bool cap) {
Mesh *mesh = new Mesh();
for (int i = 0; i <= slices; ++i) {
float theta = (k2Pi / slices) * i;
Vec3 p = Vec3(sinf(theta), 0.0f, cosf(theta));
Vec3 n = p;
mesh->m_positions.push_back(
Point3(p * radius - Vec3(0.0f, halfHeight, 0.0f)));
mesh->m_positions.push_back(
Point3(p * radius + Vec3(0.0f, halfHeight, 0.0f)));
mesh->m_normals.push_back(n);
mesh->m_normals.push_back(n);
mesh->m_texcoords.push_back(Vec2(2.0f * float(i) / slices, 0.0f));
mesh->m_texcoords.push_back(Vec2(2.0f * float(i) / slices, 1.0f));
if (i > 0) {
int a = (i - 1) * 2 + 0;
int b = (i - 1) * 2 + 1;
int c = i * 2 + 0;
int d = i * 2 + 1;
// quad between last two vertices and these two
mesh->m_indices.push_back(a);
mesh->m_indices.push_back(c);
mesh->m_indices.push_back(b);
mesh->m_indices.push_back(c);
mesh->m_indices.push_back(d);
mesh->m_indices.push_back(b);
}
}
if (cap) {
// Create cap
int st = int(mesh->m_positions.size());
mesh->m_positions.push_back(-Point3(0.0f, halfHeight, 0.0f));
mesh->m_texcoords.push_back(Vec2(0.0f, 0.0f));
mesh->m_normals.push_back(-Vec3(0.0f, 1.0f, 0.0f));
for (int i = 0; i <= slices; ++i) {
float theta = -(k2Pi / slices) * i;
Vec3 p = Vec3(sinf(theta), 0.0f, cosf(theta));
mesh->m_positions.push_back(
Point3(p * radius - Vec3(0.0f, halfHeight, 0.0f)));
mesh->m_normals.push_back(-Vec3(0.0f, 1.0f, 0.0f));
mesh->m_texcoords.push_back(Vec2(2.0f * float(i) / slices, 0.0f));
if (i > 0) {
mesh->m_indices.push_back(st);
mesh->m_indices.push_back(st + 1 + i - 1);
mesh->m_indices.push_back(st + 1 + i % slices);
}
}
st = int(mesh->m_positions.size());
mesh->m_positions.push_back(Point3(0.0f, halfHeight, 0.0f));
mesh->m_texcoords.push_back(Vec2(0.0f, 0.0f));
mesh->m_normals.push_back(Vec3(0.0f, 1.0f, 0.0f));
for (int i = 0; i <= slices; ++i) {
float theta = (k2Pi / slices) * i;
Vec3 p = Vec3(sinf(theta), 0.0f, cosf(theta));
mesh->m_positions.push_back(
Point3(p * radius + Vec3(0.0f, halfHeight, 0.0f)));
mesh->m_normals.push_back(Vec3(0.0f, 1.0f, 0.0f));
mesh->m_texcoords.push_back(Vec2(2.0f * float(i) / slices, 0.0f));
if (i > 0) {
mesh->m_indices.push_back(st);
mesh->m_indices.push_back(st + 1 + i - 1);
mesh->m_indices.push_back(st + 1 + i % slices);
}
}
}
return mesh;
}
Mesh *CreateSphere(int slices, int segments, float radius) {
float dTheta = kPi / slices;
float dPhi = k2Pi / segments;
int vertsPerRow = segments + 1;
Mesh *mesh = new Mesh();
for (int i = 0; i <= slices; ++i) {
for (int j = 0; j <= segments; ++j) {
float u = float(i) / slices;
float v = float(j) / segments;
float theta = dTheta * i;
float phi = dPhi * j;
float x = sinf(theta) * cosf(phi);
float y = cosf(theta);
float z = sinf(theta) * sinf(phi);
mesh->m_positions.push_back(Point3(x, y, z) * radius);
mesh->m_normals.push_back(Vec3(x, y, z));
mesh->m_texcoords.push_back(Vec2(u, v));
if (i > 0 && j > 0) {
int a = i * vertsPerRow + j;
int b = (i - 1) * vertsPerRow + j;
int c = (i - 1) * vertsPerRow + j - 1;
int d = i * vertsPerRow + j - 1;
// add a quad for this slice
mesh->m_indices.push_back(b);
mesh->m_indices.push_back(a);
mesh->m_indices.push_back(d);
mesh->m_indices.push_back(b);
mesh->m_indices.push_back(d);
mesh->m_indices.push_back(c);
}
}
}
return mesh;
}
Mesh *CreateEllipsoid(int slices, int segments, Vec3 radiis) {
float dTheta = kPi / slices;
float dPhi = k2Pi / segments;
int vertsPerRow = segments + 1;
Mesh *mesh = new Mesh();
for (int i = 0; i <= slices; ++i) {
for (int j = 0; j <= segments; ++j) {
float u = float(i) / slices;
float v = float(j) / segments;
float theta = dTheta * i;
float phi = dPhi * j;
float x = sinf(theta) * cosf(phi);
float y = cosf(theta);
float z = sinf(theta) * sinf(phi);
mesh->m_positions.push_back(
Point3(x * radiis.x, y * radiis.y, z * radiis.z));
mesh->m_normals.push_back(
Normalize(Vec3(x / radiis.x, y / radiis.y, z / radiis.z)));
mesh->m_texcoords.push_back(Vec2(u, v));
if (i > 0 && j > 0) {
int a = i * vertsPerRow + j;
int b = (i - 1) * vertsPerRow + j;
int c = (i - 1) * vertsPerRow + j - 1;
int d = i * vertsPerRow + j - 1;
// add a quad for this slice
mesh->m_indices.push_back(b);
mesh->m_indices.push_back(a);
mesh->m_indices.push_back(d);
mesh->m_indices.push_back(b);
mesh->m_indices.push_back(d);
mesh->m_indices.push_back(c);
}
}
}
return mesh;
}
Mesh *CreateCapsule(int slices, int segments, float radius, float halfHeight) {
float dTheta = kPi / (slices * 2);
float dPhi = k2Pi / segments;
int vertsPerRow = segments + 1;
Mesh *mesh = new Mesh();
float theta = 0.0f;
for (int i = 0; i <= 2 * slices + 1; ++i) {
for (int j = 0; j <= segments; ++j) {
float phi = dPhi * j;
float x = sinf(theta) * cosf(phi);
float y = cosf(theta);
float z = sinf(theta) * sinf(phi);
// add y offset based on which hemisphere we're in
float yoffset = (i < slices) ? halfHeight : -halfHeight;
Point3 p = Point3(x, y, z) * radius + Vec3(0.0f, yoffset, 0.0f);
float u = float(j) / segments;
float v = (halfHeight + radius + float(p.y)) / fabsf(halfHeight + radius);
mesh->m_positions.push_back(p);
mesh->m_normals.push_back(Vec3(x, y, z));
mesh->m_texcoords.push_back(Vec2(u, v));
if (i > 0 && j > 0) {
int a = i * vertsPerRow + j;
int b = (i - 1) * vertsPerRow + j;
int c = (i - 1) * vertsPerRow + j - 1;
int d = i * vertsPerRow + j - 1;
// add a quad for this slice
mesh->m_indices.push_back(b);
mesh->m_indices.push_back(a);
mesh->m_indices.push_back(d);
mesh->m_indices.push_back(b);
mesh->m_indices.push_back(d);
mesh->m_indices.push_back(c);
}
}
// don't update theta for the middle slice
if (i != slices)
theta += dTheta;
}
return mesh;
}
| 40,304 | C++ | 27.646055 | 99 | 0.565626 |
NVIDIA-Omniverse/mjcf-importer-extension/source/extensions/omni.importer.mjcf/plugins/utils/Path.h | // SPDX-FileCopyrightText: Copyright (c) 2023 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
// SPDX-License-Identifier: Apache-2.0
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#pragma once
// clang-format off
#include "../UsdPCH.h"
// clang-format on
#include <OmniClient.h>
#include <carb/logging/Log.h>
#include <string>
namespace omni {
namespace isaac {
namespace utils {
namespace path {
inline std::string normalizeUrl(const char *url) {
std::string ret;
char stringBuffer[1024];
std::unique_ptr<char[]> stringBufferHeap;
size_t bufferSize = sizeof(stringBuffer);
const char *normalizedUrl =
omniClientNormalizeUrl(url, stringBuffer, &bufferSize);
if (!normalizedUrl) {
stringBufferHeap = std::unique_ptr<char[]>(new char[bufferSize]);
normalizedUrl =
omniClientNormalizeUrl(url, stringBufferHeap.get(), &bufferSize);
if (!normalizedUrl) {
normalizedUrl = "";
CARB_LOG_ERROR("Cannot normalize %s", url);
}
}
ret = normalizedUrl;
for (auto &c : ret) {
if (c == '\\') {
c = '/';
}
}
return ret;
}
std::string resolve_absolute(std::string parent, std::string relative) {
size_t bufferSize = parent.size() + relative.size();
std::unique_ptr<char[]> stringBuffer =
std::unique_ptr<char[]>(new char[bufferSize]);
std::string combined_url = normalizeUrl((parent + "/" + relative).c_str());
return combined_url;
}
} // namespace path
} // namespace utils
} // namespace isaac
} // namespace omni
| 2,011 | C | 28.15942 | 99 | 0.692193 |
NVIDIA-Omniverse/mjcf-importer-extension/source/extensions/omni.importer.mjcf/docs/CHANGELOG.md | # Changelog
## [1.1.0] - 2023-10-03
### Changed
- Structural and packaging changes
## [1.0.1] - 2023-07-07
### Added
- Support for `autolimits` compiler setting for joints
## [1.0.0] - 2023-06-13
### Changed
- Renamed the extension to omni.importer.mjcf
- Published the extension to the default registry
## [0.5.0] - 2023-05-09
### Added
- Support for ball and free joint
- Support for `<freejoint>` tag
- Support for plane geom type
- Support for intrinsic Euler sequences
### Changed
- Default value for fix_base is now false
- Root bodies no longer have their translation automatically set to the origin
- Visualize collision geom option now sets collision geom's visibility to invisible
- Change prim hierarchy to support multiple world body level prims
### Fixed
- Fix support for full inertia matrix
- Fix collision geom for ellipsoid prim
- Fix zaxis orientation parsing
- Fix 2D texture by enabling UVW projection
## [0.4.1] - 2023-05-02
### Added
- High level code overview in README.md
## [0.4.0] - 2023-03-27
### Added
- Support for sites and spatial tendons
- Support for specifying mesh root directory
## [0.3.1] - 2023-01-06
### Fixed
- onclick_fn warning when creating UI
## [0.3.0] - 2022-10-13
### Added
- Added material and texture support
## [0.2.3] - 2022-09-07
### Fixed
- Fixes for kit 103.5
## [0.2.2] - 2022-07-21
### Added
- Add armature to joints
## [0.2.1] - 2022-07-21
### Fixed
- Display Bookmarks when selecting files
## [0.2.0] - 2022-06-30
### Added
- Add instanceable option to importer
## [0.1.3] - 2022-05-17
### Added
- Add joint values API
## [0.1.2] - 2022-05-10
### Changed
- Collision filtering now uses filteredPairsAPI instead of collision groups
- Adding tendons no longer has limitations on the number of joints per tendon and the order of the joints
## [0.1.1] - 2022-04-14
### Added
- Joint name annotation USD attribute for preserving joint names
### Fixed
- Correctly parse distance scaling from UI
## [0.1.0] - 2022-02-07
### Added
- Initial version of MJCF importer extension
| 2,053 | Markdown | 20.621052 | 105 | 0.701413 |
NVIDIA-Omniverse/mjcf-importer-extension/source/extensions/omni.importer.mjcf/docs/index.rst | MJCF Importer Extension [omni.importer.mjcf]
############################################
MJCF Import Commands
====================
The following commands can be used to simplify the import process.
Below is a sample demonstrating how to import the Ant MJCF included with this extension
.. code-block:: python
:linenos:
import omni.kit.commands
from pxr import UsdLux, Sdf, Gf, UsdPhysics, PhysicsSchemaTools
# setting up import configuration:
status, import_config = omni.kit.commands.execute("MJCFCreateImportConfig")
import_config.set_fix_base(True)
import_config.set_import_inertia_tensor(True)
# Get path to extension data:
ext_manager = omni.kit.app.get_app().get_extension_manager()
ext_id = ext_manager.get_enabled_extension_id("omni.importer.mjcf")
extension_path = ext_manager.get_extension_path(ext_id)
# import MJCF
omni.kit.commands.execute(
"MJCFCreateAsset",
mjcf_path=extension_path + "/data/mjcf/nv_ant.xml",
import_config=import_config,
prim_path="/ant"
)
# get stage handle
stage = omni.usd.get_context().get_stage()
# enable physics
scene = UsdPhysics.Scene.Define(stage, Sdf.Path("/physicsScene"))
# set gravity
scene.CreateGravityDirectionAttr().Set(Gf.Vec3f(0.0, 0.0, -1.0))
scene.CreateGravityMagnitudeAttr().Set(9.81)
# add lighting
distantLight = UsdLux.DistantLight.Define(stage, Sdf.Path("/DistantLight"))
distantLight.CreateIntensityAttr(500)
.. automodule:: omni.importer.mjcf.scripts.commands
:members:
:undoc-members:
:exclude-members: do, undo
.. automodule:: omni.importer.mjcf._mjcf
.. autoclass:: omni.importer.mjcf._mjcf.Mjcf
:members:
:undoc-members:
:no-show-inheritance:
.. autoclass:: omni.importer.mjcf._mjcf.ImportConfig
:members:
:undoc-members:
:no-show-inheritance:
| 1,890 | reStructuredText | 29.015873 | 87 | 0.675132 |
NVIDIA-Omniverse/mjcf-importer-extension/source/extensions/omni.importer.mjcf/docs/Overview.md | # Usage
To enable this extension, go to the Extension Manager menu and enable omni.importer.mjcf extension.
# High Level Code Overview
## Python
The `MJCF Importer` extension sets attributes of `ImportConfig` on initialization,
along with the UI giving the user options to change certain attributes, such as `set_fix_base`.
The complete list of configs can be found in `bindings/BindingsMjcfPython.cpp`.
In `python/scripts/commands.py`, `MJCFCreateAsset` defines a command that takes
in `ImportConfig` and file path/usd path related to the desired MJCF file to import;
it then calls `self._mjcf_interface.create_asset_mjcf`, which binds to
the C++ function `createAssetFromMJCF` in `plugins/Mjcf.cpp`.
## C++
`plugins/Mjcf.cpp` contains the `createAssetFromMJCF` function, which is the entry
point to parsing the MJCF file and converting it to a USD file. In this function, it
initializes the `MJCFImporter` class from `plugins/MJCFImporter.cpp` which parses the MJCF file,
sets up a UsdStage in accordance with the import config settings, creates the parsed entities
to the stage via `MJCFImporter::AddPhysicsEntities`, and saves the stage if specified in the config.
Upon initialization of the `MJFImporter` class, it parses the given MJCF file by mainly utilziing
functions from `plugins/MjcfParser.cpp` as follows:
- Initializes various buffers to contain bodies, actuators, tendons, etc.
- Calls `LoadFile`, which parses the xml file using tinyxml2 and returns the root element.
- Calls `LoadInclude`, which parses any xml file referenced using the `<include filename='...'>` tag
- Calls `LoadGlobals`, which performs the majority of the parsing by saving all bodies, actuators,
tendons, contact pairs, etc. and their associated settings into classes (defined in `plugins/MjcfTypes.h`)
to be converted into USD assets later on. Details of this function are described in a seperate section below.
- Calls `populateBodyLookup` recursively to go through all bodies in the kinematic tree and populates `nameToBody`,
which maps from the body name to its `MJCFBody`. It also records all the geometries that participate in collision in `geomNameToIdx` and `collisionGeoms`, which are used to populate a contact graph later on.
- Calls `computeKinematicHierarchy`, which runs breadth-first search on the kinematic tree to determine the depth
of each body on the kinematic tree. For instance, the root body has a depth of 0 and its children have a depth of 1, etc.
This information is used to determine the parent-child relationship of the bodies, which is used later on when importing
tendons to USD.
- Calls `createContactGraph` to populate a graph where each node represents a body that participates in collisions and its
neighboring nodes are the bodies that it can collide with.
`LoadGlobals` from `plugins/MjcfParser.cpp`:
- Calls `LoadCompiler`, which saves settings defined in the `<compiler>` tag into the `MJCFCompiler` class.
`MJCFCompiler` contains attributes such as the unit of measurement of angles (rad/deg), the mesh directory
path, the Euler rotation sequence (xyz/zyx/etc.).
- Parses the `<default>` tags, which calls `LoadDefault` and saves settings for bodies, actuators, tendons,
etc into an `MJCFClass` for each default tag. Note that `LoadDefault` is recursively called to deal with
nested `<default>` tags.
- Calls `LoadAssets`, which saves data regarding meshes and textures into the `MJCFMesh` and `MJCFTexture` classes respectively.
- Finds the `<worldbody>` tag, which defines the origin of the world frame within which the rest of the kinematic tree is defined. From there, it calls `LoadInclude` to load any included file and then calls `LoadBody` recursively
to save data regarding the kinematic tree into the `MJCFBody` class. It also calls `LoadGeom` and `LoadSite`. Note that the `MJCFBody` class contains the following attributes: name, pose, inertial, a list of geometries (`MJCFGeom`), a list of joints that attaches to the body (`MJCFJoint`), and a list of child bodies.
- Calls `LoadActuator` for all the `<actuator>` tags. For each actuator, there is an assoicated joint, which is saved in the `jointToActuatorIdx` map.
- Calls `LoadTendon` for all the `<tendon>` tags, which saves data regarding each tendon into `MJCFTendon` classes. For each fixed tendon, `MJCFTendon` contains a list of joints that the tendon is attached to. For each spatial tendon, `MJCFTendon` contains a list of spatial attachements, pulleys, and branches.
- Calls `LoadContact` to parse contact pairs and contact exclusions into the `MJCFContact` class.
`MJCFImporter::AddPhysicsEntities` adds all the parsed entities to the stage by mainly utilizing functions
from `plugins/MjcfUsd.cpp` as follows:
- Calls `setStageMetadata`, which sets up the UsdPhysicsScene
- Calls `createRoot` which defines the robot's root USD prim. Will also make this prim the default prim if
makeDefaultPrim is set to true in the import config.
- Handles making the imported USD instanceable if desired in the import config. For more information regarding instanceable assets, please visit https://docs.omniverse.nvidia.com/app_isaacsim/app_isaacsim/tutorial_gym_instanceable_assets.html
- For each body, calls `CreatePhysicsBodyAndJoint` recursively, which imports the kinematic tree onto the USD stage.
- Calls `addWorldGeomsAndSites`, which creates dummy links to place the sites/geoms defined in the world body
- Calls `AddContactFilters`, which adds collisions between the prims in accordance with the contact graph.
- Calls `AddTendons` to add all the fixed and spatial tendons.
| 5,589 | Markdown | 77.732393 | 318 | 0.789945 |
NVIDIA-Omniverse/kit-extension-sample-asset-search/README.md | # Asset Provider Search Example

### About
This extension is a template for connecting a search API for assets to Omniverse's *Asset Browser*.
### [README](exts/omni.example.asset_provider/)
See the [README for this extension](exts/omni.example.asset_provider/) to learn more about it including how to use it.
## Adding one of those Extension
To add a those extensions to your Omniverse app:
1. Go into: Extension Manager -> Gear Icon -> Extension Search Path
2. Add this as a search path: `git://github.com/NVIDIA-Omniverse/kit-extension-sample-asset-search?branch=main&dir=exts`
## Linking with an Omniverse app
For a better developer experience, it is recommended to create a folder link named `app` to the *Omniverse Kit* app installed from *Omniverse Launcher*. A convenience script to use is included.
Run:
```bash
> link_app.bat
```
There is also an analogous `link_app.sh` for Linux. If successful you should see `app` folder link in the root of this repo.
If multiple Omniverse apps is installed script will select recommended one. Or you can explicitly pass an app:
```bash
> link_app.bat --app code
```
You can also just pass a path to create link to:
```bash
> link_app.bat --path "C:/Users/bob/AppData/Local/ov/pkg/create-2022.1.3"
```
## Contributing
The source code for this repository is provided as-is and we are not accepting outside contributions.
| 1,450 | Markdown | 31.977272 | 193 | 0.752414 |
NVIDIA-Omniverse/kit-extension-sample-asset-search/exts/omni.example.asset_provider/omni/assetprovider/template/constants.py | SETTING_ROOT = "/exts/omni.assetprovider.template/"
SETTING_STORE_ENABLE = SETTING_ROOT + "enable" | 98 | Python | 48.499976 | 51 | 0.765306 |
NVIDIA-Omniverse/kit-extension-sample-asset-search/exts/omni.example.asset_provider/omni/assetprovider/template/extension.py | # Copyright (c) 2021, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
import importlib
import carb
import carb.settings
import carb.tokens
import omni.ext
from omni.services.browser.asset import get_instance as get_asset_services
from .model import TemplateAssetProvider
from .constants import SETTING_STORE_ENABLE
class TemplateAssetProviderExtension(omni.ext.IExt):
""" Template Asset Provider extension.
"""
def on_startup(self, ext_id):
self._asset_provider = TemplateAssetProvider()
self._asset_service = get_asset_services()
self._asset_service.register_store(self._asset_provider)
carb.settings.get_settings().set(SETTING_STORE_ENABLE, True)
def on_shutdown(self):
self._asset_service.unregister_store(self._asset_provider)
carb.settings.get_settings().set(SETTING_STORE_ENABLE, False)
self._asset_provider = None
self._asset_service = None
| 1,291 | Python | 34.888888 | 76 | 0.751356 |
NVIDIA-Omniverse/kit-extension-sample-asset-search/exts/omni.example.asset_provider/omni/assetprovider/template/model.py | # Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
from typing import Dict, List, Optional, Union, Tuple
import aiohttp
from omni.services.browser.asset import BaseAssetStore, AssetModel, SearchCriteria, ProviderModel
from .constants import SETTING_STORE_ENABLE
from pathlib import Path
CURRENT_PATH = Path(__file__).parent
DATA_PATH = CURRENT_PATH.parent.parent.parent.parent.joinpath("data")
# The name of your company
PROVIDER_ID = "PROVIDER_NAME"
# The URL location of your API
STORE_URL = "https://www.your_store_url.com"
class TemplateAssetProvider(BaseAssetStore):
"""
Asset provider implementation.
"""
def __init__(self, ov_app="Kit", ov_version="na") -> None:
super().__init__(PROVIDER_ID)
self._ov_app = ov_app
self._ov_version = ov_version
async def _search(self, search_criteria: SearchCriteria) -> Tuple[List[AssetModel], bool]:
""" Searches the asset store.
This function needs to be implemented as part of an implementation of the BaseAssetStore.
This function is called by the public `search` function that will wrap this function in a timeout.
"""
params = {}
# Setting for filter search criteria
if search_criteria.filter.categories:
# No category search, also use keywords instead
categories = search_criteria.filter.categories
for category in categories:
if category.startswith("/"):
category = category[1:]
category_keywords = category.split("/")
params["filter[categories]"] = ",".join(category_keywords).lower()
# Setting for keywords search criteria
if search_criteria.keywords:
params["keywords"] = ",".join(search_criteria.keywords)
# Setting for page number search criteria
if search_criteria.page.number:
params["page"] = search_criteria.page.number
# Setting for max number of items per page
if search_criteria.page.size:
params["page_size"] = search_criteria.page.size
items = []
# TODO: Uncomment once valid Store URL has been provided
# async with aiohttp.ClientSession() as session:
# async with session.get(f"{STORE_URL}", params=params) as resp:
# result = await resp.read()
# result = await resp.json()
# items = result
assets: List[AssetModel] = []
# Create AssetModel based off of JSON data
for item in items:
assets.append(
AssetModel(
identifier="",
name="",
published_at="",
categories=[],
tags=[],
vendor=PROVIDER_ID,
product_url="",
download_url="",
price=0.0,
thumbnail="",
)
)
# Are there more assets that we can load?
more = True
if search_criteria.page.size and len(assets) < search_criteria.page.size:
more = False
return (assets, more)
def provider(self) -> ProviderModel:
"""Return provider info"""
return ProviderModel(
name=PROVIDER_ID, icon=f"{DATA_PATH}/logo_placeholder.png", enable_setting=SETTING_STORE_ENABLE
)
| 3,820 | Python | 34.055046 | 110 | 0.605497 |
NVIDIA-Omniverse/kit-extension-sample-asset-search/exts/omni.example.asset_provider/docs/README.md | # Asset Provider Sample
This is a sample going through how to add asset content to Omniverse's Asset Store.

## Step 1: Add Base Extension
To start the base extension needs to be inside of Omniverse.
### Step 1.1: Add Extension
To add the extension to your Omniverse app there are two ways:
#### Add via GitHub Link
#### Step 1.1.1a **Go** into: Extension Manager -> Gear Icon -> Extension Search Path
#### Step 1.1.2a Add this as a search path: git://github.com/NVIDIA-Omniverse/kit-extension-sample-asset-search?branch=main&dir=exts
#### Download Folder from GitHub
#### Step 1.1.1b **Click** on Code
#### Step 1.1.2b **Select** download zip

#### Step 1.1.3b **Save** the Folder
#### Step 1.1.4b **Extract** the folder's contents
#### Step 1.1.5b **Locate** the `exts` directory in the extracted folder
#### Step 1.1.6b **Copy** the directory path
An example of what the directory path would look like: "c:/users/username/documents/kit-extension-sample-asset-search/exts"
#### Step 1.1.7b With Code open**Go** into: Extension Manager -> Gear Icon -> Extension Search Path
#### Step 1.1.8b **Add** the copied directory path as a search path
### Step 1.2 Open in Visual Studio Code
#### Step 1.2.1 **Search** for the extension in the *Extension Tab* `Asset Provider Extension Template`
#### Step 1.2.2 **Click** on the Visual Studio Icon to open it in Visual Studio Code

#### Step 1.2.3 **Open** `model.py`.
Here is what is inside of `model.py`
``` python
# Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
from typing import Dict, List, Optional, Union, Tuple
import aiohttp
from omni.services.browser.asset import BaseAssetStore, AssetModel, SearchCriteria, ProviderModel
from .constants import SETTING_STORE_ENABLE
from pathlib import Path
CURRENT_PATH = Path(__file__).parent
DATA_PATH = CURRENT_PATH.parent.parent.parent.parent.joinpath("data")
# The name of your company
PROVIDER_ID = "PROVIDER_NAME"
# The URL location of your API
STORE_URL = "https://www.your_store_url.com"
class TemplateAssetProvider(BaseAssetStore):
"""
Asset provider implementation.
"""
def __init__(self, ov_app="Kit", ov_version="na") -> None:
super().__init__(PROVIDER_ID)
self._ov_app = ov_app
self._ov_version = ov_version
async def _search(self, search_criteria: SearchCriteria) -> Tuple[List[AssetModel], bool]:
""" Searches the asset store.
This function needs to be implemented as part of an implementation of the BaseAssetStore.
This function is called by the public `search` function that will wrap this function in a timeout.
"""
params = {}
# Setting for filter search criteria
if search_criteria.filter.categories:
# No category search, also use keywords instead
categories = search_criteria.filter.categories
for category in categories:
if category.startswith("/"):
category = category[1:]
category_keywords = category.split("/")
params["filter[categories]"] = ",".join(category_keywords).lower()
# Setting for keywords search criteria
if search_criteria.keywords:
params["keywords"] = ",".join(search_criteria.keywords)
# Setting for page number search criteria
if search_criteria.page.number:
params["page"] = search_criteria.page.number
# Setting for max number of items per page
if search_criteria.page.size:
params["page_size"] = search_criteria.page.size
items = []
# TODO: Uncomment once valid Store URL has been provided
# async with aiohttp.ClientSession() as session:
# async with session.get(f"{STORE_URL}", params=params) as resp:
# result = await resp.read()
# result = await resp.json()
# items = result
assets: List[AssetModel] = []
# Create AssetModel based off of JSON data
for item in items:
assets.append(
AssetModel(
identifier="",
name="",
published_at="",
categories=[],
tags=[],
vendor=PROVIDER_ID,
product_url="",
download_url="",
price=0.0,
thumbnail="",
)
)
# Are there more assets that we can load?
more = True
if search_criteria.page.size and len(assets) < search_criteria.page.size:
more = False
return (assets, more)
def provider(self) -> ProviderModel:
"""Return provider info"""
return ProviderModel(
name=PROVIDER_ID, icon=f"{DATA_PATH}/logo_placeholder.png", enable_setting=SETTING_STORE_ENABLE
)
```
## Step 2: Inputting Provider Information
### Step 2.1: Update Basic Information
#### Step 2.1.1 **Replace** `"PROVIDER_NAME"` with your Company name related to these lines.
``` python
# The name of your company
PROVIDER_ID = "PROVIDER_NAME" # REPLACE WITH YOUR NAME
```
#### Step 2.1.2 **Replace** `"https://www.your_store_url.com"` with your Company's URL containing the API call.
``` python
# The URL location of your API
STORE_URL = "https://www.your_store_url.com" # REPLACE WITH YOUR URL
```
#### Step 2.1.3 To use a logo, **place** it in the `data` folder located in the root of `exts`.
#### Step 2.1.4 At the end of `model.py` **update** the `icon` parameter inside the `provider` function.
``` python
def provider(self) -> ProviderModel:
"""Return provider info"""
return ProviderModel( # REPLACE logo_placeholder.png WITH YOUR IMAGE
name=PROVIDER_ID, icon=f"{DATA_PATH}/logo_placeholder.png", enable_setting=SETTING_STORE_ENABLE
)
```
### Step 2.2: Update Search criteria
This is dependent on your API. The BaseAssetStore has search criteria's that can be assigned depending on how the site's search API works.
Search criteria that is apart of `BaseAssetModel` include:
``` python
"example": {
"keywords": ["GPU", "RTX"],
"page": {"number": 5, "size": 75},
"sort": ["price", "desc"],
"filter": {"categories": ["hardware", "electronics"]},
"vendors": ["Vendor1", "Vendor2"],
"search_timeout": 60,
}
```
For example if your search api uses `key` as a parameter for `keywords` then update the following lines from:
``` python
if search_criteria.keywords:
params["keywords"] = ",".join(search_criteria.keywords)
```
To:
``` python
if search_criteria.keywords:
params["key"] = ",".join(search_criteria.keywords)
```
#### Step 2.2.1 **Update** and **add** each parameter based on your API.
### Step 2.3: Update AssetModel Creation
After getting the data in JSON format from the API it must turn them into an AssetModel List. If the API already does this then use that value inside the return statement.
The code that will update:
``` python
# Create AssetModel based off of JSON data
for item in items:
assets.append(
AssetModel(
identifier="",
name="",
published_at="",
categories=[],
tags=[],
vendor=PROVIDER_ID,
product_url="",
download_url="",
price=0.0,
thumbnail="",
)
)
```
Take for example this JSON object:
``` python
{
"identifier":"1382049",
"categories":[
"category_1",
"category_2",
"category_3"
],
"download_url":"None",
"name":"Asset Name",
"price":"29.00",
"url":"https://www.awesomestuff.com/3d-models/toysandstuff?utm_source=omniverse",
"pub_at":"2015-12-07T21:19:08+00:00",
"tags":[
"3d",
"tag_1",
"tag_2"
],
"thumbnail":"https://url_to_thumbnail.jpg",
"vendor":"Vendor Name"
}
```
Then the corresponding AssetModel creation will look like the following:
``` python
# Create AssetModel based off of JSON data
for item in items:
assets.append(
AssetModel(
identifier=item.get("identifier", "")
name=item.get("name", ""),
published_at=item.get("pub_at", ""),
categories=item.get("categories", []),
tags=item.get("tags", []),
vendor=PROVIDER_ID,
product_url=item.get("url", ""),
download_url=item.get("download_url", None),
price=item.get("price", 0),
thumbnail=item.get("thumbnail", ""),
)
)
```
### Step 2.4 Uncomment and test
#### Step 2.4.1 **Uncomment** the following code block in `model.py`
``` python
# TODO: Uncomment once valid Store URL has been provided
# async with aiohttp.ClientSession() as session:
# async with session.get(f"{STORE_URL}", params=params) as resp:
# result = await resp.read()
# result = await resp.json()
# items = result
```
#### Step 2.4.2 **Save** `model.py` and go to Omniverse and check the `Asset Store`. Your assets should now be visible in the *Asset Browser*. | 9,617 | Markdown | 31.275168 | 171 | 0.624519 |
NVIDIA-Omniverse/urdf-importer-extension/CONTRIBUTING.md | # Contributing to the URDF Importer Extension
## Did you find a bug?
* Check in the GitHub [Issues](https://github.com/NVIDIA-Omniverse/urdf-importer-extension/issues) if a report for your bug already exists.
* If the bug has not been reported yet, open a new Issue.
* Use a short and descriptive title which contains relevant keywords.
* Write a clear description of the bug.
* Document the environment including your operating system, compiler version, and hardware specifications.
* Add code samples and executable test cases with instructions for reproducing the bug.
## Did you find an issue in the documentation?
* Please create an [Issue](https://github.com/NVIDIA-Omniverse/urdf-importer-extension/issues/) if you find a documentation issue.
## Did you write a bug fix?
* Open a new [Pull Request](https://github.com/NVIDIA-Omniverse/urdf-importer-extension/pulls) with your bug fix.
* Write a description of the bug which is fixed by your patch or link to related Issues.
* If your patch fixes for example Issue #33, write `Fixes #33`.
* Explain your solution with a few words.
## Did you write a cosmetic patch?
* Patches that are purely cosmetic will not be considered and associated Pull Requests will be closed.
* Cosmetic are patches which do not improve stability, performance, functionality, etc.
* Examples for cosmetic patches: code formatting, fixing whitespaces.
## Do you have a question?
* Search the GitHub [Discussions](https://github.com/NVIDIA-Omniverse/urdf-importer-extension/discussions/) for your question.
* If nobody asked your question before, feel free to open a new discussion.
* Once somebody shares a satisfying answer to your question, click "Mark as answer".
* GitHub Issues should only be used for bug reports.
* If you open an Issue with a question, we may convert it into a discussion.
| 1,840 | Markdown | 50.138887 | 139 | 0.773913 |
NVIDIA-Omniverse/urdf-importer-extension/README.md | # Omniverse URDF Importer
The URDF Importer Extension is used to import URDF representations of robots.
`Unified Robot Description Format (URDF)` is an XML format for representing a robot model in ROS.
## Getting Started
1. Clone the GitHub repo to your local machine.
2. Open a command prompt and navigate to the root of your cloned repo.
3. Run `build.bat` to bootstrap your dev environment and build the example extensions.
4. Run `_build\{platform}\release\omni.importer.urdf.app.bat` to start the Kit application.
5. From the menu, select `Isaac Utils->URDF Importer` to launch the UI for the URDF Importer extension.
This extension is enabled by default. If it is ever disabled, it can be re-enabled from the Extension Manager
by searching for `omni.importer.urdf`.
**Note:** On Linux, replace `.bat` with `.sh` in the instructions above.
## Conventions
Special characters in link or joint names are not supported and will be replaced with an underscore. In the event that the name starts with an underscore due to the replacement, an a is pre-pended. It is recommended to make these name changes in the mjcf directly.
See the [Convention References](https://docs.omniverse.nvidia.com/app_isaacsim/app_isaacsim/reference_conventions.html#isaac-sim-conventions) documentation for a complete list of `Isaac Sim` conventions.
## User Interface

1. Information Panel: This panel has useful information about this extension.
2. Import Options Panel: This panel has utility functions for testing the gains being set for the Articulation.
See `Import Options` below for full details.
3. Import Panel: This panel holds the source path, destination path, and import button.
## Import Options
* **Merge Fixed Joints**: Consolidate links that are connected by fixed joints, so that an articulation is only applied to joints that move.
* **Fix Base Link**: When checked, the robot will have its base fixed where it's placed in world coordinates.
* **Import Inertia Tensor**: Check to load inertia from urdf directly. If the urdf does not specify an inertia tensor, identity will be used and scaled by the scaling factor. If unchecked, Physx will compute it automatically.
* **Stage Units Per Meter**: |kit| default length unit is centimeters. Here you can set the scaling factor to match the unit used in your URDF. Currently, the URDF importer only supports uniform global scaling. Applying different scaling for different axes and specific mesh parts (i.e. using the ``scale`` parameter under the URDF mesh label) will be available in future releases. If you have a ``scale`` parameter in your URDF, you may need to manually adjust the other values in the URDF so that all parameters are in the same unit.
* **Link Density**: If a link does not have a given mass, uses this density (in Kg/m^3) to compute mass based on link volume. A value of 0.0 can be used to tell the physics engine to automatically compute density as well.
* **Joint Drive Type**: Default Joint drive type, Values can be `None`, `Position`, and `Velocity`.
* **Joint Drive Strength**: The drive strength is the joint stiffness for position drive, or damping for velocity driven joints.
* **Joint Position Drive Damping**: If the drive type is set to position this is the default damping value used.
* **Clear Stage**: When checked, cleans the stage before loading the new URDF, otherwise loads it on current open stage at position `(0,0,0)`
* **Convex Decomposition**: If Checked, the collision object will be made a set of Convex meshes to better match the visual asset. Otherwise a convex hull will be used.
* **Self Collision**: Enables self collision between adjacent links. It may cause instability if the collision meshes are intersecting at the joint.
* **Create Physics Scene**: Creates a default physics scene on the stage. Because this physics scene is created outside of the robot asset, it won't be loaded into other scenes composed with the robot asset.
* **Output Directory**: The destination of the imported asset. it will create a folder structure with the robot asset and all textures used for its rendering. You must have write access to this directory.
**Note:**
- It is recommended to set Self Collision to false unless you are certain that links on the robot are not self colliding.
- You must have write access to the output directory used for import, it will default to the current open stage, change this as necessary.
**Known Issue:** If more than one asset in URDF contains the same material name, only one material will be created, regardless if the parameters in the material are different (e.g two meshes have materials with the name "material", one is blue and the other is red. both meshes will be either red or blue.). This also applies for textured materials.
## Robot Properties
There might be many properties you want to tune on your robot. These properties can be spread across many different Schemas and APIs.
The general steps of getting and setting a parameter are:
1. Find which API is the parameter under. Most common ones can be found in the [Pixar USD API](https://docs.omniverse.nvidia.com/kit/docs/kit-manual/latest/api/pxr_index.html).
2. Get the prim handle that the API is applied to. For example, Articulation and Drive APIs are applied to joints, and MassAPIs are applied to the rigid bodies.
3. Get the handle to the API. From there on, you can Get or Set the attributes associated with that API.
For example, if we want to set the wheel's drive velocity and the actuators' stiffness, we need to find the DriveAPI:
```python
# get handle to the Drive API for both wheels
left_wheel_drive = UsdPhysics.DriveAPI.Get(stage.GetPrimAtPath("/carter/chassis_link/left_wheel"), "angular")
right_wheel_drive = UsdPhysics.DriveAPI.Get(stage.GetPrimAtPath("/carter/chassis_link/right_wheel"), "angular")
# Set the velocity drive target in degrees/second
left_wheel_drive.GetTargetVelocityAttr().Set(150)
right_wheel_drive.GetTargetVelocityAttr().Set(150)
# Set the drive damping, which controls the strength of the velocity drive
left_wheel_drive.GetDampingAttr().Set(15000)
right_wheel_drive.GetDampingAttr().Set(15000)
# Set the drive stiffness, which controls the strength of the position drive
# In this case because we want to do velocity control this should be set to zero
left_wheel_drive.GetStiffnessAttr().Set(0)
right_wheel_drive.GetStiffnessAttr().Set(0)
```
Alternatively you can use the [Omniverse Commands Tool](https://docs.omniverse.nvidia.com/app_isaacsim/app_isaacsim/ext_omni_kit_commands.html#isaac-sim-command-tool) to change a value in the UI and get the associated Omniverse command that changes the property.
**Note:**
- The drive stiffness parameter should be set when using position control on a joint drive.
- The drive damping parameter should be set when using velocity control on a joint drive.
- A combination of setting stiffness and damping on a drive will result in both targets being applied, this can be useful in position control to reduce vibrations.
## Examples
The following examples showcase how to best use this extension:
- Carter Example: `Isaac Examples > Import Robot > Carter URDF`
- Franka Example: `Isaac Examples > Import Robot > Franka URDF`
- Kaya Example: `Isaac Examples > Import Robot > Kaya URDF`
- UR10 Example: `Isaac Examples > Import Robot > UR10 URDF`
**Note:** For these example, please wait for materials to get loaded. You can track progress on the bottom right corner of UI.
### Carter URDF Example
To run the Example:
- Go to the top menu bar and click `Isaac Examples > Import Robots > Carter URDF`.
- Press the ``Load Robot`` button to import the URDF into the stage, add a ground plane, add a light, and and a physics scene.
- Press the ``Configure Drives`` button to to configure the joint drives and allow the rear pivot to spin freely.
- Press the `Open Source Code` button to view the source code. The source code illustrates how to import and integrate the robot using the Python API.
- Press the ``PLAY`` button to begin simulating.
- Press the ``Move to Pose`` button to make the robot drive forward.

### Franka URDF Example
To run the Example:
- Go to the top menu bar and click `Isaac Examples > Import Robots > Franka URDF`.
- Press the ``Load Robot`` button to import the URDF into the stage, add a ground plane, add a light, and and a physics scene.
- Press the ``Configure Drives`` button to to configure the joint drives. This sets each drive stiffness and damping value.
- Press the `Open Source Code` button to view the source code. The source code illustrates how to import and integrate the robot using the Python API.
- Press the ``PLAY`` button to begin simulating.
- Press the ``Move to Pose`` button to make the robot move to a home/rest position.

### Kaya URDF Example
To run the Example:
- Go to the top menu bar and click `Isaac Examples > Import Robots > Kaya URDF`.
- Press the ``Load Robot`` button to import the URDF into the stage, add a ground plane, add a light, and and a physics scene.
- Press the ``Configure Drives`` button to to configure the joint drives. This sets the drive stiffness and damping value of each wheel, sets all of its rollers as freely rotating.
- Press the `Open Source Code` button to view the source code. The source code illustrates how to import and integrate the robot using the Python API.
- Press the ``PLAY`` button to begin simulating.
- Press the ``Move to Pose`` button to make the robot rotate in place.

### UR10 URDF Example
- Go to the top menu bar and click `Isaac Examples > Import Robots > Kaya URDF`.
- Press the ``Load Robot`` button to import the URDF into the stage, add a ground plane, add a light, and and a physics scene.
- Press the ``Configure Drives`` button to to configure the joint drives. This sets each drive stiffness and damping value.
- Press the `Open Source Code` button to view the source code. The source code illustrates how to import and integrate the robot using the Python API.
- Press the ``PLAY`` button to begin simulating.
- Press the ``Move to Pose`` button to make the robot move to a home/rest position.

| 10,435 | Markdown | 63.819875 | 535 | 0.763297 |
NVIDIA-Omniverse/urdf-importer-extension/index.rst | Omniverse URDF Importer
=======================
.. mdinclude:: README.md
Extension Documentation
~~~~~~~~~~~~~~~~~~~~~~~~
.. toctree::
:maxdepth: 1
:glob:
source/extensions/omni.importer.urdf/docs/index
source/extensions/omni.importer.urdf/docs/Overview
source/extensions/omni.importer.urdf/docs/CHANGELOG
CONTRIBUTING | 339 | reStructuredText | 21.666665 | 54 | 0.654867 |
NVIDIA-Omniverse/urdf-importer-extension/source/extensions/omni.importer.urdf/python/scripts/commands.py | # SPDX-FileCopyrightText: Copyright (c) 2023 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
# SPDX-License-Identifier: Apache-2.0
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import os
import omni.client
import omni.kit.commands
# import omni.kit.utils
from omni.client._omniclient import Result
from omni.importer.urdf import _urdf
from pxr import Usd
class URDFCreateImportConfig(omni.kit.commands.Command):
"""
Returns an ImportConfig object that can be used while parsing and importing.
Should be used with `URDFParseFile` and `URDFParseAndImportFile` commands
Returns:
:obj:`omni.importer.urdf._urdf.ImportConfig`: Parsed URDF stored in an internal structure.
"""
def __init__(self) -> None:
pass
def do(self) -> _urdf.ImportConfig:
return _urdf.ImportConfig()
def undo(self) -> None:
pass
class URDFParseFile(omni.kit.commands.Command):
"""
This command parses a given urdf and returns a UrdfRobot object
Args:
arg0 (:obj:`str`): The absolute path to where the urdf file is
arg1 (:obj:`omni.importer.urdf._urdf.ImportConfig`): Import Configuration
Returns:
:obj:`omni.importer.urdf._urdf.UrdfRobot`: Parsed URDF stored in an internal structure.
"""
def __init__(self, urdf_path: str = "", import_config: _urdf.ImportConfig = _urdf.ImportConfig()) -> None:
self._root_path, self._filename = os.path.split(os.path.abspath(urdf_path))
self._import_config = import_config
self._urdf_interface = _urdf.acquire_urdf_interface()
pass
def do(self) -> _urdf.UrdfRobot:
return self._urdf_interface.parse_urdf(self._root_path, self._filename, self._import_config)
def undo(self) -> None:
pass
class URDFParseAndImportFile(omni.kit.commands.Command):
"""
This command parses and imports a given urdf and returns a UrdfRobot object
Args:
arg0 (:obj:`str`): The absolute path to where the urdf file is
arg1 (:obj:`omni.importer.urdf._urdf.ImportConfig`): Import Configuration
arg2 (:obj:`str`): destination path for robot usd. Default is "" which will load the robot in-memory on the open stage.
Returns:
:obj:`str`: Path to the robot on the USD stage.
"""
def __init__(self, urdf_path: str = "", import_config=_urdf.ImportConfig(), dest_path: str = "") -> None:
self.dest_path = dest_path
self._urdf_path = urdf_path
self._root_path, self._filename = os.path.split(os.path.abspath(urdf_path))
self._import_config = import_config
self._urdf_interface = _urdf.acquire_urdf_interface()
pass
def do(self) -> str:
status, imported_robot = omni.kit.commands.execute(
"URDFParseFile", urdf_path=self._urdf_path, import_config=self._import_config
)
if self.dest_path:
self.dest_path = self.dest_path.replace(
"\\", "/"
) # Omni client works with both slashes cross platform, making it standard to make it easier later on
result = omni.client.read_file(self.dest_path)
if result[0] != Result.OK:
stage = Usd.Stage.CreateNew(self.dest_path)
stage.Save()
return self._urdf_interface.import_robot(
self._root_path, self._filename, imported_robot, self._import_config, self.dest_path
)
def undo(self) -> None:
pass
omni.kit.commands.register_all_commands_in_module(__name__)
| 4,037 | Python | 33.51282 | 127 | 0.662868 |
NVIDIA-Omniverse/urdf-importer-extension/source/extensions/omni.importer.urdf/python/scripts/extension.py | # SPDX-FileCopyrightText: Copyright (c) 2023 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
# SPDX-License-Identifier: Apache-2.0
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import asyncio
import gc
import os
import weakref
import carb
import omni.client
import omni.ext
import omni.ui as ui
from omni.importer.urdf import _urdf
from omni.importer.urdf.scripts.ui import (
btn_builder,
cb_builder,
dropdown_builder,
float_builder,
get_style,
make_menu_item_description,
setup_ui_headers,
str_builder,
)
from omni.kit.menu.utils import MenuItemDescription, add_menu_items, remove_menu_items
from pxr import Sdf, Usd, UsdGeom, UsdPhysics
# from .menu import make_menu_item_description
# from .ui_utils import (
# btn_builder,
# cb_builder,
# dropdown_builder,
# float_builder,
# get_style,
# setup_ui_headers,
# str_builder,
# )
EXTENSION_NAME = "URDF Importer"
def is_urdf_file(path: str):
_, ext = os.path.splitext(path.lower())
return ext in [".urdf", ".URDF"]
def on_filter_item(item) -> bool:
if not item or item.is_folder:
return not (item.name == "Omniverse" or item.path.startswith("omniverse:"))
return is_urdf_file(item.path)
def on_filter_folder(item) -> bool:
if item and item.is_folder:
return True
else:
return False
class Extension(omni.ext.IExt):
def on_startup(self, ext_id):
self._ext_id = ext_id
self._urdf_interface = _urdf.acquire_urdf_interface()
self._usd_context = omni.usd.get_context()
self._window = omni.ui.Window(
EXTENSION_NAME, width=400, height=500, visible=False, dockPreference=ui.DockPreference.LEFT_BOTTOM
)
self._window.set_visibility_changed_fn(self._on_window)
menu_items = [
make_menu_item_description(ext_id, EXTENSION_NAME, lambda a=weakref.proxy(self): a._menu_callback())
]
self._menu_items = [MenuItemDescription(name="Workflows", sub_menu=menu_items)]
add_menu_items(self._menu_items, "Isaac Utils")
self._file_picker = None
self._models = {}
result, self._config = omni.kit.commands.execute("URDFCreateImportConfig")
self._filepicker = None
self._last_folder = None
self._content_browser = None
self._extension_path = omni.kit.app.get_app().get_extension_manager().get_extension_path(ext_id)
self._imported_robot = None
# Set defaults
self._config.set_merge_fixed_joints(False)
self._config.set_replace_cylinders_with_capsules(False)
self._config.set_convex_decomp(False)
self._config.set_fix_base(True)
self._config.set_import_inertia_tensor(False)
self._config.set_distance_scale(1.0)
self._config.set_density(0.0)
self._config.set_default_drive_type(1)
self._config.set_default_drive_strength(1e7)
self._config.set_default_position_drive_damping(1e5)
self._config.set_self_collision(False)
self._config.set_up_vector(0, 0, 1)
self._config.set_make_default_prim(True)
self._config.set_create_physics_scene(True)
self._config.set_collision_from_visuals(False)
def build_ui(self):
with self._window.frame:
with ui.VStack(spacing=5, height=0):
self._build_info_ui()
self._build_options_ui()
self._build_import_ui()
stage = self._usd_context.get_stage()
if stage:
if UsdGeom.GetStageUpAxis(stage) == UsdGeom.Tokens.y:
self._config.set_up_vector(0, 1, 0)
if UsdGeom.GetStageUpAxis(stage) == UsdGeom.Tokens.z:
self._config.set_up_vector(0, 0, 1)
units_per_meter = 1.0 / UsdGeom.GetStageMetersPerUnit(stage)
self._models["scale"].set_value(units_per_meter)
async def dock_window():
await omni.kit.app.get_app().next_update_async()
def dock(space, name, location, pos=0.5):
window = omni.ui.Workspace.get_window(name)
if window and space:
window.dock_in(space, location, pos)
return window
tgt = ui.Workspace.get_window("Viewport")
dock(tgt, EXTENSION_NAME, omni.ui.DockPosition.LEFT, 0.33)
await omni.kit.app.get_app().next_update_async()
self._task = asyncio.ensure_future(dock_window())
def _build_info_ui(self):
title = EXTENSION_NAME
doc_link = "https://docs.omniverse.nvidia.com/app_isaacsim/app_isaacsim/ext_omni_isaac_urdf.html"
overview = "This utility is used to import URDF representations of robots into Isaac Sim. "
overview += "URDF is an XML format for representing a robot model in ROS."
overview += "\n\nPress the 'Open in IDE' button to view the source code."
setup_ui_headers(self._ext_id, __file__, title, doc_link, overview)
def _build_options_ui(self):
frame = ui.CollapsableFrame(
title="Import Options",
height=0,
collapsed=False,
style=get_style(),
style_type_name_override="CollapsableFrame",
horizontal_scrollbar_policy=ui.ScrollBarPolicy.SCROLLBAR_AS_NEEDED,
vertical_scrollbar_policy=ui.ScrollBarPolicy.SCROLLBAR_ALWAYS_ON,
)
with frame:
with ui.VStack(style=get_style(), spacing=5, height=0):
cb_builder(
label="Merge Fixed Joints",
tooltip="Consolidate links that are connected by fixed joints.",
on_clicked_fn=lambda m, config=self._config: config.set_merge_fixed_joints(m),
)
cb_builder(
label="Replace Cylinders with Capsules",
tooltip="Replace Cylinder collision bodies by capsules.",
on_clicked_fn=lambda m, config=self._config: config.set_replace_cylinders_with_capsules(m),
)
cb_builder(
"Fix Base Link",
tooltip="Fix the robot base robot to where it's imported in world coordinates.",
default_val=True,
on_clicked_fn=lambda m, config=self._config: config.set_fix_base(m),
)
cb_builder(
"Import Inertia Tensor",
tooltip="Load inertia tensor directly from the URDF.",
on_clicked_fn=lambda m, config=self._config: config.set_import_inertia_tensor(m),
)
self._models["scale"] = float_builder(
"Stage Units Per Meter",
default_val=1.0,
tooltip="Sets the scaling factor to match the units used in the URDF. Default Stage units are (cm).",
)
self._models["scale"].add_value_changed_fn(
lambda m, config=self._config: config.set_distance_scale(m.get_value_as_float())
)
self._models["density"] = float_builder(
"Link Density",
default_val=0.0,
tooltip="Density value to compute mass based on link volume. Use 0.0 to automatically compute density.",
)
self._models["density"].add_value_changed_fn(
lambda m, config=self._config: config.set_density(m.get_value_as_float())
)
dropdown_builder(
"Joint Drive Type",
items=["None", "Position", "Velocity"],
default_val=1,
on_clicked_fn=lambda i, config=self._config: config.set_default_drive_type(
0 if i == "None" else (1 if i == "Position" else 2)
),
tooltip="Default Joint drive type.",
)
self._models["drive_strength"] = float_builder(
"Joint Drive Strength",
default_val=1e4,
tooltip="Joint stiffness for position drive, or damping for velocity driven joints. Set to -1 to prevent this parameter from getting used.",
)
self._models["drive_strength"].add_value_changed_fn(
lambda m, config=self._config: config.set_default_drive_strength(m.get_value_as_float())
)
self._models["position_drive_damping"] = float_builder(
"Joint Position Damping",
default_val=1e3,
tooltip="Default damping value when drive type is set to Position. Set to -1 to prevent this parameter from getting used.",
)
self._models["position_drive_damping"].add_value_changed_fn(
lambda m, config=self._config: config.set_default_position_drive_damping(m.get_value_as_float())
)
self._models["clean_stage"] = cb_builder(
label="Clear Stage", tooltip="Clear the Stage prior to loading the URDF."
)
dropdown_builder(
"Normals Subdivision",
items=["catmullClark", "loop", "bilinear", "none"],
default_val=2,
on_clicked_fn=lambda i, dict={
"catmullClark": 0,
"loop": 1,
"bilinear": 2,
"none": 3,
}, config=self._config: config.set_subdivision_scheme(dict[i]),
tooltip="Mesh surface normal subdivision scheme. Use `none` to avoid overriding authored values.",
)
cb_builder(
"Convex Decomposition",
tooltip="Decompose non-convex meshes into convex collision shapes. If false, convex hull will be used.",
on_clicked_fn=lambda m, config=self._config: config.set_convex_decomp(m),
)
cb_builder(
"Self Collision",
tooltip="Enables self collision between adjacent links.",
on_clicked_fn=lambda m, config=self._config: config.set_self_collision(m),
)
cb_builder(
"Collision From Visuals",
tooltip="Creates collision geometry from visual geometry.",
on_clicked_fn=lambda m, config=self._config: config.set_collision_from_visuals(m),
)
cb_builder(
"Create Physics Scene",
tooltip="Creates a default physics scene on the stage on import.",
default_val=True,
on_clicked_fn=lambda m, config=self._config: config.set_create_physics_scene(m),
)
cb_builder(
"Create Instanceable Asset",
tooltip="If true, creates an instanceable version of the asset. Meshes will be saved in a separate USD file",
default_val=False,
on_clicked_fn=lambda m, config=self._config: config.set_make_instanceable(m),
)
self._models["instanceable_usd_path"] = str_builder(
"Instanceable USD Path",
tooltip="USD file to store instanceable meshes in",
default_val="./instanceable_meshes.usd",
use_folder_picker=True,
folder_dialog_title="Select Output File",
folder_button_title="Select File",
)
self._models["instanceable_usd_path"].add_value_changed_fn(
lambda m, config=self._config: config.set_instanceable_usd_path(m.get_value_as_string())
)
def _build_import_ui(self):
frame = ui.CollapsableFrame(
title="Import",
height=0,
collapsed=False,
style=get_style(),
style_type_name_override="CollapsableFrame",
horizontal_scrollbar_policy=ui.ScrollBarPolicy.SCROLLBAR_AS_NEEDED,
vertical_scrollbar_policy=ui.ScrollBarPolicy.SCROLLBAR_ALWAYS_ON,
)
with frame:
with ui.VStack(style=get_style(), spacing=5, height=0):
def check_file_type(model=None):
path = model.get_value_as_string()
if is_urdf_file(path) and "omniverse:" not in path.lower():
self._models["import_btn"].enabled = True
else:
carb.log_warn(f"Invalid path to URDF: {path}")
kwargs = {
"label": "Input File",
"default_val": "",
"tooltip": "Click the Folder Icon to Set Filepath",
"use_folder_picker": True,
"item_filter_fn": on_filter_item,
"bookmark_label": "Built In URDF Files",
"bookmark_path": f"{self._extension_path}/data/urdf",
"folder_dialog_title": "Select URDF File",
"folder_button_title": "Select URDF",
}
self._models["input_file"] = str_builder(**kwargs)
self._models["input_file"].add_value_changed_fn(check_file_type)
kwargs = {
"label": "Output Directory",
"type": "stringfield",
"default_val": self.get_dest_folder(),
"tooltip": "Click the Folder Icon to Set Filepath",
"use_folder_picker": True,
}
self.dest_model = str_builder(**kwargs)
# btn_builder("Import URDF", text="Select and Import", on_clicked_fn=self._parse_urdf)
self._models["import_btn"] = btn_builder("Import", text="Import", on_clicked_fn=self._load_robot)
self._models["import_btn"].enabled = False
def get_dest_folder(self):
stage = omni.usd.get_context().get_stage()
if stage:
path = stage.GetRootLayer().identifier
if not path.startswith("anon"):
basepath = path[: path.rfind("/")]
if path.rfind("/") < 0:
basepath = path[: path.rfind("\\")]
return basepath
return "(same as source)"
def _menu_callback(self):
self._window.visible = not self._window.visible
def _on_window(self, visible):
if self._window.visible:
self.build_ui()
self._events = self._usd_context.get_stage_event_stream()
self._stage_event_sub = self._events.create_subscription_to_pop(
self._on_stage_event, name="urdf importer stage event"
)
else:
self._events = None
self._stage_event_sub = None
def _on_stage_event(self, event):
stage = self._usd_context.get_stage()
if event.type == int(omni.usd.StageEventType.OPENED) and stage:
if UsdGeom.GetStageUpAxis(stage) == UsdGeom.Tokens.y:
self._config.set_up_vector(0, 1, 0)
if UsdGeom.GetStageUpAxis(stage) == UsdGeom.Tokens.z:
self._config.set_up_vector(0, 0, 1)
units_per_meter = 1.0 / UsdGeom.GetStageMetersPerUnit(stage)
self._models["scale"].set_value(units_per_meter)
self.dest_model.set_value(self.get_dest_folder())
def _load_robot(self, path=None):
path = self._models["input_file"].get_value_as_string()
if path:
dest_path = self.dest_model.get_value_as_string()
base_path = path[: path.rfind("/")]
basename = path[path.rfind("/") + 1 :]
basename = basename[: basename.rfind(".")]
if path.rfind("/") < 0:
base_path = path[: path.rfind("\\")]
basename = path[path.rfind("\\") + 1]
if dest_path != "(same as source)":
base_path = dest_path # + "/" + basename
dest_path = "{}/{}/{}.usd".format(base_path, basename, basename)
# counter = 1
# while result[0] == Result.OK:
# dest_path = "{}/{}_{:02}.usd".format(base_path, basename, counter)
# result = omni.client.read_file(dest_path)
# counter +=1
# result = omni.client.read_file(dest_path)
# if
# stage = Usd.Stage.Open(dest_path)
# else:
# stage = Usd.Stage.CreateNew(dest_path)
# UsdGeom.SetStageUpAxis(stage, UsdGeom.Tokens.z)
omni.kit.commands.execute(
"URDFParseAndImportFile", urdf_path=path, import_config=self._config, dest_path=dest_path
)
# print("Created file, instancing it now")
stage = Usd.Stage.Open(dest_path)
prim_name = str(stage.GetDefaultPrim().GetName())
# print(prim_name)
# stage.Save()
def add_reference_to_stage():
current_stage = omni.usd.get_context().get_stage()
if current_stage:
prim_path = omni.usd.get_stage_next_free_path(
current_stage, str(current_stage.GetDefaultPrim().GetPath()) + "/" + prim_name, False
)
robot_prim = current_stage.OverridePrim(prim_path)
if "anon:" in current_stage.GetRootLayer().identifier:
robot_prim.GetReferences().AddReference(dest_path)
else:
robot_prim.GetReferences().AddReference(
omni.client.make_relative_url(current_stage.GetRootLayer().identifier, dest_path)
)
if self._config.create_physics_scene:
UsdPhysics.Scene.Define(current_stage, Sdf.Path("/physicsScene"))
async def import_with_clean_stage():
await omni.usd.get_context().new_stage_async()
await omni.kit.app.get_app().next_update_async()
add_reference_to_stage()
await omni.kit.app.get_app().next_update_async()
if self._models["clean_stage"].get_value_as_bool():
asyncio.ensure_future(import_with_clean_stage())
else:
add_reference_to_stage()
def on_shutdown(self):
_urdf.release_urdf_interface(self._urdf_interface)
remove_menu_items(self._menu_items, "Isaac Utils")
if self._window:
self._window = None
gc.collect()
| 19,344 | Python | 43.267734 | 160 | 0.549783 |
NVIDIA-Omniverse/urdf-importer-extension/source/extensions/omni.importer.urdf/python/scripts/ui/menu.py | # SPDX-FileCopyrightText: Copyright (c) 2023 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
# SPDX-License-Identifier: Apache-2.0
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import omni.ext
from omni.kit.menu.utils import MenuItemDescription
def make_menu_item_description(ext_id: str, name: str, onclick_fun, action_name: str = "") -> None:
"""Easily replace the onclick_fn with onclick_action when creating a menu description
Args:
ext_id (str): The extension you are adding the menu item to.
name (str): Name of the menu item displayed in UI.
onclick_fun (Function): The function to run when clicking the menu item.
action_name (str): name for the action, in case ext_id+name don't make a unique string
Note:
ext_id + name + action_name must concatenate to a unique identifier.
"""
# TODO, fix errors when reloading extensions
# action_unique = f'{ext_id.replace(" ", "_")}{name.replace(" ", "_")}{action_name.replace(" ", "_")}'
# action_registry = omni.kit.actions.core.get_action_registry()
# action_registry.register_action(ext_id, action_unique, onclick_fun)
return MenuItemDescription(name=name, onclick_fn=onclick_fun)
| 1,716 | Python | 44.184209 | 106 | 0.716783 |
NVIDIA-Omniverse/urdf-importer-extension/source/extensions/omni.importer.urdf/python/scripts/ui/ui_utils.py | # SPDX-FileCopyrightText: Copyright (c) 2023 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
# SPDX-License-Identifier: Apache-2.0
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import asyncio
import os
import subprocess
import sys
from cmath import inf
import carb.settings
import omni.appwindow
import omni.ext
import omni.ui as ui
from omni.kit.window.extensions import SimpleCheckBox
from omni.kit.window.filepicker import FilePickerDialog
from omni.kit.window.property.templates import LABEL_HEIGHT, LABEL_WIDTH
# from .callbacks import on_copy_to_clipboard, on_docs_link_clicked, on_open_folder_clicked, on_open_IDE_clicked
from .style import BUTTON_WIDTH, COLOR_W, COLOR_X, COLOR_Y, COLOR_Z, get_style
def btn_builder(label="", type="button", text="button", tooltip="", on_clicked_fn=None):
"""Creates a stylized button.
Args:
label (str, optional): Label to the left of the UI element. Defaults to "".
type (str, optional): Type of UI element. Defaults to "button".
text (str, optional): Text rendered on the button. Defaults to "button".
tooltip (str, optional): Tooltip to display over the Label. Defaults to "".
on_clicked_fn (Callable, optional): Call-back function when clicked. Defaults to None.
Returns:
ui.Button: Button
"""
with ui.HStack():
ui.Label(label, width=LABEL_WIDTH, alignment=ui.Alignment.LEFT_CENTER, tooltip=format_tt(tooltip))
btn = ui.Button(
text.upper(),
name="Button",
width=BUTTON_WIDTH,
clicked_fn=on_clicked_fn,
style=get_style(),
alignment=ui.Alignment.LEFT_CENTER,
)
ui.Spacer(width=5)
add_line_rect_flourish(True)
# ui.Spacer(width=ui.Fraction(1))
# ui.Spacer(width=10)
# with ui.Frame(width=0):
# with ui.VStack():
# with ui.Placer(offset_x=0, offset_y=7):
# ui.Rectangle(height=5, width=5, alignment=ui.Alignment.CENTER)
# ui.Spacer(width=5)
return btn
def state_btn_builder(
label="", type="state_button", a_text="STATE A", b_text="STATE B", tooltip="", on_clicked_fn=None
):
"""Creates a State Change Button that changes text when pressed.
Args:
label (str, optional): Label to the left of the UI element. Defaults to "".
type (str, optional): Type of UI element. Defaults to "button".
a_text (str, optional): Text rendered on the button for State A. Defaults to "STATE A".
b_text (str, optional): Text rendered on the button for State B. Defaults to "STATE B".
tooltip (str, optional): Tooltip to display over the Label. Defaults to "".
on_clicked_fn (Callable, optional): Call-back function when clicked. Defaults to None.
"""
def toggle():
if btn.text == a_text.upper():
btn.text = b_text.upper()
on_clicked_fn(True)
else:
btn.text = a_text.upper()
on_clicked_fn(False)
with ui.HStack():
ui.Label(label, width=LABEL_WIDTH, alignment=ui.Alignment.LEFT_CENTER, tooltip=format_tt(tooltip))
btn = ui.Button(
a_text.upper(),
name="Button",
width=BUTTON_WIDTH,
clicked_fn=toggle,
style=get_style(),
alignment=ui.Alignment.LEFT_CENTER,
)
ui.Spacer(width=5)
# add_line_rect_flourish(False)
ui.Spacer(width=ui.Fraction(1))
ui.Spacer(width=10)
with ui.Frame(width=0):
with ui.VStack():
with ui.Placer(offset_x=0, offset_y=7):
ui.Rectangle(height=5, width=5, alignment=ui.Alignment.CENTER)
ui.Spacer(width=5)
return btn
def cb_builder(label="", type="checkbox", default_val=False, tooltip="", on_clicked_fn=None):
"""Creates a Stylized Checkbox
Args:
label (str, optional): Label to the left of the UI element. Defaults to "".
type (str, optional): Type of UI element. Defaults to "checkbox".
default_val (bool, optional): Checked is True, Unchecked is False. Defaults to False.
tooltip (str, optional): Tooltip to display over the Label. Defaults to "".
on_clicked_fn (Callable, optional): Call-back function when clicked. Defaults to None.
Returns:
ui.SimpleBoolModel: model
"""
with ui.HStack():
ui.Label(label, width=LABEL_WIDTH - 12, alignment=ui.Alignment.LEFT_CENTER, tooltip=format_tt(tooltip))
model = ui.SimpleBoolModel()
callable = on_clicked_fn
if callable is None:
callable = lambda x: None
SimpleCheckBox(default_val, callable, model=model)
add_line_rect_flourish()
return model
def multi_btn_builder(
label="", type="multi_button", count=2, text=["button", "button"], tooltip=["", "", ""], on_clicked_fn=[None, None]
):
"""Creates a Row of Stylized Buttons
Args:
label (str, optional): Label to the left of the UI element. Defaults to "".
type (str, optional): Type of UI element. Defaults to "multi_button".
count (int, optional): Number of UI elements to create. Defaults to 2.
text (list, optional): List of text rendered on the UI elements. Defaults to ["button", "button"].
tooltip (list, optional): List of tooltips to display over the UI elements. Defaults to ["", "", ""].
on_clicked_fn (list, optional): List of call-backs function when clicked. Defaults to [None, None].
Returns:
list(ui.Button): List of Buttons
"""
btns = []
with ui.HStack():
ui.Label(label, width=LABEL_WIDTH, alignment=ui.Alignment.LEFT_CENTER, tooltip=format_tt(tooltip[0]))
for i in range(count):
btn = ui.Button(
text[i].upper(),
name="Button",
width=BUTTON_WIDTH,
clicked_fn=on_clicked_fn[i],
tooltip=format_tt(tooltip[i + 1]),
style=get_style(),
alignment=ui.Alignment.LEFT_CENTER,
)
btns.append(btn)
if i < count:
ui.Spacer(width=5)
add_line_rect_flourish()
return btns
def multi_cb_builder(
label="",
type="multi_checkbox",
count=2,
text=[" ", " "],
default_val=[False, False],
tooltip=["", "", ""],
on_clicked_fn=[None, None],
):
"""Creates a Row of Stylized Checkboxes.
Args:
label (str, optional): Label to the left of the UI element. Defaults to "".
type (str, optional): Type of UI element. Defaults to "multi_checkbox".
count (int, optional): Number of UI elements to create. Defaults to 2.
text (list, optional): List of text rendered on the UI elements. Defaults to [" ", " "].
default_val (list, optional): List of default values. Checked is True, Unchecked is False. Defaults to [False, False].
tooltip (list, optional): List of tooltips to display over the UI elements. Defaults to ["", "", ""].
on_clicked_fn (list, optional): List of call-backs function when clicked. Defaults to [None, None].
Returns:
list(ui.SimpleBoolModel): List of models
"""
cbs = []
with ui.HStack():
ui.Label(label, width=LABEL_WIDTH - 12, alignment=ui.Alignment.LEFT_CENTER, tooltip=format_tt(tooltip[0]))
for i in range(count):
cb = ui.SimpleBoolModel(default_value=default_val[i])
callable = on_clicked_fn[i]
if callable is None:
callable = lambda x: None
SimpleCheckBox(default_val[i], callable, model=cb)
ui.Label(
text[i], width=BUTTON_WIDTH / 2, alignment=ui.Alignment.LEFT_CENTER, tooltip=format_tt(tooltip[i + 1])
)
if i < count - 1:
ui.Spacer(width=5)
cbs.append(cb)
add_line_rect_flourish()
return cbs
def str_builder(
label="",
type="stringfield",
default_val=" ",
tooltip="",
on_clicked_fn=None,
use_folder_picker=False,
read_only=False,
item_filter_fn=None,
bookmark_label=None,
bookmark_path=None,
folder_dialog_title="Select Output Folder",
folder_button_title="Select Folder",
):
"""Creates a Stylized Stringfield Widget
Args:
label (str, optional): Label to the left of the UI element. Defaults to "".
type (str, optional): Type of UI element. Defaults to "stringfield".
default_val (str, optional): Text to initialize in Stringfield. Defaults to " ".
tooltip (str, optional): Tooltip to display over the UI elements. Defaults to "".
use_folder_picker (bool, optional): Add a folder picker button to the right. Defaults to False.
read_only (bool, optional): Prevents editing. Defaults to False.
item_filter_fn (Callable, optional): filter function to pass to the FilePicker
bookmark_label (str, optional): bookmark label to pass to the FilePicker
bookmark_path (str, optional): bookmark path to pass to the FilePicker
Returns:
AbstractValueModel: model of Stringfield
"""
with ui.HStack():
ui.Label(label, width=LABEL_WIDTH, alignment=ui.Alignment.LEFT_CENTER, tooltip=format_tt(tooltip))
str_field = ui.StringField(
name="StringField", width=ui.Fraction(1), height=0, alignment=ui.Alignment.LEFT_CENTER, read_only=read_only
).model
str_field.set_value(default_val)
if use_folder_picker:
def update_field(filename, path):
if filename == "":
val = path
elif filename[0] != "/" and path[-1] != "/":
val = path + "/" + filename
elif filename[0] == "/" and path[-1] == "/":
val = path + filename[1:]
else:
val = path + filename
str_field.set_value(val)
add_folder_picker_icon(
update_field,
item_filter_fn,
bookmark_label,
bookmark_path,
dialog_title=folder_dialog_title,
button_title=folder_button_title,
)
else:
add_line_rect_flourish(False)
return str_field
def int_builder(label="", type="intfield", default_val=0, tooltip="", min=sys.maxsize * -1, max=sys.maxsize):
"""Creates a Stylized Intfield Widget
Args:
label (str, optional): Label to the left of the UI element. Defaults to "".
type (str, optional): Type of UI element. Defaults to "intfield".
default_val (int, optional): Default Value of UI element. Defaults to 0.
tooltip (str, optional): Tooltip to display over the UI elements. Defaults to "".
min (int, optional): Minimum limit for int field. Defaults to sys.maxsize * -1
max (int, optional): Maximum limit for int field. Defaults to sys.maxsize * 1
Returns:
AbstractValueModel: model
"""
with ui.HStack():
ui.Label(label, width=LABEL_WIDTH, alignment=ui.Alignment.LEFT_CENTER, tooltip=format_tt(tooltip))
int_field = ui.IntDrag(
name="Field", height=LABEL_HEIGHT, min=min, max=max, alignment=ui.Alignment.LEFT_CENTER
).model
int_field.set_value(default_val)
add_line_rect_flourish(False)
return int_field
def float_builder(label="", type="floatfield", default_val=0, tooltip="", min=-inf, max=inf, step=0.1, format="%.2f"):
"""Creates a Stylized Floatfield Widget
Args:
label (str, optional): Label to the left of the UI element. Defaults to "".
type (str, optional): Type of UI element. Defaults to "floatfield".
default_val (int, optional): Default Value of UI element. Defaults to 0.
tooltip (str, optional): Tooltip to display over the UI elements. Defaults to "".
Returns:
AbstractValueModel: model
"""
with ui.HStack():
ui.Label(label, width=LABEL_WIDTH, alignment=ui.Alignment.LEFT_CENTER, tooltip=format_tt(tooltip))
float_field = ui.FloatDrag(
name="FloatField",
width=ui.Fraction(1),
height=0,
alignment=ui.Alignment.LEFT_CENTER,
min=min,
max=max,
step=step,
format=format,
).model
float_field.set_value(default_val)
add_line_rect_flourish(False)
return float_field
def combo_cb_str_builder(
label="",
type="checkbox_stringfield",
default_val=[False, " "],
tooltip="",
on_clicked_fn=lambda x: None,
use_folder_picker=False,
read_only=False,
folder_dialog_title="Select Output Folder",
folder_button_title="Select Folder",
):
"""Creates a Stylized Checkbox + Stringfield Widget
Args:
label (str, optional): Label to the left of the UI element. Defaults to "".
type (str, optional): Type of UI element. Defaults to "checkbox_stringfield".
default_val (str, optional): Text to initialize in Stringfield. Defaults to [False, " "].
tooltip (str, optional): Tooltip to display over the UI elements. Defaults to "".
use_folder_picker (bool, optional): Add a folder picker button to the right. Defaults to False.
read_only (bool, optional): Prevents editing. Defaults to False.
Returns:
Tuple(ui.SimpleBoolModel, AbstractValueModel): (cb_model, str_field_model)
"""
with ui.HStack():
ui.Label(label, width=LABEL_WIDTH - 12, alignment=ui.Alignment.LEFT_CENTER, tooltip=format_tt(tooltip))
cb = ui.SimpleBoolModel(default_value=default_val[0])
SimpleCheckBox(default_val[0], on_clicked_fn, model=cb)
str_field = ui.StringField(
name="StringField", width=ui.Fraction(1), height=0, alignment=ui.Alignment.LEFT_CENTER, read_only=read_only
).model
str_field.set_value(default_val[1])
if use_folder_picker:
def update_field(val):
str_field.set_value(val)
add_folder_picker_icon(update_field, dialog_title=folder_dialog_title, button_title=folder_button_title)
else:
add_line_rect_flourish(False)
return cb, str_field
def dropdown_builder(
label="", type="dropdown", default_val=0, items=["Option 1", "Option 2", "Option 3"], tooltip="", on_clicked_fn=None
):
"""Creates a Stylized Dropdown Combobox
Args:
label (str, optional): Label to the left of the UI element. Defaults to "".
type (str, optional): Type of UI element. Defaults to "dropdown".
default_val (int, optional): Default index of dropdown items. Defaults to 0.
items (list, optional): List of items for dropdown box. Defaults to ["Option 1", "Option 2", "Option 3"].
tooltip (str, optional): Tooltip to display over the Label. Defaults to "".
on_clicked_fn (Callable, optional): Call-back function when clicked. Defaults to None.
Returns:
AbstractItemModel: model
"""
with ui.HStack():
ui.Label(label, width=LABEL_WIDTH, alignment=ui.Alignment.LEFT_CENTER, tooltip=format_tt(tooltip))
combo_box = ui.ComboBox(
default_val, *items, name="ComboBox", width=ui.Fraction(1), alignment=ui.Alignment.LEFT_CENTER
).model
add_line_rect_flourish(False)
def on_clicked_wrapper(model, val):
on_clicked_fn(items[model.get_item_value_model().as_int])
if on_clicked_fn is not None:
combo_box.add_item_changed_fn(on_clicked_wrapper)
return combo_box
def combo_intfield_slider_builder(
label="", type="intfield_stringfield", default_val=0.5, min=0, max=1, step=0.01, tooltip=["", ""]
):
"""Creates a Stylized IntField + Stringfield Widget
Args:
label (str, optional): Label to the left of the UI element. Defaults to "".
type (str, optional): Type of UI element. Defaults to "intfield_stringfield".
default_val (float, optional): Default Value. Defaults to 0.5.
min (int, optional): Minimum Value. Defaults to 0.
max (int, optional): Maximum Value. Defaults to 1.
step (float, optional): Step. Defaults to 0.01.
tooltip (list, optional): List of tooltips. Defaults to ["", ""].
Returns:
Tuple(AbstractValueModel, IntSlider): (flt_field_model, flt_slider_model)
"""
with ui.HStack():
ui.Label(label, width=LABEL_WIDTH, alignment=ui.Alignment.LEFT_CENTER, tooltip=format_tt(tooltip[0]))
ff = ui.IntDrag(
name="Field", width=BUTTON_WIDTH / 2, alignment=ui.Alignment.LEFT_CENTER, tooltip=format_tt(tooltip[1])
).model
ff.set_value(default_val)
ui.Spacer(width=5)
fs = ui.IntSlider(
width=ui.Fraction(1), alignment=ui.Alignment.LEFT_CENTER, min=min, max=max, step=step, model=ff
)
add_line_rect_flourish(False)
return ff, fs
def combo_floatfield_slider_builder(
label="", type="floatfield_stringfield", default_val=0.5, min=0, max=1, step=0.01, tooltip=["", ""]
):
"""Creates a Stylized FloatField + FloatSlider Widget
Args:
label (str, optional): Label to the left of the UI element. Defaults to "".
type (str, optional): Type of UI element. Defaults to "floatfield_stringfield".
default_val (float, optional): Default Value. Defaults to 0.5.
min (int, optional): Minimum Value. Defaults to 0.
max (int, optional): Maximum Value. Defaults to 1.
step (float, optional): Step. Defaults to 0.01.
tooltip (list, optional): List of tooltips. Defaults to ["", ""].
Returns:
Tuple(AbstractValueModel, IntSlider): (flt_field_model, flt_slider_model)
"""
with ui.HStack():
ui.Label(label, width=LABEL_WIDTH, alignment=ui.Alignment.LEFT_CENTER, tooltip=format_tt(tooltip[0]))
ff = ui.FloatField(
name="Field", width=BUTTON_WIDTH / 2, alignment=ui.Alignment.LEFT_CENTER, tooltip=format_tt(tooltip[1])
).model
ff.set_value(default_val)
ui.Spacer(width=5)
fs = ui.FloatSlider(
width=ui.Fraction(1), alignment=ui.Alignment.LEFT_CENTER, min=min, max=max, step=step, model=ff
)
add_line_rect_flourish(False)
return ff, fs
def multi_dropdown_builder(
label="",
type="multi_dropdown",
count=2,
default_val=[0, 0],
items=[["Option 1", "Option 2", "Option 3"], ["Option A", "Option B", "Option C"]],
tooltip="",
on_clicked_fn=[None, None],
):
"""Creates a Stylized Multi-Dropdown Combobox
Returns:
AbstractItemModel: model
Args:
label (str, optional): Label to the left of the UI element. Defaults to "".
type (str, optional): Type of UI element. Defaults to "multi_dropdown".
count (int, optional): Number of UI elements. Defaults to 2.
default_val (list(int), optional): List of default indices of dropdown items. Defaults to 0.. Defaults to [0, 0].
items (list(list), optional): List of list of items for dropdown boxes. Defaults to [["Option 1", "Option 2", "Option 3"], ["Option A", "Option B", "Option C"]].
tooltip (str, optional): Tooltip to display over the Label. Defaults to "".
on_clicked_fn (list(Callable), optional): List of call-back function when clicked. Defaults to [None, None].
Returns:
list(AbstractItemModel): list(models)
"""
elems = []
with ui.HStack():
ui.Label(label, width=LABEL_WIDTH, alignment=ui.Alignment.LEFT_CENTER, tooltip=format_tt(tooltip))
for i in range(count):
elem = ui.ComboBox(
default_val[i], *items[i], name="ComboBox", width=ui.Fraction(1), alignment=ui.Alignment.LEFT_CENTER
)
def on_clicked_wrapper(model, val, index):
on_clicked_fn[index](items[index][model.get_item_value_model().as_int])
elem.model.add_item_changed_fn(lambda m, v, index=i: on_clicked_wrapper(m, v, index))
elems.append(elem)
if i < count - 1:
ui.Spacer(width=5)
add_line_rect_flourish(False)
return elems
def combo_cb_dropdown_builder(
label="",
type="checkbox_dropdown",
default_val=[False, 0],
items=["Option 1", "Option 2", "Option 3"],
tooltip="",
on_clicked_fn=[lambda x: None, None],
):
"""Creates a Stylized Dropdown Combobox with an Enable Checkbox
Args:
label (str, optional): Label to the left of the UI element. Defaults to "".
type (str, optional): Type of UI element. Defaults to "checkbox_dropdown".
default_val (list, optional): list(cb_default, dropdown_default). Defaults to [False, 0].
items (list, optional): List of items for dropdown box. Defaults to ["Option 1", "Option 2", "Option 3"].
tooltip (str, optional): Tooltip to display over the Label. Defaults to "".
on_clicked_fn (list, optional): List of callback functions. Defaults to [lambda x: None, None].
Returns:
Tuple(ui.SimpleBoolModel, ui.ComboBox): (cb_model, combobox)
"""
with ui.HStack():
ui.Label(label, width=LABEL_WIDTH - 12, alignment=ui.Alignment.LEFT_CENTER, tooltip=format_tt(tooltip))
cb = ui.SimpleBoolModel(default_value=default_val[0])
SimpleCheckBox(default_val[0], on_clicked_fn[0], model=cb)
combo_box = ui.ComboBox(
default_val[1], *items, name="ComboBox", width=ui.Fraction(1), alignment=ui.Alignment.LEFT_CENTER
)
def on_clicked_wrapper(model, val):
on_clicked_fn[1](items[model.get_item_value_model().as_int])
combo_box.model.add_item_changed_fn(on_clicked_wrapper)
add_line_rect_flourish(False)
return cb, combo_box
def scrolling_frame_builder(label="", type="scrolling_frame", default_val="No Data", tooltip=""):
"""Creates a Labeled Scrolling Frame with CopyToClipboard button
Args:
label (str, optional): Label to the left of the UI element. Defaults to "".
type (str, optional): Type of UI element. Defaults to "scrolling_frame".
default_val (str, optional): Default Text. Defaults to "No Data".
tooltip (str, optional): Tooltip to display over the Label. Defaults to "".
Returns:
ui.Label: label
"""
with ui.VStack(style=get_style(), spacing=5):
with ui.HStack():
ui.Label(label, width=LABEL_WIDTH, alignment=ui.Alignment.LEFT_TOP, tooltip=format_tt(tooltip))
with ui.ScrollingFrame(
height=LABEL_HEIGHT * 5,
style_type_name_override="ScrollingFrame",
alignment=ui.Alignment.LEFT_TOP,
horizontal_scrollbar_policy=ui.ScrollBarPolicy.SCROLLBAR_AS_NEEDED,
vertical_scrollbar_policy=ui.ScrollBarPolicy.SCROLLBAR_ALWAYS_ON,
):
text = ui.Label(
default_val,
style_type_name_override="Label::label",
word_wrap=True,
alignment=ui.Alignment.LEFT_TOP,
)
with ui.Frame(width=0, tooltip="Copy To Clipboard"):
ui.Button(
name="IconButton",
width=20,
height=20,
clicked_fn=lambda: on_copy_to_clipboard(to_copy=text.text),
style=get_style()["IconButton.Image::CopyToClipboard"],
alignment=ui.Alignment.RIGHT_TOP,
)
return text
def combo_cb_scrolling_frame_builder(
label="", type="cb_scrolling_frame", default_val=[False, "No Data"], tooltip="", on_clicked_fn=lambda x: None
):
"""Creates a Labeled, Checkbox-enabled Scrolling Frame with CopyToClipboard button
Args:
label (str, optional): Label to the left of the UI element. Defaults to "".
type (str, optional): Type of UI element. Defaults to "cb_scrolling_frame".
default_val (list, optional): List of Checkbox and Frame Defaults. Defaults to [False, "No Data"].
tooltip (str, optional): Tooltip to display over the Label. Defaults to "".
on_clicked_fn (Callable, optional): Callback function when clicked. Defaults to lambda x : None.
Returns:
list(SimpleBoolModel, ui.Label): (model, label)
"""
with ui.VStack(style=get_style(), spacing=5):
with ui.HStack():
ui.Label(label, width=LABEL_WIDTH - 12, alignment=ui.Alignment.LEFT_TOP, tooltip=format_tt(tooltip))
with ui.VStack(width=0):
cb = ui.SimpleBoolModel(default_value=default_val[0])
SimpleCheckBox(default_val[0], on_clicked_fn, model=cb)
ui.Spacer(height=18 * 4)
with ui.ScrollingFrame(
height=18 * 5,
style_type_name_override="ScrollingFrame",
alignment=ui.Alignment.LEFT_TOP,
horizontal_scrollbar_policy=ui.ScrollBarPolicy.SCROLLBAR_AS_NEEDED,
vertical_scrollbar_policy=ui.ScrollBarPolicy.SCROLLBAR_ALWAYS_ON,
):
text = ui.Label(
default_val[1],
style_type_name_override="Label::label",
word_wrap=True,
alignment=ui.Alignment.LEFT_TOP,
)
with ui.Frame(width=0, tooltip="Copy to Clipboard"):
ui.Button(
name="IconButton",
width=20,
height=20,
clicked_fn=lambda: on_copy_to_clipboard(to_copy=text.text),
style=get_style()["IconButton.Image::CopyToClipboard"],
alignment=ui.Alignment.RIGHT_TOP,
)
return cb, text
def xyz_builder(
label="",
tooltip="",
axis_count=3,
default_val=[0.0, 0.0, 0.0, 0.0],
min=float("-inf"),
max=float("inf"),
step=0.001,
on_value_changed_fn=[None, None, None, None],
):
"""[summary]
Args:
label (str, optional): Label to the left of the UI element. Defaults to "".
type (str, optional): Type of UI element. Defaults to "".
axis_count (int, optional): Number of Axes to Display. Max 4. Defaults to 3.
default_val (list, optional): List of default values. Defaults to [0.0, 0.0, 0.0, 0.0].
min (float, optional): Minimum Float Value. Defaults to float("-inf").
max (float, optional): Maximum Float Value. Defaults to float("inf").
step (float, optional): Step. Defaults to 0.001.
on_value_changed_fn (list, optional): List of callback functions for each axes. Defaults to [None, None, None, None].
Returns:
list(AbstractValueModel): list(model)
"""
# These styles & colors are taken from omni.kit.property.transform_builder.py _create_multi_float_drag_matrix_with_labels
if axis_count <= 0 or axis_count > 4:
import builtins
carb.log_warn("Invalid axis_count: must be in range 1 to 4. Clamping to default range.")
axis_count = builtins.max(builtins.min(axis_count, 4), 1)
field_labels = [("X", COLOR_X), ("Y", COLOR_Y), ("Z", COLOR_Z), ("W", COLOR_W)]
field_tooltips = ["X Value", "Y Value", "Z Value", "W Value"]
RECT_WIDTH = 13
# SPACING = 4
val_models = [None] * axis_count
with ui.HStack():
ui.Label(label, width=LABEL_WIDTH, alignment=ui.Alignment.LEFT_CENTER, tooltip=format_tt(tooltip))
with ui.ZStack():
with ui.HStack():
ui.Spacer(width=RECT_WIDTH)
for i in range(axis_count):
val_models[i] = ui.FloatDrag(
name="Field",
height=LABEL_HEIGHT,
min=min,
max=max,
step=step,
alignment=ui.Alignment.LEFT_CENTER,
tooltip=field_tooltips[i],
).model
val_models[i].set_value(default_val[i])
if on_value_changed_fn[i] is not None:
val_models[i].add_value_changed_fn(on_value_changed_fn[i])
if i != axis_count - 1:
ui.Spacer(width=19)
with ui.HStack():
for i in range(axis_count):
if i != 0:
ui.Spacer() # width=BUTTON_WIDTH - 1)
field_label = field_labels[i]
with ui.ZStack(width=RECT_WIDTH + 2 * i):
ui.Rectangle(name="vector_label", style={"background_color": field_label[1]})
ui.Label(field_label[0], name="vector_label", alignment=ui.Alignment.CENTER)
ui.Spacer()
add_line_rect_flourish(False)
return val_models
def color_picker_builder(label="", type="color_picker", default_val=[1.0, 1.0, 1.0, 1.0], tooltip="Color Picker"):
"""Creates a Color Picker Widget
Args:
label (str, optional): Label to the left of the UI element. Defaults to "".
type (str, optional): Type of UI element. Defaults to "color_picker".
default_val (list, optional): List of (R,G,B,A) default values. Defaults to [1.0, 1.0, 1.0, 1.0].
tooltip (str, optional): Tooltip to display over the Label. Defaults to "Color Picker".
Returns:
AbstractItemModel: ui.ColorWidget.model
"""
with ui.HStack():
ui.Label(label, width=LABEL_WIDTH, alignment=ui.Alignment.LEFT_CENTER, tooltip=format_tt(tooltip))
model = ui.ColorWidget(*default_val, width=BUTTON_WIDTH).model
ui.Spacer(width=5)
add_line_rect_flourish()
return model
def progress_bar_builder(label="", type="progress_bar", default_val=0, tooltip="Progress"):
"""Creates a Progress Bar Widget
Args:
label (str, optional): Label to the left of the UI element. Defaults to "".
type (str, optional): Type of UI element. Defaults to "progress_bar".
default_val (int, optional): Starting Value. Defaults to 0.
tooltip (str, optional): Tooltip to display over the Label. Defaults to "Progress".
Returns:
AbstractValueModel: ui.ProgressBar().model
"""
with ui.HStack():
ui.Label(label, width=LABEL_WIDTH, alignment=ui.Alignment.LEFT_CENTER)
model = ui.ProgressBar().model
model.set_value(default_val)
add_line_rect_flourish(False)
return model
def plot_builder(label="", data=None, min=-1, max=1, type=ui.Type.LINE, value_stride=1, color=None, tooltip=""):
"""Creates a stylized static plot
Args:
label (str, optional): Label to the left of the UI element. Defaults to "".
data (list(float), optional): Data to plot. Defaults to None.
min (int, optional): Minimum Y Value. Defaults to -1.
max (int, optional): Maximum Y Value. Defaults to 1.
type (ui.Type, optional): Plot Type. Defaults to ui.Type.LINE.
value_stride (int, optional): Width of plot stride. Defaults to 1.
color (int, optional): Plot color. Defaults to None.
tooltip (str, optional): Tooltip to display over the Label. Defaults to "".
Returns:
ui.Plot: plot
"""
with ui.VStack(spacing=5):
with ui.HStack():
ui.Label(label, width=LABEL_WIDTH, alignment=ui.Alignment.LEFT_TOP, tooltip=format_tt(tooltip))
plot_height = LABEL_HEIGHT * 2 + 13
plot_width = ui.Fraction(1)
with ui.ZStack():
ui.Rectangle(width=plot_width, height=plot_height)
if not color:
color = 0xFFDDDDDD
plot = ui.Plot(
type,
min,
max,
*data,
value_stride=value_stride,
width=plot_width,
height=plot_height,
style={"color": color, "background_color": 0x0},
)
def update_min(model):
plot.scale_min = model.as_float
def update_max(model):
plot.scale_max = model.as_float
ui.Spacer(width=5)
with ui.Frame(width=0):
with ui.VStack(spacing=5):
max_model = ui.FloatDrag(
name="Field", width=40, alignment=ui.Alignment.LEFT_BOTTOM, tooltip="Max"
).model
max_model.set_value(max)
min_model = ui.FloatDrag(
name="Field", width=40, alignment=ui.Alignment.LEFT_TOP, tooltip="Min"
).model
min_model.set_value(min)
min_model.add_value_changed_fn(update_min)
max_model.add_value_changed_fn(update_max)
ui.Spacer(width=20)
add_separator()
return plot
def xyz_plot_builder(label="", data=[], min=-1, max=1, tooltip=""):
"""Creates a stylized static XYZ plot
Args:
label (str, optional): Label to the left of the UI element. Defaults to "".
data (list(float), optional): Data to plot. Defaults to [].
min (int, optional): Minimum Y Value. Defaults to -1.
max (int, optional): Maximum Y Value. Defaults to "".
tooltip (str, optional): Tooltip to display over the Label.. Defaults to "".
Returns:
list(ui.Plot): list(x_plot, y_plot, z_plot)
"""
with ui.VStack(spacing=5):
with ui.HStack():
ui.Label(label, width=LABEL_WIDTH, alignment=ui.Alignment.LEFT_TOP, tooltip=format_tt(tooltip))
plot_height = LABEL_HEIGHT * 2 + 13
plot_width = ui.Fraction(1)
with ui.ZStack():
ui.Rectangle(width=plot_width, height=plot_height)
plot_0 = ui.Plot(
ui.Type.LINE,
min,
max,
*data[0],
width=plot_width,
height=plot_height,
style=get_style()["PlotLabel::X"],
)
plot_1 = ui.Plot(
ui.Type.LINE,
min,
max,
*data[1],
width=plot_width,
height=plot_height,
style=get_style()["PlotLabel::Y"],
)
plot_2 = ui.Plot(
ui.Type.LINE,
min,
max,
*data[2],
width=plot_width,
height=plot_height,
style=get_style()["PlotLabel::Z"],
)
def update_min(model):
plot_0.scale_min = model.as_float
plot_1.scale_min = model.as_float
plot_2.scale_min = model.as_float
def update_max(model):
plot_0.scale_max = model.as_float
plot_1.scale_max = model.as_float
plot_2.scale_max = model.as_float
ui.Spacer(width=5)
with ui.Frame(width=0):
with ui.VStack(spacing=5):
max_model = ui.FloatDrag(
name="Field", width=40, alignment=ui.Alignment.LEFT_BOTTOM, tooltip="Max"
).model
max_model.set_value(max)
min_model = ui.FloatDrag(
name="Field", width=40, alignment=ui.Alignment.LEFT_TOP, tooltip="Min"
).model
min_model.set_value(min)
min_model.add_value_changed_fn(update_min)
max_model.add_value_changed_fn(update_max)
ui.Spacer(width=20)
add_separator()
return [plot_0, plot_1, plot_2]
def combo_cb_plot_builder(
label="",
default_val=False,
on_clicked_fn=lambda x: None,
data=None,
min=-1,
max=1,
type=ui.Type.LINE,
value_stride=1,
color=None,
tooltip="",
):
"""Creates a Checkbox-Enabled dyanamic plot
Args:
label (str, optional): Label to the left of the UI element. Defaults to "".
default_val (bool, optional): Checkbox default. Defaults to False.
on_clicked_fn (Callable, optional): Checkbox Callback function. Defaults to lambda x: None.
data (list(), optional): Data to plat. Defaults to None.
min (int, optional): Min Y Value. Defaults to -1.
max (int, optional): Max Y Value. Defaults to 1.
type (ui.Type, optional): Plot Type. Defaults to ui.Type.LINE.
value_stride (int, optional): Width of plot stride. Defaults to 1.
color (int, optional): Plot color. Defaults to None.
tooltip (str, optional): Tooltip to display over the Label. Defaults to "".
Returns:
list(SimpleBoolModel, ui.Plot): (cb_model, plot)
"""
with ui.VStack(spacing=5):
with ui.HStack():
# Label
ui.Label(label, width=LABEL_WIDTH, alignment=ui.Alignment.LEFT_TOP, tooltip=format_tt(tooltip))
# Checkbox
with ui.Frame(width=0):
with ui.Placer(offset_x=-10, offset_y=0):
with ui.VStack():
SimpleCheckBox(default_val, on_clicked_fn)
ui.Spacer(height=ui.Fraction(1))
ui.Spacer()
# Plot
plot_height = LABEL_HEIGHT * 2 + 13
plot_width = ui.Fraction(1)
with ui.ZStack():
ui.Rectangle(width=plot_width, height=plot_height)
if not color:
color = 0xFFDDDDDD
plot = ui.Plot(
type,
min,
max,
*data,
value_stride=value_stride,
width=plot_width,
height=plot_height,
style={"color": color, "background_color": 0x0},
)
# Min/Max Helpers
def update_min(model):
plot.scale_min = model.as_float
def update_max(model):
plot.scale_max = model.as_float
ui.Spacer(width=5)
with ui.Frame(width=0):
with ui.VStack(spacing=5):
# Min/Max Fields
max_model = ui.FloatDrag(
name="Field", width=40, alignment=ui.Alignment.LEFT_BOTTOM, tooltip="Max"
).model
max_model.set_value(max)
min_model = ui.FloatDrag(
name="Field", width=40, alignment=ui.Alignment.LEFT_TOP, tooltip="Min"
).model
min_model.set_value(min)
min_model.add_value_changed_fn(update_min)
max_model.add_value_changed_fn(update_max)
ui.Spacer(width=20)
with ui.HStack():
ui.Spacer(width=LABEL_WIDTH + 29)
# Current Value Field (disabled by default)
val_model = ui.FloatDrag(
name="Field",
width=BUTTON_WIDTH,
height=LABEL_HEIGHT,
enabled=False,
alignment=ui.Alignment.LEFT_CENTER,
tooltip="Value",
).model
add_separator()
return plot, val_model
def combo_cb_xyz_plot_builder(
label="",
default_val=False,
on_clicked_fn=lambda x: None,
data=[],
min=-1,
max=1,
type=ui.Type.LINE,
value_stride=1,
tooltip="",
):
"""[summary]
Args:
label (str, optional): Label to the left of the UI element. Defaults to "".
default_val (bool, optional): Checkbox default. Defaults to False.
on_clicked_fn (Callable, optional): Checkbox Callback function. Defaults to lambda x: None.
data list(), optional): Data to plat. Defaults to None.
min (int, optional): Min Y Value. Defaults to -1.
max (int, optional): Max Y Value. Defaults to 1.
type (ui.Type, optional): Plot Type. Defaults to ui.Type.LINE.
value_stride (int, optional): Width of plot stride. Defaults to 1.
tooltip (str, optional): Tooltip to display over the Label. Defaults to "".
Returns:
Tuple(list(ui.Plot), list(AbstractValueModel)): ([plot_0, plot_1, plot_2], [val_model_x, val_model_y, val_model_z])
"""
with ui.VStack(spacing=5):
with ui.HStack():
ui.Label(label, width=LABEL_WIDTH, alignment=ui.Alignment.LEFT_TOP, tooltip=format_tt(tooltip))
# Checkbox
with ui.Frame(width=0):
with ui.Placer(offset_x=-10, offset_y=0):
with ui.VStack():
SimpleCheckBox(default_val, on_clicked_fn)
ui.Spacer(height=ui.Fraction(1))
ui.Spacer()
# Plots
plot_height = LABEL_HEIGHT * 2 + 13
plot_width = ui.Fraction(1)
with ui.ZStack():
ui.Rectangle(width=plot_width, height=plot_height)
plot_0 = ui.Plot(
type,
min,
max,
*data[0],
value_stride=value_stride,
width=plot_width,
height=plot_height,
style=get_style()["PlotLabel::X"],
)
plot_1 = ui.Plot(
type,
min,
max,
*data[1],
value_stride=value_stride,
width=plot_width,
height=plot_height,
style=get_style()["PlotLabel::Y"],
)
plot_2 = ui.Plot(
type,
min,
max,
*data[2],
value_stride=value_stride,
width=plot_width,
height=plot_height,
style=get_style()["PlotLabel::Z"],
)
def update_min(model):
plot_0.scale_min = model.as_float
plot_1.scale_min = model.as_float
plot_2.scale_min = model.as_float
def update_max(model):
plot_0.scale_max = model.as_float
plot_1.scale_max = model.as_float
plot_2.scale_max = model.as_float
ui.Spacer(width=5)
with ui.Frame(width=0):
with ui.VStack(spacing=5):
max_model = ui.FloatDrag(
name="Field", width=40, alignment=ui.Alignment.LEFT_BOTTOM, tooltip="Max"
).model
max_model.set_value(max)
min_model = ui.FloatDrag(
name="Field", width=40, alignment=ui.Alignment.LEFT_TOP, tooltip="Min"
).model
min_model.set_value(min)
min_model.add_value_changed_fn(update_min)
max_model.add_value_changed_fn(update_max)
ui.Spacer(width=20)
# with ui.HStack():
# ui.Spacer(width=40)
# val_models = xyz_builder()#**{"args":args})
field_labels = [("X", COLOR_X), ("Y", COLOR_Y), ("Z", COLOR_Z), ("W", COLOR_W)]
RECT_WIDTH = 13
# SPACING = 4
with ui.HStack():
ui.Spacer(width=LABEL_WIDTH + 29)
with ui.ZStack():
with ui.HStack():
ui.Spacer(width=RECT_WIDTH)
# value_widget = ui.MultiFloatDragField(
# *args, name="multivalue", min=min, max=max, step=step, h_spacing=RECT_WIDTH + SPACING, v_spacing=2
# ).model
val_model_x = ui.FloatDrag(
name="Field",
width=BUTTON_WIDTH - 5,
height=LABEL_HEIGHT,
enabled=False,
alignment=ui.Alignment.LEFT_CENTER,
tooltip="X Value",
).model
ui.Spacer(width=19)
val_model_y = ui.FloatDrag(
name="Field",
width=BUTTON_WIDTH - 5,
height=LABEL_HEIGHT,
enabled=False,
alignment=ui.Alignment.LEFT_CENTER,
tooltip="Y Value",
).model
ui.Spacer(width=19)
val_model_z = ui.FloatDrag(
name="Field",
width=BUTTON_WIDTH - 5,
height=LABEL_HEIGHT,
enabled=False,
alignment=ui.Alignment.LEFT_CENTER,
tooltip="Z Value",
).model
with ui.HStack():
for i in range(3):
if i != 0:
ui.Spacer(width=BUTTON_WIDTH - 1)
field_label = field_labels[i]
with ui.ZStack(width=RECT_WIDTH + 1):
ui.Rectangle(name="vector_label", style={"background_color": field_label[1]})
ui.Label(field_label[0], name="vector_label", alignment=ui.Alignment.CENTER)
add_separator()
return [plot_0, plot_1, plot_2], [val_model_x, val_model_y, val_model_z]
def add_line_rect_flourish(draw_line=True):
"""Aesthetic element that adds a Line + Rectangle after all UI elements in the row.
Args:
draw_line (bool, optional): Set false to only draw rectangle. Defaults to True.
"""
if draw_line:
ui.Line(style={"color": 0x338A8777}, width=ui.Fraction(1), alignment=ui.Alignment.CENTER)
ui.Spacer(width=10)
with ui.Frame(width=0):
with ui.VStack():
with ui.Placer(offset_x=0, offset_y=7):
ui.Rectangle(height=5, width=5, alignment=ui.Alignment.CENTER)
ui.Spacer(width=5)
def add_separator():
"""Aesthetic element to adds a Line Separator."""
with ui.VStack(spacing=5):
ui.Spacer()
with ui.HStack():
ui.Spacer(width=LABEL_WIDTH)
ui.Line(style={"color": 0x338A8777}, width=ui.Fraction(1))
ui.Spacer(width=20)
ui.Spacer()
def add_folder_picker_icon(
on_click_fn,
item_filter_fn=None,
bookmark_label=None,
bookmark_path=None,
dialog_title="Select Output Folder",
button_title="Select Folder",
):
def open_file_picker():
def on_selected(filename, path):
on_click_fn(filename, path)
file_picker.hide()
def on_canceled(a, b):
file_picker.hide()
file_picker = FilePickerDialog(
dialog_title,
allow_multi_selection=False,
apply_button_label=button_title,
click_apply_handler=lambda a, b: on_selected(a, b),
click_cancel_handler=lambda a, b: on_canceled(a, b),
item_filter_fn=item_filter_fn,
enable_versioning_pane=True,
)
if bookmark_label and bookmark_path:
file_picker.toggle_bookmark_from_path(bookmark_label, bookmark_path, True)
with ui.Frame(width=0, tooltip=button_title):
ui.Button(
name="IconButton",
width=24,
height=24,
clicked_fn=open_file_picker,
style=get_style()["IconButton.Image::FolderPicker"],
alignment=ui.Alignment.RIGHT_TOP,
)
def add_folder_picker_btn(on_click_fn):
def open_folder_picker():
def on_selected(a, b):
on_click_fn(a, b)
folder_picker.hide()
def on_canceled(a, b):
folder_picker.hide()
folder_picker = FilePickerDialog(
"Select Output Folder",
allow_multi_selection=False,
apply_button_label="Select Folder",
click_apply_handler=lambda a, b: on_selected(a, b),
click_cancel_handler=lambda a, b: on_canceled(a, b),
)
with ui.Frame(width=0):
ui.Button("SELECT", width=BUTTON_WIDTH, clicked_fn=open_folder_picker, tooltip="Select Folder")
def format_tt(tt):
import string
formated = ""
i = 0
for w in tt.split():
if w.isupper():
formated += w + " "
elif len(w) > 3 or i == 0:
formated += string.capwords(w) + " "
else:
formated += w.lower() + " "
i += 1
return formated
def setup_ui_headers(
ext_id,
file_path,
title="My Custom Extension",
doc_link="https://docs.omniverse.nvidia.com/app_isaacsim/app_isaacsim/overview.html",
overview="",
):
"""Creates the Standard UI Elements at the top of each Isaac Extension.
Args:
ext_id (str): Extension ID.
file_path (str): File path to source code.
title (str, optional): Name of Extension. Defaults to "My Custom Extension".
doc_link (str, optional): Hyperlink to Documentation. Defaults to "https://docs.omniverse.nvidia.com/app_isaacsim/app_isaacsim/overview.html".
overview (str, optional): Overview Text explaining the Extension. Defaults to "".
"""
ext_manager = omni.kit.app.get_app().get_extension_manager()
extension_path = ext_manager.get_extension_path(ext_id)
ext_path = os.path.dirname(extension_path) if os.path.isfile(extension_path) else extension_path
build_header(ext_path, file_path, title, doc_link)
build_info_frame(overview)
def build_header(
ext_path,
file_path,
title="My Custom Extension",
doc_link="https://docs.omniverse.nvidia.com/app_isaacsim/app_isaacsim/overview.html",
):
"""Title Header with Quick Access Utility Buttons."""
def build_icon_bar():
"""Adds the Utility Buttons to the Title Header"""
with ui.Frame(style=get_style(), width=0):
with ui.VStack():
with ui.HStack():
icon_size = 24
with ui.Frame(tooltip="Open Source Code"):
ui.Button(
name="IconButton",
width=icon_size,
height=icon_size,
clicked_fn=lambda: on_open_IDE_clicked(ext_path, file_path),
style=get_style()["IconButton.Image::OpenConfig"],
# style_type_name_override="IconButton.Image::OpenConfig",
alignment=ui.Alignment.LEFT_CENTER,
# tooltip="Open in IDE",
)
with ui.Frame(tooltip="Open Containing Folder"):
ui.Button(
name="IconButton",
width=icon_size,
height=icon_size,
clicked_fn=lambda: on_open_folder_clicked(file_path),
style=get_style()["IconButton.Image::OpenFolder"],
alignment=ui.Alignment.LEFT_CENTER,
)
with ui.Placer(offset_x=0, offset_y=3):
with ui.Frame(tooltip="Link to Docs"):
ui.Button(
name="IconButton",
width=icon_size - icon_size * 0.25,
height=icon_size - icon_size * 0.25,
clicked_fn=lambda: on_docs_link_clicked(doc_link),
style=get_style()["IconButton.Image::OpenLink"],
alignment=ui.Alignment.LEFT_TOP,
)
with ui.ZStack():
ui.Rectangle(style={"border_radius": 5})
with ui.HStack():
ui.Spacer(width=5)
ui.Label(title, width=0, name="title", style={"font_size": 16})
ui.Spacer(width=ui.Fraction(1))
build_icon_bar()
ui.Spacer(width=5)
def build_info_frame(overview=""):
"""Info Frame with Overview, Instructions, and Metadata for an Extension"""
frame = ui.CollapsableFrame(
title="Information",
height=0,
collapsed=True,
horizontal_clipping=False,
style=get_style(),
style_type_name_override="CollapsableFrame",
horizontal_scrollbar_policy=ui.ScrollBarPolicy.SCROLLBAR_AS_NEEDED,
vertical_scrollbar_policy=ui.ScrollBarPolicy.SCROLLBAR_ALWAYS_ON,
)
with frame:
label = "Overview"
default_val = overview
tooltip = "Overview"
with ui.VStack(style=get_style(), spacing=5):
with ui.HStack():
ui.Label(label, width=LABEL_WIDTH / 2, alignment=ui.Alignment.LEFT_TOP, tooltip=format_tt(tooltip))
with ui.ScrollingFrame(
height=LABEL_HEIGHT * 5,
style_type_name_override="ScrollingFrame",
alignment=ui.Alignment.LEFT_TOP,
horizontal_scrollbar_policy=ui.ScrollBarPolicy.SCROLLBAR_AS_NEEDED,
vertical_scrollbar_policy=ui.ScrollBarPolicy.SCROLLBAR_ALWAYS_ON,
):
text = ui.Label(
default_val,
style_type_name_override="Label::label",
word_wrap=True,
alignment=ui.Alignment.LEFT_TOP,
)
with ui.Frame(width=0, tooltip="Copy To Clipboard"):
ui.Button(
name="IconButton",
width=20,
height=20,
clicked_fn=lambda: on_copy_to_clipboard(to_copy=text.text),
style=get_style()["IconButton.Image::CopyToClipboard"],
alignment=ui.Alignment.RIGHT_TOP,
)
return
# def build_settings_frame(log_filename="extension.log", log_to_file=False, save_settings=False):
# """Settings Frame for Common Utilities Functions"""
# frame = ui.CollapsableFrame(
# title="Settings",
# height=0,
# collapsed=True,
# horizontal_clipping=False,
# style=get_style(),
# style_type_name_override="CollapsableFrame",
# )
# def on_log_to_file_enabled(val):
# # TO DO
# carb.log_info(f"Logging to {model.get_value_as_string()}:", val)
# def on_save_out_settings(val):
# # TO DO
# carb.log_info("Save Out Settings?", val)
# with frame:
# with ui.VStack(style=get_style(), spacing=5):
# # # Log to File Settings
# # default_output_path = os.path.realpath(os.getcwd())
# # kwargs = {
# # "label": "Log to File",
# # "type": "checkbox_stringfield",
# # "default_val": [log_to_file, default_output_path + "/" + log_filename],
# # "on_clicked_fn": on_log_to_file_enabled,
# # "tooltip": "Log Out to File",
# # "use_folder_picker": True,
# # }
# # model = combo_cb_str_builder(**kwargs)[1]
# # Save Settings on Exit
# # kwargs = {
# # "label": "Save Settings",
# # "type": "checkbox",
# # "default_val": save_settings,
# # "on_clicked_fn": on_save_out_settings,
# # "tooltip": "Save out GUI Settings on Exit.",
# # }
# # cb_builder(**kwargs)
class SearchListItem(ui.AbstractItem):
def __init__(self, text):
super().__init__()
self.name_model = ui.SimpleStringModel(text)
def __repr__(self):
return f'"{self.name_model.as_string}"'
def name(self):
return self.name_model.as_string
class SearchListItemModel(ui.AbstractItemModel):
"""
Represents the model for lists. It's very easy to initialize it
with any string list:
string_list = ["Hello", "World"]
model = ListModel(*string_list)
ui.TreeView(model)
"""
def __init__(self, *args):
super().__init__()
self._children = [SearchListItem(t) for t in args]
self._filtered = [SearchListItem(t) for t in args]
def get_item_children(self, item):
"""Returns all the children when the widget asks it."""
if item is not None:
# Since we are doing a flat list, we return the children of root only.
# If it's not root we return.
return []
return self._filtered
def filter_text(self, text):
import fnmatch
self._filtered = []
if len(text) == 0:
for c in self._children:
self._filtered.append(c)
else:
parts = text.split()
# for i in range(len(parts) - 1, -1, -1):
# w = parts[i]
leftover = " ".join(parts)
if len(leftover) > 0:
filter_str = f"*{leftover.lower()}*"
for c in self._children:
if fnmatch.fnmatch(c.name().lower(), filter_str):
self._filtered.append(c)
# This tells the Delegate to update the TreeView
self._item_changed(None)
def get_item_value_model_count(self, item):
"""The number of columns"""
return 1
def get_item_value_model(self, item, column_id):
"""
Return value model.
It's the object that tracks the specific value.
In our case we use ui.SimpleStringModel.
"""
return item.name_model
class SearchListItemDelegate(ui.AbstractItemDelegate):
"""
Delegate is the representation layer. TreeView calls the methods
of the delegate to create custom widgets for each item.
"""
def __init__(self, on_double_click_fn=None):
super().__init__()
self._on_double_click_fn = on_double_click_fn
def build_branch(self, model, item, column_id, level, expanded):
"""Create a branch widget that opens or closes subtree"""
pass
def build_widget(self, model, item, column_id, level, expanded):
"""Create a widget per column per item"""
stack = ui.ZStack(height=20, style=get_style())
with stack:
with ui.HStack():
ui.Spacer(width=5)
value_model = model.get_item_value_model(item, column_id)
label = ui.Label(value_model.as_string, name="TreeView.Item")
if not self._on_double_click_fn:
self._on_double_click_fn = self.on_double_click
# Set a double click function
stack.set_mouse_double_clicked_fn(lambda x, y, b, m, l=label: self._on_double_click_fn(b, m, l))
def on_double_click(self, button, model, label):
"""Called when the user double-clicked the item in TreeView"""
if button != 0:
return
def build_simple_search(label="", type="search", model=None, delegate=None, tooltip=""):
"""A Simple Search Bar + TreeView Widget.\n
Pass a list of items through the model, and a custom on_click_fn through the delegate.\n
Returns the SearchWidget so user can destroy it on_shutdown.
Args:
label (str, optional): Label to the left of the UI element. Defaults to "".
type (str, optional): Type of UI element. Defaults to "search".
model (ui.AbstractItemModel, optional): Item Model for Search. Defaults to None.
delegate (ui.AbstractItemDelegate, optional): Item Delegate for Search. Defaults to None.
tooltip (str, optional): Tooltip to display over the Label. Defaults to "".
Returns:
Tuple(Search Widget, Treeview):
"""
with ui.HStack():
ui.Label(label, width=LABEL_WIDTH, alignment=ui.Alignment.LEFT_TOP, tooltip=format_tt(tooltip))
with ui.VStack(spacing=5):
def filter_text(item):
model.filter_text(item)
from omni.kit.window.extensions.ext_components import SearchWidget
search_bar = SearchWidget(filter_text)
with ui.ScrollingFrame(
height=LABEL_HEIGHT * 5,
horizontal_scrollbar_policy=ui.ScrollBarPolicy.SCROLLBAR_ALWAYS_OFF,
vertical_scrollbar_policy=ui.ScrollBarPolicy.SCROLLBAR_ALWAYS_ON,
style=get_style(),
style_type_name_override="TreeView.ScrollingFrame",
):
treeview = ui.TreeView(
model,
delegate=delegate,
root_visible=False,
header_visible=False,
style={
"TreeView.ScrollingFrame": {"background_color": 0xFFE0E0E0},
"TreeView.Item": {"color": 0xFF535354, "font_size": 16},
"TreeView.Item:selected": {"color": 0xFF23211F},
"TreeView:selected": {"background_color": 0x409D905C},
}
# name="TreeView",
# style_type_name_override="TreeView",
)
add_line_rect_flourish(False)
return search_bar, treeview
| 62,248 | Python | 38.373182 | 169 | 0.558958 |
NVIDIA-Omniverse/urdf-importer-extension/source/extensions/omni.importer.urdf/python/scripts/samples/common.py | # SPDX-FileCopyrightText: Copyright (c) 2023 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
# SPDX-License-Identifier: Apache-2.0
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import os
import carb.tokens
import omni
from pxr import PhysxSchema, UsdGeom, UsdPhysics
def set_drive_parameters(drive, target_type, target_value, stiffness=None, damping=None, max_force=None):
"""Enable velocity drive for a given joint"""
if target_type == "position":
if not drive.GetTargetPositionAttr():
drive.CreateTargetPositionAttr(target_value)
else:
drive.GetTargetPositionAttr().Set(target_value)
elif target_type == "velocity":
if not drive.GetTargetVelocityAttr():
drive.CreateTargetVelocityAttr(target_value)
else:
drive.GetTargetVelocityAttr().Set(target_value)
if stiffness is not None:
if not drive.GetStiffnessAttr():
drive.CreateStiffnessAttr(stiffness)
else:
drive.GetStiffnessAttr().Set(stiffness)
if damping is not None:
if not drive.GetDampingAttr():
drive.CreateDampingAttr(damping)
else:
drive.GetDampingAttr().Set(damping)
if max_force is not None:
if not drive.GetMaxForceAttr():
drive.CreateMaxForceAttr(max_force)
else:
drive.GetMaxForceAttr().Set(max_force)
| 1,900 | Python | 34.203703 | 105 | 0.693158 |
NVIDIA-Omniverse/urdf-importer-extension/source/extensions/omni.importer.urdf/python/scripts/samples/import_franka.py | # SPDX-FileCopyrightText: Copyright (c) 2023 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
# SPDX-License-Identifier: Apache-2.0
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import asyncio
import math
import weakref
import omni
import omni.ui as ui
from omni.importer.urdf.scripts.ui import (
btn_builder,
get_style,
make_menu_item_description,
setup_ui_headers,
)
from omni.kit.menu.utils import MenuItemDescription, add_menu_items, remove_menu_items
from omni.kit.viewport.utility.camera_state import ViewportCameraState
from pxr import Gf, PhysicsSchemaTools, PhysxSchema, Sdf, UsdLux, UsdPhysics
from .common import set_drive_parameters
EXTENSION_NAME = "Import Franka"
class Extension(omni.ext.IExt):
def on_startup(self, ext_id: str):
ext_manager = omni.kit.app.get_app().get_extension_manager()
self._ext_id = ext_id
self._extension_path = ext_manager.get_extension_path(ext_id)
self._menu_items = [
MenuItemDescription(
name="Import Robots",
sub_menu=[
make_menu_item_description(ext_id, "Franka URDF", lambda a=weakref.proxy(self): a._menu_callback())
],
)
]
add_menu_items(self._menu_items, "Isaac Examples")
self._build_ui()
def _build_ui(self):
self._window = omni.ui.Window(
EXTENSION_NAME, width=0, height=0, visible=False, dockPreference=ui.DockPreference.LEFT_BOTTOM
)
with self._window.frame:
with ui.VStack(spacing=5, height=0):
title = "Import a Franka Panda via URDF"
doc_link = "https://docs.omniverse.nvidia.com/app_isaacsim/app_isaacsim/ext_omni_isaac_urdf.html"
overview = (
"This Example shows you import a URDF.\n\nPress the 'Open in IDE' button to view the source code."
)
setup_ui_headers(self._ext_id, __file__, title, doc_link, overview)
frame = ui.CollapsableFrame(
title="Command Panel",
height=0,
collapsed=False,
style=get_style(),
style_type_name_override="CollapsableFrame",
horizontal_scrollbar_policy=ui.ScrollBarPolicy.SCROLLBAR_AS_NEEDED,
vertical_scrollbar_policy=ui.ScrollBarPolicy.SCROLLBAR_ALWAYS_ON,
)
with frame:
with ui.VStack(style=get_style(), spacing=5):
dict = {
"label": "Load Robot",
"type": "button",
"text": "Load",
"tooltip": "Load a UR10 Robot into the Scene",
"on_clicked_fn": self._on_load_robot,
}
btn_builder(**dict)
dict = {
"label": "Configure Drives",
"type": "button",
"text": "Configure",
"tooltip": "Configure Joint Drives",
"on_clicked_fn": self._on_config_robot,
}
btn_builder(**dict)
dict = {
"label": "Move to Pose",
"type": "button",
"text": "move",
"tooltip": "Drive the Robot to a specific pose",
"on_clicked_fn": self._on_config_drives,
}
btn_builder(**dict)
def on_shutdown(self):
remove_menu_items(self._menu_items, "Isaac Examples")
self._window = None
def _menu_callback(self):
self._window.visible = not self._window.visible
def _on_load_robot(self):
load_stage = asyncio.ensure_future(omni.usd.get_context().new_stage_async())
asyncio.ensure_future(self._load_franka(load_stage))
async def _load_franka(self, task):
done, pending = await asyncio.wait({task})
if task in done:
status, import_config = omni.kit.commands.execute("URDFCreateImportConfig")
import_config.merge_fixed_joints = False
import_config.fix_base = True
import_config.make_default_prim = True
import_config.create_physics_scene = True
omni.kit.commands.execute(
"URDFParseAndImportFile",
urdf_path=self._extension_path + "/data/urdf/robots/franka_description/robots/panda_arm_hand.urdf",
import_config=import_config,
)
camera_state = ViewportCameraState("/OmniverseKit_Persp")
camera_state.set_position_world(Gf.Vec3d(1.22, -1.24, 1.13), True)
camera_state.set_target_world(Gf.Vec3d(-0.96, 1.08, 0.0), True)
stage = omni.usd.get_context().get_stage()
scene = UsdPhysics.Scene.Define(stage, Sdf.Path("/physicsScene"))
scene.CreateGravityDirectionAttr().Set(Gf.Vec3f(0.0, 0.0, -1.0))
scene.CreateGravityMagnitudeAttr().Set(9.81)
plane_path = "/groundPlane"
PhysicsSchemaTools.addGroundPlane(
stage,
plane_path,
"Z",
1500.0,
Gf.Vec3f(0, 0, 0),
Gf.Vec3f([0.5, 0.5, 0.5]),
)
# make sure the ground plane is under root prim and not robot
omni.kit.commands.execute(
"MovePrimCommand", path_from=plane_path, path_to="/groundPlane", keep_world_transform=True
)
distantLight = UsdLux.DistantLight.Define(stage, Sdf.Path("/DistantLight"))
distantLight.CreateIntensityAttr(500)
def _on_config_robot(self):
stage = omni.usd.get_context().get_stage()
# Set the solver parameters on the articulation
PhysxSchema.PhysxArticulationAPI.Get(stage, "/panda").CreateSolverPositionIterationCountAttr(64)
PhysxSchema.PhysxArticulationAPI.Get(stage, "/panda").CreateSolverVelocityIterationCountAttr(64)
self.joint_1 = UsdPhysics.DriveAPI.Get(stage.GetPrimAtPath("/panda/panda_link0/panda_joint1"), "angular")
self.joint_2 = UsdPhysics.DriveAPI.Get(stage.GetPrimAtPath("/panda/panda_link1/panda_joint2"), "angular")
self.joint_3 = UsdPhysics.DriveAPI.Get(stage.GetPrimAtPath("/panda/panda_link2/panda_joint3"), "angular")
self.joint_4 = UsdPhysics.DriveAPI.Get(stage.GetPrimAtPath("/panda/panda_link3/panda_joint4"), "angular")
self.joint_5 = UsdPhysics.DriveAPI.Get(stage.GetPrimAtPath("/panda/panda_link4/panda_joint5"), "angular")
self.joint_6 = UsdPhysics.DriveAPI.Get(stage.GetPrimAtPath("/panda/panda_link5/panda_joint6"), "angular")
self.joint_7 = UsdPhysics.DriveAPI.Get(stage.GetPrimAtPath("/panda/panda_link6/panda_joint7"), "angular")
self.finger_1 = UsdPhysics.DriveAPI.Get(stage.GetPrimAtPath("/panda/panda_hand/panda_finger_joint1"), "linear")
self.finger_2 = UsdPhysics.DriveAPI.Get(stage.GetPrimAtPath("/panda/panda_hand/panda_finger_joint2"), "linear")
# Set the drive mode, target, stiffness, damping and max force for each joint
set_drive_parameters(self.joint_1, "position", math.degrees(0), math.radians(1e8), math.radians(1e7))
set_drive_parameters(self.joint_2, "position", math.degrees(0), math.radians(1e8), math.radians(1e7))
set_drive_parameters(self.joint_3, "position", math.degrees(0), math.radians(1e8), math.radians(1e7))
set_drive_parameters(self.joint_4, "position", math.degrees(0), math.radians(1e8), math.radians(1e7))
set_drive_parameters(self.joint_5, "position", math.degrees(0), math.radians(1e8), math.radians(1e7))
set_drive_parameters(self.joint_6, "position", math.degrees(0), math.radians(1e8), math.radians(1e7))
set_drive_parameters(self.joint_7, "position", math.degrees(0), math.radians(1e8), math.radians(1e7))
set_drive_parameters(self.finger_1, "position", 0, 1e7, 1e6)
set_drive_parameters(self.finger_2, "position", 0, 1e7, 1e6)
def _on_config_drives(self):
self._on_config_robot() # make sure drives are configured first
# Set the drive mode, target, stiffness, damping and max force for each joint
set_drive_parameters(self.joint_1, "position", math.degrees(0.012))
set_drive_parameters(self.joint_2, "position", math.degrees(-0.57))
set_drive_parameters(self.joint_3, "position", math.degrees(0))
set_drive_parameters(self.joint_4, "position", math.degrees(-2.81))
set_drive_parameters(self.joint_5, "position", math.degrees(0))
set_drive_parameters(self.joint_6, "position", math.degrees(3.037))
set_drive_parameters(self.joint_7, "position", math.degrees(0.741))
set_drive_parameters(self.finger_1, "position", 4)
set_drive_parameters(self.finger_2, "position", 4)
| 9,623 | Python | 47.361809 | 119 | 0.601268 |
NVIDIA-Omniverse/urdf-importer-extension/source/extensions/omni.importer.urdf/python/scripts/samples/import_kaya.py | # SPDX-FileCopyrightText: Copyright (c) 2023 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
# SPDX-License-Identifier: Apache-2.0
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import asyncio
import math
import weakref
import omni
import omni.kit.commands
import omni.ui as ui
from omni.importer.urdf.scripts.ui import (
btn_builder,
get_style,
make_menu_item_description,
setup_ui_headers,
)
from omni.kit.menu.utils import MenuItemDescription, add_menu_items, remove_menu_items
from omni.kit.viewport.utility.camera_state import ViewportCameraState
from pxr import Gf, PhysicsSchemaTools, Sdf, UsdLux, UsdPhysics
from .common import set_drive_parameters
EXTENSION_NAME = "Import Kaya"
class Extension(omni.ext.IExt):
def on_startup(self, ext_id: str):
ext_manager = omni.kit.app.get_app().get_extension_manager()
self._ext_id = ext_id
self._extension_path = ext_manager.get_extension_path(ext_id)
self._menu_items = [
MenuItemDescription(
name="Import Robots",
sub_menu=[
make_menu_item_description(ext_id, "Kaya URDF", lambda a=weakref.proxy(self): a._menu_callback())
],
)
]
add_menu_items(self._menu_items, "Isaac Examples")
self._build_ui()
def _build_ui(self):
self._window = omni.ui.Window(
EXTENSION_NAME, width=0, height=0, visible=False, dockPreference=ui.DockPreference.LEFT_BOTTOM
)
with self._window.frame:
with ui.VStack(spacing=5, height=0):
title = "Import a Kaya Robot via URDF"
doc_link = "https://docs.omniverse.nvidia.com/app_isaacsim/app_isaacsim/ext_omni_isaac_urdf.html"
overview = "This Example shows you import an NVIDIA Kaya robot via URDF.\n\nPress the 'Open in IDE' button to view the source code."
setup_ui_headers(self._ext_id, __file__, title, doc_link, overview)
frame = ui.CollapsableFrame(
title="Command Panel",
height=0,
collapsed=False,
style=get_style(),
style_type_name_override="CollapsableFrame",
horizontal_scrollbar_policy=ui.ScrollBarPolicy.SCROLLBAR_AS_NEEDED,
vertical_scrollbar_policy=ui.ScrollBarPolicy.SCROLLBAR_ALWAYS_ON,
)
with frame:
with ui.VStack(style=get_style(), spacing=5):
dict = {
"label": "Load Robot",
"type": "button",
"text": "Load",
"tooltip": "Load a UR10 Robot into the Scene",
"on_clicked_fn": self._on_load_robot,
}
btn_builder(**dict)
dict = {
"label": "Configure Drives",
"type": "button",
"text": "Configure",
"tooltip": "Configure Joint Drives",
"on_clicked_fn": self._on_config_robot,
}
btn_builder(**dict)
dict = {
"label": "Spin Robot",
"type": "button",
"text": "move",
"tooltip": "Spin the Robot in Place",
"on_clicked_fn": self._on_config_drives,
}
btn_builder(**dict)
def on_shutdown(self):
remove_menu_items(self._menu_items, "Isaac Examples")
self._window = None
def _menu_callback(self):
self._window.visible = not self._window.visible
def _on_load_robot(self):
load_stage = asyncio.ensure_future(omni.usd.get_context().new_stage_async())
asyncio.ensure_future(self._load_kaya(load_stage))
async def _load_kaya(self, task):
done, pending = await asyncio.wait({task})
if task in done:
status, import_config = omni.kit.commands.execute("URDFCreateImportConfig")
import_config.merge_fixed_joints = True
import_config.import_inertia_tensor = False
# import_config.distance_scale = 1.0
import_config.fix_base = False
import_config.make_default_prim = True
import_config.create_physics_scene = True
omni.kit.commands.execute(
"URDFParseAndImportFile",
urdf_path=self._extension_path + "/data/urdf/robots/kaya/urdf/kaya.urdf",
import_config=import_config,
)
camera_state = ViewportCameraState("/OmniverseKit_Persp")
camera_state.set_position_world(Gf.Vec3d(-1.0, 1.5, 0.5), True)
camera_state.set_target_world(Gf.Vec3d(0.0, 0.0, 0.0), True)
stage = omni.usd.get_context().get_stage()
scene = UsdPhysics.Scene.Define(stage, Sdf.Path("/physicsScene"))
scene.CreateGravityDirectionAttr().Set(Gf.Vec3f(0.0, 0.0, -1.0))
scene.CreateGravityMagnitudeAttr().Set(9.81)
plane_path = "/groundPlane"
PhysicsSchemaTools.addGroundPlane(
stage, plane_path, "Z", 1500.0, Gf.Vec3f(0, 0, -0.25), Gf.Vec3f([0.5, 0.5, 0.5])
)
# make sure the ground plane is under root prim and not robot
omni.kit.commands.execute(
"MovePrimCommand", path_from=plane_path, path_to="/groundPlane", keep_world_transform=True
)
distantLight = UsdLux.DistantLight.Define(stage, Sdf.Path("/DistantLight"))
distantLight.CreateIntensityAttr(500)
def _on_config_robot(self):
stage = omni.usd.get_context().get_stage()
# Make all rollers spin freely by removing extra drive API
for axle in range(0, 2 + 1):
for ring in range(0, 1 + 1):
for roller in range(0, 4 + 1):
prim_path = (
"/kaya/axle_"
+ str(axle)
+ "/roller_"
+ str(axle)
+ "_"
+ str(ring)
+ "_"
+ str(roller)
+ "_joint"
)
prim = stage.GetPrimAtPath(prim_path)
# omni.kit.commands.execute(
# "UnapplyAPISchemaCommand",
# api=UsdPhysics.DriveAPI,
# prim=prim,
# api_prefix="drive",
# multiple_api_token="angular",
# )
prim.RemoveAPI(UsdPhysics.DriveAPI, "angular")
def _on_config_drives(self):
self._on_config_robot() # make sure drives are configured first
stage = omni.usd.get_context().get_stage()
# set each axis to spin at a rate of 1 rad/s
axle_0 = UsdPhysics.DriveAPI.Get(stage.GetPrimAtPath("/kaya/base_link/axle_0_joint"), "angular")
axle_1 = UsdPhysics.DriveAPI.Get(stage.GetPrimAtPath("/kaya/base_link/axle_1_joint"), "angular")
axle_2 = UsdPhysics.DriveAPI.Get(stage.GetPrimAtPath("/kaya/base_link/axle_2_joint"), "angular")
set_drive_parameters(axle_0, "velocity", math.degrees(1), 0, math.radians(1e7))
set_drive_parameters(axle_1, "velocity", math.degrees(1), 0, math.radians(1e7))
set_drive_parameters(axle_2, "velocity", math.degrees(1), 0, math.radians(1e7))
| 8,253 | Python | 41.328205 | 148 | 0.545499 |
NVIDIA-Omniverse/urdf-importer-extension/source/extensions/omni.importer.urdf/python/tests/test_urdf.py | # SPDX-FileCopyrightText: Copyright (c) 2023 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
# SPDX-License-Identifier: Apache-2.0
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import asyncio
import os
import numpy as np
import omni.kit.commands
# NOTE:
# omni.kit.test - std python's unittest module with additional wrapping to add suport for async/await tests
# For most things refer to unittest docs: https://docs.python.org/3/library/unittest.html
import omni.kit.test
import pxr
from pxr import Gf, PhysicsSchemaTools, Sdf, UsdGeom, UsdPhysics, UsdShade
# Having a test class dervived from omni.kit.test.AsyncTestCase declared on the root of module will make it auto-discoverable by omni.kit.test
class TestUrdf(omni.kit.test.AsyncTestCase):
# Before running each test
async def setUp(self):
self._timeline = omni.timeline.get_timeline_interface()
ext_manager = omni.kit.app.get_app().get_extension_manager()
ext_id = ext_manager.get_enabled_extension_id("omni.importer.urdf")
self._extension_path = ext_manager.get_extension_path(ext_id)
self.dest_path = os.path.abspath(self._extension_path + "/tests_out")
await omni.usd.get_context().new_stage_async()
await omni.kit.app.get_app().next_update_async()
pass
# After running each test
async def tearDown(self):
# _urdf.release_urdf_interface(self._urdf_interface)
await omni.kit.app.get_app().next_update_async()
pass
# Tests to make sure visual mesh names are incremented
async def test_urdf_mesh_naming(self):
urdf_path = os.path.abspath(self._extension_path + "/data/urdf/tests/test_names.urdf")
stage = omni.usd.get_context().get_stage()
status, import_config = omni.kit.commands.execute("URDFCreateImportConfig")
import_config.merge_fixed_joints = True
omni.kit.commands.execute("URDFParseAndImportFile", urdf_path=urdf_path, import_config=import_config)
prim = stage.GetPrimAtPath("/test_names/cube/visuals")
prim_range = prim.GetChildren()
# There should be a total of 6 visual meshes after import
self.assertEqual(len(prim_range), 6)
# basic urdf test: joints and links are imported correctly
async def test_urdf_basic(self):
urdf_path = os.path.abspath(self._extension_path + "/data/urdf/tests/test_basic.urdf")
stage = omni.usd.get_context().get_stage()
status, import_config = omni.kit.commands.execute("URDFCreateImportConfig")
import_config.import_inertia_tensor = True
omni.kit.commands.execute("URDFParseAndImportFile", urdf_path=urdf_path, import_config=import_config)
await omni.kit.app.get_app().next_update_async()
prim = stage.GetPrimAtPath("/test_basic")
self.assertNotEqual(prim.GetPath(), Sdf.Path.emptyPath)
# make sure the joints exist
root_joint = stage.GetPrimAtPath("/test_basic/root_joint")
self.assertNotEqual(root_joint.GetPath(), Sdf.Path.emptyPath)
wristJoint = stage.GetPrimAtPath("/test_basic/link_2/wrist_joint")
self.assertNotEqual(wristJoint.GetPath(), Sdf.Path.emptyPath)
self.assertEqual(wristJoint.GetTypeName(), "PhysicsRevoluteJoint")
fingerJoint = stage.GetPrimAtPath("/test_basic/palm_link/finger_1_joint")
self.assertNotEqual(fingerJoint.GetPath(), Sdf.Path.emptyPath)
self.assertEqual(fingerJoint.GetTypeName(), "PhysicsPrismaticJoint")
self.assertAlmostEqual(fingerJoint.GetAttribute("physics:upperLimit").Get(), 0.08)
fingerLink = stage.GetPrimAtPath("/test_basic/finger_link_2")
self.assertAlmostEqual(fingerLink.GetAttribute("physics:diagonalInertia").Get()[0], 2.0)
self.assertAlmostEqual(fingerLink.GetAttribute("physics:mass").Get(), 3)
# Start Simulation and wait
self._timeline.play()
await omni.kit.app.get_app().next_update_async()
await asyncio.sleep(1.0)
# nothing crashes
self._timeline.stop()
self.assertAlmostEqual(UsdGeom.GetStageMetersPerUnit(stage), 1.0)
pass
async def test_urdf_save_to_file(self):
urdf_path = os.path.abspath(self._extension_path + "/data/urdf/tests/test_basic.urdf")
dest_path = os.path.abspath(self.dest_path + "/test_basic.usd")
status, import_config = omni.kit.commands.execute("URDFCreateImportConfig")
import_config.import_inertia_tensor = True
omni.kit.commands.execute(
"URDFParseAndImportFile", urdf_path=urdf_path, import_config=import_config, dest_path=dest_path
)
await omni.kit.app.get_app().next_update_async()
stage = pxr.Usd.Stage.Open(dest_path)
prim = stage.GetPrimAtPath("/test_basic")
self.assertNotEqual(prim.GetPath(), Sdf.Path.emptyPath)
# make sure the joints exist
root_joint = stage.GetPrimAtPath("/test_basic/root_joint")
self.assertNotEqual(root_joint.GetPath(), Sdf.Path.emptyPath)
wristJoint = stage.GetPrimAtPath("/test_basic/link_2/wrist_joint")
self.assertNotEqual(wristJoint.GetPath(), Sdf.Path.emptyPath)
self.assertEqual(wristJoint.GetTypeName(), "PhysicsRevoluteJoint")
fingerJoint = stage.GetPrimAtPath("/test_basic/palm_link/finger_1_joint")
self.assertNotEqual(fingerJoint.GetPath(), Sdf.Path.emptyPath)
self.assertEqual(fingerJoint.GetTypeName(), "PhysicsPrismaticJoint")
self.assertAlmostEqual(fingerJoint.GetAttribute("physics:upperLimit").Get(), 0.08)
fingerLink = stage.GetPrimAtPath("/test_basic/finger_link_2")
self.assertAlmostEqual(fingerLink.GetAttribute("physics:diagonalInertia").Get()[0], 2.0)
self.assertAlmostEqual(fingerLink.GetAttribute("physics:mass").Get(), 3)
self.assertAlmostEqual(UsdGeom.GetStageMetersPerUnit(stage), 1.0)
stage = None
pass
async def test_urdf_textured_obj(self):
base_path = self._extension_path + "/data/urdf/tests/test_textures_urdf"
basename = "cube_obj"
dest_path = "{}/{}/{}.usd".format(self.dest_path, basename, basename)
mats_path = "{}/{}/materials".format(self.dest_path, basename)
omni.client.create_folder("{}/{}".format(self.dest_path, basename))
omni.client.create_folder(mats_path)
urdf_path = "{}/{}.urdf".format(base_path, basename)
status, import_config = omni.kit.commands.execute("URDFCreateImportConfig")
omni.kit.commands.execute(
"URDFParseAndImportFile", urdf_path=urdf_path, import_config=import_config, dest_path=dest_path
)
await omni.kit.app.get_app().next_update_async()
result = omni.client.list(mats_path)
self.assertEqual(result[0], omni.client._omniclient.Result.OK)
self.assertEqual(len(result[1]), 4) # Metallic texture is unsuported by assimp on OBJ
pass
async def test_urdf_textured_in_memory(self):
base_path = self._extension_path + "/data/urdf/tests/test_textures_urdf"
basename = "cube_obj"
urdf_path = "{}/{}.urdf".format(base_path, basename)
status, import_config = omni.kit.commands.execute("URDFCreateImportConfig")
omni.kit.commands.execute("URDFParseAndImportFile", urdf_path=urdf_path, import_config=import_config)
await omni.kit.app.get_app().next_update_async()
pass
async def test_urdf_textured_dae(self):
base_path = self._extension_path + "/data/urdf/tests/test_textures_urdf"
basename = "cube_dae"
dest_path = "{}/{}/{}.usd".format(self.dest_path, basename, basename)
mats_path = "{}/{}/materials".format(self.dest_path, basename)
omni.client.create_folder("{}/{}".format(self.dest_path, basename))
omni.client.create_folder(mats_path)
urdf_path = "{}/{}.urdf".format(base_path, basename)
status, import_config = omni.kit.commands.execute("URDFCreateImportConfig")
omni.kit.commands.execute(
"URDFParseAndImportFile", urdf_path=urdf_path, import_config=import_config, dest_path=dest_path
)
await omni.kit.app.get_app().next_update_async()
result = omni.client.list(mats_path)
self.assertEqual(result[0], omni.client._omniclient.Result.OK)
self.assertEqual(len(result[1]), 1) # only albedo is supported for Collada
pass
async def test_urdf_overwrite_file(self):
urdf_path = os.path.abspath(self._extension_path + "/data/urdf/tests/test_basic.urdf")
dest_path = os.path.abspath(self._extension_path + "/data/urdf/tests/tests_out/test_basic.usd")
status, import_config = omni.kit.commands.execute("URDFCreateImportConfig")
import_config.import_inertia_tensor = True
omni.kit.commands.execute(
"URDFParseAndImportFile", urdf_path=urdf_path, import_config=import_config, dest_path=dest_path
)
await omni.kit.app.get_app().next_update_async()
omni.kit.commands.execute(
"URDFParseAndImportFile", urdf_path=urdf_path, import_config=import_config, dest_path=dest_path
)
await omni.kit.app.get_app().next_update_async()
stage = pxr.Usd.Stage.Open(dest_path)
prim = stage.GetPrimAtPath("/test_basic")
self.assertNotEqual(prim.GetPath(), Sdf.Path.emptyPath)
# make sure the joints exist
root_joint = stage.GetPrimAtPath("/test_basic/root_joint")
self.assertNotEqual(root_joint.GetPath(), Sdf.Path.emptyPath)
wristJoint = stage.GetPrimAtPath("/test_basic/link_2/wrist_joint")
self.assertNotEqual(wristJoint.GetPath(), Sdf.Path.emptyPath)
self.assertEqual(wristJoint.GetTypeName(), "PhysicsRevoluteJoint")
fingerJoint = stage.GetPrimAtPath("/test_basic/palm_link/finger_1_joint")
self.assertNotEqual(fingerJoint.GetPath(), Sdf.Path.emptyPath)
self.assertEqual(fingerJoint.GetTypeName(), "PhysicsPrismaticJoint")
self.assertAlmostEqual(fingerJoint.GetAttribute("physics:upperLimit").Get(), 0.08)
fingerLink = stage.GetPrimAtPath("/test_basic/finger_link_2")
self.assertAlmostEqual(fingerLink.GetAttribute("physics:diagonalInertia").Get()[0], 2.0)
self.assertAlmostEqual(fingerLink.GetAttribute("physics:mass").Get(), 3)
# Start Simulation and wait
self._timeline.play()
await omni.kit.app.get_app().next_update_async()
await asyncio.sleep(1.0)
# nothing crashes
self._timeline.stop()
self.assertAlmostEqual(UsdGeom.GetStageMetersPerUnit(stage), 1.0)
stage = None
pass
# advanced urdf test: test for all the categories of inputs that an urdf can hold
async def test_urdf_advanced(self):
urdf_path = os.path.abspath(self._extension_path + "/data/urdf/tests/test_advanced.urdf")
stage = omni.usd.get_context().get_stage()
# enable merging fixed joints
status, import_config = omni.kit.commands.execute("URDFCreateImportConfig")
import_config.merge_fixed_joints = True
import_config.default_position_drive_damping = -1 # ignore this setting by making it -1
omni.kit.commands.execute("URDFParseAndImportFile", urdf_path=urdf_path, import_config=import_config)
await omni.kit.app.get_app().next_update_async()
# check if object is there
prim = stage.GetPrimAtPath("/test_advanced")
self.assertNotEqual(prim.GetPath(), Sdf.Path.emptyPath)
# check color are imported
mesh = stage.GetPrimAtPath("/test_advanced/link_1/visuals")
self.assertNotEqual(mesh.GetPath(), Sdf.Path.emptyPath)
mat, rel = UsdShade.MaterialBindingAPI(mesh).ComputeBoundMaterial()
shader = UsdShade.Shader(stage.GetPrimAtPath(mat.GetPath().pathString + "/Shader"))
self.assertTrue(Gf.IsClose(shader.GetInput("diffuse_color_constant").Get(), Gf.Vec3f(0, 0.8, 0), 1e-5))
# check joint properties
elbowPrim = stage.GetPrimAtPath("/test_advanced/link_1/elbow_joint")
self.assertNotEqual(elbowPrim.GetPath(), Sdf.Path.emptyPath)
self.assertAlmostEqual(elbowPrim.GetAttribute("physxJoint:jointFriction").Get(), 0.1)
self.assertAlmostEqual(elbowPrim.GetAttribute("drive:angular:physics:damping").Get(), 0.1)
# check position of a link
joint_pos = elbowPrim.GetAttribute("physics:localPos0").Get()
self.assertTrue(Gf.IsClose(joint_pos, Gf.Vec3f(0, 0, 0.40), 1e-5))
# Start Simulation and wait
self._timeline.play()
await omni.kit.app.get_app().next_update_async()
await asyncio.sleep(1.0)
# nothing crashes
self._timeline.stop()
pass
# test for importing urdf where fixed joints are merged
async def test_urdf_merge_joints(self):
urdf_path = os.path.abspath(self._extension_path + "/data/urdf/tests/test_merge_joints.urdf")
stage = omni.usd.get_context().get_stage()
# enable merging fixed joints
status, import_config = omni.kit.commands.execute("URDFCreateImportConfig")
import_config.merge_fixed_joints = True
omni.kit.commands.execute("URDFParseAndImportFile", urdf_path=urdf_path, import_config=import_config)
# the merged link shouldn't be there
prim = stage.GetPrimAtPath("/test_merge_joints/link_2")
self.assertEqual(prim.GetPath(), Sdf.Path.emptyPath)
pass
async def test_urdf_mtl(self):
urdf_path = os.path.abspath(self._extension_path + "/data/urdf/tests/test_mtl.urdf")
stage = omni.usd.get_context().get_stage()
status, import_config = omni.kit.commands.execute("URDFCreateImportConfig")
omni.kit.commands.execute("URDFParseAndImportFile", urdf_path=urdf_path, import_config=import_config)
mesh = stage.GetPrimAtPath("/test_mtl/cube/visuals")
self.assertTrue(UsdShade.MaterialBindingAPI(mesh) is not None)
mat, rel = UsdShade.MaterialBindingAPI(mesh).ComputeBoundMaterial()
shader = UsdShade.Shader(stage.GetPrimAtPath(mat.GetPath().pathString + "/Shader"))
print(shader)
self.assertTrue(Gf.IsClose(shader.GetInput("diffuse_color_constant").Get(), Gf.Vec3f(0.8, 0.0, 0), 1e-5))
async def test_urdf_material(self):
urdf_path = os.path.abspath(self._extension_path + "/data/urdf/tests/test_material.urdf")
stage = omni.usd.get_context().get_stage()
status, import_config = omni.kit.commands.execute("URDFCreateImportConfig")
omni.kit.commands.execute("URDFParseAndImportFile", urdf_path=urdf_path, import_config=import_config)
mesh = stage.GetPrimAtPath("/test_material/base/visuals")
self.assertTrue(UsdShade.MaterialBindingAPI(mesh) is not None)
mat, rel = UsdShade.MaterialBindingAPI(mesh).ComputeBoundMaterial()
shader = UsdShade.Shader(stage.GetPrimAtPath(mat.GetPath().pathString + "/Shader"))
print(shader)
self.assertTrue(Gf.IsClose(shader.GetInput("diffuse_color_constant").Get(), Gf.Vec3f(1.0, 0.0, 0.0), 1e-5))
async def test_urdf_mtl_stl(self):
urdf_path = os.path.abspath(self._extension_path + "/data/urdf/tests/test_mtl_stl.urdf")
stage = omni.usd.get_context().get_stage()
status, import_config = omni.kit.commands.execute("URDFCreateImportConfig")
omni.kit.commands.execute("URDFParseAndImportFile", urdf_path=urdf_path, import_config=import_config)
mesh = stage.GetPrimAtPath("/test_mtl_stl/cube/visuals")
self.assertTrue(UsdShade.MaterialBindingAPI(mesh) is not None)
mat, rel = UsdShade.MaterialBindingAPI(mesh).ComputeBoundMaterial()
shader = UsdShade.Shader(stage.GetPrimAtPath(mat.GetPath().pathString + "/Shader"))
print(shader)
self.assertTrue(Gf.IsClose(shader.GetInput("diffuse_color_constant").Get(), Gf.Vec3f(0.8, 0.0, 0), 1e-5))
async def test_urdf_carter(self):
urdf_path = os.path.abspath(self._extension_path + "/data/urdf/robots/carter/urdf/carter.urdf")
status, import_config = omni.kit.commands.execute("URDFCreateImportConfig")
import_config.merge_fixed_joints = False
status, path = omni.kit.commands.execute(
"URDFParseAndImportFile", urdf_path=urdf_path, import_config=import_config
)
self.assertTrue(path, "/carter")
# TODO add checks here
async def test_urdf_franka(self):
urdf_path = os.path.abspath(
self._extension_path + "/data/urdf/robots/franka_description/robots/panda_arm_hand.urdf"
)
status, import_config = omni.kit.commands.execute("URDFCreateImportConfig")
omni.kit.commands.execute("URDFParseAndImportFile", urdf_path=urdf_path, import_config=import_config)
# TODO add checks here'
async def test_urdf_ur10(self):
urdf_path = os.path.abspath(self._extension_path + "/data/urdf/robots/ur10/urdf/ur10.urdf")
status, import_config = omni.kit.commands.execute("URDFCreateImportConfig")
omni.kit.commands.execute("URDFParseAndImportFile", urdf_path=urdf_path, import_config=import_config)
# TODO add checks here'
async def test_urdf_kaya(self):
urdf_path = os.path.abspath(self._extension_path + "/data/urdf/robots/kaya/urdf/kaya.urdf")
status, import_config = omni.kit.commands.execute("URDFCreateImportConfig")
import_config.merge_fixed_joints = False
omni.kit.commands.execute("URDFParseAndImportFile", urdf_path=urdf_path, import_config=import_config)
# TODO add checks here
async def test_missing(self):
urdf_path = os.path.abspath(self._extension_path + "/data/urdf/tests/test_missing.urdf")
status, import_config = omni.kit.commands.execute("URDFCreateImportConfig")
omni.kit.commands.execute("URDFParseAndImportFile", urdf_path=urdf_path, import_config=import_config)
# This sample corresponds to the example in the docs, keep this and the version in the docs in sync
async def test_doc_sample(self):
import omni.kit.commands
from pxr import Gf, Sdf, UsdLux, UsdPhysics
# setting up import configuration:
status, import_config = omni.kit.commands.execute("URDFCreateImportConfig")
import_config.merge_fixed_joints = False
import_config.convex_decomp = False
import_config.import_inertia_tensor = True
import_config.fix_base = False
# Get path to extension data:
ext_manager = omni.kit.app.get_app().get_extension_manager()
ext_id = ext_manager.get_enabled_extension_id("omni.importer.urdf")
extension_path = ext_manager.get_extension_path(ext_id)
# import URDF
omni.kit.commands.execute(
"URDFParseAndImportFile",
urdf_path=extension_path + "/data/urdf/robots/carter/urdf/carter.urdf",
import_config=import_config,
)
# get stage handle
stage = omni.usd.get_context().get_stage()
# enable physics
scene = UsdPhysics.Scene.Define(stage, Sdf.Path("/physicsScene"))
# set gravity
scene.CreateGravityDirectionAttr().Set(Gf.Vec3f(0.0, 0.0, -1.0))
scene.CreateGravityMagnitudeAttr().Set(9.81)
# add ground plane
PhysicsSchemaTools.addGroundPlane(stage, "/World/groundPlane", "Z", 1500, Gf.Vec3f(0, 0, -50), Gf.Vec3f(0.5))
# add lighting
distantLight = UsdLux.DistantLight.Define(stage, Sdf.Path("/DistantLight"))
distantLight.CreateIntensityAttr(500)
####
#### Next Docs section
####
# get handle to the Drive API for both wheels
left_wheel_drive = UsdPhysics.DriveAPI.Get(stage.GetPrimAtPath("/carter/chassis_link/left_wheel"), "angular")
right_wheel_drive = UsdPhysics.DriveAPI.Get(stage.GetPrimAtPath("/carter/chassis_link/right_wheel"), "angular")
# Set the velocity drive target in degrees/second
left_wheel_drive.GetTargetVelocityAttr().Set(150)
right_wheel_drive.GetTargetVelocityAttr().Set(150)
# Set the drive damping, which controls the strength of the velocity drive
left_wheel_drive.GetDampingAttr().Set(15000)
right_wheel_drive.GetDampingAttr().Set(15000)
# Set the drive stiffness, which controls the strength of the position drive
# In this case because we want to do velocity control this should be set to zero
left_wheel_drive.GetStiffnessAttr().Set(0)
right_wheel_drive.GetStiffnessAttr().Set(0)
# Make sure that a urdf with more than 63 links imports
async def test_64(self):
urdf_path = os.path.abspath(self._extension_path + "/data/urdf/tests/test_large.urdf")
status, import_config = omni.kit.commands.execute("URDFCreateImportConfig")
omni.kit.commands.execute("URDFParseAndImportFile", urdf_path=urdf_path, import_config=import_config)
stage = omni.usd.get_context().get_stage()
prim = stage.GetPrimAtPath("/test_large")
self.assertTrue(prim)
# basic urdf test: joints and links are imported correctly
async def test_urdf_floating(self):
urdf_path = os.path.abspath(self._extension_path + "/data/urdf/tests/test_floating.urdf")
stage = omni.usd.get_context().get_stage()
status, import_config = omni.kit.commands.execute("URDFCreateImportConfig")
import_config.import_inertia_tensor = True
omni.kit.commands.execute("URDFParseAndImportFile", urdf_path=urdf_path, import_config=import_config)
await omni.kit.app.get_app().next_update_async()
prim = stage.GetPrimAtPath("/test_floating")
self.assertNotEqual(prim.GetPath(), Sdf.Path.emptyPath)
# make sure the joints exist
root_joint = stage.GetPrimAtPath("/test_floating/root_joint")
self.assertNotEqual(root_joint.GetPath(), Sdf.Path.emptyPath)
link_1 = stage.GetPrimAtPath("/test_floating/link_1")
self.assertNotEqual(link_1.GetPath(), Sdf.Path.emptyPath)
link_1_trans = np.array(omni.usd.get_world_transform_matrix(link_1).ExtractTranslation())
self.assertAlmostEqual(np.linalg.norm(link_1_trans - np.array([0, 0, 0.45])), 0, delta=0.03)
floating_link = stage.GetPrimAtPath("/test_floating/floating_link")
self.assertNotEqual(floating_link.GetPath(), Sdf.Path.emptyPath)
floating_link_trans = np.array(omni.usd.get_world_transform_matrix(floating_link).ExtractTranslation())
self.assertAlmostEqual(np.linalg.norm(floating_link_trans - np.array([0, 0, 1.450])), 0, delta=0.03)
# Start Simulation and wait
self._timeline.play()
await omni.kit.app.get_app().next_update_async()
await asyncio.sleep(1.0)
# nothing crashes
self._timeline.stop()
pass
async def test_urdf_scale(self):
urdf_path = os.path.abspath(self._extension_path + "/data/urdf/tests/test_basic.urdf")
stage = omni.usd.get_context().get_stage()
status, import_config = omni.kit.commands.execute("URDFCreateImportConfig")
import_config.distance_scale = 1.0
omni.kit.commands.execute("URDFParseAndImportFile", urdf_path=urdf_path, import_config=import_config)
await omni.kit.app.get_app().next_update_async()
# Start Simulation and wait
self._timeline.play()
await omni.kit.app.get_app().next_update_async()
await asyncio.sleep(1.0)
# nothing crashes
self._timeline.stop()
self.assertAlmostEqual(UsdGeom.GetStageMetersPerUnit(stage), 1.0)
pass
async def test_urdf_drive_none(self):
urdf_path = os.path.abspath(self._extension_path + "/data/urdf/tests/test_basic.urdf")
stage = omni.usd.get_context().get_stage()
status, import_config = omni.kit.commands.execute("URDFCreateImportConfig")
from omni.importer.urdf._urdf import UrdfJointTargetType
import_config.default_drive_type = UrdfJointTargetType.JOINT_DRIVE_NONE
omni.kit.commands.execute("URDFParseAndImportFile", urdf_path=urdf_path, import_config=import_config)
await omni.kit.app.get_app().next_update_async()
self.assertFalse(stage.GetPrimAtPath("/test_basic/root_joint").HasAPI(UsdPhysics.DriveAPI))
self.assertTrue(stage.GetPrimAtPath("/test_basic/link_1/elbow_joint").HasAPI(UsdPhysics.DriveAPI))
# Start Simulation and wait
self._timeline.play()
await omni.kit.app.get_app().next_update_async()
await asyncio.sleep(1.0)
# nothing crashes
self._timeline.stop()
pass
async def test_urdf_usd(self):
urdf_path = os.path.abspath(self._extension_path + "/data/urdf/tests/test_usd.urdf")
stage = omni.usd.get_context().get_stage()
status, import_config = omni.kit.commands.execute("URDFCreateImportConfig")
from omni.importer.urdf._urdf import UrdfJointTargetType
import_config.default_drive_type = UrdfJointTargetType.JOINT_DRIVE_NONE
omni.kit.commands.execute("URDFParseAndImportFile", urdf_path=urdf_path, import_config=import_config)
await omni.kit.app.get_app().next_update_async()
self.assertNotEqual(stage.GetPrimAtPath("/test_usd/cube/visuals/mesh_0/Cylinder"), Sdf.Path.emptyPath)
self.assertNotEqual(stage.GetPrimAtPath("/test_usd/cube/visuals/mesh_1/Torus"), Sdf.Path.emptyPath)
# Start Simulation and wait
self._timeline.play()
await omni.kit.app.get_app().next_update_async()
await asyncio.sleep(1.0)
# nothing crashes
self._timeline.stop()
pass
# test negative joint limits
async def test_urdf_limits(self):
urdf_path = os.path.abspath(self._extension_path + "/data/urdf/tests/test_limits.urdf")
stage = omni.usd.get_context().get_stage()
status, import_config = omni.kit.commands.execute("URDFCreateImportConfig")
import_config.import_inertia_tensor = True
omni.kit.commands.execute("URDFParseAndImportFile", urdf_path=urdf_path, import_config=import_config)
await omni.kit.app.get_app().next_update_async()
# ensure the import completed.
prim = stage.GetPrimAtPath("/test_limits")
self.assertNotEqual(prim.GetPath(), Sdf.Path.emptyPath)
# ensure the joint limits are set on the elbow
elbowJoint = stage.GetPrimAtPath("/test_limits/link_1/elbow_joint")
self.assertNotEqual(elbowJoint.GetPath(), Sdf.Path.emptyPath)
self.assertEqual(elbowJoint.GetTypeName(), "PhysicsRevoluteJoint")
self.assertTrue(elbowJoint.HasAPI(UsdPhysics.DriveAPI))
# ensure the joint limits are set on the wrist
wristJoint = stage.GetPrimAtPath("/test_limits/link_2/wrist_joint")
self.assertNotEqual(wristJoint.GetPath(), Sdf.Path.emptyPath)
self.assertEqual(wristJoint.GetTypeName(), "PhysicsRevoluteJoint")
self.assertTrue(wristJoint.HasAPI(UsdPhysics.DriveAPI))
# ensure the joint limits are set on the finger1
finger1Joint = stage.GetPrimAtPath("/test_limits/palm_link/finger_1_joint")
self.assertNotEqual(finger1Joint.GetPath(), Sdf.Path.emptyPath)
self.assertEqual(finger1Joint.GetTypeName(), "PhysicsPrismaticJoint")
self.assertTrue(finger1Joint.HasAPI(UsdPhysics.DriveAPI))
# ensure the joint limits are set on the finger2
finger2Joint = stage.GetPrimAtPath("/test_limits/palm_link/finger_2_joint")
self.assertNotEqual(finger2Joint.GetPath(), Sdf.Path.emptyPath)
self.assertEqual(finger2Joint.GetTypeName(), "PhysicsPrismaticJoint")
self.assertTrue(finger2Joint.HasAPI(UsdPhysics.DriveAPI))
# Start Simulation and wait
self._timeline.play()
await omni.kit.app.get_app().next_update_async()
await asyncio.sleep(1.0)
# nothing crashes
self._timeline.stop()
pass
# test collision from visuals
async def test_collision_from_visuals(self):
# import a urdf file without collision
urdf_path = os.path.abspath(self._extension_path + "/data/urdf/tests/test_collision_from_visuals.urdf")
stage = omni.usd.get_context().get_stage()
status, import_config = omni.kit.commands.execute("URDFCreateImportConfig")
import_config.set_collision_from_visuals(True)
omni.kit.commands.execute("URDFParseAndImportFile", urdf_path=urdf_path, import_config=import_config)
await omni.kit.app.get_app().next_update_async()
# ensure the import completed.
prim = stage.GetPrimAtPath("/test_collision_from_visuals")
self.assertNotEqual(prim.GetPath(), Sdf.Path.emptyPath)
# ensure the base_link collision prim exists and has the collision API applied.
base_link = stage.GetPrimAtPath("/test_collision_from_visuals/base_link/collisions")
self.assertNotEqual(base_link.GetPath(), Sdf.Path.emptyPath)
self.assertTrue(base_link.GetAttribute("physics:collisionEnabled").Get())
# ensure the link_1 collision prim exists and has the collision API applied.
link_1 = stage.GetPrimAtPath("/test_collision_from_visuals/link_1/collisions")
self.assertNotEqual(link_1.GetPath(), Sdf.Path.emptyPath)
self.assertTrue(link_1.GetAttribute("physics:collisionEnabled").Get())
# ensure the link_2 collision prim exists and has the collision API applied.
link_2 = stage.GetPrimAtPath("/test_collision_from_visuals/link_2/collisions")
self.assertNotEqual(link_2.GetPath(), Sdf.Path.emptyPath)
self.assertTrue(link_2.GetAttribute("physics:collisionEnabled").Get())
# ensure the palm_link collision prim exists and has the collision API applied.
palm_link = stage.GetPrimAtPath("/test_collision_from_visuals/palm_link/collisions")
self.assertNotEqual(palm_link.GetPath(), Sdf.Path.emptyPath)
self.assertTrue(palm_link.GetAttribute("physics:collisionEnabled").Get())
# ensure the finger_link_1 collision prim exists and has the collision API applied.
finger_link_1 = stage.GetPrimAtPath("/test_collision_from_visuals/finger_link_1/collisions")
self.assertNotEqual(finger_link_1.GetPath(), Sdf.Path.emptyPath)
self.assertTrue(finger_link_1.GetAttribute("physics:collisionEnabled").Get())
# ensure the finger_link_2 collision prim exists and has the collision API applied.
finger_link_2 = stage.GetPrimAtPath("/test_collision_from_visuals/finger_link_2/collisions")
self.assertNotEqual(finger_link_2.GetPath(), Sdf.Path.emptyPath)
self.assertTrue(finger_link_2.GetAttribute("physics:collisionEnabled").Get())
# Start Simulation and wait
self._timeline.play()
await omni.kit.app.get_app().next_update_async()
await asyncio.sleep(2.0)
# nothing crashes
self._timeline.stop()
pass
| 31,541 | Python | 46.646526 | 142 | 0.682287 |
NVIDIA-Omniverse/urdf-importer-extension/source/extensions/omni.importer.urdf/bindings/BindingsUrdfPython.cpp | // SPDX-FileCopyrightText: Copyright (c) 2023 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
// SPDX-License-Identifier: Apache-2.0
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include <carb/BindingsPythonUtils.h>
#include "../plugins/math/core/maths.h"
#include "../plugins/Urdf.h"
#include <pybind11/stl.h>
#include <pybind11/stl_bind.h>
CARB_BINDINGS("omni.importer.urdf.python")
PYBIND11_MAKE_OPAQUE(std::map<std::string, omni::importer::urdf::UrdfMaterial>);
namespace omni
{
namespace importer
{
namespace urdf
{
}
}
}
namespace
{
// Helper function that creates a python type for a std::map with a string key and a custom value type
template <class T>
void declare_map(py::module& m, const std::string typestr)
{
py::class_<std::map<std::string, T>>(m, typestr.c_str())
.def(py::init<>())
.def("__getitem__",
[](const std::map<std::string, T>& map, std::string key)
{
try
{
return map.at(key);
}
catch (const std::out_of_range&)
{
throw py::key_error("key '" + key + "' does not exist");
}
})
.def("__iter__",
[](std::map<std::string, T>& items) { return py::make_key_iterator(items.begin(), items.end()); },
py::keep_alive<0, 1>())
.def("items", [](std::map<std::string, T>& items) { return py::make_iterator(items.begin(), items.end()); },
py::keep_alive<0, 1>())
.def("__len__", [](std::map<std::string, T>& items) { return items.size(); });
}
PYBIND11_MODULE(_urdf, m)
{
using namespace carb;
using namespace omni::importer::urdf;
m.doc() = R"pbdoc(
This extension provides an interface to the URDF importer.
Example:
Setup the configuration parameters before importing.
Files must be parsed before imported.
::
from omni.importer.urdf import _urdf
urdf_interface = _urdf.acquire_urdf_interface()
# setup config params
import_config = _urdf.ImportConfig()
import_config.set_merge_fixed_joints(False)
import_config.set_fix_base(True)
# parse and import file
imported_robot = urdf_interface.parse_urdf(robot_path, filename, import_config)
urdf_interface.import_robot(robot_path, filename, imported_robot, import_config, "")
Refer to the sample documentation for more examples and usage
)pbdoc";
py::class_<ImportConfig>(m, "ImportConfig")
.def(py::init<>())
.def_readwrite("merge_fixed_joints", &ImportConfig::mergeFixedJoints,
"Consolidating links that are connected by fixed joints")
.def_readwrite("convex_decomp", &ImportConfig::convexDecomp,
"Decompose a convex mesh into smaller pieces for a closer fit")
.def_readwrite("import_inertia_tensor", &ImportConfig::importInertiaTensor,
"Import inertia tensor from urdf, if not specified in urdf it will import as identity")
.def_readwrite("fix_base", &ImportConfig::fixBase, "Create fix joint for base link")
// .def_readwrite("flip_visuals", &ImportConfig::flipVisuals, "Flip visuals from Y up to Z up")
.def_readwrite("self_collision", &ImportConfig::selfCollision, "Self collisions between links in the articulation")
.def_readwrite("density", &ImportConfig::density, "default density used for links, use 0 to autocompute")
.def_readwrite("default_drive_type", &ImportConfig::defaultDriveType, "default drive type used for joints")
.def_readwrite(
"subdivision_scheme", &ImportConfig::subdivisionScheme, "Subdivision scheme to be used for mesh normals")
.def_readwrite(
"default_drive_strength", &ImportConfig::defaultDriveStrength, "default drive stiffness used for joints")
.def_readwrite("default_position_drive_damping", &ImportConfig::defaultPositionDriveDamping,
"default drive damping used if drive type is set to position")
.def_readwrite("distance_scale", &ImportConfig::distanceScale,
"Set the unit scaling factor, 1.0 means meters, 100.0 means cm")
.def_readwrite("up_vector", &ImportConfig::upVector, "Up vector used for import")
.def_readwrite("create_physics_scene", &ImportConfig::createPhysicsScene,
"add a physics scene to the stage on import if none exists")
.def_readwrite("make_default_prim", &ImportConfig::makeDefaultPrim, "set imported robot as default prim")
.def_readwrite("make_instanceable", &ImportConfig::makeInstanceable,
"Creates an instanceable version of the asset. All meshes will be placed in a separate USD file")
.def_readwrite(
"instanceable_usd_path", &ImportConfig::instanceableMeshUsdPath, "USD file to store instanceable mehses in")
.def_readwrite("collision_from_visuals", &ImportConfig::collisionFromVisuals,
"Generate convex collision from the visual meshes.")
.def_readwrite("replace_cylinders_with_capsules", &ImportConfig::replaceCylindersWithCapsules,
"Replace all cylinder bodies in the URDF with capsules.")
// setters for each property
.def("set_merge_fixed_joints", [](ImportConfig& config, const bool value) { config.mergeFixedJoints = value; })
.def("set_replace_cylinders_with_capsules", [](ImportConfig& config, const bool value) { config.replaceCylindersWithCapsules = value; })
.def("set_convex_decomp", [](ImportConfig& config, const bool value) { config.convexDecomp = value; })
.def("set_import_inertia_tensor",
[](ImportConfig& config, const bool value) { config.importInertiaTensor = value; })
.def("set_fix_base", [](ImportConfig& config, const bool value) { config.fixBase = value; })
// .def("set_flip_visuals", [](ImportConfig& config, const bool value) { config.flipVisuals = value; })
.def("set_self_collision", [](ImportConfig& config, const bool value) { config.selfCollision = value; })
.def("set_density", [](ImportConfig& config, const float value) { config.density = value; })
.def("set_default_drive_type", [](ImportConfig& config, const int value)
{ config.defaultDriveType = static_cast<UrdfJointTargetType>(value); })
.def("set_subdivision_scheme", [](ImportConfig& config, const int value)
{ config.subdivisionScheme = static_cast<UrdfNormalSubdivisionScheme>(value); })
.def("set_default_drive_strength",
[](ImportConfig& config, const float value) { config.defaultDriveStrength = value; })
.def("set_default_position_drive_damping",
[](ImportConfig& config, const float value) { config.defaultPositionDriveDamping = value; })
.def("set_distance_scale", [](ImportConfig& config, const float value) { config.distanceScale = value; })
.def("set_up_vector",
[](ImportConfig& config, const float x, const float y, const float z) {
config.upVector = { x, y, z };
})
.def("set_create_physics_scene",
[](ImportConfig& config, const bool value) { config.createPhysicsScene = value; })
.def("set_make_default_prim", [](ImportConfig& config, const bool value) { config.makeDefaultPrim = value; })
.def("set_make_instanceable", [](ImportConfig& config, const bool value) { config.makeInstanceable = value; })
.def("set_instanceable_usd_path",
[](ImportConfig& config, const std::string value) { config.instanceableMeshUsdPath = value; })
.def("set_collision_from_visuals",
[](ImportConfig& config, const bool value) { config.collisionFromVisuals = value; });
py::class_<Vec3>(m, "Position", "")
.def_readwrite("x", &Vec3::x, "")
.def_readwrite("y", &Vec3::y, "")
.def_readwrite("z", &Vec3::z, "")
.def(py::init<>());
py::class_<Quat>(m, "Orientation", "")
.def_readwrite("w", &Quat::w, "")
.def_readwrite("x", &Quat::x, "")
.def_readwrite("y", &Quat::y, "")
.def_readwrite("z", &Quat::z, "")
.def(py::init<>());
py::class_<Transform>(m, "UrdfOrigin", "")
.def_readwrite("p", &Transform::p, "")
.def_readwrite("q", &Transform::q, "")
.def(py::init<>());
py::class_<UrdfInertia>(m, "UrdfInertia", "")
.def_readwrite("ixx", &UrdfInertia::ixx, "")
.def_readwrite("ixy", &UrdfInertia::ixy, "")
.def_readwrite("ixz", &UrdfInertia::ixz, "")
.def_readwrite("iyy", &UrdfInertia::iyy, "")
.def_readwrite("iyz", &UrdfInertia::iyz, "")
.def_readwrite("izz", &UrdfInertia::izz, "")
.def(py::init<>());
py::class_<UrdfInertial>(m, "UrdfInertial", "")
.def_readwrite("origin", &UrdfInertial::origin, "")
.def_readwrite("mass", &UrdfInertial::mass, "")
.def_readwrite("inertia", &UrdfInertial::inertia, "")
.def_readwrite("has_origin", &UrdfInertial::hasOrigin, "")
.def_readwrite("has_mass", &UrdfInertial::hasMass, "")
.def_readwrite("has_inertia", &UrdfInertial::hasInertia, "")
.def(py::init<>());
py::class_<UrdfAxis>(m, "UrdfAxis", "")
.def_readwrite("x", &UrdfAxis::x, "")
.def_readwrite("y", &UrdfAxis::y, "")
.def_readwrite("z", &UrdfAxis::z, "")
.def(py::init<>());
py::class_<UrdfColor>(m, "UrdfColor", "")
.def_readwrite("r", &UrdfColor::r, "")
.def_readwrite("g", &UrdfColor::g, "")
.def_readwrite("b", &UrdfColor::b, "")
.def_readwrite("a", &UrdfColor::a, "")
.def(py::init<>());
py::enum_<UrdfJointType>(m, "UrdfJointType", py::arithmetic(), "")
.value("JOINT_REVOLUTE", UrdfJointType::REVOLUTE)
.value("JOINT_CONTINUOUS", UrdfJointType::CONTINUOUS)
.value("JOINT_PRISMATIC", UrdfJointType::PRISMATIC)
.value("JOINT_FIXED", UrdfJointType::FIXED)
.value("JOINT_FLOATING", UrdfJointType::FLOATING)
.value("JOINT_PLANAR", UrdfJointType::PLANAR)
.export_values();
py::enum_<UrdfJointTargetType>(m, "UrdfJointTargetType", py::arithmetic(), "")
.value("JOINT_DRIVE_NONE", UrdfJointTargetType::NONE)
.value("JOINT_DRIVE_POSITION", UrdfJointTargetType::POSITION)
.value("JOINT_DRIVE_VELOCITY", UrdfJointTargetType::VELOCITY)
.export_values();
py::enum_<UrdfJointDriveType>(m, "UrdfJointDriveType", py::arithmetic(), "")
.value("JOINT_DRIVE_ACCELERATION", UrdfJointDriveType::ACCELERATION)
.value("JOINT_DRIVE_FORCE", UrdfJointDriveType::FORCE)
.export_values();
py::class_<UrdfDynamics>(m, "UrdfDynamics", "")
.def_readwrite("damping", &UrdfDynamics::damping, "")
.def_readwrite("friction", &UrdfDynamics::friction, "")
.def_readwrite("stiffness", &UrdfDynamics::stiffness, "")
.def("set_damping", [](UrdfDynamics& drive, const float value) { drive.damping = value; })
.def("set_friction", [](UrdfDynamics& drive, const float value) { drive.friction = value; })
.def("set_stiffness", [](UrdfDynamics& drive, const float value) { drive.stiffness = value; })
.def(py::init<>());
py::class_<UrdfJointDrive>(m, "UrdfJointDrive", "")
.def_readwrite("target", &UrdfJointDrive::target, "")
.def_readwrite("target_type", &UrdfJointDrive::targetType, "")
.def_readwrite("drive_type", &UrdfJointDrive::driveType, "")
.def("set_target", [](UrdfJointDrive& drive, const float value) { drive.target = value; })
.def("set_target_type",
[](UrdfJointDrive& drive, const int value) { drive.targetType = static_cast<UrdfJointTargetType>(value); })
.def("set_drive_type",
[](UrdfJointDrive& drive, const int value) { drive.driveType = static_cast<UrdfJointDriveType>(value); })
.def(py::init<>());
py::class_<UrdfLimit>(m, "UrdfLimit", "")
.def_readwrite("lower", &UrdfLimit::lower, "")
.def_readwrite("upper", &UrdfLimit::upper, "")
.def_readwrite("effort", &UrdfLimit::effort, "")
.def_readwrite("velocity", &UrdfLimit::velocity, "")
.def("set_lower", [](UrdfLimit& limit, const float value) { limit.lower = value; })
.def("set_upper", [](UrdfLimit& limit, const float value) { limit.upper = value; })
.def("set_effort", [](UrdfLimit& limit, const float value) { limit.effort = value; })
.def("set_velocity", [](UrdfLimit& limit, const float value) { limit.velocity = value; })
.def(py::init<>());
py::enum_<UrdfGeometryType>(m, "UrdfGeometryType", py::arithmetic(), "")
.value("GEOMETRY_BOX", UrdfGeometryType::BOX)
.value("GEOMETRY_CYLINDER", UrdfGeometryType::CYLINDER)
.value("GEOMETRY_CAPSULE", UrdfGeometryType::CAPSULE)
.value("GEOMETRY_SPHERE", UrdfGeometryType::SPHERE)
.value("GEOMETRY_MESH", UrdfGeometryType::MESH)
.export_values();
py::class_<UrdfGeometry>(m, "UrdfGeometry", "")
.def_readwrite("type", &UrdfGeometry::type, "")
.def_readwrite("size_x", &UrdfGeometry::size_x, "")
.def_readwrite("size_y", &UrdfGeometry::size_y, "")
.def_readwrite("size_z", &UrdfGeometry::size_z, "")
.def_readwrite("radius", &UrdfGeometry::radius, "")
.def_readwrite("length", &UrdfGeometry::length, "")
.def_readwrite("scale_x", &UrdfGeometry::scale_x, "")
.def_readwrite("scale_y", &UrdfGeometry::scale_y, "")
.def_readwrite("scale_z", &UrdfGeometry::scale_z, "")
.def_readwrite("mesh_file_path", &UrdfGeometry::meshFilePath, "")
.def(py::init<>());
py::class_<UrdfMaterial>(m, "UrdfMaterial", "")
.def_readwrite("name", &UrdfMaterial::name, "")
.def_readwrite("color", &UrdfMaterial::color, "")
.def_readwrite("texture_file_path", &UrdfMaterial::textureFilePath, "")
.def(py::init<>());
py::class_<UrdfVisual>(m, "UrdfVisual", "")
.def_readwrite("name", &UrdfVisual::name, "")
.def_readwrite("origin", &UrdfVisual::origin, "")
.def_readwrite("geometry", &UrdfVisual::geometry, "")
.def_readwrite("material", &UrdfVisual::material, "")
.def(py::init<>());
py::class_<UrdfCollision>(m, "UrdfCollision", "")
.def_readwrite("name", &UrdfCollision::name, "")
.def_readwrite("origin", &UrdfCollision::origin, "")
.def_readwrite("geometry", &UrdfCollision::geometry, "")
.def(py::init<>());
py::class_<UrdfLink>(m, "UrdfLink", "")
.def_readwrite("name", &UrdfLink::name, "")
.def_readwrite("inertial", &UrdfLink::inertial, "")
.def_readwrite("visuals", &UrdfLink::visuals, "")
.def_readwrite("collisions", &UrdfLink::collisions, "")
.def(py::init<>());
py::class_<UrdfJoint>(m, "UrdfJoint", "")
.def_readwrite("name", &UrdfJoint::name, "")
.def_readwrite("type", &UrdfJoint::type, "")
.def_readwrite("origin", &UrdfJoint::origin, "")
.def_readwrite("parent_link_name", &UrdfJoint::parentLinkName, "")
.def_readwrite("child_link_name", &UrdfJoint::childLinkName, "")
.def_readwrite("axis", &UrdfJoint::axis, "")
.def_readwrite("dynamics", &UrdfJoint::dynamics, "")
.def_readwrite("limit", &UrdfJoint::limit, "")
.def_readwrite("drive", &UrdfJoint::drive, "")
.def(py::init<>());
py::class_<UrdfRobot>(m, "UrdfRobot", "")
.def_readwrite("name", &UrdfRobot::name, "")
.def_readwrite("links", &UrdfRobot::links, "")
.def_readwrite("joints", &UrdfRobot::joints, "")
.def_readwrite("materials", &UrdfRobot::materials, "")
.def(py::init<>());
declare_map<UrdfLink>(m, std::string("UrdfLinkMap"));
declare_map<UrdfJoint>(m, std::string("UrdfJointMap"));
declare_map<UrdfMaterial>(m, std::string("UrdfMaterialMap"));
defineInterfaceClass<Urdf>(m, "Urdf", "acquire_urdf_interface", "release_urdf_interface")
.def("parse_urdf", wrapInterfaceFunction(&Urdf::parseUrdf),
R"pbdoc(
Parse URDF file into the internal data structure, which is displayed in the importer window for inspection.
Args:
arg0 (:obj:`str`): The absolute path to where the urdf file is
arg1 (:obj:`str`): The name of the urdf file
arg2 (:obj:`omni.importer.urdf._urdf.ImportConfig`): Import configuration parameters
Returns:
:obj:`omni.importer.urdf._urdf.UrdfRobot`: Parsed URDF stored in an internal structure.
)pbdoc")
.def("import_robot", wrapInterfaceFunction(&Urdf::importRobot), py::arg("assetRoot"), py::arg("assetName"),
py::arg("robot"), py::arg("importConfig"), py::arg("stage") = std::string(""),
R"pbdoc(
Importing the robot, from the already parsed URDF file.
Args:
arg0 (:obj:`str`): The absolute path to where the urdf file is
arg1 (:obj:`str`): The name of the urdf file
arg2 (:obj:`omni.importer.urdf._urdf.UrdfRobot`): The parsed URDF file, the output from :obj:`parse_urdf`
arg3 (:obj:`omni.importer.urdf._urdf.ImportConfig`): Import configuration parameters
arg4 (:obj:`str`): optional: path to stage to use for importing. leaving it empty will import on open stage. If the open stage is a new stage, textures will not load.
Returns:
:obj:`str`: Path to the robot on the USD stage.
)pbdoc")
.def("get_kinematic_chain", wrapInterfaceFunction(&Urdf::getKinematicChain),
R"pbdoc(
Get the kinematic chain of the robot. Mostly used for graphic display of the kinematic tree.
Args:
arg0 (:obj:`omni.importer.urdf._urdf.UrdfRobot`): The parsed URDF, the output from :obj:`parse_urdf`
Returns:
:obj:`dict`: A dictionary with information regarding the parent-child relationship between all the links and joints
)pbdoc");
}
}
| 19,097 | C++ | 48.348837 | 186 | 0.605331 |
NVIDIA-Omniverse/urdf-importer-extension/source/extensions/omni.importer.urdf/config/extension.toml | [core]
reloadable = true
order = 0
[package]
version = "1.1.4"
category = "Simulation"
title = "Omniverse URDF Importer"
description = "URDF Importer"
repository = "https://github.com/NVIDIA-Omniverse/urdf-importer-extension"
authors = ["Isaac Sim Team"]
keywords = ["urdf", "importer", "isaac"]
changelog = "docs/CHANGELOG.md"
readme = "docs/Overview.md"
icon = "data/icon.png"
writeTarget.kit = true
preview_image = "data/preview.png"
[dependencies]
"omni.kit.commands" = {}
"omni.kit.uiapp" = {}
"omni.kit.window.filepicker" = {}
"omni.kit.window.content_browser" = {}
"omni.kit.viewport.utility" = {}
"omni.kit.pip_archive" = {} # pulls in pillow
"omni.physx" = {}
"omni.kit.window.extensions" = {}
"omni.kit.window.property" = {}
[[python.module]]
name = "omni.importer.urdf"
[[python.module]]
name = "omni.importer.urdf.tests"
[[python.module]]
name = "omni.importer.urdf.scripts.ui"
[[python.module]]
name = "omni.importer.urdf.scripts.samples.import_carter"
[[python.module]]
name = "omni.importer.urdf.scripts.samples.import_franka"
[[python.module]]
name = "omni.importer.urdf.scripts.samples.import_kaya"
[[python.module]]
name = "omni.importer.urdf.scripts.samples.import_ur10"
[[native.plugin]]
path = "bin/*.plugin"
recursive = false
[[test]]
# this is to catch issues where our assimp is out of sync with the one that comes with
# asset importer as this can cause segfaults due to binary incompatibility.
dependencies = ["omni.kit.tool.asset_importer"]
stdoutFailPatterns.exclude = [
"*extension object is still alive, something holds a reference on it*", # exclude warning as failure
]
args = ["--/app/file/ignoreUnsavedOnExit=1"]
[documentation]
pages = [
"docs/Overview.md",
"docs/CHANGELOG.md",
] | 1,741 | TOML | 23.885714 | 104 | 0.709937 |
NVIDIA-Omniverse/urdf-importer-extension/source/extensions/omni.importer.urdf/plugins/Urdf.h | // SPDX-FileCopyrightText: Copyright (c) 2023 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
// SPDX-License-Identifier: Apache-2.0
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#pragma once
#include "UrdfTypes.h"
#include <carb/Defines.h>
#include <pybind11/pybind11.h>
#include <stdint.h>
namespace omni
{
namespace importer
{
namespace urdf
{
struct ImportConfig
{
bool mergeFixedJoints = false;
bool replaceCylindersWithCapsules = false;
bool convexDecomp = false;
bool importInertiaTensor = false;
bool fixBase = true;
bool selfCollision = false;
float density = 0.0f; // default density used for objects without mass/inertia, 0 to autocompute
UrdfJointTargetType defaultDriveType = UrdfJointTargetType::POSITION;
float defaultDriveStrength = 1e7f;
float defaultPositionDriveDamping = 1e5f;
float distanceScale = 1.0f;
UrdfAxis upVector = { 0.0f, 0.0f, 1.0f };
bool createPhysicsScene = false;
bool makeDefaultPrim = false;
UrdfNormalSubdivisionScheme subdivisionScheme = UrdfNormalSubdivisionScheme::BILINEAR;
// bool flipVisuals = false;
bool makeInstanceable = false;
std::string instanceableMeshUsdPath = "./instanceable_meshes.usd";
bool collisionFromVisuals = false; // Create collision geometry from visual geometry when missing collision.
};
struct Urdf
{
CARB_PLUGIN_INTERFACE("omni::importer::urdf::Urdf", 0, 1);
// Parses a urdf file into a UrdfRobot data structure
UrdfRobot(CARB_ABI* parseUrdf)(const std::string& assetRoot, const std::string& assetName, ImportConfig& importConfig);
// Imports a UrdfRobot into the stage
std::string(CARB_ABI* importRobot)(const std::string& assetRoot,
const std::string& assetName,
const UrdfRobot& robot,
ImportConfig& importConfig,
const std::string& stage);
pybind11::dict(CARB_ABI* getKinematicChain)(const UrdfRobot& robot);
};
}
}
}
| 2,576 | C | 32.467532 | 123 | 0.694876 |
NVIDIA-Omniverse/urdf-importer-extension/source/extensions/omni.importer.urdf/plugins/Urdf.cpp | // SPDX-FileCopyrightText: Copyright (c) 2023 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
// SPDX-License-Identifier: Apache-2.0
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#define CARB_EXPORTS
// clang-format off
#include "UsdPCH.h"
// clang-format on
#include "import/ImportHelpers.h"
#include "import/UrdfImporter.h"
#include "Urdf.h"
#include <carb/PluginUtils.h>
#include <carb/logging/Log.h>
#include <omni/ext/IExt.h>
#include <omni/kit/IApp.h>
#include <omni/kit/IStageUpdate.h>
#include <pybind11/pybind11.h>
#include <fstream>
#include <memory>
using namespace carb;
const struct carb::PluginImplDesc kPluginImpl = { "omni.importer.urdf", "URDF Utilities", "NVIDIA",
carb::PluginHotReload::eEnabled, "dev" };
CARB_PLUGIN_IMPL(kPluginImpl, omni::importer::urdf::Urdf)
CARB_PLUGIN_IMPL_DEPS(omni::kit::IApp, carb::logging::ILogging)
namespace
{
omni::importer::urdf::UrdfRobot parseUrdf(const std::string& assetRoot,
const std::string& assetName,
omni::importer::urdf::ImportConfig& importConfig)
{
omni::importer::urdf::UrdfRobot robot;
std::string filename = assetRoot + "/" + assetName;
{
CARB_LOG_INFO("Trying to import %s", filename.c_str());
if (parseUrdf(assetRoot, assetName, robot))
{
}
else
{
CARB_LOG_ERROR("Failed to parse URDF file '%s'", assetName.c_str());
return robot;
}
if (importConfig.mergeFixedJoints)
{
collapseFixedJoints(robot);
}
if (importConfig.collisionFromVisuals)
{
addVisualMeshToCollision(robot);
}
for (auto& joint : robot.joints)
{
joint.second.drive.targetType = importConfig.defaultDriveType;
if (joint.second.drive.targetType == omni::importer::urdf::UrdfJointTargetType::POSITION)
{
// set position gain
if (importConfig.defaultDriveStrength > 0)
{
joint.second.dynamics.stiffness = importConfig.defaultDriveStrength;
}
// set velocity gain
if (importConfig.defaultPositionDriveDamping > 0)
{
joint.second.dynamics.damping = importConfig.defaultPositionDriveDamping;
}
}
else if (joint.second.drive.targetType == omni::importer::urdf::UrdfJointTargetType::VELOCITY)
{
// set position gain
joint.second.dynamics.stiffness = 0.0f;
// set velocity gain
if (importConfig.defaultDriveStrength > 0)
{
joint.second.dynamics.damping = importConfig.defaultDriveStrength;
}
}
else if (joint.second.drive.targetType == omni::importer::urdf::UrdfJointTargetType::NONE)
{
// set both gains to 0
joint.second.dynamics.stiffness = 0.0f;
joint.second.dynamics.damping = 0.0f;
}
else
{
CARB_LOG_ERROR("Unknown drive target type %d", (int)joint.second.drive.targetType);
}
}
}
return robot;
}
std::string importRobot(const std::string& assetRoot,
const std::string& assetName,
const omni::importer::urdf::UrdfRobot& robot,
omni::importer::urdf::ImportConfig& importConfig,
const std::string& stage_identifier = "")
{
omni::importer::urdf::UrdfImporter urdfImporter(assetRoot, assetName, importConfig);
bool save_stage = true;
pxr::UsdStageRefPtr _stage;
if (stage_identifier != "" && pxr::UsdStage::IsSupportedFile(stage_identifier))
{
_stage = pxr::UsdStage::Open(stage_identifier);
if (!_stage)
{
CARB_LOG_INFO("Creating Stage: %s", stage_identifier.c_str());
_stage = pxr::UsdStage::CreateNew(stage_identifier);
}
else
{
for (const auto& p : _stage->GetPrimAtPath(pxr::SdfPath("/")).GetChildren())
{
_stage->RemovePrim(p.GetPath());
}
}
importConfig.makeDefaultPrim = true;
pxr::UsdGeomSetStageUpAxis(_stage, pxr::UsdGeomTokens->z);
}
if (!_stage) // If all else fails, import on current stage
{
CARB_LOG_INFO("Importing URDF to Current Stage");
// Get the 'active' USD stage from the USD stage cache.
const std::vector<pxr::UsdStageRefPtr> allStages = pxr::UsdUtilsStageCache::Get().GetAllStages();
if (allStages.size() != 1)
{
CARB_LOG_ERROR("Cannot determine the 'active' USD stage (%zu stages present in the USD stage cache).", allStages.size());
return "";
}
_stage = allStages[0];
save_stage = false;
}
std::string result = "";
if (_stage)
{
pxr::UsdGeomSetStageMetersPerUnit(_stage, 1.0 / importConfig.distanceScale);
result = urdfImporter.addToStage(_stage, robot);
// CARB_LOG_WARN("Import Done, saving");
if (save_stage)
{
// CARB_LOG_WARN("Saving Stage %s", _stage->GetRootLayer()->GetIdentifier().c_str());
_stage->Save();
}
}
else
{
CARB_LOG_ERROR("Stage pointer not valid, could not import urdf to stage");
}
return result;
}
}
pybind11::list addLinksAndJoints(omni::importer::urdf::KinematicChain::Node* parentNode)
{
if (parentNode->parentJointName_ == "")
{
}
pybind11::list temp_list;
if (!parentNode->childNodes_.empty())
{
for (const auto& childNode : parentNode->childNodes_)
{
pybind11::dict temp;
temp["A_joint"] = childNode->parentJointName_;
temp["A_link"] = parentNode->linkName_;
temp["B_link"] = childNode->linkName_;
temp["B_node"] = addLinksAndJoints(childNode.get());
temp_list.append(temp);
}
}
return temp_list;
}
pybind11::dict getKinematicChain(const omni::importer::urdf::UrdfRobot& robot)
{
pybind11::dict robotDict;
omni::importer::urdf::KinematicChain chain;
if (chain.computeKinematicChain(robot))
{
robotDict["A_joint"] = "";
robotDict["B_link"] = chain.baseNode->linkName_;
robotDict["B_node"] = addLinksAndJoints(chain.baseNode.get());
}
return robotDict;
}
CARB_EXPORT void carbOnPluginStartup()
{
CARB_LOG_INFO("Startup URDF Extension");
}
CARB_EXPORT void carbOnPluginShutdown()
{
}
void fillInterface(omni::importer::urdf::Urdf& iface)
{
using namespace omni::importer::urdf;
memset(&iface, 0, sizeof(iface));
iface.parseUrdf = parseUrdf;
iface.importRobot = importRobot;
iface.getKinematicChain = getKinematicChain;
}
| 7,554 | C++ | 31.012712 | 133 | 0.59121 |
NVIDIA-Omniverse/urdf-importer-extension/source/extensions/omni.importer.urdf/plugins/UrdfTypes.h | // SPDX-FileCopyrightText: Copyright (c) 2023 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
// SPDX-License-Identifier: Apache-2.0
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#pragma once
#include "math/core/maths.h"
#include <float.h>
#include <iostream>
#include <map>
#include <string>
#include <vector>
namespace omni
{
namespace importer
{
namespace urdf
{
// The default values and data structures are mostly the same as defined in the official URDF documentation
// http://wiki.ros.org/urdf/XML
struct UrdfInertia
{
float ixx = 0.0f;
float ixy = 0.0f;
float ixz = 0.0f;
float iyy = 0.0f;
float iyz = 0.0f;
float izz = 0.0f;
};
struct UrdfInertial
{
Transform origin; // This is the pose of the inertial reference frame, relative to the link reference frame. The
// origin of the inertial reference frame needs to be at the center of gravity
float mass = 0.0f;
UrdfInertia inertia;
bool hasOrigin = false;
bool hasMass = false; // Whether the inertial field defined a mass
bool hasInertia = false; // Whether the inertial field defined an inertia
};
struct UrdfAxis
{
float x = 1.0f;
float y = 0.0f;
float z = 0.0f;
};
// By Default a UrdfColor struct will have an invalid color unless it was found in the xml
struct UrdfColor
{
float r = -1.0f;
float g = -1.0f;
float b = -1.0f;
float a = 1.0f;
};
enum class UrdfJointType
{
REVOLUTE = 0, // A hinge joint that rotates along the axis and has a limited range specified by the upper and lower
// limits
CONTINUOUS = 1, // A continuous hinge joint that rotates around the axis and has no upper and lower limits
PRISMATIC = 2, // A sliding joint that slides along the axis, and has a limited range specified by the upper and
// lower limits
FIXED = 3, // this is not really a joint because it cannot move. All degrees of freedom are locked. This type of
// joint does not require the axis, calibration, dynamics, limits or safety_controller
FLOATING = 4, // This joint allows motion for all 6 degrees of freedom
PLANAR = 5 // This joint allows motion in a plane perpendicular to the axis
};
enum class UrdfJointTargetType
{
NONE = 0,
POSITION = 1,
VELOCITY = 2
};
enum class UrdfNormalSubdivisionScheme
{
CATMULLCLARK = 0,
LOOP = 1,
BILINEAR = 2,
NONE = 3
};
enum class UrdfJointDriveType
{
ACCELERATION = 0,
FORCE = 2
};
struct UrdfDynamics
{
float damping = 0.0f;
float friction = 0.0f;
float stiffness = 0.0f;
};
struct UrdfJointDrive
{
float target = 0.0;
UrdfJointTargetType targetType = UrdfJointTargetType::POSITION;
UrdfJointDriveType driveType = UrdfJointDriveType::FORCE;
};
struct UrdfJointMimic
{
std::string joint = "";
float multiplier;
float offset;
};
struct UrdfLimit
{
float lower = -FLT_MAX; // An attribute specifying the lower joint limit (radians for revolute joints, meters for
// prismatic joints)
float upper = FLT_MAX; // An attribute specifying the upper joint limit (radians for revolute joints, meters for
// prismatic joints)
float effort = FLT_MAX; // An attribute for enforcing the maximum joint effort
float velocity = FLT_MAX; // An attribute for enforcing the maximum joint velocity
};
enum class UrdfGeometryType
{
BOX = 0,
CYLINDER = 1,
CAPSULE = 2,
SPHERE = 3,
MESH = 4
};
struct UrdfGeometry
{
UrdfGeometryType type;
// Box
float size_x = 0.0f;
float size_y = 0.0f;
float size_z = 0.0f;
// Cylinder and Sphere
float radius = 0.0f;
float length = 0.0f;
// Mesh
float scale_x = 1.0f;
float scale_y = 1.0f;
float scale_z = 1.0f;
std::string meshFilePath;
};
struct UrdfMaterial
{
std::string name;
UrdfColor color;
std::string textureFilePath;
};
struct UrdfVisual
{
std::string name;
Transform origin; // The reference frame of the visual element with respect to the reference frame of the link
UrdfGeometry geometry;
UrdfMaterial material;
};
struct UrdfCollision
{
std::string name;
Transform origin; // The reference frame of the collision element, relative to the reference frame of the link
UrdfGeometry geometry;
};
struct UrdfLink
{
std::string name;
UrdfInertial inertial;
std::vector<UrdfVisual> visuals;
std::vector<UrdfCollision> collisions;
std::map<std::string, Transform> mergedChildren;
};
struct UrdfJoint
{
std::string name;
UrdfJointType type;
Transform origin; // This is the transform from the parent link to the child link. The joint is located at the
// origin of the child link
std::string parentLinkName;
std::string childLinkName;
UrdfAxis axis;
UrdfDynamics dynamics;
UrdfLimit limit;
UrdfJointDrive drive;
UrdfJointMimic mimic;
std::map<std::string, float> mimicChildren;
bool dontCollapse = false; // This is a custom attribute that is used to prevent the child link from being
// collapsed into the parent link when a fixed joint is used. It is used when user
// enables "merging of fixed joints" but does not want to merge this particular joint.
// For example: for sensor or end-effector frames.
// Note: The tag is not part of the URDF specification. Rather it is a custom tag
// that was first introduced in Isaac Gym for the purpose of merging fixed joints.
};
struct UrdfRobot
{
std::string name;
std::map<std::string, UrdfLink> links;
std::map<std::string, UrdfJoint> joints;
std::map<std::string, UrdfMaterial> materials;
};
} // namespace urdf
}
}
| 6,415 | C | 26.774892 | 119 | 0.66516 |
NVIDIA-Omniverse/urdf-importer-extension/source/extensions/omni.importer.urdf/plugins/import/KinematicChain.cpp | // SPDX-FileCopyrightText: Copyright (c) 2023 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
// SPDX-License-Identifier: Apache-2.0
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include "KinematicChain.h"
#include <carb/logging/Log.h>
#include <algorithm>
namespace omni
{
namespace importer
{
namespace urdf
{
KinematicChain::~KinematicChain()
{
baseNode.reset();
}
// Computes the kinematic chain for a Urdf robot
bool KinematicChain::computeKinematicChain(const UrdfRobot& urdfRobot)
{
bool success = true;
if (urdfRobot.joints.empty())
{
if (urdfRobot.links.empty())
{
CARB_LOG_ERROR("*** URDF robot is empty \n");
success = false;
}
else if (urdfRobot.links.size() == 1)
{
baseNode = std::make_unique<Node>(urdfRobot.links.begin()->second.name, "");
}
else
{
CARB_LOG_ERROR("*** URDF has multiple links that are not connected to a joint \n");
success = false;
}
}
else
{
std::vector<std::string> childLinkNames;
for (auto& joint : urdfRobot.joints)
{
childLinkNames.push_back(joint.second.childLinkName);
}
// Find the base link
std::string baseLinkName;
for (auto& link : urdfRobot.links)
{
if (std::find(childLinkNames.begin(), childLinkNames.end(), link.second.name) == childLinkNames.end())
{
CARB_LOG_INFO("Found base link called %s \n", link.second.name.c_str());
baseLinkName = link.second.name;
break;
}
}
if (baseLinkName.empty())
{
CARB_LOG_ERROR("*** Could not find base link \n");
success = false;
}
baseNode = std::make_unique<Node>(baseLinkName, "");
// Recursively add the rest of the kinematic chain
computeChildNodes(baseNode, urdfRobot);
}
return success;
}
void KinematicChain::computeChildNodes(std::unique_ptr<Node>& parentNode, const UrdfRobot& urdfRobot)
{
for (auto& joint : urdfRobot.joints)
{
if (joint.second.parentLinkName == parentNode->linkName_)
{
std::unique_ptr<Node> childNode = std::make_unique<Node>(joint.second.childLinkName, joint.second.name);
parentNode->childNodes_.push_back(std::move(childNode));
CARB_LOG_INFO("Link %s has child %s \n", parentNode->linkName_.c_str(), joint.second.childLinkName.c_str());
}
}
if (parentNode->childNodes_.empty())
{
return;
}
else
{
for (auto& childLink : parentNode->childNodes_)
{
computeChildNodes(childLink, urdfRobot);
}
}
}
}
}
}
| 3,295 | C++ | 27.17094 | 120 | 0.607587 |
NVIDIA-Omniverse/urdf-importer-extension/source/extensions/omni.importer.urdf/plugins/import/ImportHelpers.h | // SPDX-FileCopyrightText: Copyright (c) 2023 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
// SPDX-License-Identifier: Apache-2.0
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#pragma once
// clang-format off
#include "../UsdPCH.h"
// clang-format on
#include "../parse/UrdfParser.h"
#include "KinematicChain.h"
#include "../math/core/maths.h"
#include "../UrdfTypes.h"
namespace omni
{
namespace importer
{
namespace urdf
{
Quat indexedRotation(int axis, float s, float c);
Vec3 Diagonalize(const Matrix33& m, Quat& massFrame);
void inertiaToUrdf(const Matrix33& inertia, UrdfInertia& urdfInertia);
void urdfToInertia(const UrdfInertia& urdfInertia, Matrix33& inertia);
void mergeFixedChildLinks(const KinematicChain::Node& parentNode, UrdfRobot& robot);
bool collapseFixedJoints(UrdfRobot& robot);
Vec3 urdfAxisToVec(const UrdfAxis& axis);
std::string resolveXrefPath(const std::string& assetRoot, const std::string& urdfPath, const std::string& xrefpath);
bool IsUsdFile(const std::string& filename);
// Make a path name that is not already used.
std::string GetNewSdfPathString(pxr::UsdStageWeakPtr stage, std::string path, int nameClashNum = -1);
bool addVisualMeshToCollision(UrdfRobot& robot);
}
}
}
| 1,731 | C | 32.960784 | 116 | 0.76372 |
NVIDIA-Omniverse/urdf-importer-extension/source/extensions/omni.importer.urdf/plugins/import/ImportHelpers.cpp | // SPDX-FileCopyrightText: Copyright (c) 2023 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
// SPDX-License-Identifier: Apache-2.0
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include "ImportHelpers.h"
#include "../core/PathUtils.h"
#include <carb/logging/Log.h>
#include <boost/algorithm/string.hpp>
namespace omni
{
namespace importer
{
namespace urdf
{
Quat indexedRotation(int axis, float s, float c)
{
float v[3] = { 0, 0, 0 };
v[axis] = s;
return Quat(v[0], v[1], v[2], c);
}
Vec3 Diagonalize(const Matrix33& m, Quat& massFrame)
{
const int MAX_ITERS = 24;
Quat q = Quat();
Matrix33 d;
for (int i = 0; i < MAX_ITERS; i++)
{
Matrix33 axes;
quat2Mat(q, axes);
d = Transpose(axes) * m * axes;
float d0 = fabs(d(1, 2)), d1 = fabs(d(0, 2)), d2 = fabs(d(0, 1));
// rotation axis index, from largest off-diagonal element
int a = int(d0 > d1 && d0 > d2 ? 0 : d1 > d2 ? 1 : 2);
int a1 = (a + 1 + (a >> 1)) & 3, a2 = (a1 + 1 + (a1 >> 1)) & 3;
if (d(a1, a2) == 0.0f || fabs(d(a1, a1) - d(a2, a2)) > 2e6f * fabs(2.0f * d(a1, a2)))
break;
// cot(2 * phi), where phi is the rotation angle
float w = (d(a1, a1) - d(a2, a2)) / (2.0f * d(a1, a2));
float absw = fabs(w);
Quat r;
if (absw > 1000)
{
// h will be very close to 1, so use small angle approx instead
r = indexedRotation(a, 1 / (4 * w), 1.f);
}
else
{
float t = 1 / (absw + Sqrt(w * w + 1)); // absolute value of tan phi
float h = 1 / Sqrt(t * t + 1); // absolute value of cos phi
assert(h != 1); // |w|<1000 guarantees this with typical IEEE754 machine eps (approx 6e-8)
r = indexedRotation(a, Sqrt((1 - h) / 2) * Sign(w), Sqrt((1 + h) / 2));
}
q = Normalize(q * r);
}
massFrame = q;
return Vec3(d.cols[0].x, d.cols[1].y, d.cols[2].z);
}
void inertiaToUrdf(const Matrix33& inertia, UrdfInertia& urdfInertia)
{
urdfInertia.ixx = inertia.cols[0].x;
urdfInertia.ixy = inertia.cols[0].y;
urdfInertia.ixz = inertia.cols[0].z;
urdfInertia.iyy = inertia.cols[1].y;
urdfInertia.iyz = inertia.cols[1].z;
urdfInertia.izz = inertia.cols[2].z;
}
void urdfToInertia(const UrdfInertia& urdfInertia, Matrix33& inertia)
{
inertia.cols[0].x = urdfInertia.ixx;
inertia.cols[0].y = urdfInertia.ixy;
inertia.cols[0].z = urdfInertia.ixz;
inertia.cols[1].x = urdfInertia.ixy;
inertia.cols[1].y = urdfInertia.iyy;
inertia.cols[1].z = urdfInertia.iyz;
inertia.cols[2].x = urdfInertia.ixz;
inertia.cols[2].y = urdfInertia.iyz;
inertia.cols[2].z = urdfInertia.izz;
}
void mergeFixedChildLinks(const KinematicChain::Node& parentNode, UrdfRobot& robot)
{
// Child contribution to inertia
for (auto& childNode : parentNode.childNodes_)
{
// Depth first
mergeFixedChildLinks(*childNode, robot);
if (robot.joints.at(childNode->parentJointName_).type == UrdfJointType::FIXED &&
!robot.joints.at(childNode->parentJointName_).dontCollapse)
{
auto& urdfParentLink = robot.links.at(parentNode.linkName_);
auto& urdfChildLink = robot.links.at(childNode->linkName_);
// The pose of the child with respect to the parent is defined at the joint connecting them
Transform poseChildToParent = robot.joints.at(childNode->parentJointName_).origin;
//Add a reference to the merged link
urdfParentLink.mergedChildren[childNode->linkName_] = poseChildToParent;
// At least one of the link masses has to be defined
if ((urdfParentLink.inertial.hasMass || urdfChildLink.inertial.hasMass) &&
(urdfParentLink.inertial.mass > 0.0f || urdfChildLink.inertial.mass > 0.0f))
{
// Move inertial parameters to parent
Transform parentInertialInParentFrame = urdfParentLink.inertial.origin;
Transform childInertialInParentFrame = poseChildToParent * urdfChildLink.inertial.origin;
float totMass = urdfParentLink.inertial.mass + urdfChildLink.inertial.mass;
Vec3 com = (urdfParentLink.inertial.mass * parentInertialInParentFrame.p +
urdfChildLink.inertial.mass * childInertialInParentFrame.p) /
totMass;
Vec3 deltaParent = parentInertialInParentFrame.p - com;
Vec3 deltaChild = childInertialInParentFrame.p - com;
Matrix33 rotParentOrigin(parentInertialInParentFrame.q);
Matrix33 rotChildOrigin(childInertialInParentFrame.q);
Matrix33 parentInertia;
Matrix33 childInertia;
urdfToInertia(urdfParentLink.inertial.inertia, parentInertia);
urdfToInertia(urdfChildLink.inertial.inertia, childInertia);
Matrix33 inertiaParent = rotParentOrigin * parentInertia * Transpose(rotParentOrigin) +
urdfParentLink.inertial.mass * (LengthSq(deltaParent) * Matrix33::Identity() -
Outer(deltaParent, deltaParent));
Matrix33 inertiaChild = rotChildOrigin * childInertia * Transpose(rotChildOrigin) +
urdfChildLink.inertial.mass * (LengthSq(deltaChild) * Matrix33::Identity() -
Outer(deltaChild, deltaChild));
Matrix33 inertia = Transpose(rotParentOrigin) * (inertiaParent + inertiaChild) * rotParentOrigin;
urdfParentLink.inertial.origin.p.x = com.x;
urdfParentLink.inertial.origin.p.y = com.y;
urdfParentLink.inertial.origin.p.z = com.z;
urdfParentLink.inertial.mass = totMass;
inertiaToUrdf(inertia, urdfParentLink.inertial.inertia);
urdfParentLink.inertial.hasMass = true;
urdfParentLink.inertial.hasInertia = true;
urdfParentLink.inertial.hasOrigin = true;
}
// Move collisions to parent
for (auto& collision : urdfChildLink.collisions)
{
collision.origin = poseChildToParent * collision.origin;
urdfParentLink.collisions.push_back(collision);
}
urdfChildLink.collisions.clear();
// Move visuals to parent
for (auto& visual : urdfChildLink.visuals)
{
visual.origin = poseChildToParent * visual.origin;
urdfParentLink.visuals.push_back(visual);
}
urdfChildLink.visuals.clear();
for (auto& joint : robot.joints)
{
if (joint.second.parentLinkName == childNode->linkName_)
{
joint.second.parentLinkName = parentNode.linkName_;
joint.second.origin = poseChildToParent * joint.second.origin;
}
}
// Remove this link and parent joint
// if (!urdfChildLink.softs.size())
// {
robot.links.erase(childNode->linkName_);
robot.joints.erase(childNode->parentJointName_);
// }
}
}
}
bool collapseFixedJoints(UrdfRobot& robot)
{
KinematicChain chain;
if (!chain.computeKinematicChain(robot))
{
return false;
}
auto& parentNode = chain.baseNode;
if (!parentNode->childNodes_.empty())
{
mergeFixedChildLinks(*parentNode, robot);
}
return true;
}
Vec3 urdfAxisToVec(const UrdfAxis& axis)
{
return { axis.x, axis.y, axis.z };
}
std::string resolveXrefPath(const std::string& assetRoot, const std::string& urdfPath, const std::string& xrefpath)
{
// Remove the package prefix if it exists
std::string xrefPath = xrefpath;
if (xrefPath.find("omniverse://") != std::string::npos)
{
CARB_LOG_INFO("Path is on nucleus server, will assume that it is fully resolved already");
return xrefPath;
}
// removal of any prefix ending with "://"
std::size_t p = xrefPath.find("://");
if (p != std::string::npos)
{
xrefPath = xrefPath.substr(p + 3); // +3 to remove "://"
}
if (isAbsolutePath(xrefPath.c_str()))
{
if (testPath(xrefPath.c_str()) == PathType::eFile)
{
return xrefPath;
}
else
{
// xref not found
return std::string();
}
}
std::string rootPath;
if (isAbsolutePath(urdfPath.c_str()))
{
rootPath = urdfPath;
}
else
{
rootPath = pathJoin(assetRoot, urdfPath);
}
auto s = rootPath.find_last_of("/\\");
while (s != std::string::npos && s > 0)
{
auto basePath = rootPath.substr(0, s + 1);
auto path = pathJoin(basePath, xrefPath);
CARB_LOG_INFO("trying '%s' (%d)\n", path.c_str(), int(testPath(path.c_str())));
if (testPath(path.c_str()) == PathType::eFile)
{
return path;
}
// if (strncmp(basePath.c_str(), assetRoot.c_str(), s) == 0)
// {
// // don't search upwards of assetRoot
// break;
// }
s = rootPath.find_last_of("/\\", s - 1);
}
// hmmm, should we accept pure relative paths?
if (testPath(xrefPath.c_str()) == PathType::eFile)
{
return xrefPath;
}
// Check if ROS_PACKAGE_PATH is defined and if so go through all searching for the package
char* exists = getenv("ROS_PACKAGE_PATH");
if (exists != NULL)
{
std::string rosPackagePath = std::string(exists);
if (rosPackagePath.size())
{
std::vector<std::string> results;
boost::split(results, rosPackagePath, [](char c) { return c == ':'; });
for (size_t i = 0; i < results.size(); i++)
{
std::string path = results[i];
if (path.size() > 0)
{
auto packagePath = pathJoin(path, xrefPath);
CARB_LOG_INFO("Testing ROS Package path '%s' (%d)\n", packagePath.c_str(),
int(testPath(packagePath.c_str())));
if (testPath(packagePath.c_str()) == PathType::eFile)
{
return packagePath;
}
}
}
}
}
else
{
CARB_LOG_WARN("ROS_PACKAGE_PATH not defined, will skip checking ROS packages");
}
CARB_LOG_WARN("Path: %s not found", xrefpath.c_str());
// if we got here, we failed to resolve the path
return std::string();
}
bool IsUsdFile(const std::string& filename)
{
std::vector<std::string> types = { ".usd", ".usda" };
for (auto& t : types)
{
if (t.size() > filename.size())
continue;
if (std::equal(t.rbegin(), t.rend(), filename.rbegin()))
{
return true;
}
}
return false;
}
// Make a path name that is not already used.
std::string GetNewSdfPathString(pxr::UsdStageWeakPtr stage, std::string path, int nameClashNum)
{
bool appendedNumber = false;
int numberAppended = std::max<int>(nameClashNum, 0);
size_t indexOfNumber = 0;
if (stage->GetPrimAtPath(pxr::SdfPath(path)))
{
appendedNumber = true;
std::string name = pxr::SdfPath(path).GetName();
size_t last_ = name.find_last_of('_');
indexOfNumber = path.length() + 1;
if (last_ == std::string::npos)
{
// no '_' found, so just tack on the end.
path += "_" + std::to_string(numberAppended);
}
else
{
// There was a _, if the last part of that is a number
// then replace that number with one higher or nameClashNum,
// or just tack on the number if it is last character.
if (last_ == name.length() - 1)
{
path += "_" + std::to_string(numberAppended);
}
else
{
char* p;
std::string after_ = name.substr(last_ + 1, name.length());
long converted = strtol(after_.c_str(), &p, 10);
if (*p)
{
// not a number
path += "_" + std::to_string(numberAppended);
}
else
{
numberAppended = nameClashNum == -1 ? converted + 1 : nameClashNum;
indexOfNumber = path.length() - name.length() + last_ + 1;
path = path.substr(0, indexOfNumber);
path += std::to_string(numberAppended);
}
}
}
}
if (appendedNumber)
{
// we just added a number, so we have to make sure the new path is unique.
while (stage->GetPrimAtPath(pxr::SdfPath(path)))
{
path = path.substr(0, indexOfNumber);
numberAppended += 1;
path += std::to_string(numberAppended);
}
}
#if 0
else
{
while (stage->GetPrimAtPath(pxr::SdfPath(path))) path += ":" + std::to_string(nameClashNum);
}
#endif
return path;
}
bool addVisualMeshToCollision(UrdfRobot& robot)
{
for (auto& link : robot.links)
{
if (!link.second.visuals.empty() && link.second.collisions.empty())
{
for (auto& visual : link.second.visuals)
{
UrdfCollision collision{ visual.name, visual.origin, visual.geometry };
link.second.collisions.push_back(collision);
}
}
}
return true;
}
}
}
}
| 14,465 | C++ | 32.87822 | 119 | 0.554787 |
NVIDIA-Omniverse/urdf-importer-extension/source/extensions/omni.importer.urdf/plugins/import/MeshImporter.cpp | // SPDX-FileCopyrightText: Copyright (c) 2023 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
// SPDX-License-Identifier: Apache-2.0
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include "MeshImporter.h"
#include <carb/logging/Log.h>
#include "../core/PathUtils.h"
#include "ImportHelpers.h"
#include "assimp/Importer.hpp"
#include "assimp/postprocess.h"
#if __has_include(<filesystem>)
#include <filesystem>
#elif __has_include(<experimental/filesystem>)
#include <experimental/filesystem>
#else
error "Missing the <filesystem> header."
#endif
#include "../utils/Path.h"
#include <OmniClient.h>
#include <cmath>
#include <set>
#include <stack>
#include <unordered_set>
namespace omni
{
namespace importer
{
namespace urdf
{
using namespace omni::importer::utils::path;
const static size_t INVALID_MATERIAL_INDEX = SIZE_MAX;
struct ImportTransform
{
pxr::GfMatrix4d matrix;
pxr::GfVec3f translation;
pxr::GfVec3f eulerAngles; // XYZ order
pxr::GfVec3f scale;
};
struct MeshGeomSubset
{
pxr::VtArray<int> faceIndices;
size_t materialIndex = INVALID_MATERIAL_INDEX;
};
struct Mesh
{
std::string name;
pxr::VtArray<pxr::GfVec3f> points;
pxr::VtArray<int> faceVertexCounts;
pxr::VtArray<int> faceVertexIndices;
pxr::VtArray<pxr::GfVec3f> normals; // Face varing normals
pxr::VtArray<pxr::VtArray<pxr::GfVec2f>> uvs; // Face varing uvs
pxr::VtArray<pxr::VtArray<pxr::GfVec3f>> colors; // Face varing colors
std::vector<MeshGeomSubset> meshSubsets;
};
// static pxr::GfMatrix4d AiMatrixToGfMatrix(const aiMatrix4x4& matrix)
// {
// return pxr::GfMatrix4d(matrix.a1, matrix.b1, matrix.c1, matrix.d1, matrix.a2, matrix.b2, matrix.c2, matrix.d2,
// matrix.a3, matrix.b3, matrix.c3, matrix.d3, matrix.a4, matrix.b4, matrix.c4, matrix.d4);
// }
static pxr::GfVec3f AiVector3dToGfVector3f(const aiVector3D& vector)
{
return pxr::GfVec3f(vector.x, vector.y, vector.z);
}
static pxr::GfVec2f AiVector3dToGfVector2f(const aiVector3D& vector)
{
return pxr::GfVec2f(vector.x, vector.y);
}
// static pxr::GfVec3h AiVector3dToGfVector3h(const aiVector3D& vector)
// {
// return pxr::GfVec3h(vector.x, vector.y, vector.z);
// }
// static pxr::GfQuatf AiQuatToGfVector(const aiQuaternion& quat)
// {
// return pxr::GfQuatf(quat.w, quat.x, quat.y, quat.z);
// }
// static pxr::GfQuath AiQuatToGfVectorh(const aiQuaternion& quat)
// {
// return pxr::GfQuath(quat.w, quat.x, quat.y, quat.z);
// }
// static pxr::GfVec3f AiColor3DToGfVector3f(const aiColor3D& color)
// {
// return pxr::GfVec3f(color.r, color.g, color.b);
// }
// static ImportTransform AiMatrixToTransform(const aiMatrix4x4& matrix)
// {
// ImportTransform transform;
// transform.matrix =
// pxr::GfMatrix4d(matrix.a1, matrix.b1, matrix.c1, matrix.d1, matrix.a2, matrix.b2, matrix.c2, matrix.d2,
// matrix.a3, matrix.b3, matrix.c3, matrix.d3, matrix.a4, matrix.b4, matrix.c4, matrix.d4);
// aiVector3D translation, rotation, scale;
// matrix.Decompose(scale, rotation, translation);
// transform.translation = AiVector3dToGfVector3f(translation);
// transform.eulerAngles = AiVector3dToGfVector3f(
// aiVector3D(AI_RAD_TO_DEG(rotation.x), AI_RAD_TO_DEG(rotation.y), AI_RAD_TO_DEG(rotation.z)));
// transform.scale = AiVector3dToGfVector3f(scale);
// return transform;
// }
pxr::GfVec3f AiColor4DToGfVector3f(const aiColor4D& color)
{
return pxr::GfVec3f(color.r, color.g, color.b);
}
struct MeshMaterial
{
std::string name;
std::string texturePaths[5];
bool has_diffuse;
aiColor3D diffuse;
bool has_emissive;
aiColor3D emissive;
bool has_metallic;
float metallic{ 0 };
bool has_specular;
float specular{ 0 };
aiTextureType textures[5] = { aiTextureType_DIFFUSE, aiTextureType_HEIGHT, aiTextureType_REFLECTION,
aiTextureType_EMISSIVE, aiTextureType_SHININESS };
const char* props[5] = {
"diffuse_texture", "normalmap_texture", "metallic_texture",
"emissive_mask_texture", "reflectionroughness_texture",
};
MeshMaterial(aiMaterial* m)
{
name = std::string(m->GetName().C_Str());
std::array<aiTextureMapMode, 2> modes;
aiString path;
for (int i = 0; i < 5; i++)
{
if (m->GetTexture(textures[i], 0, &path, nullptr, nullptr, nullptr, nullptr, modes.data()) == aiReturn_SUCCESS)
{
texturePaths[i] = std::string(path.C_Str());
}
}
has_diffuse = (m->Get(AI_MATKEY_COLOR_DIFFUSE, diffuse) == aiReturn_SUCCESS);
has_metallic = (m->Get(AI_MATKEY_METALLIC_FACTOR, metallic) == aiReturn_SUCCESS);
has_specular = (m->Get(AI_MATKEY_SPECULAR_FACTOR, specular) == aiReturn_SUCCESS);
has_emissive = (m->Get(AI_MATKEY_COLOR_EMISSIVE, emissive) == aiReturn_SUCCESS);
}
std::string get_hash()
{
std::ostringstream ss;
ss << name;
for (int i = 0; i < 5; i++)
{
if (texturePaths[i] != "")
{
ss << std::string(props[i]) + texturePaths[i];
}
}
ss << std::string("D") << diffuse.r << diffuse.g << diffuse.b;
ss << std::string("M") << metallic;
ss << std::string("S") << specular;
ss << std::string("E") << emissive.r << emissive.g << emissive.g;
return ss.str();
}
};
std::string ReplaceBackwardSlash(std::string in)
{
for (auto& c : in)
{
if (c == '\\')
{
c = '/';
}
}
return in;
}
static aiMatrix4x4 GetLocalTransform(const aiNode* node)
{
aiMatrix4x4 transform = node->mTransformation;
auto parent = node->mParent;
while (parent)
{
std::string name = parent->mName.data;
// only take scale from root transform, if the parent has a parent then its not a root node
if (parent->mParent)
{
// parent has a parent, not a root note, use full transform
transform = parent->mTransformation * transform;
parent = parent->mParent;
}
else
{
// this is a root node, only take scale
aiVector3D pos, scale;
aiQuaternion rot;
parent->mTransformation.Decompose(scale, rot, pos);
aiMatrix4x4 scale_mat;
transform = aiMatrix4x4::Scaling(scale, scale_mat) * transform;
break;
}
}
return transform;
}
std::string copyTexture(std::string usdStageIdentifier, std::string texturePath)
{
// switch any windows-style path into linux backwards slash (omniclient handles windows paths)
usdStageIdentifier = ReplaceBackwardSlash(usdStageIdentifier);
texturePath = ReplaceBackwardSlash(texturePath);
// Assumes the folder structure has already been created.
int path_idx = (int)usdStageIdentifier.rfind('/');
std::string parent_folder = usdStageIdentifier.substr(0, path_idx);
int basename_idx = (int)texturePath.rfind('/');
std::string textureName = texturePath.substr(basename_idx + 1);
std::string out = (parent_folder + "/materials/" + textureName);
omniClientWait(omniClientCopy(texturePath.c_str(), out.c_str(), {}, {}));
return out;
}
pxr::SdfPath SimpleImport(pxr::UsdStageRefPtr usdStage,
std::string path,
const aiScene* mScene,
const std::string meshPath,
std::map<pxr::TfToken, std::string>& materialsList,
const bool loadMaterials,
const bool flipVisuals,
const char* subdivisionScheme,
const bool instanceable)
{
std::vector<Mesh> mMeshPrims;
std::vector<aiNode*> nodesToProcess;
std::vector<std::pair<int, aiMatrix4x4>> meshTransforms;
// Traverse tree and get all of the meshes and the full transform for that node
nodesToProcess.push_back(mScene->mRootNode);
std::string mesh_path = ReplaceBackwardSlash(meshPath);
int basename_idx = (int)mesh_path.rfind('/');
std::string base_path = mesh_path.substr(0, basename_idx);
while (nodesToProcess.size() > 0)
{
// remove the node
aiNode* node = nodesToProcess.back();
if (!node)
{
// printf("INVALID NODE\n");
continue;
}
nodesToProcess.pop_back();
aiMatrix4x4 transform = GetLocalTransform(node);
for (size_t i = 0; i < node->mNumMeshes; i++)
{
// if (flipVisuals)
// {
// aiMatrix4x4 flip;
// flip[0][0] = 1.0;
// flip[2][1] = 1.0;
// flip[1][2] = -1.0;
// flip[3][3] = 1.0f;
// transform = transform * flip;
// }
meshTransforms.push_back(std::pair<int, aiMatrix4x4>(node->mMeshes[i], transform));
}
// process any meshes in this node:
for (size_t i = 0; i < node->mNumChildren; i++)
{
nodesToProcess.push_back(node->mChildren[i]);
}
}
// printf("%s TOTAL MESHES: %d\n", path.c_str(), meshTransforms.size());
mMeshPrims.resize(meshTransforms.size());
// for (size_t i = 0; i < mScene->mNumMaterials; i++)
// {
// auto material = mScene->mMaterials[i];
// // printf("AA %d %s \n", i, material->GetName().C_Str());
// }
for (size_t i = 0; i < meshTransforms.size(); i++)
{
auto transformedMesh = meshTransforms[i];
auto assimpMesh = mScene->mMeshes[transformedMesh.first];
// printf("material index: %d \n", assimpMesh->mMaterialIndex);
// Gather all mesh points information to sort
std::vector<Mesh> meshImported;
for (size_t j = 0; j < assimpMesh->mNumVertices; j++)
{
auto vertex = assimpMesh->mVertices[j];
vertex *= transformedMesh.second;
mMeshPrims[i].points.push_back(AiVector3dToGfVector3f(vertex));
}
for (size_t j = 0; j < assimpMesh->mNumFaces; j++)
{
const aiFace& face = assimpMesh->mFaces[j];
if (face.mNumIndices >= 3)
{
for (size_t k = 0; k < face.mNumIndices; k++)
{
mMeshPrims[i].faceVertexIndices.push_back(face.mIndices[k]);
}
}
}
mMeshPrims[i].uvs.resize(assimpMesh->GetNumUVChannels());
mMeshPrims[i].colors.resize(assimpMesh->GetNumColorChannels());
for (size_t j = 0; j < assimpMesh->mNumFaces; j++)
{
const aiFace& face = assimpMesh->mFaces[j];
if (face.mNumIndices >= 3)
{
for (size_t k = 0; k < face.mNumIndices; k++)
{
if (assimpMesh->mNormals)
{
mMeshPrims[i].normals.push_back(AiVector3dToGfVector3f(assimpMesh->mNormals[face.mIndices[k]]));
}
for (size_t m = 0; m < mMeshPrims[i].uvs.size(); m++)
{
mMeshPrims[i].uvs[m].push_back(
AiVector3dToGfVector2f(assimpMesh->mTextureCoords[m][face.mIndices[k]]));
}
for (size_t m = 0; m < mMeshPrims[i].colors.size(); m++)
{
mMeshPrims[i].colors[m].push_back(AiColor4DToGfVector3f(assimpMesh->mColors[m][face.mIndices[k]]));
}
}
mMeshPrims[i].faceVertexCounts.push_back(face.mNumIndices);
}
}
}
auto usdMesh =
pxr::UsdGeomMesh::Define(usdStage, pxr::SdfPath(omni::importer::urdf::GetNewSdfPathString(usdStage, path)));
pxr::VtArray<pxr::GfVec3f> allPoints;
pxr::VtArray<int> allFaceVertexCounts;
pxr::VtArray<int> allFaceVertexIndices;
pxr::VtArray<pxr::GfVec3f> allNormals;
pxr::VtArray<pxr::VtArray<pxr::GfVec2f>> uvs;
pxr::VtArray<pxr::VtArray<pxr::GfVec3f>> allColors;
size_t indexOffset = 0;
size_t vertexOffset = 0;
std::map<int, pxr::VtArray<int>> materialMap;
for (size_t m = 0; m < meshTransforms.size(); m++)
{
auto transformedMesh = meshTransforms[m];
auto mesh = mScene->mMeshes[transformedMesh.first];
auto& meshPrim = mMeshPrims[m];
for (size_t k = 0; k < meshPrim.uvs.size(); k++)
{
uvs.push_back(meshPrim.uvs[k]);
}
for (size_t i = 0; i < meshPrim.points.size(); i++)
{
allPoints.push_back(meshPrim.points[i]);
}
for (size_t i = 0; i < meshPrim.faceVertexCounts.size(); i++)
{
allFaceVertexCounts.push_back(meshPrim.faceVertexCounts[i]);
}
for (size_t i = 0; i < meshPrim.faceVertexIndices.size(); i++)
{
allFaceVertexIndices.push_back(static_cast<int>(meshPrim.faceVertexIndices[i] + indexOffset));
}
for (size_t i = vertexOffset; i < vertexOffset + meshPrim.faceVertexCounts.size(); i++)
{
materialMap[mesh->mMaterialIndex].push_back(static_cast<int>(i));
}
// printf("faceVertexOffset %d %d %d %d\n", indexOffset, points.size(), vertexOffset, faceVertexCounts.size());
indexOffset = indexOffset + meshPrim.points.size();
vertexOffset = vertexOffset + meshPrim.faceVertexCounts.size();
for (size_t i = 0; i < meshPrim.normals.size(); i++)
{
allNormals.push_back(meshPrim.normals[i]);
}
}
usdMesh.CreatePointsAttr(pxr::VtValue(allPoints));
usdMesh.CreateFaceVertexCountsAttr(pxr::VtValue(allFaceVertexCounts));
usdMesh.CreateFaceVertexIndicesAttr(pxr::VtValue(allFaceVertexIndices));
pxr::VtArray<pxr::GfVec3f> Extent;
pxr::UsdGeomPointBased::ComputeExtent(allPoints, &Extent);
usdMesh.CreateExtentAttr().Set(Extent);
// Normals
if (!allNormals.empty())
{
usdMesh.CreateNormalsAttr(pxr::VtValue(allNormals));
usdMesh.SetNormalsInterpolation(pxr::UsdGeomTokens->faceVarying);
}
// Texture UV
for (size_t j = 0; j < uvs.size(); j++)
{
pxr::TfToken stName;
if (j == 0)
{
stName = pxr::TfToken("st");
}
else
{
stName = pxr::TfToken("st_" + std::to_string(j));
}
pxr::UsdGeomPrimvarsAPI primvarsAPI(usdMesh);
pxr::UsdGeomPrimvar Primvar =
primvarsAPI.CreatePrimvar(stName, pxr::SdfValueTypeNames->TexCoord2fArray, pxr::UsdGeomTokens->faceVarying);
Primvar.Set(uvs[j]);
}
usdMesh.CreateSubdivisionSchemeAttr(pxr::VtValue(pxr::TfToken(subdivisionScheme)));
if (loadMaterials)
{
std::string prefix_path;
if (instanceable)
{
prefix_path = pxr::SdfPath(path).GetParentPath().GetString(); // body category root
}
else
{
prefix_path = pxr::SdfPath(path).GetParentPath().GetParentPath().GetString(); // Robot root
}
// For each material, store the face indices and create GeomSubsets
usdStage->DefinePrim(pxr::SdfPath(prefix_path + "/Looks"), pxr::TfToken("Scope"));
for (auto const& mat : materialMap)
{
MeshMaterial material(mScene->mMaterials[mat.first]);
// printf("materials: %s\n", name.c_str());
pxr::TfToken mat_token(material.get_hash());
// if (std::find(materialsList.begin(), materialsList.end(),mat_token) == materialsList.end())
if (materialsList.find(mat_token) == materialsList.end())
{
pxr::UsdPrim prim;
pxr::UsdShadeMaterial matPrim;
std::string mat_path(prefix_path + "/Looks/" + makeValidUSDIdentifier("material_" + material.name));
prim = usdStage->GetPrimAtPath(pxr::SdfPath(mat_path));
int counter = 0;
while (prim)
{
mat_path = std::string(
prefix_path + "/Looks/" +
makeValidUSDIdentifier("material_" + material.name + "_" + std::to_string(++counter)));
printf("%s \n", mat_path.c_str());
prim = usdStage->GetPrimAtPath(pxr::SdfPath(mat_path));
}
materialsList[mat_token] = mat_path;
matPrim = pxr::UsdShadeMaterial::Define(usdStage, pxr::SdfPath(mat_path));
pxr::UsdShadeShader pbrShader = pxr::UsdShadeShader::Define(usdStage, pxr::SdfPath(mat_path + "/Shader"));
pbrShader.CreateIdAttr(pxr::VtValue(pxr::UsdImagingTokens->UsdPreviewSurface));
auto shader_out = pbrShader.CreateOutput(pxr::TfToken("out"), pxr::SdfValueTypeNames->Token);
matPrim.CreateSurfaceOutput(pxr::TfToken("mdl")).ConnectToSource(shader_out);
matPrim.CreateVolumeOutput(pxr::TfToken("mdl")).ConnectToSource(shader_out);
matPrim.CreateDisplacementOutput(pxr::TfToken("mdl")).ConnectToSource(shader_out);
pbrShader.GetImplementationSourceAttr().Set(pxr::UsdShadeTokens->sourceAsset);
pbrShader.SetSourceAsset(pxr::SdfAssetPath("OmniPBR.mdl"), pxr::TfToken("mdl"));
pbrShader.SetSourceAssetSubIdentifier(pxr::TfToken("OmniPBR"), pxr::TfToken("mdl"));
bool has_emissive_map = false;
for (int i = 0; i < 5; i++)
{
if (material.texturePaths[i] != "")
{
if (!usdStage->GetRootLayer()->IsAnonymous())
{
auto texture_path = copyTexture(usdStage->GetRootLayer()->GetIdentifier(),
resolve_absolute(base_path, material.texturePaths[i]));
int basename_idx = (int)texture_path.rfind('/');
std::string filename = texture_path.substr(basename_idx + 1);
std::string texture_relative_path = "materials/" + filename;
pbrShader.CreateInput(pxr::TfToken(material.props[i]), pxr::SdfValueTypeNames->Asset)
.Set(pxr::SdfAssetPath(texture_relative_path));
if (material.textures[i] == aiTextureType_EMISSIVE)
{
pbrShader.CreateInput(pxr::TfToken("emissive_color"), pxr::SdfValueTypeNames->Color3f)
.Set(pxr::GfVec3f(1.0f, 1.0f, 1.0f));
pbrShader.CreateInput(pxr::TfToken("enable_emission"), pxr::SdfValueTypeNames->Bool)
.Set(true);
pbrShader.CreateInput(pxr::TfToken("emissive_intensity"), pxr::SdfValueTypeNames->Float)
.Set(10000.0f);
has_emissive_map = true;
}
}
else
{
CARB_LOG_WARN(
"Material %s has an image texture, but it won't be imported since the asset is being loaded on memory. Please import it into a destination folder to get all textures.",
material.name.c_str());
}
}
}
if (material.has_diffuse)
{
pbrShader.CreateInput(pxr::TfToken("diffuse_color_constant"), pxr::SdfValueTypeNames->Color3f)
.Set(pxr::GfVec3f(material.diffuse.r, material.diffuse.g, material.diffuse.b));
}
if (material.has_metallic)
{
pbrShader.CreateInput(pxr::TfToken("metallic_constant"), pxr::SdfValueTypeNames->Float)
.Set(material.metallic);
}
if (material.has_specular)
{
pbrShader.CreateInput(pxr::TfToken("specular_level"), pxr::SdfValueTypeNames->Float)
.Set(material.specular);
}
if (!has_emissive_map && material.has_emissive)
{
pbrShader.CreateInput(pxr::TfToken("emissive_color"), pxr::SdfValueTypeNames->Color3f)
.Set(pxr::GfVec3f(material.emissive.r, material.emissive.g, material.emissive.b));
}
// auto output = matPrim.CreateSurfaceOutput();
// output.ConnectToSource(pbrShader, pxr::TfToken("surface"));
}
pxr::UsdShadeMaterial matPrim =
pxr::UsdShadeMaterial(usdStage->GetPrimAtPath(pxr::SdfPath(materialsList[mat_token])));
if (materialMap.size() > 1)
{
auto geomSubset = pxr::UsdGeomSubset::Define(
usdStage, pxr::SdfPath(usdMesh.GetPath().GetString() + "/material_" + std::to_string(mat.first)));
geomSubset.CreateElementTypeAttr(pxr::VtValue(pxr::TfToken("face")));
geomSubset.CreateFamilyNameAttr(pxr::VtValue(pxr::TfToken("materialBind")));
geomSubset.CreateIndicesAttr(pxr::VtValue(mat.second));
if (matPrim)
{
pxr::UsdShadeMaterialBindingAPI mbi(geomSubset);
mbi.Bind(matPrim);
}
}
else
{
if (matPrim)
{
pxr::UsdShadeMaterialBindingAPI mbi(usdMesh);
mbi.Bind(matPrim);
}
}
}
}
return usdMesh.GetPath();
}
}
}
}
| 22,606 | C++ | 36.804348 | 200 | 0.566841 |
NVIDIA-Omniverse/urdf-importer-extension/source/extensions/omni.importer.urdf/plugins/import/UrdfImporter.cpp | // SPDX-FileCopyrightText: Copyright (c) 2023 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
// SPDX-License-Identifier: Apache-2.0
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include "UrdfImporter.h"
#include "../core/PathUtils.h"
#include "UrdfImporter.h"
// #include "../../GymJoint.h"
// #include "../../helpers.h"
#include "assimp/Importer.hpp"
#include "assimp/cfileio.h"
#include "assimp/cimport.h"
#include "assimp/postprocess.h"
#include "assimp/scene.h"
#include "ImportHelpers.h"
#include <carb/logging/Log.h>
#include <physicsSchemaTools/UsdTools.h>
#include <physxSchema/jointStateAPI.h>
#include <physxSchema/physxArticulationAPI.h>
#include <physxSchema/physxCollisionAPI.h>
#include <physxSchema/physxJointAPI.h>
#include <physxSchema/physxTendonAxisRootAPI.h>
#include <physxSchema/physxTendonAxisAPI.h>
#include <physxSchema/physxSceneAPI.h>
#include <pxr/usd/usdPhysics/articulationRootAPI.h>
#include <pxr/usd/usdPhysics/collisionAPI.h>
#include <pxr/usd/usdPhysics/driveAPI.h>
#include <pxr/usd/usdPhysics/fixedJoint.h>
#include <pxr/usd/usdPhysics/joint.h>
#include <pxr/usd/usdPhysics/limitAPI.h>
#include <pxr/usd/usdPhysics/massAPI.h>
#include <pxr/usd/usdPhysics/meshCollisionAPI.h>
#include <pxr/usd/usdPhysics/prismaticJoint.h>
#include <pxr/usd/usdPhysics/revoluteJoint.h>
#include <pxr/usd/usdPhysics/rigidBodyAPI.h>
#include <pxr/usd/usdPhysics/scene.h>
#include <pxr/usd/usdPhysics/sphericalJoint.h>
namespace omni
{
namespace importer
{
namespace urdf
{
UrdfRobot UrdfImporter::createAsset()
{
UrdfRobot robot;
if (!parseUrdf(assetRoot_, urdfPath_, robot))
{
CARB_LOG_ERROR("Failed to parse URDF file '%s'", urdfPath_.c_str());
return robot;
}
if (config.mergeFixedJoints)
{
collapseFixedJoints(robot);
}
if (config.collisionFromVisuals)
{
addVisualMeshToCollision(robot);
}
return robot;
}
const char* subdivisionschemes[4] = { "catmullClark", "loop", "bilinear", "none" };
pxr::UsdPrim addMesh(pxr::UsdStageWeakPtr stage,
UrdfGeometry geometry,
std::string assetRoot,
std::string urdfPath,
std::string name,
Transform origin,
const bool loadMaterials,
const double distanceScale,
const bool flipVisuals,
std::map<pxr::TfToken, std::string>& materialsList,
const char* subdivisionScheme,
const bool instanceable = false,
const bool replaceCylindersWithCapsules = false)
{
pxr::SdfPath path;
if (geometry.type == UrdfGeometryType::MESH)
{
std::string meshUri = geometry.meshFilePath;
std::string meshPath = resolveXrefPath(assetRoot, urdfPath, meshUri);
// pxr::GfMatrix4d meshMat;
if (meshPath.empty())
{
CARB_LOG_WARN("Failed to resolve mesh '%s'", meshUri.c_str());
return pxr::UsdPrim(); // move to next shape
}
// mesh is a usd file, add as a reference directly to a new xform
else if (IsUsdFile(meshPath))
{
CARB_LOG_INFO("Adding Usd reference '%s'", meshPath.c_str());
path = pxr::SdfPath(omni::importer::urdf::GetNewSdfPathString(stage, name));
pxr::UsdGeomXform usdXform = pxr::UsdGeomXform::Define(stage, path);
usdXform.GetPrim().GetReferences().AddReference(meshPath);
}
else
{
CARB_LOG_INFO("Found Mesh At: %s", meshPath.c_str());
auto assimpScene =
aiImportFile(meshPath.c_str(), aiProcess_GenSmoothNormals | aiProcess_OptimizeMeshes |
aiProcess_RemoveRedundantMaterials | aiProcess_GlobalScale);
static auto sceneDeleter = [](const aiScene* scene)
{
if (scene)
{
aiReleaseImport(scene);
}
};
auto sceneRAII = std::shared_ptr<const aiScene>(assimpScene, sceneDeleter);
// Add visuals
if (!sceneRAII || !sceneRAII->mRootNode)
{
CARB_LOG_WARN("Asset convert failed as asset file is broken.");
}
else if (sceneRAII->mRootNode->mNumChildren == 0)
{
CARB_LOG_WARN("Asset convert failed as asset cannot be loaded.");
}
else
{
path = SimpleImport(stage, name, sceneRAII.get(), meshPath, materialsList, loadMaterials, flipVisuals,
subdivisionScheme, instanceable);
}
}
}
else if (geometry.type == UrdfGeometryType::SPHERE)
{
pxr::UsdGeomSphere gprim = pxr::UsdGeomSphere::Define(stage, pxr::SdfPath(name));
pxr::VtVec3fArray extentArray(2);
gprim.ComputeExtent(geometry.radius, &extentArray);
gprim.GetExtentAttr().Set(extentArray);
gprim.GetRadiusAttr().Set(double(geometry.radius));
path = pxr::SdfPath(name);
}
else if (geometry.type == UrdfGeometryType::BOX)
{
pxr::UsdGeomCube gprim = pxr::UsdGeomCube::Define(stage, pxr::SdfPath(name));
pxr::VtVec3fArray extentArray(2);
extentArray[1] = pxr::GfVec3f(geometry.size_x * 0.5f, geometry.size_y * 0.5f, geometry.size_z * 0.5f);
extentArray[0] = -extentArray[1];
gprim.GetExtentAttr().Set(extentArray);
gprim.GetSizeAttr().Set(1.0);
path = pxr::SdfPath(name);
}
else if (geometry.type == UrdfGeometryType::CYLINDER && !replaceCylindersWithCapsules)
{
pxr::UsdGeomCylinder gprim = pxr::UsdGeomCylinder::Define(stage, pxr::SdfPath(name));
pxr::VtVec3fArray extentArray(2);
gprim.ComputeExtent(geometry.length, geometry.radius, pxr::UsdGeomTokens->x, &extentArray);
gprim.GetAxisAttr().Set(pxr::UsdGeomTokens->z);
gprim.GetExtentAttr().Set(extentArray);
gprim.GetHeightAttr().Set(double(geometry.length));
gprim.GetRadiusAttr().Set(double(geometry.radius));
path = pxr::SdfPath(name);
}
else if (geometry.type == UrdfGeometryType::CAPSULE || (geometry.type == UrdfGeometryType::CYLINDER && replaceCylindersWithCapsules))
{
pxr::UsdGeomCapsule gprim = pxr::UsdGeomCapsule::Define(stage, pxr::SdfPath(name));
pxr::VtVec3fArray extentArray(2);
gprim.ComputeExtent(geometry.length, geometry.radius, pxr::UsdGeomTokens->x, &extentArray);
gprim.GetAxisAttr().Set(pxr::UsdGeomTokens->z);
gprim.GetExtentAttr().Set(extentArray);
gprim.GetHeightAttr().Set(double(geometry.length));
gprim.GetRadiusAttr().Set(double(geometry.radius));
path = pxr::SdfPath(name);
}
pxr::UsdPrim prim = stage->GetPrimAtPath(path);
if (prim)
{
Transform transform = origin;
pxr::GfVec3d scale;
if (geometry.type == UrdfGeometryType::MESH)
{
scale = pxr::GfVec3d(geometry.scale_x, geometry.scale_y, geometry.scale_z);
}
else if (geometry.type == UrdfGeometryType::BOX)
{
scale = pxr::GfVec3d(geometry.size_x, geometry.size_y, geometry.size_z);
}
else
{
scale = pxr::GfVec3d(1, 1, 1);
}
pxr::UsdGeomXformable gprim = pxr::UsdGeomXformable(prim);
gprim.ClearXformOpOrder();
gprim.AddTranslateOp(pxr::UsdGeomXformOp::PrecisionDouble)
.Set(distanceScale * pxr::GfVec3d(transform.p.x, transform.p.y, transform.p.z));
gprim.AddOrientOp(pxr::UsdGeomXformOp::PrecisionDouble)
.Set(pxr::GfQuatd(transform.q.w, transform.q.x, transform.q.y, transform.q.z));
gprim.AddScaleOp(pxr::UsdGeomXformOp::PrecisionDouble).Set(distanceScale * scale);
}
return prim;
}
void UrdfImporter::buildInstanceableStage(pxr::UsdStageRefPtr stage,
const KinematicChain::Node* parentNode,
const std::string& robotBasePath,
const UrdfRobot& urdfRobot)
{
if (parentNode->parentJointName_ == "")
{
const UrdfLink& urdfLink = urdfRobot.links.at(parentNode->linkName_);
addInstanceableMeshes(stage, urdfLink, robotBasePath, urdfRobot);
}
if (!parentNode->childNodes_.empty())
{
for (const auto& childNode : parentNode->childNodes_)
{
if (urdfRobot.joints.find(childNode->parentJointName_) != urdfRobot.joints.end())
{
if (urdfRobot.links.find(childNode->linkName_) != urdfRobot.links.end())
{
const UrdfLink& childLink = urdfRobot.links.at(childNode->linkName_);
addInstanceableMeshes(stage, childLink, robotBasePath, urdfRobot);
// Recurse through the links children
buildInstanceableStage(stage, childNode.get(), robotBasePath, urdfRobot);
}
}
}
}
}
void UrdfImporter::addInstanceableMeshes(pxr::UsdStageRefPtr stage,
const UrdfLink& link,
const std::string& robotBasePath,
const UrdfRobot& robot)
{
std::map<std::string, std::string> linkMatPrimPaths;
std::map<pxr::TfToken, std::string> linkMaterialList;
// Add visuals
for (size_t i = 0; i < link.visuals.size(); i++)
{
std::string meshName;
std::string name = "mesh_" + std::to_string(i);
if (link.visuals[i].name.size() > 0)
{
name = link.visuals[i].name;
}
meshName = robotBasePath + link.name + "/visuals/" + name;
bool loadMaterial = true;
auto mat = link.visuals[i].material;
auto urdfMatIter = robot.materials.find(link.visuals[i].material.name);
if (urdfMatIter != robot.materials.end())
{
mat = urdfMatIter->second;
}
auto& color = mat.color;
if (color.r >= 0 && color.g >= 0 && color.b >= 0)
{
loadMaterial = false;
}
pxr::UsdPrim prim = addMesh(stage, link.visuals[i].geometry, assetRoot_, urdfPath_, meshName,
link.visuals[i].origin, loadMaterial, config.distanceScale, false, linkMaterialList,
subdivisionschemes[(int)config.subdivisionScheme], true);
if (prim)
{
if (loadMaterial == false)
{
// This Material was already created for this link, reuse
auto urdfMatIter = linkMatPrimPaths.find(link.visuals[i].material.name);
if (urdfMatIter != linkMatPrimPaths.end())
{
std::string path = linkMatPrimPaths[link.visuals[i].material.name];
auto matPrim = stage->GetPrimAtPath(pxr::SdfPath(path));
if (matPrim)
{
auto shadePrim = pxr::UsdShadeMaterial(matPrim);
if (shadePrim)
{
pxr::UsdShadeMaterialBindingAPI mbi(prim);
mbi.Bind(shadePrim);
}
}
}
else
{
auto& color = link.visuals[i].material.color;
std::stringstream ss;
ss << std::uppercase << std::hex << (int)(256 * color.r) << std::uppercase << std::hex
<< (int)(256 * color.g) << std::uppercase << std::hex << (int)(256 * color.b);
std::pair<std::string, UrdfMaterial> mat_pair(ss.str(), link.visuals[i].material);
pxr::UsdShadeMaterial matPrim = addMaterial(stage, mat_pair, prim.GetPath().GetParentPath());
std::string matName = link.visuals[i].material.name;
std::string matPrimName = matName == "" ? mat_pair.first : matName;
linkMatPrimPaths[matName] =
prim.GetPath()
.GetParentPath()
.AppendPath(pxr::SdfPath("Looks/" + makeValidUSDIdentifier("material_" + name)))
.GetString();
if (matPrim)
{
pxr::UsdShadeMaterialBindingAPI mbi(prim);
mbi.Bind(matPrim);
}
}
}
}
else
{
CARB_LOG_WARN("Prim %s not created", meshName.c_str());
}
}
// Add collisions
CARB_LOG_INFO("Add collisions: %s", link.name.c_str());
for (size_t i = 0; i < link.collisions.size(); i++)
{
std::string meshName;
std::string name = "mesh_" + std::to_string(i);
if (link.collisions[i].name.size() > 0)
{
name = link.collisions[i].name;
}
meshName = robotBasePath + link.name + "/collisions/" + name;
pxr::UsdPrim prim = addMesh(stage, link.collisions[i].geometry, assetRoot_, urdfPath_, meshName,
link.collisions[i].origin, false, config.distanceScale, false, materialsList,
subdivisionschemes[(int)config.subdivisionScheme], false, config.replaceCylindersWithCapsules);
// Enable collisions on prim
if (prim)
{
pxr::UsdPhysicsCollisionAPI::Apply(prim);
if (link.collisions[i].geometry.type == UrdfGeometryType::SPHERE)
{
pxr::UsdPhysicsCollisionAPI::Apply(prim);
}
else if (link.collisions[i].geometry.type == UrdfGeometryType::BOX)
{
pxr::UsdPhysicsCollisionAPI::Apply(prim);
}
else if (link.collisions[i].geometry.type == UrdfGeometryType::CYLINDER)
{
pxr::UsdPhysicsCollisionAPI::Apply(prim);
}
else if (link.collisions[i].geometry.type == UrdfGeometryType::CAPSULE)
{
pxr::UsdPhysicsCollisionAPI::Apply(prim);
}
else
{
pxr::UsdPhysicsMeshCollisionAPI physicsMeshAPI = pxr::UsdPhysicsMeshCollisionAPI::Apply(prim);
if (config.convexDecomp == true)
{
physicsMeshAPI.CreateApproximationAttr().Set(pxr::UsdPhysicsTokens.Get()->convexDecomposition);
}
else
{
physicsMeshAPI.CreateApproximationAttr().Set(pxr::UsdPhysicsTokens.Get()->convexHull);
}
}
pxr::UsdGeomMesh(prim).CreatePurposeAttr().Set(pxr::UsdGeomTokens->guide);
}
else
{
CARB_LOG_WARN("Prim %s not created", meshName.c_str());
}
}
}
void UrdfImporter::addRigidBody(pxr::UsdStageWeakPtr stage,
const UrdfLink& link,
const Transform& poseBodyToWorld,
pxr::UsdGeomXform robotPrim,
const UrdfRobot& robot)
{
std::string robotBasePath = robotPrim.GetPath().GetString() + "/";
CARB_LOG_INFO("Add Rigid Body: %s", link.name.c_str());
// Create Link Prim
auto linkPrim = pxr::UsdGeomXform::Define(stage, pxr::SdfPath(robotBasePath + link.name));
if (linkPrim)
{
Transform transform = poseBodyToWorld; // urdfOriginToTransform(link.inertial.origin);
linkPrim.ClearXformOpOrder();
linkPrim.AddTranslateOp(pxr::UsdGeomXformOp::PrecisionDouble)
.Set(config.distanceScale * pxr::GfVec3d(transform.p.x, transform.p.y, transform.p.z));
linkPrim.AddOrientOp(pxr::UsdGeomXformOp::PrecisionDouble)
.Set(pxr::GfQuatd(transform.q.w, transform.q.x, transform.q.y, transform.q.z));
linkPrim.AddScaleOp(pxr::UsdGeomXformOp::PrecisionDouble).Set(pxr::GfVec3d(1, 1, 1));
for (const auto& pair : link.mergedChildren) {
auto childXform = pxr::UsdGeomXform::Define(stage, linkPrim.GetPath().AppendPath(pxr::SdfPath(pair.first)));
if (childXform)
{
childXform.ClearXformOpOrder();
childXform.AddTranslateOp(pxr::UsdGeomXformOp::PrecisionDouble)
.Set(config.distanceScale * pxr::GfVec3d(pair.second.p.x, pair.second.p.y, pair.second.p.z));
childXform.AddOrientOp(pxr::UsdGeomXformOp::PrecisionDouble)
.Set(pxr::GfQuatd(pair.second.q.w, pair.second.q.x, pair.second.q.y, pair.second.q.z));
childXform.AddScaleOp(pxr::UsdGeomXformOp::PrecisionDouble).Set(pxr::GfVec3d(1, 1, 1));
}
}
pxr::UsdPhysicsRigidBodyAPI physicsAPI = pxr::UsdPhysicsRigidBodyAPI::Apply(linkPrim.GetPrim());
pxr::UsdPhysicsMassAPI massAPI = pxr::UsdPhysicsMassAPI::Apply(linkPrim.GetPrim());
if (link.inertial.hasMass)
{
massAPI.CreateMassAttr().Set(link.inertial.mass);
}
else if (config.density > 0)
{
// scale from kg/m^2 to specified units
massAPI.CreateDensityAttr().Set(config.density);
}
if (link.inertial.hasInertia && config.importInertiaTensor)
{
Matrix33 inertiaMatrix;
inertiaMatrix.cols[0] = Vec3(link.inertial.inertia.ixx, link.inertial.inertia.ixy, link.inertial.inertia.ixz);
inertiaMatrix.cols[1] = Vec3(link.inertial.inertia.ixy, link.inertial.inertia.iyy, link.inertial.inertia.iyz);
inertiaMatrix.cols[2] = Vec3(link.inertial.inertia.ixz, link.inertial.inertia.iyz, link.inertial.inertia.izz);
Quat principalAxes;
Vec3 diaginertia = Diagonalize(inertiaMatrix, principalAxes);
// input is meters, but convert to kit units
massAPI.CreateDiagonalInertiaAttr().Set(config.distanceScale * config.distanceScale *
pxr::GfVec3f(diaginertia.x, diaginertia.y, diaginertia.z));
massAPI.CreatePrincipalAxesAttr().Set(
pxr::GfQuatf(principalAxes.w, principalAxes.x, principalAxes.y, principalAxes.z));
}
if (link.inertial.hasOrigin)
{
massAPI.CreateCenterOfMassAttr().Set(pxr::GfVec3f(float(config.distanceScale * link.inertial.origin.p.x),
float(config.distanceScale * link.inertial.origin.p.y),
float(config.distanceScale * link.inertial.origin.p.z)));
}
}
else
{
CARB_LOG_WARN("linkPrim %s not created", link.name.c_str());
return;
}
// Add visuals
if (config.makeInstanceable && link.visuals.size() > 0)
{
pxr::SdfPath visualPrimPath = pxr::SdfPath(robotBasePath + link.name + "/visuals");
pxr::UsdPrim visualPrim = stage->DefinePrim(visualPrimPath);
visualPrim.GetReferences().AddReference(config.instanceableMeshUsdPath, visualPrimPath);
visualPrim.SetInstanceable(true);
}
else
{
for (size_t i = 0; i < link.visuals.size(); i++)
{
std::string meshName;
if (link.visuals.size() > 1)
{
std::string name = "mesh_" + std::to_string(i);
if (link.visuals[i].name.size() > 0)
{
name = link.visuals[i].name;
}
meshName = robotBasePath + link.name + "/visuals/" + name;
}
else
{
meshName = robotBasePath + link.name + "/visuals";
}
bool loadMaterial = true;
auto mat = link.visuals[i].material;
auto urdfMatIter = robot.materials.find(link.visuals[i].material.name);
if (urdfMatIter != robot.materials.end())
{
mat = urdfMatIter->second;
}
auto& color = mat.color;
if (color.r >= 0 && color.g >= 0 && color.b >= 0)
{
loadMaterial = false;
}
pxr::UsdPrim prim = addMesh(stage, link.visuals[i].geometry, assetRoot_, urdfPath_, meshName,
link.visuals[i].origin, loadMaterial, config.distanceScale, false,
materialsList, subdivisionschemes[(int)config.subdivisionScheme]);
if (prim)
{
if (loadMaterial == false)
{
// This Material was in the master list, reuse
auto urdfMatIter = robot.materials.find(link.visuals[i].material.name);
if (urdfMatIter != robot.materials.end())
{
std::string path = matPrimPaths[link.visuals[i].material.name];
auto matPrim = stage->GetPrimAtPath(pxr::SdfPath(path));
if (matPrim)
{
auto shadePrim = pxr::UsdShadeMaterial(matPrim);
if (shadePrim)
{
pxr::UsdShadeMaterialBindingAPI mbi(prim);
mbi.Bind(shadePrim);
}
}
}
else
{
auto& color = link.visuals[i].material.color;
std::stringstream ss;
ss << std::uppercase << std::hex << (int)(256 * color.r) << std::uppercase << std::hex
<< (int)(256 * color.g) << std::uppercase << std::hex << (int)(256 * color.b);
std::pair<std::string, UrdfMaterial> mat_pair(ss.str(), link.visuals[i].material);
pxr::UsdShadeMaterial matPrim =
addMaterial(stage, mat_pair, prim.GetPath().GetParentPath().GetParentPath());
if (matPrim)
{
pxr::UsdShadeMaterialBindingAPI mbi(prim);
mbi.Bind(matPrim);
}
}
}
}
else
{
CARB_LOG_WARN("Prim %s not created", meshName.c_str());
}
}
}
// Add collisions
CARB_LOG_INFO("Add collisions: %s", link.name.c_str());
if (config.makeInstanceable && link.collisions.size() > 0)
{
pxr::SdfPath collisionPrimPath = pxr::SdfPath(robotBasePath + link.name + "/collisions");
pxr::UsdPrim collisionPrim = stage->DefinePrim(collisionPrimPath);
collisionPrim.GetReferences().AddReference(config.instanceableMeshUsdPath, collisionPrimPath);
collisionPrim.SetInstanceable(true);
}
else
{
for (size_t i = 0; i < link.collisions.size(); i++)
{
std::string meshName;
if (link.collisions.size() > 1 || config.makeInstanceable)
{
std::string name = "mesh_" + std::to_string(i);
if (link.collisions[i].name.size() > 0)
{
name = link.collisions[i].name;
}
meshName = robotBasePath + link.name + "/collisions/" + name;
}
else
{
meshName = robotBasePath + link.name + "/collisions";
}
pxr::UsdPrim prim = addMesh(stage, link.collisions[i].geometry, assetRoot_, urdfPath_, meshName,
link.collisions[i].origin, false, config.distanceScale, false, materialsList,
subdivisionschemes[(int)config.subdivisionScheme], false, config.replaceCylindersWithCapsules);
// Enable collisions on prim
if (prim)
{
pxr::UsdPhysicsCollisionAPI::Apply(prim);
if (link.collisions[i].geometry.type == UrdfGeometryType::SPHERE)
{
pxr::UsdPhysicsCollisionAPI::Apply(prim);
}
else if (link.collisions[i].geometry.type == UrdfGeometryType::BOX)
{
pxr::UsdPhysicsCollisionAPI::Apply(prim);
}
else if (link.collisions[i].geometry.type == UrdfGeometryType::CYLINDER)
{
pxr::UsdPhysicsCollisionAPI::Apply(prim);
}
else if (link.collisions[i].geometry.type == UrdfGeometryType::CAPSULE)
{
pxr::UsdPhysicsCollisionAPI::Apply(prim);
}
else
{
pxr::UsdPhysicsMeshCollisionAPI physicsMeshAPI = pxr::UsdPhysicsMeshCollisionAPI::Apply(prim);
if (config.convexDecomp == true)
{
physicsMeshAPI.CreateApproximationAttr().Set(pxr::UsdPhysicsTokens.Get()->convexDecomposition);
}
else
{
physicsMeshAPI.CreateApproximationAttr().Set(pxr::UsdPhysicsTokens.Get()->convexHull);
}
}
pxr::UsdGeomMesh(prim).CreatePurposeAttr().Set(pxr::UsdGeomTokens->guide);
}
else
{
CARB_LOG_WARN("Prim %s not created", meshName.c_str());
}
}
}
}
template <class T>
void AddSingleJoint(const UrdfJoint& joint,
pxr::UsdStageWeakPtr stage,
const pxr::SdfPath& jointPath,
pxr::UsdPhysicsJoint& jointPrimBase,
const float distanceScale)
{
T jointPrim = T::Define(stage, pxr::SdfPath(jointPath));
jointPrimBase = jointPrim;
jointPrim.CreateAxisAttr().Set(pxr::TfToken("X"));
// Set the limits if the joint is anything except a continuous joint
if (joint.type != UrdfJointType::CONTINUOUS)
{
// Angular limits are in degrees so scale accordingly
float scale = 180.0f / static_cast<float>(M_PI);
if (joint.type == UrdfJointType::PRISMATIC)
{
scale = distanceScale;
}
jointPrim.CreateLowerLimitAttr().Set(scale * joint.limit.lower);
jointPrim.CreateUpperLimitAttr().Set(scale * joint.limit.upper);
}
pxr::PhysxSchemaPhysxJointAPI physxJoint = pxr::PhysxSchemaPhysxJointAPI::Apply(jointPrim.GetPrim());
physxJoint.CreateJointFrictionAttr().Set(joint.dynamics.friction);
if (joint.type == UrdfJointType::PRISMATIC)
{
pxr::PhysxSchemaJointStateAPI::Apply(jointPrim.GetPrim(), pxr::TfToken("linear"));
if (joint.mimic.joint == "")
{
pxr::UsdPhysicsDriveAPI driveAPI = pxr::UsdPhysicsDriveAPI::Apply(jointPrim.GetPrim(), pxr::TfToken("linear"));
// convert kg*m/s^2 to kg * cm /s^2
driveAPI.CreateMaxForceAttr().Set(joint.limit.effort > 0.0f ? joint.limit.effort * distanceScale : FLT_MAX);
// change drive type
if (joint.drive.driveType == UrdfJointDriveType::FORCE)
{
driveAPI.CreateTypeAttr().Set(pxr::TfToken("force"));
}
else
{
driveAPI.CreateTypeAttr().Set(pxr::TfToken("acceleration"));
}
// change drive target type
if (joint.drive.targetType == UrdfJointTargetType::POSITION)
{
driveAPI.CreateTargetPositionAttr().Set(joint.drive.target);
}
else if (joint.drive.targetType == UrdfJointTargetType::VELOCITY)
{
driveAPI.CreateTargetVelocityAttr().Set(joint.drive.target);
}
// change drive stiffness and damping
if (joint.drive.targetType != UrdfJointTargetType::NONE)
{
driveAPI.CreateDampingAttr().Set(joint.dynamics.damping);
driveAPI.CreateStiffnessAttr().Set(joint.dynamics.stiffness);
}
else
{
driveAPI.CreateDampingAttr().Set(0.0f);
driveAPI.CreateStiffnessAttr().Set(0.0f);
}
}
// Prismatic joint velocity should be scaled to stage units, but not revolute
physxJoint.CreateMaxJointVelocityAttr().Set(
joint.limit.velocity > 0.0f ? static_cast<float>(joint.limit.velocity * distanceScale) : FLT_MAX);
}
// continuous and revolute are identical except for setting limits
else if (joint.type == UrdfJointType::REVOLUTE || joint.type == UrdfJointType::CONTINUOUS)
{
pxr::PhysxSchemaJointStateAPI::Apply(jointPrim.GetPrim(), pxr::TfToken("angular"));
if (joint.mimic.joint == "")
{
pxr::UsdPhysicsDriveAPI driveAPI = pxr::UsdPhysicsDriveAPI::Apply(jointPrim.GetPrim(), pxr::TfToken("angular"));
// convert kg*m/s^2 * m to kg * cm /s^2 * cm
driveAPI.CreateMaxForceAttr().Set(
joint.limit.effort > 0.0f ? joint.limit.effort * distanceScale * distanceScale : FLT_MAX);
// change drive type
if (joint.drive.driveType == UrdfJointDriveType::FORCE)
{
driveAPI.CreateTypeAttr().Set(pxr::TfToken("force"));
}
else
{
driveAPI.CreateTypeAttr().Set(pxr::TfToken("acceleration"));
}
// change drive target type
if (joint.drive.targetType == UrdfJointTargetType::POSITION)
{
driveAPI.CreateTargetPositionAttr().Set(joint.drive.target);
}
else if (joint.drive.targetType == UrdfJointTargetType::VELOCITY)
{
driveAPI.CreateTargetVelocityAttr().Set(joint.drive.target);
}
// change drive stiffness and damping
if (joint.drive.targetType != UrdfJointTargetType::NONE)
{
driveAPI.CreateDampingAttr().Set(joint.dynamics.damping);
driveAPI.CreateStiffnessAttr().Set(joint.dynamics.stiffness);
}
else
{
driveAPI.CreateDampingAttr().Set(0.0f);
driveAPI.CreateStiffnessAttr().Set(0.0f);
}
}
// Convert revolute joint velocity limit to deg/s
physxJoint.CreateMaxJointVelocityAttr().Set(
joint.limit.velocity > 0.0f ? static_cast<float>(180.0f / M_PI * joint.limit.velocity) : FLT_MAX);
}
for (auto &mimic : joint.mimicChildren)
{
auto tendonRoot = pxr::PhysxSchemaPhysxTendonAxisRootAPI::Apply(jointPrim.GetPrim(), pxr::TfToken(mimic.first));
tendonRoot.CreateStiffnessAttr().Set(1.e5f);
tendonRoot.CreateDampingAttr().Set(10.0);
float scale = 180.0f / static_cast<float>(M_PI);
if (joint.type == UrdfJointType::PRISMATIC)
{
scale = distanceScale;
}
auto offset = scale*mimic.second;
tendonRoot.CreateOffsetAttr().Set(offset);
// Manually setting the coefficients to avoid adding an extra API that makes it messy.
std::string attrName1 = "physxTendon:"+mimic.first+":forceCoefficient";
auto attr1 = tendonRoot.GetPrim().CreateAttribute( pxr::TfToken(attrName1.c_str()), pxr::SdfValueTypeNames->FloatArray, false);
std::string attrName2 = "physxTendon:"+mimic.first+":gearing";
auto attr2 = tendonRoot.GetPrim().CreateAttribute( pxr::TfToken(attrName2.c_str()), pxr::SdfValueTypeNames->FloatArray, false);
pxr::VtArray<float> forceattr;
pxr::VtArray<float> gearing;
forceattr.push_back(-1.0f);
gearing.push_back(-1.0f);
attr1.Set(forceattr);
attr2.Set(gearing);
}
if (joint.mimic.joint != "")
{
auto tendon = pxr::PhysxSchemaPhysxTendonAxisAPI::Apply(jointPrim.GetPrim(), pxr::TfToken(joint.name));
pxr::VtArray<float> forceattr;
pxr::VtArray<float> gearing;
forceattr.push_back(joint.mimic.multiplier>0?1:-1);
// Tendon Gear ratio is the inverse of the mimic multiplier
gearing.push_back(1.0f/joint.mimic.multiplier);
tendon.CreateForceCoefficientAttr().Set(forceattr);
tendon.CreateGearingAttr().Set(gearing);
}
}
void UrdfImporter::addJoint(pxr::UsdStageWeakPtr stage,
pxr::UsdGeomXform robotPrim,
const UrdfJoint& joint,
const Transform& poseJointToParentBody)
{
std::string parentLinkPath = robotPrim.GetPath().GetString() + "/" + joint.parentLinkName;
std::string childLinkPath = robotPrim.GetPath().GetString() + "/" + joint.childLinkName;
std::string jointPath = parentLinkPath + "/" + joint.name;
if (!pxr::SdfPath::IsValidPathString(jointPath))
{
// jn->getName starts with a number which is not valid for usd path, so prefix it with "joint"
jointPath = parentLinkPath + "/joint" + joint.name;
}
pxr::UsdPhysicsJoint jointPrim;
if (joint.type == UrdfJointType::FIXED)
{
jointPrim = pxr::UsdPhysicsFixedJoint::Define(stage, pxr::SdfPath(jointPath));
}
else if (joint.type == UrdfJointType::PRISMATIC)
{
AddSingleJoint<pxr::UsdPhysicsPrismaticJoint>(
joint, stage, pxr::SdfPath(jointPath), jointPrim, float(config.distanceScale));
}
// else if (joint.type == UrdfJointType::SPHERICAL)
// {
// AddSingleJoint<PhysicsSchemaSphericalJoint>(jn, stage, SdfPath(jointPath), jointPrim, skel,
// distanceScale);
// }
else if (joint.type == UrdfJointType::REVOLUTE || joint.type == UrdfJointType::CONTINUOUS)
{
AddSingleJoint<pxr::UsdPhysicsRevoluteJoint>(
joint, stage, pxr::SdfPath(jointPath), jointPrim, float(config.distanceScale));
}
else if (joint.type == UrdfJointType::FLOATING)
{
// There is no joint, skip
return;
}
pxr::SdfPathVector val0{ pxr::SdfPath(parentLinkPath) };
pxr::SdfPathVector val1{ pxr::SdfPath(childLinkPath) };
if (parentLinkPath != "")
{
jointPrim.CreateBody0Rel().SetTargets(val0);
}
pxr::GfVec3f localPos0 = config.distanceScale * pxr::GfVec3f(poseJointToParentBody.p.x, poseJointToParentBody.p.y,
poseJointToParentBody.p.z);
pxr::GfQuatf localRot0 = pxr::GfQuatf(
poseJointToParentBody.q.w, poseJointToParentBody.q.x, poseJointToParentBody.q.y, poseJointToParentBody.q.z);
pxr::GfVec3f localPos1 = config.distanceScale * pxr::GfVec3f(0, 0, 0);
pxr::GfQuatf localRot1 = pxr::GfQuatf(1, 0, 0, 0);
// Need to rotate the joint frame to match the urdf defined axis
// convert joint axis to angle-axis representation
Vec3 jointAxisRotAxis = -Cross(urdfAxisToVec(joint.axis), Vec3(1.0f, 0.0f, 0.0f));
float jointAxisRotAngle = acos(joint.axis.x); // this is equal to acos(Dot(joint.axis, Vec3(1.0f, 0.0f, 0.0f)))
if (Dot(jointAxisRotAxis, jointAxisRotAxis) < 1e-5f)
{
// for axis along x we define an arbitrary perpendicular rotAxis (along y).
// In that case the angle is 0 or 180deg
jointAxisRotAxis = Vec3(0.0f, 1.0f, 0.0f);
}
// normalize jointAxisRotAxis
jointAxisRotAxis /= sqrtf(Dot(jointAxisRotAxis, jointAxisRotAxis));
// rotate the parent frame by the axis
Quat jointAxisRotQuat = QuatFromAxisAngle(jointAxisRotAxis, jointAxisRotAngle);
// apply transforms
jointPrim.CreateLocalPos0Attr().Set(localPos0);
jointPrim.CreateLocalRot0Attr().Set(localRot0 * pxr::GfQuatf(jointAxisRotQuat.w, jointAxisRotQuat.x, jointAxisRotQuat.y, jointAxisRotQuat.z));
if (childLinkPath != "")
{
jointPrim.CreateBody1Rel().SetTargets(val1);
}
jointPrim.CreateLocalPos1Attr().Set(localPos1);
jointPrim.CreateLocalRot1Attr().Set(localRot1 * pxr::GfQuatf(jointAxisRotQuat.w, jointAxisRotQuat.x, jointAxisRotQuat.y, jointAxisRotQuat.z));
jointPrim.CreateBreakForceAttr().Set(FLT_MAX);
jointPrim.CreateBreakTorqueAttr().Set(FLT_MAX);
// TODO: FIx?
// auto linkAPI = pxr::UsdPhysicsJoint::Apply(stage->GetPrimAtPath(pxr::SdfPath(jointPath)));
// linkAPI.CreateArticulationTypeAttr().Set(pxr::TfToken("articulatedJoint"));
}
void UrdfImporter::addLinksAndJoints(pxr::UsdStageWeakPtr stage,
const Transform& poseParentToWorld,
const KinematicChain::Node* parentNode,
const UrdfRobot& robot,
pxr::UsdGeomXform robotPrim)
{
// Create root joint only once
if (parentNode->parentJointName_ == "")
{
const UrdfLink& urdfLink = robot.links.at(parentNode->linkName_);
addRigidBody(stage, urdfLink, poseParentToWorld, robotPrim, robot);
if (config.fixBase)
{
std::string rootJointPath = robotPrim.GetPath().GetString() + "/root_joint";
pxr::UsdPhysicsFixedJoint rootJoint = pxr::UsdPhysicsFixedJoint::Define(stage, pxr::SdfPath(rootJointPath));
pxr::SdfPathVector val1{ pxr::SdfPath(robotPrim.GetPath().GetString() + "/" + urdfLink.name) };
rootJoint.CreateBody1Rel().SetTargets(val1);
}
}
if (!parentNode->childNodes_.empty())
{
for (const auto& childNode : parentNode->childNodes_)
{
if (robot.joints.find(childNode->parentJointName_) != robot.joints.end())
{
if (robot.links.find(childNode->linkName_) != robot.links.end())
{
const UrdfJoint urdfJoint = robot.joints.at(childNode->parentJointName_);
const UrdfLink& childLink = robot.links.at(childNode->linkName_);
// const UrdfLink& parentLink = robot.links.at(parentNode->linkName_);
Transform poseJointToLink = urdfJoint.origin;
// According to URDF spec, the frame of a link coincides with its parent joint frame
Transform poseLinkToWorld = poseParentToWorld * poseJointToLink;
// if (!parentLink.softs.size() && !childLink.softs.size()) // rigid parent, rigid child
{
addRigidBody(stage, childLink, poseLinkToWorld, robotPrim, robot);
addJoint(stage, robotPrim, urdfJoint, poseJointToLink);
// RigidBodyTopo bodyTopo;
// bodyTopo.bodyIndex = asset->bodyLookup.at(childNode->linkName_);
// bodyTopo.parentIndex = asset->bodyLookup.at(parentNode->linkName_);
// bodyTopo.jointIndex = asset->jointLookup.at(childNode->parentJointName_);
// bodyTopo.jointSpecStart = asset->jointLookup.at(childNode->parentJointName_);
// // URDF only has 1 DOF joints
// bodyTopo.jointSpecCount = 1;
// asset->rigidBodyHierarchy.push_back(bodyTopo);
}
// Recurse through the links children
addLinksAndJoints(stage, poseLinkToWorld, childNode.get(), robot, robotPrim);
}
else
{
CARB_LOG_ERROR("Failed to Create Joint <%s>: Child link <%s> not found",
childNode->parentJointName_.c_str(), childNode->linkName_.c_str());
}
}
else
{
CARB_LOG_WARN("Joint <%s> is undefined", childNode->parentJointName_.c_str());
}
}
}
}
void UrdfImporter::addMaterials(pxr::UsdStageWeakPtr stage, const UrdfRobot& robot, const pxr::SdfPath& prefixPath)
{
stage->DefinePrim(pxr::SdfPath(prefixPath.GetString() + "/Looks"), pxr::TfToken("Scope"));
for (auto& mat : robot.materials)
{
addMaterial(stage, mat, prefixPath);
}
}
pxr::UsdShadeMaterial UrdfImporter::addMaterial(pxr::UsdStageWeakPtr stage,
const std::pair<std::string, UrdfMaterial>& mat,
const pxr::SdfPath& prefixPath)
{
auto& color = mat.second.color;
std::string name = mat.second.name;
if (name == "")
{
name = mat.first;
}
if (color.r >= 0 && color.g >= 0 && color.b >= 0)
{
pxr::SdfPath shaderPath =
prefixPath.AppendPath(pxr::SdfPath("Looks/" + makeValidUSDIdentifier("material_" + name)));
pxr::UsdShadeMaterial matPrim = pxr::UsdShadeMaterial::Define(stage, shaderPath);
if (matPrim)
{
pxr::UsdShadeShader pbrShader =
pxr::UsdShadeShader::Define(stage, shaderPath.AppendPath(pxr::SdfPath("Shader")));
if (pbrShader)
{
auto shader_out = pbrShader.CreateOutput(pxr::TfToken("out"), pxr::SdfValueTypeNames->Token);
matPrim.CreateSurfaceOutput(pxr::TfToken("mdl")).ConnectToSource(shader_out);
matPrim.CreateVolumeOutput(pxr::TfToken("mdl")).ConnectToSource(shader_out);
matPrim.CreateDisplacementOutput(pxr::TfToken("mdl")).ConnectToSource(shader_out);
pbrShader.GetImplementationSourceAttr().Set(pxr::UsdShadeTokens->sourceAsset);
pbrShader.SetSourceAsset(pxr::SdfAssetPath("OmniPBR.mdl"), pxr::TfToken("mdl"));
pbrShader.SetSourceAssetSubIdentifier(pxr::TfToken("OmniPBR"), pxr::TfToken("mdl"));
pbrShader.CreateInput(pxr::TfToken("diffuse_color_constant"), pxr::SdfValueTypeNames->Color3f)
.Set(pxr::GfVec3f(color.r, color.g, color.b));
matPrimPaths[name] = shaderPath.GetString();
return matPrim;
}
else
{
CARB_LOG_WARN("Couldn't create shader at: %s", shaderPath.GetString().c_str());
}
}
else
{
CARB_LOG_WARN("Couldn't create material at: %s", shaderPath.GetString().c_str());
}
}
return pxr::UsdShadeMaterial();
}
std::string UrdfImporter::addToStage(pxr::UsdStageWeakPtr stage, const UrdfRobot& urdfRobot)
{
if (urdfRobot.links.size() == 0)
{
CARB_LOG_WARN("Cannot add robot to stage, number of links is zero");
return "";
}
// The limit for links is now a 32bit index so this shouldn't be needed anymore
// if (urdfRobot.links.size() >= 64)
// {
// CARB_LOG_WARN(
// "URDF cannot have more than 63 links to be imported as a physx articulation. Try enabling the merge fixed
// joints option to reduce the number of links.");
// CARB_LOG_WARN("URDF has %d links", static_cast<int>(urdfRobot.links.size()));
// return "";
// }
if (config.createPhysicsScene)
{
bool sceneExists = false;
pxr::UsdPrimRange range = stage->Traverse();
for (pxr::UsdPrimRange::iterator iter = range.begin(); iter != range.end(); ++iter)
{
pxr::UsdPrim prim = *iter;
if (prim.IsA<pxr::UsdPhysicsScene>())
{
sceneExists = true;
}
}
if (!sceneExists)
{
// Create physics scene
pxr::UsdPhysicsScene scene = pxr::UsdPhysicsScene::Define(stage, pxr::SdfPath("/physicsScene"));
scene.CreateGravityDirectionAttr().Set(pxr::GfVec3f(0.0f, 0.0f, -1.0));
scene.CreateGravityMagnitudeAttr().Set(9.81f * config.distanceScale);
pxr::PhysxSchemaPhysxSceneAPI physxSceneAPI =
pxr::PhysxSchemaPhysxSceneAPI::Apply(stage->GetPrimAtPath(pxr::SdfPath("/physicsScene")));
physxSceneAPI.CreateEnableCCDAttr().Set(true);
physxSceneAPI.CreateEnableStabilizationAttr().Set(true);
physxSceneAPI.CreateEnableGPUDynamicsAttr().Set(false);
physxSceneAPI.CreateBroadphaseTypeAttr().Set(pxr::TfToken("MBP"));
physxSceneAPI.CreateSolverTypeAttr().Set(pxr::TfToken("TGS"));
}
}
pxr::SdfPath primPath =
pxr::SdfPath(GetNewSdfPathString(stage, stage->GetDefaultPrim().GetPath().GetString() + "/" +
makeValidUSDIdentifier(std::string(urdfRobot.name))));
if (config.makeDefaultPrim)
primPath = pxr::SdfPath(GetNewSdfPathString(stage, "/" + makeValidUSDIdentifier(std::string(urdfRobot.name))));
// // Remove the prim we are about to add in case it exists
// if (stage->GetPrimAtPath(primPath))
// {
// stage->RemovePrim(primPath);
// }
pxr::UsdGeomXform robotPrim = pxr::UsdGeomXform::Define(stage, primPath);
pxr::UsdGeomXformable gprim = pxr::UsdGeomXformable(robotPrim);
gprim.ClearXformOpOrder();
gprim.AddTranslateOp(pxr::UsdGeomXformOp::PrecisionDouble).Set(pxr::GfVec3d(0, 0, 0));
gprim.AddOrientOp(pxr::UsdGeomXformOp::PrecisionDouble).Set(pxr::GfQuatd(1, 0, 0, 0));
gprim.AddScaleOp(pxr::UsdGeomXformOp::PrecisionDouble).Set(pxr::GfVec3d(1, 1, 1));
pxr::UsdPhysicsArticulationRootAPI physicsSchema = pxr::UsdPhysicsArticulationRootAPI::Apply(robotPrim.GetPrim());
pxr::PhysxSchemaPhysxArticulationAPI physxSchema = pxr::PhysxSchemaPhysxArticulationAPI::Apply(robotPrim.GetPrim());
physxSchema.CreateEnabledSelfCollisionsAttr().Set(config.selfCollision);
// These are reasonable defaults, might want to expose them via the import config in the future.
physxSchema.CreateSolverPositionIterationCountAttr().Set(32);
physxSchema.CreateSolverVelocityIterationCountAttr().Set(16);
if (config.makeDefaultPrim)
{
stage->SetDefaultPrim(robotPrim.GetPrim());
}
KinematicChain chain;
if (!chain.computeKinematicChain(urdfRobot))
{
return "";
}
if (!config.makeInstanceable)
{
addMaterials(stage, urdfRobot, primPath);
}
else
{
// first create instanceable meshes USD
std::string instanceableStagePath = config.instanceableMeshUsdPath;
if (config.instanceableMeshUsdPath[0] == '.')
{
// make relative path relative to output directory
std::string relativePath = config.instanceableMeshUsdPath.substr(1);
std::string curStagePath = stage->GetRootLayer()->GetIdentifier();
std::string directory;
size_t pos = curStagePath.find_last_of("\\/");
directory = (std::string::npos == pos) ? "" : curStagePath.substr(0, pos);
instanceableStagePath = directory + relativePath;
}
pxr::UsdStageRefPtr instanceableMeshStage = pxr::UsdStage::CreateNew(instanceableStagePath);
std::string robotBasePath = robotPrim.GetPath().GetString() + "/";
buildInstanceableStage(instanceableMeshStage, chain.baseNode.get(), robotBasePath, urdfRobot);
instanceableMeshStage->Export(instanceableStagePath);
}
addLinksAndJoints(stage, Transform(), chain.baseNode.get(), urdfRobot, robotPrim);
return primPath.GetString();
}
}
}
}
| 48,372 | C++ | 41.432456 | 146 | 0.576222 |
NVIDIA-Omniverse/urdf-importer-extension/source/extensions/omni.importer.urdf/plugins/import/KinematicChain.h | // SPDX-FileCopyrightText: Copyright (c) 2023 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
// SPDX-License-Identifier: Apache-2.0
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#pragma once
#include "../UrdfTypes.h"
#include <memory>
#include <string>
#include <vector>
namespace omni
{
namespace importer
{
namespace urdf
{
// Represents the kinematic chain as a tree
class KinematicChain
{
public:
// A tree representing a link with its parent joint and child links
struct Node
{
std::string linkName_;
std::string parentJointName_;
std::vector<std::unique_ptr<Node>> childNodes_;
Node(std::string linkName, std::string parentJointName) : linkName_(linkName), parentJointName_(parentJointName)
{
}
};
std::unique_ptr<Node> baseNode;
KinematicChain() = default;
~KinematicChain();
// Computes the kinematic chain for a UrdfRobot description
bool computeKinematicChain(const UrdfRobot& urdfRobot);
private:
// Recursively finds a node's children
void computeChildNodes(std::unique_ptr<Node>& parentNode, const UrdfRobot& urdfRobot);
};
}
}
}
| 1,662 | C | 24.984375 | 120 | 0.712996 |
NVIDIA-Omniverse/urdf-importer-extension/source/extensions/omni.importer.urdf/plugins/import/MeshImporter.h | // SPDX-FileCopyrightText: Copyright (c) 2023 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
// SPDX-License-Identifier: Apache-2.0
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#pragma once
// clang-format off
#include "../UsdPCH.h"
// clang-format on
#include "assimp/scene.h"
#include <string>
namespace omni
{
namespace importer
{
namespace urdf
{
pxr::SdfPath SimpleImport(pxr::UsdStageRefPtr usdStage,
std::string path,
const aiScene* mScene,
const std::string mesh_path,
std::map<pxr::TfToken, std::string>& materialsList,
const bool loadMaterials = true,
const bool flipVisuals = false,
const char* subdvisionScheme = "none",
const bool instanceable = false);
}
}
}
| 1,407 | C | 27.734693 | 99 | 0.635394 |
NVIDIA-Omniverse/urdf-importer-extension/source/extensions/omni.importer.urdf/plugins/import/UrdfImporter.h | // SPDX-FileCopyrightText: Copyright (c) 2023 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
// SPDX-License-Identifier: Apache-2.0
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#pragma once
// clang-format off
#include "../UsdPCH.h"
// clang-format on
#include "../parse/UrdfParser.h"
#include "KinematicChain.h"
#include "MeshImporter.h"
#include "../math/core/maths.h"
#include "../Urdf.h"
#include "../UrdfTypes.h"
#include <carb/logging/Log.h>
#include <pxr/usd/usdPhysics/articulationRootAPI.h>
#include <pxr/usd/usdPhysics/collisionAPI.h>
#include <pxr/usd/usdPhysics/driveAPI.h>
#include <pxr/usd/usdPhysics/fixedJoint.h>
#include <pxr/usd/usdPhysics/joint.h>
#include <pxr/usd/usdPhysics/limitAPI.h>
#include <pxr/usd/usdPhysics/massAPI.h>
#include <pxr/usd/usdPhysics/prismaticJoint.h>
#include <pxr/usd/usdPhysics/revoluteJoint.h>
#include <pxr/usd/usdPhysics/scene.h>
#include <pxr/usd/usdPhysics/sphericalJoint.h>
namespace omni
{
namespace importer
{
namespace urdf
{
class UrdfImporter
{
private:
std::string assetRoot_;
std::string urdfPath_;
const ImportConfig config;
std::map<std::string, std::string> matPrimPaths;
std::map<pxr::TfToken, std::string> materialsList;
public:
UrdfImporter(const std::string& assetRoot, const std::string& urdfPath, const ImportConfig& options)
: assetRoot_(assetRoot), urdfPath_(urdfPath), config(options)
{
}
// Creates and populates a GymAsset
UrdfRobot createAsset();
std::string addToStage(pxr::UsdStageWeakPtr stage, const UrdfRobot& robot);
private:
void buildInstanceableStage(pxr::UsdStageRefPtr stage,
const KinematicChain::Node* parentNode,
const std::string& robotBasePath,
const UrdfRobot& urdfRobot);
void addInstanceableMeshes(pxr::UsdStageRefPtr stage,
const UrdfLink& link,
const std::string& robotBasePath,
const UrdfRobot& robot);
void addRigidBody(pxr::UsdStageWeakPtr stage,
const UrdfLink& link,
const Transform& poseBodyToWorld,
pxr::UsdGeomXform robotPrim,
const UrdfRobot& robot);
void addJoint(pxr::UsdStageWeakPtr stage,
pxr::UsdGeomXform robotPrim,
const UrdfJoint& joint,
const Transform& poseJointToParentBody);
void addLinksAndJoints(pxr::UsdStageWeakPtr stage,
const Transform& poseParentToWorld,
const KinematicChain::Node* parentNode,
const UrdfRobot& robot,
pxr::UsdGeomXform robotPrim);
void addMaterials(pxr::UsdStageWeakPtr stage, const UrdfRobot& robot, const pxr::SdfPath& prefixPath);
pxr::UsdShadeMaterial addMaterial(pxr::UsdStageWeakPtr stage,
const std::pair<std::string, UrdfMaterial>& mat,
const pxr::SdfPath& prefixPath);
};
}
}
}
| 3,651 | C | 34.803921 | 106 | 0.649137 |
NVIDIA-Omniverse/urdf-importer-extension/source/extensions/omni.importer.urdf/plugins/core/PathUtils.h | // SPDX-FileCopyrightText: Copyright (c) 2023 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
// SPDX-License-Identifier: Apache-2.0
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#pragma once
// clang-format off
#include "../UsdPCH.h"
// clang-format on
#include <string>
#include <vector>
namespace omni
{
namespace importer
{
namespace urdf
{
enum class PathType
{
eNone, // path does not exist
eFile, // path is a regular file
eDirectory, // path is a directory
eOther, // path is something else
};
PathType testPath(const char* path);
bool isAbsolutePath(const char* path);
bool makeDirectory(const char* path);
std::string pathJoin(const std::string& path1, const std::string& path2);
std::string getCwd();
// returns filename without extension (e.g. "foo/bar/bingo.txt" -> "bingo")
std::string getPathStem(const char* path);
std::vector<std::string> getFileListRecursive(const std::string& dir, bool sorted = true);
std::string makeValidUSDIdentifier(const std::string& name);
}
}
}
| 1,532 | C | 24.98305 | 99 | 0.730418 |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.