file_path
stringlengths 21
224
| content
stringlengths 0
80.8M
|
---|---|
renanmb/Omniverse_legged_robotics/CHAMP-stuff/configs/anymal_b_config/config/links/links.yaml | base: base
left_front:
- LF_HIP
- LF_THIGH
- LF_SHANK
- LF_FOOT
right_front:
- RF_HIP
- RF_THIGH
- RF_SHANK
- RF_FOOT
left_hind:
- LH_HIP
- LH_THIGH
- LH_SHANK
- LH_FOOT
right_hind:
- RH_HIP
- RH_THIGH
- RH_SHANK
- RH_FOOT |
renanmb/Omniverse_legged_robotics/CHAMP-stuff/configs/anymal_b_config/config/ros_control/ros_control.yaml | "":
joint_states_controller:
type: joint_state_controller/JointStateController
publish_rate: 50
joint_group_position_controller:
type: effort_controllers/JointTrajectoryController
joints:
- LF_HAA
- LF_HFE
- LF_KFE
- RF_HAA
- RF_HFE
- RF_KFE
- LH_HAA
- LH_HFE
- LH_KFE
- RH_HAA
- RH_HFE
- RH_KFE
gains:
LF_HAA : {p: 250, i: 0, d: 15}
LF_HFE : {p: 250, i: 0, d: 15}
LF_KFE : {p: 250, i: 0, d: 15}
RF_HAA : {p: 250, i: 0, d: 15}
RF_HFE : {p: 250, i: 0, d: 15}
RF_KFE : {p: 250, i: 0, d: 15}
LH_HAA : {p: 250, i: 0, d: 15}
LH_HFE : {p: 250, i: 0, d: 15}
LH_KFE : {p: 250, i: 0, d: 15}
RH_HAA : {p: 250, i: 0, d: 15}
RH_HFE : {p: 250, i: 0, d: 15}
RH_KFE : {p: 250, i: 0, d: 15}
|
renanmb/Omniverse_legged_robotics/CHAMP-stuff/configs/anymal_b_config/config/gait/gait.yaml | knee_orientation : "><"
pantograph_leg : false
odom_scaler: 1.0
max_linear_velocity_x : 0.5
max_linear_velocity_y : 0.25
max_angular_velocity_z : 1.0
com_x_translation : 0.0
swing_height : 0.05
stance_depth : 0.0
stance_duration : 0.3
nominal_height : 0.43 |
renanmb/Omniverse_legged_robotics/CHAMP-stuff/configs/anymal_b_config/config/joints/joints.yaml | left_front:
- LF_HAA
- LF_HFE
- LF_KFE
- LF_ADAPTER_TO_FOOT
right_front:
- RF_HAA
- RF_HFE
- RF_KFE
- RF_ADAPTER_TO_FOOT
left_hind:
- LH_HAA
- LH_HFE
- LH_KFE
- LH_ADAPTER_TO_FOOT
right_hind:
- RH_HAA
- RH_HFE
- RH_KFE
- RH_ADAPTER_TO_FOOT |
renanmb/Omniverse_legged_robotics/CHAMP-stuff/configs/anymal_b_config/config/move_base/costmap_common_params.yaml | obstacle_range: 2.5
raytrace_range: 3.0
footprint: [[-0.25, -0.145], [-0.25, 0.145], [0.25, 0.145], [0.25, -0.145]]
transform_tolerance: 0.5
resolution: 0.05
static_map_layer:
map_topic: map
subscribe_to_updates: true
2d_obstacles_layer:
observation_sources: scan
scan: {data_type: LaserScan,
topic: scan,
marking: true,
clearing: true}
3d_obstacles_layer:
observation_sources: depth
depth: {data_type: PointCloud2,
topic: camera/depth/points,
min_obstacle_height: 0.1,
marking: true,
clearing: true}
inflation_layer:
inflation_radius: 2.0 |
renanmb/Omniverse_legged_robotics/CHAMP-stuff/configs/anymal_b_config/config/move_base/base_local_planner_holonomic_params.yaml | DWAPlannerROS:
#http://wiki.ros.org/dwa_local_planner
min_vel_trans: 0.01
max_vel_trans: 0.5
min_vel_x: -0.025
max_vel_x: 0.5
min_vel_y: 0.0
max_vel_y: 0.0
max_vel_rot: 1.0
min_vel_rot: -1.0
acc_lim_trans: 1.7
acc_lim_x: 1.7
acc_lim_y: 0.0
acc_lim_theta: 3
trans_stopped_vel: 0.1
theta_stopped_vel: 0.1
xy_goal_tolerance: 0.25
yaw_goal_tolerance: 0.34
sim_time: 3.5
sim_granularity: 0.1
vx_samples: 20
vy_samples: 0
vth_samples: 40
path_distance_bias: 34.0
goal_distance_bias: 24.0
occdist_scale: 0.05
forward_point_distance: 0.2
stop_time_buffer: 0.5
scaling_speed: 0.25
max_scaling_factor: 0.2
oscillation_reset_dist: 0.05
use_dwa: true
prune_plan: false
|
renanmb/Omniverse_legged_robotics/CHAMP-stuff/configs/anymal_b_config/config/move_base/move_base_params.yaml | base_global_planner: global_planner/GlobalPlanner
base_local_planner: dwa_local_planner/DWAPlannerROS
shutdown_costmaps: false
controller_frequency: 5.0
controller_patience: 3.0
planner_frequency: 0.5
planner_patience: 5.0
oscillation_timeout: 10.0
oscillation_distance: 0.2
conservative_reset_dist: 0.1 |
renanmb/Omniverse_legged_robotics/CHAMP-stuff/configs/anymal_b_config/config/move_base/global_costmap_params.yaml | global_costmap:
global_frame: map
robot_base_frame: base_footprint
update_frequency: 1.0
publish_frequency: 0.5
static_map: true
cost_scaling_factor: 10.0
plugins:
- {name: static_map_layer, type: "costmap_2d::StaticLayer"}
- {name: inflation_layer, type: "costmap_2d::InflationLayer"}
- {name: 2d_obstacles_layer, type: "costmap_2d::ObstacleLayer"}
- {name: 3d_obstacles_layer, type: "costmap_2d::VoxelLayer"}
|
renanmb/Omniverse_legged_robotics/CHAMP-stuff/configs/anymal_b_config/config/move_base/local_costmap_params.yaml | local_costmap:
global_frame: odom
robot_base_frame: base_footprint
update_frequency: 1.0
publish_frequency: 2.0
static_map: false
rolling_window: true
width: 2.5
height: 2.5
cost_scaling_factor: 5
plugins:
- {name: inflation_layer, type: "costmap_2d::InflationLayer"}
- {name: 2d_obstacles_layer, type: "costmap_2d::ObstacleLayer"}
- {name: 3d_obstacles_layer, type: "costmap_2d::VoxelLayer"}
|
ft-lab/omniverse_sample_scripts/readme.md | # Omniverse sample scripts
ここでは、NVIDIA Omniverse ( https://www.nvidia.com/ja-jp/omniverse/ ) のスクリプトのサンプルを貯めていってます。
Omniverseは、データ構造としてUSDを使用してます。
3Dモデルやシーンのファイルへの保存、読み込みでUSDが使用されるだけでなく、
Omniverse CreateやOmniverse ViewなどのOmniverseアプリのビュー上の制御もUSDを介して行われます(形状の表示/非表示の切り替えや移動など)。
ここでは、OmniverseアプリであるOmniverse CreateのScript Editorで試せるスクリプトのサンプルを用途別に列挙します。
Omniverse Create ~~2021.3.8~~ ~~2022.1.4~~ 2022.3.1(Kit.104)で確認しました。
## 開発の参考サイト
Omniverseの情報は、Omniverse Launcherがポータルになっています。
ここのLEARNにチュートリアル動画やドキュメントなどが列挙されています。
### NVIDIA Omniverse Developer Resource Center
https://developer.nvidia.com/nvidia-omniverse-developer-resource-center
Omniverse開発の入口となるサイトです。
全体的に何ができて何が重要か、というのは俯瞰して見ることができます。
### Omniverse Kit
https://docs.omniverse.nvidia.com/prod_kit/prod_kit/overview.html
Omniverse Kitのトップページです。
"Search API"のようなAPIからの検索もあるため、ある程度理解が進んだ方はこちらから進めるのがよいかもしれません。
## はじめに
Omniverse Createで、メインメニューの [Window] - [Script Editor]を選択して、Script Editorを起動します。

この中でPythonを使用してプログラムを書きます。
左下のRunボタンを押すか、[Ctrl] +[Enter]キーを押すことで実行します。
以下、Pythonの初歩的な説明です。
### コメント
1行のコメントの場合、"#"から行の末尾までがコメントになります。
```python
# comment.
```
複数行の場合は、""" から """ までがコメントになります。
```python
"""
comment.
line2.
"""
```
### print
デバッグ用のメッセージはprintで記載します。
```python
print('Hello Omniverse !')
```
## 学習のための知識
* [Omniverseでの開発手段](./knowledge/dev_method.md)
* [Omniverseのスクリプトの学習手順](./knowledge/dev_info.md)
* [USDについての情報](./knowledge/dev_usd.md)
## Pythonの基礎的なこと
|サンプル|説明|
|---|---|
|[Python](./Python)|Pythonの文字列処理やクラスなど。<br>Pythonの標準機能。|
## 機能説明用のサンプル
|サンプル|説明|
|---|---|
|[Audio](./Audio)|Audioの再生|
|[Animation](./Animation)|Animation関連|
|[Camera](./Camera)|カメラ操作|
|[Geometry](./Geometry)|ジオメトリの作成/情報取得|
|[Light](./Light)|光源の作成/操作|
|[Material](./Material)|マテリアルの割り当て|
|[Math](./Math)|ベクトル/行列計算関連|
|[Operation](./Operation)|Ominverseの操作/イベント処理|
|[Event](./Event)|イベント処理|
|[Physics](./Physics)|Physics(物理)処理|
|[pip_archive](./pip_archive)|Pythonのよく使われるモジュールの使用|
|[Prim](./Prim)|USDのPrim(ノード)の操作|
|[Rendering](./Rendering)|レンダリング画像の取得|
|[Scene](./Scene)|シーン(Stage)情報の取得/読み込みなど|
|[Settings](./Settings)|設定の取得|
|[System](./System)|システム関連情報の取得|
|[UI](./UI)|UI操作|
|[Post Processing](./PostProcessing)|Post Processingのパラメータを変更 (omni.kit.commands.executeを使用)|
|[AssetConverter](./AssetConverter)|obj/fbx/glTFファイルなどをUSDファイルに変換|
|[Nucleus](./Nucleus)|Nucleus上のファイル操作|
## プロジェクト別のサンプル
|サンプル|説明|
|---|---|
|[PLATEAU](./PLATEAU)|Project PLATEAUの3D都市データをOmniverseに読み込み|
## ツール的なサンプル
|サンプル|説明|
|---|---|
|[Samples](./Samples)|サンプルスクリプト|
## Extension
|サンプル|説明|
|---|---|
|[Extensions](./Extensions)|サンプルExtension|
|
ft-lab/omniverse_sample_scripts/Light/readme.md | # Light
光源を作成/取得するためのサンプルです。
## Samples
|ファイル|説明|
|---|---|
|[CreateLight.py](./CreateLight.py)|DistantLightを作成してパラメータを指定。|
|[CreateSphereLight.py](./CreateSphereLight.py)|SphereLightを作成してパラメータを指定。|
|[CheckLightPrim.py](./CheckLightPrim.py)|選択PrimがLightかどうか判断。|
|
ft-lab/omniverse_sample_scripts/Light/CheckLightPrim.py | from pxr import Usd, UsdGeom, UsdPhysics, UsdLux, UsdShade, Sdf, Gf, Tf
# Get stage.
stage = omni.usd.get_context().get_stage()
# Get selection.
selection = omni.usd.get_context().get_selection()
paths = selection.get_selected_prim_paths()
# Check if prim is Light.
def checkLight (prim : Usd.Prim):
typeName = prim.GetTypeName()
if typeName == "DistantLight" or typeName == "CylinderLight" or \
typeName == "DiskLight" or typeName == "DomeLight" or \
typeName == "RectLight" or typeName == "SphereLight":
return True
return False
for path in paths:
# Get prim.
prim = stage.GetPrimAtPath(path)
if checkLight(prim):
print(f"[ {prim.GetPath().pathString} ] : {prim.GetTypeName()}")
|
ft-lab/omniverse_sample_scripts/Light/CreateSphereLight.py | from pxr import Usd, UsdGeom, UsdPhysics, UsdLux, UsdShade, Sdf, Gf, Tf
# Get stage.
stage = omni.usd.get_context().get_stage()
# Create sphere light.
pathName = "/World/sphereLight"
light = UsdLux.SphereLight.Define(stage, pathName)
# Set Radius.
light.CreateRadiusAttr(2.0)
# Set intensity.
light.CreateIntensityAttr(10000.0)
# Set color.
light.CreateColorAttr(Gf.Vec3f(1.0, 0.9, 0.8))
# Set Exposure.
light.CreateExposureAttr(0.0)
# cone angle.
shapingAPI = UsdLux.ShapingAPI(light)
shapingAPI.CreateShapingConeAngleAttr(180.0)
shapingAPI.Apply(light.GetPrim()) # Register ShapingAPI as a schema in prim.
# Compute extent.
boundable = UsdGeom.Boundable(light.GetPrim())
extent = boundable.ComputeExtent(Usd.TimeCode(0))
# Set Extent.
light.CreateExtentAttr(extent)
|
ft-lab/omniverse_sample_scripts/Light/CreateLight.py | from pxr import Usd, UsdGeom, UsdPhysics, UsdLux, UsdShade, Sdf, Gf, Tf
# Get stage.
stage = omni.usd.get_context().get_stage()
# Create distant light.
pathName = "/World/distantLight"
light = UsdLux.DistantLight.Define(stage, pathName)
# Set intensity.
light.CreateIntensityAttr(100.0)
# Set color.
light.CreateColorAttr(Gf.Vec3f(1.0, 0.5, 0.2))
# Set Exposure.
light.CreateExposureAttr(0.0)
# Compute extent.
boundable = UsdGeom.Boundable(light.GetPrim())
extent = boundable.ComputeExtent(Usd.TimeCode(0))
# Set Extent.
light.CreateExtentAttr(extent)
|
ft-lab/omniverse_sample_scripts/Nucleus/createFolder.py | # See : https://docs.omniverse.nvidia.com/py/kit/source/extensions/omni.client/docs/index.html
import asyncio
import omni.client
# The following should be rewritten for your environment.
url = "omniverse://localhost/test/new_folder"
result = omni.client.create_folder(url)
if result == omni.client.Result.OK:
print("success !")
else:
print("failed ...")
|
ft-lab/omniverse_sample_scripts/Nucleus/readme.md | # Nucleus
OmniverseではUSDからの保存はNucleusの指定のパス(omniverse://localhost/xxx/yyy.usd)に出力できます。
別途、Nucleus上でファイル操作を行う「omni.client」が用意されています。
## 参考
https://docs.omniverse.nvidia.com/py/kit/source/extensions/omni.client/docs/index.html
## サンプル
|ファイル|説明|
|---|---|
|[existPath.py](./existPath.py)|Nucleus上のファイルまたはフォルダが存在するかチェック。|
|[listFiles.py](./listFiles.py)|Nucleus上の指定のフォルダ内のファイルを一覧。|
|[FileCopy.py](./FileCopy.py)|ローカルからNucleus上にファイルを転送。|
|[createFolder.py](./createFolder.py)|Nucleus上にフォルダを作成。|
|[deleteFile.py](./deleteFile.py)|Nucleus上のファイルやフォルダを削除。|
|[ReadImageFile.py](./ReadImageFile.py)|Nucleus上の画像ファイルをPIL.Imageに読み込み。|
|
ft-lab/omniverse_sample_scripts/Nucleus/existPath.py | # See : https://docs.omniverse.nvidia.com/py/kit/source/extensions/omni.client/docs/index.html
import asyncio
import omni.client
# Check for the existence of the specified path.
async def existPath (path : str):
(result, entry) = await omni.client.stat_async(path)
if result == omni.client.Result.ERROR_NOT_FOUND:
print("Does not exist : " + path)
return
print("Exist : " + path)
# Awaiting results.
async def _ocl_existPath (path : str):
(result, entry) = await omni.client.stat_async(path)
if result == omni.client.Result.ERROR_NOT_FOUND:
return False
return True
def ocl_existPath (path : str):
loop = asyncio.get_event_loop()
return loop.run_until_complete(_ocl_existPath(path))
# ------------------------------------------.
path1 = "omniverse://localhost/Users/test"
asyncio.ensure_future(existPath(path1))
path2 = "omniverse://localhost/Users/test/xxx.usd"
asyncio.ensure_future(existPath(path2))
if ocl_existPath(path1):
print("Exist : " + path1)
else:
print("Does not exist : " + path1)
|
ft-lab/omniverse_sample_scripts/Nucleus/deleteFile.py | # See : https://docs.omniverse.nvidia.com/py/kit/source/extensions/omni.client/docs/index.html
import asyncio
import omni.client
# The following should be rewritten for your environment.
url = "omniverse://localhost/test/new_folder"
# Delete file or folder.
result = omni.client.delete(url)
if result == omni.client.Result.OK:
print("success !")
else:
print("failed ...")
|
ft-lab/omniverse_sample_scripts/Nucleus/listFiles.py | # See : https://docs.omniverse.nvidia.com/py/kit/source/extensions/omni.client/docs/index.html
import asyncio
import omni.client
# Lists files in the specified path.
async def listFiles (_depth : int, _path : str):
(result, entries) = await omni.client.list_async(_path)
if result != omni.client.Result.OK:
return
for entry in entries:
# Skip for Channel file.
if (entry.flags & omni.client.ItemFlags.IS_CHANNEL) != 0:
continue
name = entry.relative_path
if name == "" or name.find(".") == 0:
continue
path = _path + "/" + name
isFolder = (entry.flags & omni.client.ItemFlags.CAN_HAVE_CHILDREN) != 0
msg = ""
for i in range(_depth):
msg += " "
if isFolder:
msg += "[" + name + "]"
else:
msg += name
msg += " "
if (entry.flags & omni.client.ItemFlags.READABLE_FILE) != 0:
msg += " [R]"
if (entry.flags & omni.client.ItemFlags.WRITEABLE_FILE) != 0:
msg += " [W]"
if (entry.flags & omni.client.ItemFlags.CAN_LIVE_UPDATE) != 0:
msg += " [LiveUpdate]"
if not isFolder:
msg += f" {entry.size} bytes"
print(msg)
if isFolder:
await listFiles(_depth + 1, path)
# -----------------------------------------------.
path1 = "omniverse://localhost/Users/test"
asyncio.ensure_future(listFiles(0, path1))
|
ft-lab/omniverse_sample_scripts/Nucleus/ReadImageFile.py | # See : https://docs.omniverse.nvidia.com/py/kit/source/extensions/omni.client/docs/index.html
import io
import omni.client
from PIL import Image
result, vers, content = omni.client.read_file("omniverse://localhost/Users/test/xxx.png")
if result != omni.client.Result.ERROR_NOT_FOUND:
image_data = memoryview(content).tobytes()
image = Image.open(io.BytesIO(image_data))
# Show Image.
image.show()
# Save Image.
#image.save("C:\\temp\\xxx.png")
|
ft-lab/omniverse_sample_scripts/Nucleus/FileCopy.py | # See : https://docs.omniverse.nvidia.com/py/kit/source/extensions/omni.client/docs/index.html
import asyncio
import omni.client
# The following should be rewritten for your environment.
srcURL = "K:\\NVIDIA_omniverse\\images\\tile_image.png"
dstURL = "omniverse://localhost/test/tile_image.png"
# Copy a file or folder.
# When copying is complete, proceed.
result = omni.client.copy(srcURL, dstURL)
if result == omni.client.Result.OK:
print("success !")
else:
print("failed ...")
|
ft-lab/omniverse_sample_scripts/Physics/RayCast.py | from pxr import Usd, UsdGeom, UsdPhysics, UsdShade, Sdf, Gf, Tf
import random
import omni.physx
# Get stage.
stage = omni.usd.get_context().get_stage()
# Y-Up.
UsdGeom.SetStageUpAxis(stage, UsdGeom.Tokens.y)
# Get default prim.
defaultPrim = stage.GetDefaultPrim()
defaultPrimPath = defaultPrim.GetPath().pathString
# Physics scene definition.
scene = UsdPhysics.Scene.Define(stage, defaultPrimPath + '/physicsScene')
scene.CreateGravityDirectionAttr().Set(Gf.Vec3f(0.0, -1.0, 0.0))
scene.CreateGravityMagnitudeAttr().Set(981.0)
# --------------------------------------------.
# Create cube.
# --------------------------------------------.
def CreateCube (name : str, pos : Gf.Vec3f, scale : Gf.Vec3f):
path = defaultPrimPath + '/cubes'
prim = stage.GetPrimAtPath(path)
if prim.IsValid() == False:
UsdGeom.Xform.Define(stage, path)
cubePath = path + '/' + name
cubeGeom = UsdGeom.Cube.Define(stage, cubePath)
# Set cube size.
cubeGeom.CreateSizeAttr(10.0)
# Set color.
cubeGeom.CreateDisplayColorAttr([(0.0, 1.0, 0.0)])
# Set position.
UsdGeom.XformCommonAPI(cubeGeom).SetTranslate((pos[0], pos[1], pos[2]))
# Set scale.
UsdGeom.XformCommonAPI(cubeGeom).SetScale((scale[0], scale[1], scale[2]))
# Physics settings.
cubePrim = stage.GetPrimAtPath(cubePath)
UsdPhysics.CollisionAPI.Apply(cubePrim)
# --------------------------------------------.
# Create red sphere.
# --------------------------------------------.
def CreateRedSphere (name : str, pos : Gf.Vec3f, radius : float):
path = defaultPrimPath + '/spheres'
prim = stage.GetPrimAtPath(path)
if prim.IsValid() == False:
UsdGeom.Xform.Define(stage, path)
spherePath = path + '/' + name
sphereGeom = UsdGeom.Sphere.Define(stage, spherePath)
# Set radius.
sphereGeom.CreateRadiusAttr(radius)
# Set color.
sphereGeom.CreateDisplayColorAttr([(1.0, 0.0, 0.0)])
# Set position.
UsdGeom.XformCommonAPI(sphereGeom).SetTranslate((pos[0], pos[1], pos[2]))
# ------------------------------------------------------.
# Create cubes.
areaV = 100.0
cubeScale = 1.0
for i in range(50):
posX = (random.random() - 0.5) * areaV
posY = (random.random() - 0.5) * (areaV * 0.1)
posZ = (random.random() - 0.5) * areaV + 100.0
pos = Gf.Vec3f(posX, posY, posZ)
scale = Gf.Vec3f(cubeScale, cubeScale, cubeScale)
name = 'cube_' + str(i)
CreateCube(name, pos, scale)
# Remove spheres.
path = defaultPrimPath + '/spheres'
prim = stage.GetPrimAtPath(path)
if prim.IsValid():
stage.RemovePrim(path)
# Callback for Rayhit.
# rayhit works during animation playback.
sphereIndex = 0
def ray_hit (hit):
global sphereIndex
print("distance : " + str(hit.distance))
print("Hit position : " + str(hit.position))
print("Hit normal : " + str(hit.normal))
print("Collision prim path : " + str(hit.collision))
# Get collision prim.
prim = stage.GetPrimAtPath(hit.collision)
print(" name : " + str(prim.GetName()))
print("-----------------------------")
# Create sphere.
name = "sphere_" + str(sphereIndex)
CreateRedSphere(name, hit.position, 1.0)
sphereIndex += 1
for i in range(100):
# Ray position.
rayPos = Gf.Vec3f(0, 0, 0)
# Ray direction.
dx = (random.random() - 0.5) * 0.3
dy = (random.random() - 0.5) * 0.3
dz = 1.0
rayDir = Gf.Vec3f(dx, dy, dz).GetNormalized()
# Ray distance.
distance = 10000.0
# raycast.
omni.physx.get_physx_scene_query_interface().raycast_all(rayPos, rayDir, distance, ray_hit)
|
ft-lab/omniverse_sample_scripts/Physics/readme.md | # Physics
Physicsのサンプルです。
Physicsの計算はGPU上で行われます。
PhysicsはUSDのUsdPhysics ( https://graphics.pixar.com/usd/release/api/usd_physics_page_front.html ) が使用されます。
## Physicsデモ
Physicsのデモは、Omniverse Createのメインメニューの「Window」-「Physics」-「Demo Scenes」から確認でき、Extensionとしてのソースはすべて公開されているため参考になります。
また、メインメニューの「Help」-「Physics Scripting Manual」から表示されるドキュメントに、
Physicsを使用する場合の説明がされています。
これらの情報はかなり詳しく書かれており分かりやすいですので、PhysicsについてはOmniverse Create上のPhysicsデモから学習するほうが理解が深まると思います。
## Physicsのアニメーションが遅い場合
デフォルトでは、Physicsの剛体を配置してアニメーション再生すると重いです。
これは、アニメーション時にフレームごとにUSDを更新する書き込みが走るのが原因になります。
USD Composer 2023.2.1の場合は、Viewportの設定から Show By Type - Physics - Simulation Settings を選択。
Simulation Settingsウィンドウで"Fabric GPU"を選択します。

## サンプル
|ファイル|説明|
|---|---|
|[RayCast.py](./RayCast.py)|Collisionの形状を配置し、レイの始点と向きを指定して衝突判定します。<br>このRayCastはアニメーション再生中に機能します。<br>|
|サンプル|説明|
|---|---|
|[simpleJoint01.py](./Joint/simpleJoint01.py)|2つのCubeをつなぐ簡単なジョイント<br>|
|[simpleJoint02.py](./Joint/simpleJoint02.py)|3つのCubeをつなぐ簡単なジョイント<br>|
|[rigidBody_01.py](./RigidBody/rigidBody_01.py)|RigidBodyによる簡単な自由落下<br>|
|[rigidbody_benchmark.py](./RigidBody/rigidbody_benchmark.py)|RigidBodyによる球の自由落下。<br>たくさんの球を配置。<br>|
|[gear_01.py](./Gear/gear_01.py)|歯車の回転。<br>アニメーション再生中に、歯車を回転させると連動します。<br>|
|
ft-lab/omniverse_sample_scripts/Physics/RigidBody/rigidbody_benchmark.py | from pxr import Usd, UsdGeom, UsdPhysics, UsdShade, Sdf, Gf, Tf
import math
import random
# Get stage.
g_stage = omni.usd.get_context().get_stage()
# Y-Up.
UsdGeom.SetStageUpAxis(g_stage, UsdGeom.Tokens.y)
# Physics scene definition.
scene = UsdPhysics.Scene.Define(g_stage, "/physicsScene")
scene.CreateGravityDirectionAttr().Set(Gf.Vec3f(0.0, -1.0, 0.0))
scene.CreateGravityMagnitudeAttr().Set(981.0)
# Create Xform.
g_basePath = '/World/spheres'
xformPrim = UsdGeom.Xform.Define(g_stage, g_basePath)
# --------------------------------------------------------.
# Create ground.
# --------------------------------------------------------.
def createGround ():
# Create cube.
path = '/World/ground'
cubeGeom = UsdGeom.Cube.Define(g_stage, path)
# Set color.
cubeGeom.CreateDisplayColorAttr([(0.2, 0.2, 0.2)])
# Set position.
UsdGeom.XformCommonAPI(cubeGeom).SetTranslate((0.0, -5.0, 0.0))
# Set scale.
UsdGeom.XformCommonAPI(cubeGeom).SetScale((200.0, 10, 200.0))
# Create collider.
objPrim = g_stage.GetPrimAtPath(path)
UsdPhysics.CollisionAPI.Apply(objPrim)
# --------------------------------------------------------.
# Create sphere.
# @param[in] index serial number.
# @param[in] radius radius of sphere.
# @param[in] wPos world position (x, y, z).
# @param[in] colorV color (red, green, blue).
# --------------------------------------------------------.
def createSphere(index, radius, wPos, colorV):
# Create sphere.
name = 'sphere_' + str(index)
path = g_basePath + '/' + name
spherePrim = UsdGeom.Sphere.Define(g_stage, path)
# Set radius.
spherePrim.CreateRadiusAttr(radius)
# Set color.
spherePrim.CreateDisplayColorAttr([colorV])
objPrim = g_stage.GetPrimAtPath(path)
# Set position.
UsdGeom.XformCommonAPI(spherePrim).SetTranslate(wPos)
# Create collider.
UsdPhysics.CollisionAPI.Apply(objPrim)
UsdPhysics.MeshCollisionAPI(objPrim).CreateApproximationAttr("boundingSphere")
UsdPhysics.MeshCollisionAPI.Apply(objPrim)
# Rigid body.
rigidBodyAPI = UsdPhysics.RigidBodyAPI.Apply(objPrim)
# --------------------------------------------------------.
# Create cube.
# @param[in] wPos world position (x, y, z).
# @param[in] wSize size (x, y, z).
# --------------------------------------------------------.
def createCube (index, wPos, wSize):
name = 'cube_' + str(index)
path = '/World/' + name
cubePrim = UsdGeom.Cube.Define(g_stage, path)
# Set cube size.
cubePrim.CreateSizeAttr(1.0)
# Set color.
cubePrim.CreateDisplayColorAttr([(0.2, 0.2, 0.2)])
# Set position.
UsdGeom.XformCommonAPI(cubePrim).SetTranslate((wPos[0], wPos[1], wPos[2]))
# Set scale.
UsdGeom.XformCommonAPI(cubePrim).SetScale((wSize[0], wSize[1], wSize[2]))
# Create collider.
objPrim = g_stage.GetPrimAtPath(path)
UsdPhysics.CollisionAPI.Apply(objPrim)
# --------------------------------------------------------.
# Create wall.
# --------------------------------------------------------.
def createWall ():
createCube(0, [-200.0, 25.0, 0.0], [ 10.0, 50.0, 400.0])
createCube(1, [ 200.0, 25.0, 0.0], [ 10.0, 50.0, 400.0])
createCube(2, [ 0.0, 25.0, -200.0], [400.0, 50.0, 10.0])
createCube(3, [ 0.0, 25.0, 200.0], [400.0, 50.0, 10.0])
# -----------------------------------------------------------.
# -----------------------------------------------------------.
# Create ground.
createGround()
# Create wall.
createWall()
# Create spheres.
sR = 5.0
dd = 15.0
sCount = 16
dMin = dd * (float)(sCount) * 0.5
i = 0
fy = 30.0
for y in range(10):
fz = -dMin
for z in range(sCount):
fx = -dMin
for x in range(sCount):
colR = random.random()
colG = random.random()
colB = random.random()
dx = random.random() * 5.0
dz = random.random() * 5.0
createSphere(i, sR, (fx + dx, fy, fz + dz), (colR, colG, colB))
i = i + 1
fx += dd
fz += dd
fy += dd
|
ft-lab/omniverse_sample_scripts/Physics/RigidBody/rigidBody_01.py | from pxr import Usd, UsdGeom, UsdPhysics, UsdShade, Sdf, Gf, Tf
import math
import random
# Get stage.
g_stage = omni.usd.get_context().get_stage()
# Y-Up.
UsdGeom.SetStageUpAxis(g_stage, UsdGeom.Tokens.y)
# Physics scene definition.
scene = UsdPhysics.Scene.Define(g_stage, "/physicsScene")
scene.CreateGravityDirectionAttr().Set(Gf.Vec3f(0.0, -1.0, 0.0))
scene.CreateGravityMagnitudeAttr().Set(981.0)
# Create Xform.
g_basePath = '/World/spheres'
xformPrim = UsdGeom.Xform.Define(g_stage, g_basePath)
# --------------------------------------------------------.
# Create ground.
# --------------------------------------------------------.
def createGround ():
# Create cube.
path = '/World/ground'
cubeGeom = UsdGeom.Cube.Define(g_stage, path)
# Set color.
cubeGeom.CreateDisplayColorAttr([(0.2, 0.2, 0.2)])
# Set position.
UsdGeom.XformCommonAPI(cubeGeom).SetTranslate((0.0, -5.0, 0.0))
# Set scale.
UsdGeom.XformCommonAPI(cubeGeom).SetScale((200.0, 10, 200.0))
# Create collider.
objPrim = g_stage.GetPrimAtPath(path)
UsdPhysics.CollisionAPI.Apply(objPrim)
# --------------------------------------------------------.
# Create sphere.
# @param[in] index serial number.
# @param[in] radius radius of sphere.
# @param[in] wPos world position (x, y, z).
# @param[in] colorV color (red, green, blue).
# --------------------------------------------------------.
def createSphere(index, radius, wPos, colorV):
# Create sphere.
name = 'sphere_' + str(index)
path = g_basePath + '/' + name
spherePrim = UsdGeom.Sphere.Define(g_stage, path)
# Set radius.
spherePrim.CreateRadiusAttr(radius)
# Set color.
spherePrim.CreateDisplayColorAttr([colorV])
objPrim = g_stage.GetPrimAtPath(path)
# Set position.
UsdGeom.XformCommonAPI(spherePrim).SetTranslate(wPos)
# Create collider.
UsdPhysics.CollisionAPI.Apply(objPrim)
UsdPhysics.MeshCollisionAPI(objPrim).CreateApproximationAttr("boundingSphere")
UsdPhysics.MeshCollisionAPI.Apply(objPrim)
# Rigid body.
rigidBodyAPI = UsdPhysics.RigidBodyAPI.Apply(objPrim)
# -----------------------------------------------------------.
# -----------------------------------------------------------.
# Create ground.
createGround()
# Create spheres.
r = 100.0
sR = 10.0
rCount = 32
fV = 0.0
fVD = 2.0 * math.pi / (float)(rCount)
fy = 50.0
fyD = 1.0
for i in range(200):
fx = r * math.cos(fV)
fz = r * math.sin(fV)
colR = random.random()
colG = random.random()
colB = random.random()
createSphere(i, sR, (fx, fy, fz), (colR, colG, colB))
fV += fVD
fy += fyD
if (i & 15) == 15:
r *= 0.9
sR *= 0.9 |
ft-lab/omniverse_sample_scripts/Physics/Joint/simpleJoint02.py | from pxr import Usd, UsdGeom, UsdPhysics, UsdShade, Sdf, Gf, Tf
# Get stage.
stage = omni.usd.get_context().get_stage()
# Y-Up.
UsdGeom.SetStageUpAxis(stage, UsdGeom.Tokens.y)
rootPath = '/World'
# Physics scene definition.
scene = UsdPhysics.Scene.Define(stage, rootPath + '/physicsScene')
scene.CreateGravityDirectionAttr().Set(Gf.Vec3f(0.0, -1.0, 0.0))
scene.CreateGravityMagnitudeAttr().Set(981.0)
hPos = 15.0
# --------------------------------------------.
# cube0.
# --------------------------------------------.
cube0Path = rootPath + '/cube0'
cube0Geom = UsdGeom.Cube.Define(stage, cube0Path)
# Set cube size.
cube0Geom.CreateSizeAttr(10.0)
# Set color.
cube0Geom.CreateDisplayColorAttr([(0.0, 1.0, 0.0)])
# Set position.
UsdGeom.XformCommonAPI(cube0Geom).SetTranslate((0.0, hPos, 0.0))
# Set scale.
UsdGeom.XformCommonAPI(cube0Geom).SetScale((2.0, 0.5, 0.5))
# --------------------------------------------.
# cube1.
# --------------------------------------------.
cube1Path = rootPath + '/cube1'
cube1Geom = UsdGeom.Cube.Define(stage, cube1Path)
# Set cube size.
cube1Geom.CreateSizeAttr(10.0)
# Set color.
cube1Geom.CreateDisplayColorAttr([(0.0, 0.0, 1.0)])
# Set position.
UsdGeom.XformCommonAPI(cube1Geom).SetTranslate((21.0, hPos, 0.0))
# Set scale.
UsdGeom.XformCommonAPI(cube1Geom).SetScale((2.0, 0.5, 0.5))
# --------------------------------------------.
# cube2.
# --------------------------------------------.
cube2Path = rootPath + '/cube2'
cube2Geom = UsdGeom.Cube.Define(stage, cube2Path)
# Set cube size.
cube2Geom.CreateSizeAttr(10.0)
# Set color.
cube2Geom.CreateDisplayColorAttr([(0.0, 1.0, 1.0)])
# Set position.
UsdGeom.XformCommonAPI(cube2Geom).SetTranslate((42.0, hPos, 0.0))
# Set scale.
UsdGeom.XformCommonAPI(cube2Geom).SetScale((2.0, 0.5, 0.5))
# --------------------------------------------.
# Physics settings.
# --------------------------------------------.
# cube0 : static body
cube0Prim = stage.GetPrimAtPath(cube0Path)
UsdPhysics.CollisionAPI.Apply(cube0Prim)
# cube1 : dynamic body
cube1Prim = stage.GetPrimAtPath(cube1Path)
UsdPhysics.CollisionAPI.Apply(cube1Prim)
UsdPhysics.RigidBodyAPI.Apply(cube1Prim)
# cube2 : dynamic body
cube2Prim = stage.GetPrimAtPath(cube2Path)
UsdPhysics.CollisionAPI.Apply(cube2Prim)
UsdPhysics.RigidBodyAPI.Apply(cube2Prim)
# ----------------------------------------.
# Setup joint.
# ----------------------------------------.
jointPath = rootPath + '/revoluteJoint'
revoluteJoint = UsdPhysics.RevoluteJoint.Define(stage, jointPath)
# define revolute joint axis and its limits, defined in degrees
revoluteJoint.CreateAxisAttr("Z")
revoluteJoint.CreateLowerLimitAttr(-50.0)
revoluteJoint.CreateUpperLimitAttr(50.0)
# define revolute joint bodies
revoluteJoint.CreateBody0Rel().SetTargets([cube0Path])
revoluteJoint.CreateBody1Rel().SetTargets([cube1Path])
# define revolute joint local poses for bodies
revoluteJoint.CreateLocalPos0Attr().Set(Gf.Vec3f(5.25, 0.0, 0.0))
revoluteJoint.CreateLocalRot0Attr().Set(Gf.Quatf(1.0))
revoluteJoint.CreateLocalPos1Attr().Set(Gf.Vec3f(-5.25, 0.0, 0.0))
revoluteJoint.CreateLocalRot1Attr().Set(Gf.Quatf(1.0))
# set break force/torque
revoluteJoint.CreateBreakForceAttr().Set(1e20)
revoluteJoint.CreateBreakTorqueAttr().Set(1e20)
# optionally add angular drive for example
angularDriveAPI = UsdPhysics.DriveAPI.Apply(stage.GetPrimAtPath(jointPath), "angular")
angularDriveAPI.CreateTypeAttr("force")
angularDriveAPI.CreateMaxForceAttr(100.0)
angularDriveAPI.CreateTargetVelocityAttr(1.0)
angularDriveAPI.CreateDampingAttr(100.0)
angularDriveAPI.CreateStiffnessAttr(0.0)
# ----------------------------------------.
# Setup joint2.
# ----------------------------------------.
jointPath2 = rootPath + '/revoluteJoint2'
revoluteJoint2 = UsdPhysics.RevoluteJoint.Define(stage, jointPath2)
# define revolute joint axis and its limits, defined in degrees
revoluteJoint2.CreateAxisAttr("Z")
revoluteJoint2.CreateLowerLimitAttr(-50.0)
revoluteJoint2.CreateUpperLimitAttr(50.0)
# define revolute joint bodies
revoluteJoint2.CreateBody0Rel().SetTargets([cube1Path])
revoluteJoint2.CreateBody1Rel().SetTargets([cube2Path])
# define revolute joint local poses for bodies
revoluteJoint2.CreateLocalPos0Attr().Set(Gf.Vec3f(5.25, 0.0, 0.0))
revoluteJoint2.CreateLocalRot0Attr().Set(Gf.Quatf(1.0))
revoluteJoint2.CreateLocalPos1Attr().Set(Gf.Vec3f(-5.25, 0.0, 0.0))
revoluteJoint2.CreateLocalRot1Attr().Set(Gf.Quatf(1.0))
# set break force/torque
revoluteJoint2.CreateBreakForceAttr().Set(1e20)
revoluteJoint2.CreateBreakTorqueAttr().Set(1e20)
# optionally add angular drive for example
#angularDriveAPI2 = UsdPhysics.DriveAPI.Apply(stage.GetPrimAtPath(jointPath2), "angular")
#angularDriveAPI2.CreateTypeAttr("force")
#angularDriveAPI2.CreateMaxForceAttr(100.0)
#angularDriveAPI2.CreateTargetVelocityAttr(1.0)
#angularDriveAPI2.CreateDampingAttr(100.0)
#angularDriveAPI2.CreateStiffnessAttr(0.0)
|
ft-lab/omniverse_sample_scripts/Physics/Joint/simpleJoint01.py | from pxr import Usd, UsdGeom, UsdPhysics, UsdShade, Sdf, Gf, Tf
# Get stage.
stage = omni.usd.get_context().get_stage()
# Y-Up.
UsdGeom.SetStageUpAxis(stage, UsdGeom.Tokens.y)
rootPath = '/World'
# Physics scene definition.
scene = UsdPhysics.Scene.Define(stage, rootPath + '/physicsScene')
scene.CreateGravityDirectionAttr().Set(Gf.Vec3f(0.0, -1.0, 0.0))
scene.CreateGravityMagnitudeAttr().Set(981.0)
hPos = 15.0
# --------------------------------------------.
# cube0.
# --------------------------------------------.
cube0Path = rootPath + '/cube0'
cube0Geom = UsdGeom.Cube.Define(stage, cube0Path)
# Set cube size.
cube0Geom.CreateSizeAttr(10.0)
# Set color.
cube0Geom.CreateDisplayColorAttr([(0.0, 1.0, 0.0)])
# Set position.
UsdGeom.XformCommonAPI(cube0Geom).SetTranslate((0.0, hPos, 0.0))
# Set scale.
UsdGeom.XformCommonAPI(cube0Geom).SetScale((2.0, 0.5, 0.5))
# --------------------------------------------.
# cube1.
# --------------------------------------------.
cube1Path = rootPath + '/cube1'
cube1Geom = UsdGeom.Cube.Define(stage, cube1Path)
# Set cube size.
cube1Geom.CreateSizeAttr(10.0)
# Set color.
cube1Geom.CreateDisplayColorAttr([(0.0, 0.0, 1.0)])
# Set position.
UsdGeom.XformCommonAPI(cube1Geom).SetTranslate((21.0, hPos, 0.0))
# Set scale.
UsdGeom.XformCommonAPI(cube1Geom).SetScale((2.0, 0.5, 0.5))
# --------------------------------------------.
# Physics settings.
# --------------------------------------------.
# cube0 : static body
cube0Prim = stage.GetPrimAtPath(cube0Path)
UsdPhysics.CollisionAPI.Apply(cube0Prim)
# cube1 : dynamic body
cube1Prim = stage.GetPrimAtPath(cube1Path)
UsdPhysics.CollisionAPI.Apply(cube1Prim)
UsdPhysics.RigidBodyAPI.Apply(cube1Prim)
# Setup joint.
jointPath = rootPath + '/revoluteJoint'
revoluteJoint = UsdPhysics.RevoluteJoint.Define(stage, jointPath)
# define revolute joint axis and its limits, defined in degrees
revoluteJoint.CreateAxisAttr("Z")
revoluteJoint.CreateLowerLimitAttr(-90.0)
revoluteJoint.CreateUpperLimitAttr(90.0)
# define revolute joint bodies
revoluteJoint.CreateBody0Rel().SetTargets([cube0Path])
revoluteJoint.CreateBody1Rel().SetTargets([cube1Path])
# define revolute joint local poses for bodies
revoluteJoint.CreateLocalPos0Attr().Set(Gf.Vec3f(5.25, 0.0, 0.0))
revoluteJoint.CreateLocalRot0Attr().Set(Gf.Quatf(1.0))
revoluteJoint.CreateLocalPos1Attr().Set(Gf.Vec3f(-5.25, 0.0, 0.0))
revoluteJoint.CreateLocalRot1Attr().Set(Gf.Quatf(1.0))
# set break force/torque
revoluteJoint.CreateBreakForceAttr().Set(1e20)
revoluteJoint.CreateBreakTorqueAttr().Set(1e20)
# optionally add angular drive for example
angularDriveAPI = UsdPhysics.DriveAPI.Apply(stage.GetPrimAtPath(jointPath), "angular")
angularDriveAPI.CreateTypeAttr("force")
angularDriveAPI.CreateMaxForceAttr(1e20)
angularDriveAPI.CreateTargetVelocityAttr(1.0)
angularDriveAPI.CreateDampingAttr(1e10)
angularDriveAPI.CreateStiffnessAttr(0.0)
|
ft-lab/omniverse_sample_scripts/Physics/Gear/gear_01.py | from pxr import Usd, UsdGeom, UsdPhysics, UsdShade, Sdf, Gf, Tf, UsdSkel, PhysxSchema
import math
# Get stage.
g_stage = omni.usd.get_context().get_stage()
# gear path.
gear_basePath = '/World/gears'
# Y-Up.
UsdGeom.SetStageUpAxis(g_stage, UsdGeom.Tokens.y)
xformCache = UsdGeom.XformCache(0)
# -------------------------------------------------------.
# Calculate normal.
# -------------------------------------------------------.
def calcTriangleNormal (v1 : Gf.Vec3d, v2 : Gf.Vec3d, v3 : Gf.Vec3d):
e1 = v2 - v1
e2 = v3 - v2
e1 = Gf.Vec4f(e1[0], e1[1], e1[2],1.0)
e2 = Gf.Vec4f(e2[0], e2[1], e2[2],1.0)
e3 = Gf.HomogeneousCross(e1, e2)
n = Gf.Vec3d(e3[0], e3[1], e3[2])
return n.GetNormalized()
# -------------------------------------------------------.
# Attach thickness.
# @param[in] primPath Target Prim path.
# @param[in] thickness Thickness.
# -------------------------------------------------------.
def AttachThickness (primPath : str, thickness : float):
prim = g_stage.GetPrimAtPath(primPath)
if prim.IsValid() == False:
return
if prim.GetTypeName() != 'Mesh':
return
m = UsdGeom.Mesh(prim)
# Number of faces.
faceVCouList = m.GetFaceVertexCountsAttr().Get()
faceCou = len(faceVCouList)
if faceCou == 0:
return
normalsList = m.GetNormalsAttr().Get()
normalsCou = len(normalsList)
if normalsCou == 0:
return
normalV = normalsList[0]
versList = m.GetPointsAttr().Get()
versCou = len(versList)
if versCou < 3:
return
faceVIList = m.GetFaceVertexIndicesAttr().Get()
faceVICou = len(faceVIList)
# Stores the face number for each vertex.
vFList = [[]] * (versCou)
for i in range(versCou):
vFList[i] = []
index = 0
for i in range(len(faceVCouList)):
faceVCou = faceVCouList[i]
for j in range(faceVCou):
vI = faceVIList[index + j]
vFList[vI].append(i)
index += faceVCou
faceIndicesList = [[]] * faceCou
for i in range(faceCou):
faceIndicesList[i] = []
# Rearrange the vertex indices per face.
index = 0
for i in range(faceCou):
faceVCou = faceVCouList[i]
for j in range(faceVCou):
faceIndicesList[i].append(faceVIList[index + j])
index += faceVCou
# Create a list of independent edges.
edgesList = []
for i in range(faceCou):
faceVCou = faceVCouList[i]
for j in range(faceVCou):
vI1 = faceIndicesList[i][j]
vI2 = faceIndicesList[i][(j + 1) % faceVCou]
chkF = False
cI = -1
for k in range(len(edgesList)):
if (edgesList[k][0] == vI1 and edgesList[k][1] == vI2) or (edgesList[k][0] == vI2 and edgesList[k][1] == vI1):
chkF = True
cI = k
break
if chkF == False:
edgesList.append([vI1, vI2, 1])
else:
cou = edgesList[cI][2]
edgesList[cI] = [vI1, vI2, cou + 1]
edgesOneList = []
for p in edgesList:
if p[2] == 1:
edgesOneList.append([p[0], p[1]])
# Create a symmetrical face.
faceVCouList2 = [0] * (faceCou * 2)
normalsList2 = [(0.0, 0.0, 0.0)] * (normalsCou * 2)
versList2 = [(0.0, 0.0, 0.0)] * (versCou * 2)
faceVIList2 = [0] * (faceVICou * 2)
for i in range(faceCou):
faceVCouList2[i] = faceVCouList[i]
faceVCouList2[i + faceCou] = faceVCouList[i]
for i in range(faceVICou):
faceVIList2[i] = faceVIList[i]
faceVIList2[i + faceVICou] = faceVIList[faceVICou - i - 1] + versCou
for i in range(normalsCou):
normalsList2[i] = normalsList[i]
normalsList2[i + normalsCou] = -normalsList[i]
for i in range(versCou):
versList2[i] = versList[i]
n = normalsList[i]
versList2[i + versCou] = versList[i] - (n * thickness)
# Create side faces.
vIndex = len(versList2)
for edgeI in edgesOneList:
e1 = edgeI[0]
e2 = edgeI[1]
i1 = e1
i2 = e2
i3 = e1 + versCou
i4 = e2 + versCou
v1 = versList2[i2]
v2 = versList2[i1]
v3 = versList2[i3]
v4 = versList2[i4]
n = calcTriangleNormal(v1, v2, v3)
faceVCouList2.append(4)
for j in range(4):
normalsList2.append(n)
versList2.append(v1)
versList2.append(v2)
versList2.append(v3)
versList2.append(v4)
for j in range(4):
faceVIList2.append(vIndex + j)
vIndex += 4
m.CreatePointsAttr(versList2)
m.CreateNormalsAttr(normalsList2)
m.CreateFaceVertexCountsAttr(faceVCouList2)
m.CreateFaceVertexIndicesAttr(faceVIList2)
# -------------------------------------------------------.
# Create gear.
# @param[in] name Prim name.
# @param[in] gearR Radius of gear.
# @param[in] filletCount Number of gear divisions.
# @param[in] filletHeight Fillet height.
# @param[in] gearWidth Gear width.
# @param[in] position position.
# -------------------------------------------------------.
def CreateGear (name : str, gearR : float, filletCount : int, filletHeight : float, gearWidth : float, position : Gf.Vec3f):
angle = 360.0 / filletCount # Angle of one tooth.
# Calculate the length of one tooth on the circumference.
D = (gearR * math.sin((angle / 2.0) * math.pi / 180.0)) * 2
dHalf = D * 0.5
dQuarter = D * 0.25
centerV = Gf.Vec3d(0, 0, 0)
versList = []
versList.append(centerV)
faceIndexList = []
maxVCou = 1 + (5 * filletCount)
index = 1
aV = 0.0
for i in range(filletCount):
# Vertices of a single tooth.
vDirX = math.cos(aV * math.pi / 180.0)
vDirY = math.sin(aV * math.pi / 180.0)
v2X = -vDirY
v2Y = vDirX
vD = Gf.Vec3d(vDirX, vDirY, 0)
vCrossD = Gf.Vec3d(v2X, v2Y, 0)
vCenter = vD * gearR
v1 = vCenter - (vCrossD * dHalf)
v2 = v1 + (vCrossD * dQuarter)
v3 = v2 + (vD * filletHeight)
v4 = v3 + (vCrossD * dHalf)
v5 = v4 - (vD * filletHeight)
v6 = v5 + (vCrossD * dQuarter)
dd = D * 0.1
vCD = vCrossD * dd
v3 += vCD
v4 -= vCD
v2 -= vCD
v5 += vCD
versList.append(v1)
versList.append(v2)
versList.append(v3)
versList.append(v4)
versList.append(v5)
faceIndexList.append(0)
faceIndexList.append(index)
faceIndexList.append(index + 1)
faceIndexList.append(index + 2)
faceIndexList.append(index + 3)
faceIndexList.append(index + 4)
if index + 5 >= maxVCou:
faceIndexList.append(1)
else:
faceIndexList.append(index + 5)
index += 5
aV += angle
# Create mesh.
pathName = "/World/gears"
prim = g_stage.GetPrimAtPath(pathName)
if prim.IsValid() == False:
UsdGeom.Xform.Define(g_stage, pathName)
pathMeshName0 = pathName + '/' + name
pathMeshName = pathMeshName0
index = 0
while True:
pathMeshName = pathMeshName0
if index > 0:
pathMeshName += '_' + str(index)
prim = g_stage.GetPrimAtPath(pathMeshName)
if prim.IsValid() == False:
break
index += 1
meshGeom = UsdGeom.Mesh.Define(g_stage, pathMeshName)
# Set vertices.
stVersList = []
stNormalList = []
for i in range(len(versList)):
stVersList.append((versList[i][0], versList[i][1], versList[i][2]))
stNormalList.append((0, 0, 1))
meshGeom.CreatePointsAttr(stVersList)
# Set normals.
meshGeom.CreateNormalsAttr(stNormalList)
# Set face vertex count.
faceVCouList = []
for i in range(filletCount):
faceVCouList.append(7)
meshGeom.CreateFaceVertexCountsAttr(faceVCouList)
# Set face vertex indices.
meshGeom.CreateFaceVertexIndicesAttr(faceIndexList)
# Set position.
UsdGeom.XformCommonAPI(meshGeom).SetTranslate((position[0], position[1], position[2]))
# Set rotation.
UsdGeom.XformCommonAPI(meshGeom).SetRotate((0.0, 0.0, 0.0), UsdGeom.XformCommonAPI.RotationOrderXYZ)
# Set scale.
UsdGeom.XformCommonAPI(meshGeom).SetScale((1.0, 1.0, 1.0))
# Attach thickness.
if gearWidth > 0.0:
AttachThickness(pathMeshName, gearWidth)
# ------------------------------------------
# Get prim center position.
# @param[in] primPath Prim path.
# @return position(Gf.Vec3f)
# ------------------------------------------
def GetPrimCenter (primPath : str):
prim = g_stage.GetPrimAtPath(primPath)
if prim.IsValid() == False:
return
globalPose = xformCache.GetLocalToWorldTransform(prim)
translate, rotation, scale = UsdSkel.DecomposeTransform(globalPose)
return translate
# ------------------------------------------
# Set RigidBody on gear.
# ------------------------------------------
def SetRigidBodyOnGear (primPath : str, index : int):
prim = g_stage.GetPrimAtPath(primPath)
if prim.IsValid() == False:
return
physicsAPI = UsdPhysics.RigidBodyAPI.Apply(prim)
UsdPhysics.MassAPI.Apply(prim)
# Create collider.
UsdPhysics.CollisionAPI.Apply(prim)
UsdPhysics.MeshCollisionAPI(prim).CreateApproximationAttr("convexHull")
UsdPhysics.MeshCollisionAPI.Apply(prim)
pos = GetPrimCenter(primPath)
# revolute joint
path = gear_basePath + '/revoluteJoint_' + str(index)
revoluteJoint = UsdPhysics.RevoluteJoint.Define(g_stage, path)
revoluteJoint.CreateAxisAttr("Z")
revoluteJoint.CreateBody1Rel().SetTargets([primPath])
revoluteJoint.CreateLocalPos0Attr().Set(pos)
revoluteJoint.CreateLocalRot0Attr().Set(Gf.Quatf(1.0))
revoluteJoint.CreateLocalPos1Attr().Set(Gf.Vec3f(0.0, 0.0, 0.0))
revoluteJoint.CreateLocalRot1Attr().Set(Gf.Quatf(1.0))
# -----------------------------------------------
# Radius.
radius1 = 5.0
radius2 = 10.0
radius3 = 6.25
# Create Gears.
CreateGear("gear", radius1, 24, 1.0, 1.0, Gf.Vec3f(0, 0, 0))
CreateGear("gear_1", radius2, 48, 1.0, 1.0, Gf.Vec3f(16.3, 0.72, 0))
CreateGear("gear_2", radius3, 30, 1.0, 1.0, Gf.Vec3f(0.0, -12.6, 0))
# gear1 path.
gear1_path = gear_basePath + '/gear'
# gear2 path.
gear2_path = gear_basePath + '/gear_1'
# gear3 path.
gear3_path = gear_basePath + '/gear_2'
# Physics scene definition.
scene = UsdPhysics.Scene.Define(g_stage, "/physicsScene")
scene.CreateGravityDirectionAttr().Set(Gf.Vec3f(0.0, -1.0, 0.0))
scene.CreateGravityMagnitudeAttr().Set(981.0)
gear1_prim = g_stage.GetPrimAtPath(gear1_path)
pos1 = GetPrimCenter(gear1_path)
# Set RigidBody on gear.
SetRigidBodyOnGear(gear1_path, 0)
SetRigidBodyOnGear(gear2_path, 1)
SetRigidBodyOnGear(gear3_path, 2)
# add angular drive.
revolute0_path = gear_basePath + "/revoluteJoint_0"
revolute1_path = gear_basePath + "/revoluteJoint_1"
revolute2_path = gear_basePath + "/revoluteJoint_2"
# gear joint (0-1)
gearJoint = PhysxSchema.PhysxPhysicsGearJoint.Define(g_stage, gear_basePath+"/gearJoint_0_1")
gearJoint.CreateBody0Rel().SetTargets([gear1_path])
gearJoint.CreateBody1Rel().SetTargets([gear2_path])
gearJoint.CreateGearRatioAttr(radius1/radius2)
gearJoint.CreateHinge0Rel().SetTargets([revolute0_path])
gearJoint.CreateHinge1Rel().SetTargets([revolute1_path])
# gear joint (0-2)
gearJoint2 = PhysxSchema.PhysxPhysicsGearJoint.Define(g_stage, gear_basePath+"/gearJoint_0_2")
gearJoint2.CreateBody0Rel().SetTargets([gear1_path])
gearJoint2.CreateBody1Rel().SetTargets([gear3_path])
gearJoint2.CreateGearRatioAttr(radius1/radius3)
gearJoint2.CreateHinge0Rel().SetTargets([revolute0_path])
gearJoint2.CreateHinge1Rel().SetTargets([revolute2_path])
|
ft-lab/omniverse_sample_scripts/PostProcessing/readme.md | # Post Processing
Post Processingの変更を行います。
Post ProcessingはOmniverse Createの「Post Processings」ウィンドウでパラメータにマウスを合わせたときのツールチップにパスが表示されています。
下記の場合は"rtx/post/lensFlares/flareScale"。

もしくはPost Processingの値を変更してusda形式でエクスポートすると、
customLayerDataで以下のように"rtx:post: ... " というパスを確認できます。
```
dictionary renderSettings = {
bool "rtx:post:lensFlares:enabled" = 1
double "rtx:post:lensFlares:flareScale" = 0.2
double "rtx:post:tonemap:fNumber" = 4.669999895617366
token "rtx:rendermode" = "PathTracing"
}
```
Pythonで以下のようにするとその値を変更できます。
```python
import omni.kit
omni.kit.commands.execute("ChangeSetting", path="rtx/post/lensFlares/enabled", value=True)
omni.kit.commands.execute("ChangeSetting", path="rtx/post/lensFlares/flareScale", value=0.2)
```
「enabled」がPost Processingのその項目自身を有効/無効にする設定です。
## サンプル
|ファイル|説明|
|---|---|
|[ChangePostProcessing.py](./ChangePostProcessing.py)|Post Processingの"FTT Bloom"のパラメータを変更します。| |
ft-lab/omniverse_sample_scripts/PostProcessing/ChangePostProcessing.py | from pxr import Usd, UsdGeom, UsdShade, Sdf, Gf, Tf
import omni.kit
# Change Post Processing parameter.
omni.kit.commands.execute("ChangeSetting", path="rtx/post/lensFlares/enabled", value=True)
omni.kit.commands.execute("ChangeSetting", path="rtx/post/lensFlares/flareScale", value=0.2)
|
ft-lab/omniverse_sample_scripts/UI/readme.md | # UI
UI関連の処理を行います。
UIは「omni.ui」からアクセスすることでさまざまなウィジットを表現できます。
UIについては生成と破棄はセットになるためExtensionで実装するほうがよいですが、Script Editorからの実行でUI表示を行うこともできます(ただし、手動で破棄処理を呼ぶ必要あり)。
|サンプル|説明|
|---|---|
|[DebugDraw](./DebugDraw)|3Dの座標指定で、Depthによる遮蔽を考慮したラインを描画 (omni.debugdrawを使用)|
|[DragAndDrop](./DragAndDrop)|UIでのドラッグ&ドロップ|
|[DrawImage](./DrawImage)|スクリーンにイメージをオーバーレイして描画|
|[Viewport](./Viewport)|ビューポートにオーバレイして表示|
|[Window](./Window)|新しいウィンドウを表示|
|
ft-lab/omniverse_sample_scripts/UI/DragAndDrop/readme.md | # DragAndDrop
UI間のドラッグ&ドロップ。
|ファイル|説明|
|---|---|
|[dropTest.py](./dropTest.py)|Primをウィンドウ内のテキスト領域にドラッグすると、パスが表示される。<br>|
|
ft-lab/omniverse_sample_scripts/UI/DragAndDrop/dropTest.py | from pxr import Usd, UsdGeom, UsdPhysics, UsdShade, Sdf, Gf, Tf
import omni.ui
# Create new window.
my_window = omni.ui.Window("Drop test window", width=300, height=200)
# ------------------------------------------.
with my_window.frame:
sField = None
# Enable Drop.
def drop_accept(url):
return True
# Called at Drop event.
def drop (uiField, event):
# prim path.
vPath = event.mime_data
# Get stage.
stage = omni.usd.get_context().get_stage()
# Get prim.
if Sdf.Path(vPath):
prim = stage.GetPrimAtPath(vPath)
if prim.IsValid():
# Set string.
uiField.model.set_value(vPath)
# Create window UI.
with omni.ui.VStack(height=0):
with omni.ui.Placer(offset_x=8, offset_y=8):
omni.ui.Label("Please drop Prim below.")
with omni.ui.Placer(offset_x=8, offset_y=0):
omni.ui.Spacer(height=4)
with omni.ui.Placer(offset_x=8, offset_y=0):
sField = omni.ui.StringField(width=240, height=14, style={"color": 0xffffffff})
sField.set_accept_drop_fn(drop_accept)
sField.set_drop_fn(lambda a, w=sField: drop(w, a))
|
ft-lab/omniverse_sample_scripts/UI/DrawImage/readme.md | # DrawImage
ビューポートに画像をオーバレイ表示します。
なお、Omniverse Code(Omniverse Kit 103を使用)では、Omniverse自身のビューポートの実装が大きく進化しているようでした (2022/01/21 確認)。
そのため、おそらく以下に列挙した描画実装は将来的には不要になると思われます。
|ファイル|説明|
|---|---|
|[drawImage.py](./drawImage.py)|omni.ui.ByteImageProviderを使用して、RGBAバッファに描画したイメージをビューポートにオーバレイ<br>|
|[drawImageWithPIL.py](./drawImageWithPIL.py)|omni.ui.ByteImageProviderを使用して、Pillow(PIL)での描画をRGBAバッファに送りビューポートにオーバレイ<br>|
|
ft-lab/omniverse_sample_scripts/UI/DrawImage/drawImageWithPIL.py | from pxr import Usd, UsdGeom, UsdPhysics, UsdShade, Sdf, Gf, Tf
import omni.ui
import omni.kit.app
import carb.events
import asyncio
import math
import itertools
# PIL exists in "kit/extscore/omni.kit.pip_archive/pip_prebundle".
from PIL import Image, ImageDraw, ImageFont
# Get main window viewport.
window = omni.ui.Window('Viewport')
# ref : omni.kit.window.images extension.py
# ------------------------------------------.
# Managing overlay image.
# ------------------------------------------.
class OverlayImageBuffer:
_width = 256
_height = 256
_byte_provider = None
_byte_data = None
def __init__(self):
self._width = 256
self._height = 256
self._byte_provider = None
self._byte_data = None
def startup (self, width : int, height : int):
self._byte_provider = omni.ui.ByteImageProvider()
self._width = width
self._height = height
# default format omni.ui.TextureFormat.RGBA8_UNORM.
self._byte_data = [0] * (4 * self._width * self._height)
self._byte_provider.set_bytes_data(self._byte_data, [self._width, self._height])
def update (self):
self._byte_provider.set_bytes_data(self._byte_data, [self._width, self._height])
# ------------------------------------------.
# Draw image with PIL.
# ------------------------------------------.
class DrawImageWithPIL:
_timeCount = 0
_image = None
_draw = None
_overlayImageBuffer = None
def __init__(self):
self._image = None
self._draw = None
self._overlayImageBuffer = None
def __del__(self):
self._image = None
self._draw = None
def getWidth (self):
return self._overlayImageBuffer._width
def getHeight (self):
return self._overlayImageBuffer._height
def getByteProvider (self):
return self._overlayImageBuffer._byte_provider
def startup (self, width : int, height : int):
# Create new image.
self._image = Image.new("RGBA", (width, height), (0, 0, 0, 0))
self._draw = ImageDraw.Draw(self._image)
self._overlayImageBuffer = OverlayImageBuffer()
self._overlayImageBuffer.startup(width, height)
def draw (self):
# Draw rectangle (fill).
self._draw.rectangle((0, 0, self._image.width, self._image.height), fill=(0, 0, 0, 0))
# Draw rectangle (fill).
self._draw.rectangle((100, 100, 200, 200), fill=(255, 0, 0))
# Draw rectangle.
self._draw.rectangle((100, 220, 200, 320), outline=(0, 0, 255), width=1)
# Draw line.
self._draw.line((0, 0, self._image.width, self._image.height), fill=(0, 255, 0), width=2)
# Draw circle.
self._draw.ellipse((100, 400, 150, 450), outline=(0, 0, 255), width=2)
# Draw circle (fill).
self._draw.ellipse((280, 300, 380, 400), fill=(0, 0, 255))
def update (self):
self.draw()
# Get image data(RGBA buffer).
imgD = self._image.getdata()
# Converting a 2d array to a 1d array.
self._overlayImageBuffer._byte_data = list(itertools.chain.from_iterable(imgD))
# Update omni.ui.ByteImageProvider.
self._overlayImageBuffer.update()
# ------------------------------------------.
# Update event.
# ------------------------------------------.
_drawImageWithPIL = None
_img1 = None
def on_update(e: carb.events.IEvent):
global _drawImageWithPIL
global _img1
if _drawImageWithPIL == None:
_drawImageWithPIL = DrawImageWithPIL()
_drawImageWithPIL.startup(512, 512)
_drawImageWithPIL.update()
with window.frame:
with omni.ui.VStack(height=0):
with omni.ui.Placer(offset_x=8, offset_y=8):
_img1 = omni.ui.ImageWithProvider(_drawImageWithPIL.getByteProvider(), width=_drawImageWithPIL.getWidth(), height=_drawImageWithPIL.getHeight())
# ------------------------------------------.
# Register for update events.
# To clear the event, specify "subs=None".
subs = omni.kit.app.get_app().get_update_event_stream().create_subscription_to_pop(on_update, name="Test update")
|
ft-lab/omniverse_sample_scripts/UI/DrawImage/drawImage.py | from pxr import Usd, UsdGeom, UsdPhysics, UsdShade, Sdf, Gf, Tf
import omni.ui
import omni.kit.app
import carb.events
import asyncio
import math
# Get main window viewport.
window = omni.ui.Window('Viewport')
# ref : omni.kit.window.images extension.py
# ------------------------------------------.
# Managing overlay image.
# ------------------------------------------.
class OverlayImageBuffer:
_width = 256
_height = 256
_byte_provider = None
_timeCount = 0
def __init__(self):
self._timeCount = 0
self._width = 512
self._height = 256
self._byte_provider = None
def startup (self):
self._byte_provider = omni.ui.ByteImageProvider()
def update (self):
# default format omni.ui.TextureFormat.RGBA8_UNORM.
byte_data = [0] * (4 * self._width * self._height)
for x in range(self._width):
hV = 100.0
v = math.cos((float)(x + self._timeCount) * 1.2 * math.pi / 180.0) * hV
iV = 128 + (int)(v)
iPos = (iV * self._width + x) * 4
byte_data[iPos + 0] = 255 # Red
byte_data[iPos + 1] = 255 # Green
byte_data[iPos + 2] = 0 # Blue
byte_data[iPos + 3] = 255 # Alpha
self._byte_provider.set_bytes_data(byte_data, [self._width, self._height])
self._timeCount += 1
# ------------------------------------------.
# Update event.
# ------------------------------------------.
_imgBuffer = None
_img1 = None
def on_update(e: carb.events.IEvent):
global _imgBuffer
global _img1
if _imgBuffer == None:
_imgBuffer = OverlayImageBuffer()
_imgBuffer.startup()
_imgBuffer.update()
with window.frame:
with omni.ui.VStack(height=0):
with omni.ui.Placer(offset_x=8, offset_y=8):
_img1 = omni.ui.ImageWithProvider(_imgBuffer._byte_provider, width=_imgBuffer._width, height=_imgBuffer._height)
_imgBuffer.update()
# ------------------------------------------.
# Register for update events.
# To clear the event, specify "subs=None".
subs = omni.kit.app.get_app().get_update_event_stream().create_subscription_to_pop(on_update, name="Test update")
|
ft-lab/omniverse_sample_scripts/UI/DebugDraw/readme.md | # DebugDraw
3Dの座標指定で、Depthによる遮蔽を考慮したラインを描画(omni.debugdrawを使用)。
|ファイル|説明|
|---|---|
|[UseDebugDraw.py](./UseDebugDraw.py)|ラインを描画<br>|
|
ft-lab/omniverse_sample_scripts/UI/DebugDraw/UseDebugDraw.py | from pxr import Usd, UsdGeom, UsdPhysics, UsdShade, Sdf, Gf, Tf
import omni.ui
import omni.kit.app
import carb
import carb.events
import math
from omni.debugdraw import _debugDraw
_debugDraw = _debugDraw.acquire_debug_draw_interface()
# --------------------------------------------.
# Draw arrow.
# --------------------------------------------.
def drawArrow (p1, p2, color):
_debugDraw.draw_line(carb.Float3(p1[0], p1[1], p1[2]), color, carb.Float3(p2[0], p2[1], p2[2]), color)
P1 = Gf.Vec3f(p1[0], p1[1], p1[2])
P2 = Gf.Vec3f(p2[0], p2[1], p2[2])
vDir = P2 - P1
lenV = vDir.GetLength()
vDir /= lenV
v1_2 = Gf.Vec4f(vDir[0], vDir[1], vDir[2], 1.0)
v2_2 = Gf.Vec4f(0, 1, 0, 1.0)
v3_2 = Gf.HomogeneousCross(v1_2, v2_2)
vDirX = Gf.Vec3f(v3_2[0], v3_2[1], v3_2[2]).GetNormalized()
vD1 = (vDir + vDirX).GetNormalized() * (lenV * 0.1)
vD2 = (vDir - vDirX).GetNormalized() * (lenV * 0.1)
pp = P1 + vD1
_debugDraw.draw_line(carb.Float3(pp[0], pp[1], pp[2]), color, carb.Float3(P1[0], P1[1], P1[2]), color)
pp = P1 + vD2
_debugDraw.draw_line(carb.Float3(pp[0], pp[1], pp[2]), color, carb.Float3(P1[0], P1[1], P1[2]), color)
pp = P2 - vD1
_debugDraw.draw_line(carb.Float3(pp[0], pp[1], pp[2]), color, carb.Float3(P2[0], P2[1], P2[2]), color)
pp = P2 - vD2
_debugDraw.draw_line(carb.Float3(pp[0], pp[1], pp[2]), color, carb.Float3(P2[0], P2[1], P2[2]), color)
# ------------------------------------------.
# Update event.
# ------------------------------------------.
def on_update(e: carb.events.IEvent):
color = 0xffffc000 # AARRGGBB
r = 100.0
angleD = 10.0
angleV = 0.0
px1 = 0.0
pz1 = 0.0
py1 = 0.0
for i in range(200):
px2 = math.cos(angleV * math.pi / 180.0) * r
pz2 = math.sin(angleV * math.pi / 180.0) * r
py2 = py1 + 0.1
if i == 0:
px1 = px2
pz1 = pz2
_debugDraw.draw_line(carb.Float3(px1, py1, pz1), color, carb.Float3(px2, py2, pz2), color)
r -= 0.5
angleV += angleD
px1 = px2
py1 = py2
pz1 = pz2
#_debugDraw.draw_point(carb.Float3(0, 30, 0), 0xffff0000)
color2 = 0xffff0000
drawArrow((-100.0, 5.0, -100.0), (-100.0, 5.0, 100.0), color2)
# ------------------------------------------.
# Register for update events.
# To clear the event, specify "subs=None".
subs = omni.kit.app.get_app().get_update_event_stream().create_subscription_to_pop(on_update, name="draw update")
|
ft-lab/omniverse_sample_scripts/UI/Window/CreateNewWindow.py | import omni.ui
# Create new window.
my_window = omni.ui.Window("New Window", width=300, height=200)
# ------------------------------------------.
# Clicked button event.
# ------------------------------------------.
def onButtonClick(floatField):
print("Button pushed.")
# get/set FloatField.
fCounter = floatField.model.get_value_as_float()
fCounter += 1.0
floatField.model.set_value(fCounter)
# ------------------------------------------.
with my_window.frame:
with omni.ui.VStack(height=0):
floatField = None
with omni.ui.Placer(offset_x=8, offset_y=8):
# Set label.
f = omni.ui.Label("Hello Omniverse!")
f.set_style({"color": 0xff00ffff, "font_size": 20})
with omni.ui.Placer(offset_x=8, offset_y=0):
f2 = omni.ui.Label("Line2!")
f2.set_style({"color": 0xff00ff00, "font_size": 20})
with omni.ui.Placer(offset_x=8, offset_y=0):
with omni.ui.HStack(width=300):
omni.ui.Label("Edit : ", width=50)
floatField = omni.ui.FloatField(width=200, height=0)
with omni.ui.Placer(offset_x=8, offset_y=0):
# Set button.
btn = omni.ui.Button("Push", width=200, height=0)
btn.set_clicked_fn(lambda f = floatField: onButtonClick(f))
|
ft-lab/omniverse_sample_scripts/UI/Window/readme.md | # Window
ウィンドウを作成。
|ファイル|説明|
|---|---|
|[CreateNewWindow.py](./CreateNewWindow.py)|新しいウィンドウを作成。<br>|
|[ImageWindow.py](./ImageWindow.py)|イメージをウィンドウ内に表示。<br>|
イメージは「kit」をカレントパスとして指定します。
Extensionで絶対パスを指定する場合は、以下のように指定します。
```python
from pathlib import Path
IMAGE_PATH = Path(__file__).parent.parent.joinpath("images")
imagePath = f"{IMAGE_PATH}/xxxx.png"
omni.ui.Image(imagePath, width=64, height=64, fill_policy=omni.ui.FillPolicy.PRESERVE_ASPECT_FIT, alignment=omni.ui.Alignment.LEFT_CENTER)
```
|ファイル|説明|
|---|---|
|[InputField.py](./InputField.py)|omni.ui.StringFieldを使った入力フィールド。<br>|
|
ft-lab/omniverse_sample_scripts/UI/Window/FileDialog.py | import omni.ui
# ref : omni.kit.window.file
|
ft-lab/omniverse_sample_scripts/UI/Window/InputField.py | import omni.ui
# Create new window.
my_window = omni.ui.Window("Input test window", width=300, height=200)
# ------------------------------------------.
with my_window.frame:
sField = None
sLabel = None
# Reset StringField, Label.
def onReset (uiField, uiLabel):
if not uiField or not uiLabel:
return
uiField.model.set_value("")
uiLabel.text = ""
# Called when a value is changed in a StringField.
def onValueChanged (uiFieldModel, uiLabel):
if not uiFieldModel or not uiLabel:
return
v = uiFieldModel.get_value_as_string()
uiLabel.text = v
# Create window UI.
with omni.ui.VStack(height=0):
with omni.ui.Placer(offset_x=8, offset_y=8):
with omni.ui.HStack(width=0):
omni.ui.Label("Input ")
sField = omni.ui.StringField(width=120, height=14, style={"color": 0xffffffff})
omni.ui.Spacer(height=4)
sLabel = omni.ui.Label("text")
omni.ui.Spacer(height=4)
btn = omni.ui.Button(" Reset ")
# Specify the callback to be called when the Button is pressed.
btn.set_clicked_fn(lambda f = sField, l = sLabel: onReset(f, l))
# Specify a callback when a value is changed in a StringField.
sField.model.add_value_changed_fn(lambda f, l = sLabel: onValueChanged(f, l))
|
ft-lab/omniverse_sample_scripts/UI/Window/ImageWindow.py | import omni.ui
# Create new window.
my_window = omni.ui.Window("New Window", width=300, height=200)
# ------------------------------------------.
with my_window.frame:
with omni.ui.VStack(height=0):
with omni.ui.Placer(offset_x=8, offset_y=8):
f = omni.ui.Label("Hello Omniverse!")
f.set_style({"color": 0xff00ffff, "font_size": 20})
with omni.ui.Placer(offset_x=8, offset_y=0):
# image search path :
# "kit" or
# absolute path
omni.ui.Image("resources/desktop-icons/omniverse_64.png", width=64, height=64, fill_policy=omni.ui.FillPolicy.PRESERVE_ASPECT_FIT, alignment=omni.ui.Alignment.LEFT_CENTER)
|
ft-lab/omniverse_sample_scripts/UI/Viewport/UpdateText2.py | import omni.ui
import omni.kit.app
import carb.events
import asyncio
import time
# Get main window viewport.
window = omni.ui.Window('Viewport')
countV = 0
timeV = time.time()
# ------------------------------------------.
# Update event.
# ------------------------------------------.
def on_update(e: carb.events.IEvent):
global countV
global timeV
# Process every second.
curTimeV = time.time()
if curTimeV - timeV > 1:
timeV = curTimeV
with window.frame:
with omni.ui.VStack(height=0):
with omni.ui.Placer(offset_x=20, offset_y=50):
# Set label.
f = omni.ui.Label("counter = " + str(countV))
f.visible = True
f.set_style({"color": 0xff00ffff, "font_size": 32})
countV += 1
# ------------------------------------------.
# Register for update events.
# To clear the event, specify "subs=None".
subs = omni.kit.app.get_app().get_update_event_stream().create_subscription_to_pop(on_update, name="Test update")
|
ft-lab/omniverse_sample_scripts/UI/Viewport/WorldToScreen.py | from pxr import Usd, UsdGeom, CameraUtil, UsdShade, Sdf, Gf, Tf
import omni.ext
import omni.ui
from omni.ui import color as cl
from omni.ui import scene as sc
import omni.kit
# Kit104 : Get active viewport window.
active_vp_window = omni.kit.viewport.utility.get_active_viewport_window()
viewport_api = active_vp_window.viewport_api
# World to NDC space (X : -1.0 to +1.0, Y : -1.0 to +1.0).
p = (0, 0, 0)
p_screen = viewport_api.world_to_ndc.Transform(p)
# NDC to Pixel space.
sPos, in_viewport = viewport_api.map_ndc_to_texture_pixel(p_screen)
if in_viewport:
print(sPos)
|
ft-lab/omniverse_sample_scripts/UI/Viewport/DrawRandomRect.py | import omni.ui
import random
# Get main window viewport.
window = omni.ui.Window('Viewport')
rectSize = 5.0
with window.frame:
# Use ZStack for multiple displays.
with omni.ui.ZStack():
for i in range(50):
px = random.random() * 500.0
py = random.random() * 500.0
with omni.ui.VStack(height=0):
with omni.ui.Placer(offset_x=px, offset_y=py):
# Set rectangle.
rect = omni.ui.Rectangle(width=rectSize, height=rectSize)
# Color : 0xAABBGGRR.
rect.set_style({"background_color":0xff0000ff})
|
ft-lab/omniverse_sample_scripts/UI/Viewport/UpdateText.py | import omni.ui
import asyncio
import omni.kit.app
# Get main window viewport.
window = omni.ui.Window('Viewport')
# ------------------------------------------.
async def my_task():
countV = 0
print('Start task.')
f = None
for i in range(10):
with window.frame:
with omni.ui.VStack():
with omni.ui.Placer(offset_x=20, offset_y=50):
# Set label.
f = omni.ui.Label("counter = " + str(countV), alignment=omni.ui.Alignment.LEFT_TOP)
f.visible = True
f.set_style({"color": 0xff00ffff, "font_size": 32})
countV += 1
await asyncio.sleep(1) # Sleep 1sec.
print('End task.')
if f != None:
f.visible = False
f = None
# ------------------------------------------.
# Start task.
asyncio.ensure_future(my_task())
|
ft-lab/omniverse_sample_scripts/UI/Viewport/GetActiveViewportInfo.py | from pxr import Usd, UsdGeom, CameraUtil, UsdShade, Sdf, Gf, Tf
import omni.ext
import omni.ui
from omni.ui import color as cl
from omni.ui import scene as sc
import omni.kit
# Kit104 : Get active viewport window.
active_vp_window = omni.kit.viewport.utility.get_active_viewport_window()
viewport_api = active_vp_window.viewport_api
# Get Viewport window title.
print("Viewport window : " + active_vp_window.name)
# Get camera path ("/OmniverseKit_Persp" etc).
cameraPath = viewport_api.camera_path.pathString
print("cameraPath : " + cameraPath)
# Resolution.
resolution = viewport_api.resolution
print("Resolution : " + str(resolution[0]) + " x " + str(resolution[1]))
# Stage (Usd.Stage).
print(viewport_api.stage)
# Projection matrix (Gf.Matrix4d).
print(viewport_api.projection)
# Transform matrix (Gf.Matrix4d).
print(viewport_api.transform)
# View matrix (Gf.Matrix4d).
print(viewport_api.view)
|
ft-lab/omniverse_sample_scripts/UI/Viewport/readme.md | # Viewport
ビューポート上のオーバレイ表示。
ビューポートの特定位置に2D図形の描画やテキスト描画、3Dのワイヤーフレーム描画などを行います。
Omniverse Kit.102/103/104で仕様が変わっており、ここではKit.104に沿うようにしています。
参考 :
https://docs.omniverse.nvidia.com/kit/docs/omni.kit.viewport.docs/latest/index.html
## ビューポートは複数持つことができる
Kit.103以降では、複数のビューポートを持てるようになりました(ただし、複数のビューポートは同じレンダラの種類になる)。

クリックして選択したビューポートがアクティブなビューポートとなります。
以下で、現在のアクティブなビューポートの"viewport_api"を取得できます。
このクラスからビューポート情報の取得を行うことになります。
```python
import omni.kit
active_vp_window = omni.kit.viewport.utility.get_active_viewport_window()
viewport_api = active_vp_window.viewport_api
```
## ビューポート名を取得
以下でアクティブなビューポートの名前("Viewport", "Viewport 2"など)を取得します。
```python
import omni.kit
active_vp_window = omni.kit.viewport.utility.get_active_viewport_window()
print(active_vp_window.name)
```
## 取得できるビューポート情報
「[GetActiveViewportInfo.py](GetActiveViewportInfo.py)」にサンプルを上げています。
以下のような要素をViewport APIから取得できます。
以下のほかにも情報を取得できます。
* カメラのPrim Path ("/OmniverseKit_Persp"など)
* レンダリングの解像度
* ビューポートで使用しているStage
* Projection/Transform/View Matrix
```python
# Get camera path ("/OmniverseKit_Persp" etc).
cameraPath = viewport_api.camera_path.pathString
print("cameraPath : " + cameraPath)
# Resolution.
resolution = viewport_api.resolution
print("Resolution : " + str(resolution[0]) + " x " + str(resolution[1]))
# Stage (Usd.Stage).
print(viewport_api.stage)
# Projection matrix (Gf.Matrix4d).
print(viewport_api.projection)
# Transform matrix (Gf.Matrix4d).
print(viewport_api.transform)
# View matrix (Gf.Matrix4d).
print(viewport_api.view)
```
Viewport APIは以下に詳しい使用例が記載されているので参考になります。
https://docs.omniverse.nvidia.com/kit/docs/omni.kit.viewport.docs/latest/viewport_api.html
## レンダラの種類を取得
レンダラの種類は"hydra_engine"と"render_mode"で判断します。
```python
import omni.kit
active_vp_window = omni.kit.viewport.utility.get_active_viewport_window()
viewport_api = active_vp_window.viewport_api
print(viewport_api.hydra_engine)
print(viewport_api.render_mode)
```
以下のように取得できました。
|レンダラの種類|hydra_engine|render_mode|
|---|---|---|
|RTX-Real-Time|rtx|RaytracedLighting|
|RTX-Interactive (Path Tracing)|rtx|PathTracing|
|RTX Accurate (Iray)|iray|iray|
|Pixar Storm|pxr|HdStormRendererPlugin|
## ワールド座標からスクリーン座標への変換 (Space Mapping)
「[WorldToScreen.py](WorldToScreen.py)」にサンプルを上げています。
上記以外の機能として、ワールド座標上の位置をスクリーンの2D座標に変換してくることができます(この逆も可能)。
これと"omni.ui.scene"を使うことで、ビューポートへのオーバーレイ描画を容易に行うことができます。
```python
# World to NDC space (X : -1.0 to +1.0, Y : -1.0 to +1.0).
p = (0, 0, 0)
p_screen = viewport_api.world_to_ndc.Transform(p)
# NDC to Pixel space.
sPos, in_viewport = viewport_api.map_ndc_to_texture_pixel(p_screen)
if in_viewport:
print(sPos)
```
Viewport APIはビューポートの情報を取得したり計算結果を返す役割になります。
描画は"omni.ui.scene"で行う、という役割分担になります。
### NDC space
"NDC space"は、ビューポート全体をX方向に-1.0から+1.0、Y方向に-1.0から+1.0としたときの座標系です。

### Pixel space
"Pixel space"は、ビューポートのレンダリング画像内のピクセル座標です。
これはViewport APIの"resolution"で取得できる解像度の範囲のピクセル位置を表します。
以下は解像度が1280 x 720ピクセルの場合のPixel spaceの例です。

## omni.ui.sceneを使用してビューポートにオーバレイ描画
ビューポートへのオーバレイ描画は"omni.ui.scene"を使用します。
サンプルExtension"[ft_lab.sample.uiSceneShowPrimName](../../Extensions/ft_lab.sample.uiSceneShowPrimName)"は、選択したPrimの名前をビューポートに表示する簡単な例です。

```python
from omni.ui import scene as sc
import omni.kit
# Get active viewport.
active_vp_window = omni.kit.viewport.utility.get_active_viewport_window()
viewport_api = active_vp_window.viewport_api
# Get viewport window.
viewport_name = active_vp_window.name # "Viewport", "Viewport 2" etc.
self._window = omni.ui.Window(viewport_name)
with self._window.frame:
with omni.ui.VStack():
# The coordinate system is NDC space.
# (X : -1.0 to +1.0, Y : -1.0 to +1.0).
self._scene_view = sc.SceneView(aspect_ratio_policy=sc.AspectRatioPolicy.STRETCH)
with self._scene_view.scene:
self._sceneDraw = SceneDraw(self._viewport_api)
# Update drawing.
self._sceneDraw.invalidate()
```
"omni.ui.Window"の第一引数に渡すビューポート名は、マルチビューポートに対応するため「アクティブなビューポート名」を取得する必要があります。
"omni.kit.viewport.utility.get_active_viewport_window()"で取得したクラスからnameを取得することで、アクティブなビューポート名を得ることができます。
ビューポートウィンドウにオーバレイするためにSceneViewを作成します。
"sc.SceneView"の引数でAspect ratioをSTRETCHとします。
これでNDC space(X : -1.0 to +1.0, Y : -1.0 to +1.0)の座標系になります。
また、SceneDrawクラスを作成するときに第一引数にViewport APIを渡しています。
SceneDrawクラスは以下のように記載しました。
```python
class SceneDraw (sc.Manipulator):
_viewport_api = None
def __init__(self, viewport_api, **kwargs):
super().__init__ (**kwargs)
# Set Viewport API.
self._viewport_api = viewport_api
# -------------------------------------------.
# Repaint.
# -------------------------------------------.
def on_build (self):
stage = omni.usd.get_context().get_stage()
# Get selection.
selection = omni.usd.get_context().get_selection()
paths = selection.get_selected_prim_paths()
time_code = Usd.TimeCode.Default()
xformCache = UsdGeom.XformCache(time_code)
for path in paths:
prim = stage.GetPrimAtPath(path)
if prim.IsValid():
# Get world Transform.
globalPose = xformCache.GetLocalToWorldTransform(prim)
# Decompose transform.
translate, rotation, scale = UsdSkel.DecomposeTransform(globalPose)
# World to NDC space (X : -1.0 to +1.0, Y : -1.0 to +1.0).
ndc_pos = self._viewport_api.world_to_ndc.Transform(translate)
# Translation matrix.
moveT = sc.Matrix44.get_translation_matrix(ndc_pos[0], ndc_pos[1], 0.0)
# Draw prim name.
with sc.Transform(transform=moveT):
sc.Label(prim.GetName(), alignment = omni.ui.Alignment.CENTER, color=cl("#ffff00a0"), size=20)
```
"self._sceneDraw.invalidate()"の指定により"on_build"が呼ばれます。
現在のStageから選択されたprimを取得し、"globalPose = xformCache.GetLocalToWorldTransform(prim)"でワールド座標の変換行列を取得。
"UsdSkel.DecomposeTransform"で移動(translate)、回転(rotation)、スケール(scale)に分解します。
Viewport APIの"self._viewport_api.world_to_ndc.Transform(translate)"でtranslateをワールド座標からNDC座標に変換します。
"sc.Matrix44.get_translation_matrix"を使ってNDC座標の位置を行列に変換。
"with sc.Transform(transform=moveT)"でこのときの位置を中心にsc.Labelでラベルを配置しています。
これはオーバーレイの描画を行う流れになり、これ以外に以下のイベントを取得して"self._sceneDraw.invalidate()"で更新する必要があります。
* Primが移動した場合(Transformの変更)
* 選択Primが変更された場合
* ビューポートのカメラが変更された場合
* アクティブなビューポートが変更された場合
これらについては、"[ft_lab.sample.uiSceneShowPrimName](../../Extensions/ft_lab.sample.uiSceneShowPrimName)"のExtensionをご参照くださいませ。
## キャプチャ
その他、レンダリング画像のキャプチャ機能があります。
※ まだ未記載。
## サンプル
|ファイル|説明|
|---|---|
|[DrawText.py](./DrawText.py)|ビューポートにテキストを描画<br><br>単一ビューポートのみ考慮。|
|[DrawText2.py](./DrawText2.py)|ビューポートに複数行のテキストを描画<br><br>単一ビューポートのみ考慮。|
|[DrawRandomRect.py](./DrawRandomRect.py)|ビューポートにランダムに小さい矩形を描画<br><br>単一ビューポートのみ考慮。|
|[UpdateText.py](./UpdateText.py)|ビューポートに10秒間カウントアップするテキストを描画。<br>asyncio.ensure_future()でタスクを起動。<br>await asyncio.sleep(1) で待つ<br><br>単一ビューポートのみ考慮。|
|[UpdateText2.py](./UpdateText2.py)|ビューポートにカウントアップするテキストを描画。<br>time.time()で1秒の間隔ごとに更新。<br><br>単一ビューポートのみ考慮。|
|[UpdateDrawImage.py](./UpdateDrawImage.py)|"omni.ui.ImageWithProvider"を使用して、ファイルから読み込んだ画像をビューポートに表示します。<br>"omni.kit.app.get_app().get_update_event_stream().create_subscription_to_pop"使用時は omni.ui.Imageでの描画がうまく反映されないようなのでそれの変わりです。<br>単一ビューポートのみ考慮。|
|[GetViewportRect.py](./GetViewportRect.py)|Kit.103までの動作。Kit.104では使用できません。<br>ビューポートの矩形情報を取得<br>単一ビューポートのみ考慮。|
|[GetActiveViewportInfo.py](./GetActiveViewportInfo.py)|アクティブなビューポートの情報を取得(omni.kit Viewport API)|
|[WorldToScreen.py](./WorldToScreen.py)|ワールド座標位置からスクリーン上の位置に変換(omni.kit Viewport API)|
|
ft-lab/omniverse_sample_scripts/UI/Viewport/GetViewportRect.py | from pxr import Usd, UsdGeom, UsdPhysics, UsdSkel, UsdShade, Sdf, Gf, Tf
import omni.ui
# Get main window viewport.
viewportI = omni.kit.viewport_legacy.acquire_viewport_interface()
vWindow = viewportI.get_viewport_window(None)
# Get viewport rect.
viewportRect = vWindow.get_viewport_rect()
viewportSize = (viewportRect[2] - viewportRect[0], viewportRect[3] - viewportRect[1])
print(viewportRect)
print(viewportSize)
# Get Viewport window rect.
uiViewportWindow = omni.ui.Workspace.get_window("Viewport")
wid = uiViewportWindow.width
hei = uiViewportWindow.height
posX = uiViewportWindow.position_x
posY = uiViewportWindow.position_y
print("wid = " + str(wid))
print("hei = " + str(hei))
print("posX = " + str(posX))
print("posY = " + str(posY))
|
ft-lab/omniverse_sample_scripts/UI/Viewport/DrawText.py | import omni.ui
# Get main window viewport.
window = omni.ui.Window('Viewport')
with window.frame:
with omni.ui.VStack():
# Display position from top left.
with omni.ui.Placer(offset_x=20, offset_y=50):
# Set label.
f = omni.ui.Label("Hello Omniverse!", alignment=omni.ui.Alignment.LEFT_TOP)
f.visible = True
# Color : 0xAABBGGRR.
f.set_style({"color": 0xff00ffff, "font_size": 32})
|
ft-lab/omniverse_sample_scripts/UI/Viewport/UpdateDrawImage.py | import omni.ui
import omni.kit.app
import carb.events
import carb.tokens
import asyncio
import time
import itertools
from pathlib import Path
import os.path
# PIL exists in "kit/extscore/omni.kit.pip_archive/pip_prebundle".
from PIL import Image, ImageDraw, ImageFont
# Get main window viewport.
window = omni.ui.Window('Viewport')
countV = 0
timeV = time.time()
# ------------------------------------------.
# Load image.
# ------------------------------------------.
class LoadImageRGBA:
_byte_provider = None
_width = 0
_height = 0
def __init__(self):
pass
def Open (self, path : str):
try:
# Load image (RGBA).
im = Image.open(path).convert('RGBA')
# Get image size.
self._width = im.size[0]
self._height = im.size[1]
# Get image data(RGBA buffer).
imgD = im.getdata()
# Converting a 2d array to a 1d array.
byte_data = list(itertools.chain.from_iterable(imgD))
self._byte_provider = omni.ui.ByteImageProvider()
self._byte_provider.set_bytes_data(byte_data, [self._width, self._height])
except Exception as e:
self._width = 0
self._height = 0
self._byte_provider = None
print(e)
return False
return True
def GetWidth (self):
return self._width
def GetHeight (self):
return self._height
def GetByteProvider (self):
return self._byte_provider
# Image data.
imgData = None
# ------------------------------------------.
# Update event.
# ------------------------------------------.
def on_update(e: carb.events.IEvent):
global countV
global timeV
global imgData
# Process every second.
curTimeV = time.time()
if curTimeV - timeV > 1:
timeV = curTimeV
countV += 1
# Update UI.
with window.frame:
with omni.ui.ZStack():
with omni.ui.VStack(height=0):
with omni.ui.Placer(offset_x=20, offset_y=50):
# Set label.
f = omni.ui.Label("counter = " + str(countV))
f.visible = True
f.set_style({"color": 0xff00ffff, "font_size": 32})
with omni.ui.VStack(height=0):
with omni.ui.Placer(offset_x=220, offset_y=150):
# "omni.ui.Image" cannot be used with "get_update_event_stream().create_subscription_to_pop".
# Use "omni.ui.ImageWithProvider" instead.
byte_provider = imgData.GetByteProvider()
imgWidth = imgData.GetWidth()
imgHeight = imgData.GetHeight()
omni.ui.ImageWithProvider(byte_provider, width=imgWidth, height=imgHeight)
# ------------------------------------------.
# Kit file path.
kitAbsPath = os.path.abspath(carb.tokens.get_tokens_interface().resolve("${kit}"))
# Load image (RGBA).
imagePath = Path(kitAbsPath).joinpath("resources").joinpath("desktop-icons")
imagePath = f"{imagePath}/omniverse_64.png"
imgData = LoadImageRGBA()
if imgData.Open(imagePath):
# Register for update events.
# To clear the event, specify "subs=None".
subs = omni.kit.app.get_app().get_update_event_stream().create_subscription_to_pop(on_update, name="Test update")
|
ft-lab/omniverse_sample_scripts/UI/Viewport/DrawText2.py | import omni.ui
# Get main window viewport.
window = omni.ui.Window('Viewport')
with window.frame:
with omni.ui.VStack(height=0):
with omni.ui.Placer(offset_x=20, offset_y=50):
# Set label.
f = omni.ui.Label("Hello Omniverse!")
f.visible = True
f.set_style({"color": 0xff00ffff, "font_size": 32})
with omni.ui.Placer(offset_x=20, offset_y=0):
f2 = omni.ui.Label("Line2!")
f2.visible = True
f2.set_style({"color": 0xff00ff00, "font_size": 32})
with omni.ui.Placer(offset_x=20, offset_y=0):
f3 = omni.ui.Label("Line3!")
f3.visible = True
f3.set_style({"color": 0xff0000ff, "font_size": 32})
|
ft-lab/omniverse_sample_scripts/knowledge/dev_method.md | # Omniverseでの開発手段
OmniverseはここでサンプルとしてアップしているPythonスクリプト以外に、
スクリプトを機能ごとにまとめてモジュール化した「Extension」、
外部ツールから3DモデルをUSDを経由して連携する「Connector」、
アプリケーション自身の「Omniverse App」があります。

Pythonスクリプトを機能別にまとめてモジュール化したものがExtensionになります。
複数のExtensionを組み合わせて目的別にアプリケーション化したものがOmniverse CreateやOmniverse Viewなどのアプリになります。
サードパーティでもOmniverseアプリは開発できます。
また、C/C++言語を使用して「Connector」を実装することにより、
外部の3DCGツールとUSDを介して連携できます。
USD SDKでは、Pythonのモジュール/メソッドと、C/C++言語のクラスや関数は1対1で対応しています。
そのため、PythonスクリプトでUSDを操作できるようになればConnectorを実装する際にはそのままその知識は活かせるようになるかと思います。
Omniverse上でのマテリアル表現は、USD標準のUsdPreviewSurface、OmniPBR、OmniSurfaceが使用されます。
これらでもかなりのマテリアル表現ができますが、
MDL(Material Definition Language : マテリアル定義言語)を使うことで、よりマテリアルを自由にカスタマイズすることができるようになります。
OmniPBR、OmniSurfaceも固定(プリセット)のMDLで実装されている構成になります。
MDLは他の3DCGエンジンで言う「Shader」に近い存在です。
MDLについては、「NVIDIA MDL SDK - Get Started」に詳しい情報があります。
https://developer.nvidia.com/mdl-sdk
このような感じで、Omniverseはあらゆる個所をカスタマイズしていくことができるようになっています。
それぞれは範囲が膨大になるため、まずはOmniverse CreateのScript Editor上でスクリプトを使ってシーンを制御できるようになる、というのが入口としてちょうどよいかもしれません。
|
ft-lab/omniverse_sample_scripts/knowledge/dev_usd.md | # USDについての情報
USD(Universal Scene Description )はPixar社が提供している3Dのシーンを管理するファイルフォーマット/プラットフォームです。
オープンソースとして公開されています。
https://graphics.pixar.com/usd/release/index.html
API Documentation :
https://graphics.pixar.com/usd/release/api/index.html
DCCツール間で3Dモデルやシーンをやりとりする中間ファイルとしての使用、大規模シーンの管理に向いています。
PythonやC++のAPIやビュワー(usdview)、usdファイル変換を行うコマンドラインツールなどが用意されており、アプリケーションに組み込むための機能が豊富にあります。
USDはファイルフォーマットとしてだけでなく、データ構造を表現するシステムとして大きな存在になっています。
iOS/iPadOSのAR(AR Quick LookやReality Composer)でも使用されています。
Omniverseではアセットやシーンすべての標準ファイルフォーマットとしてUSDを使用されています。
USDを使った開発については以下にもまとめ中です。
https://github.com/ft-lab/Documents_USD
## USDファイルの種類
USDファイルは、以下のものが存在します。
|USDファイルの拡張子|説明|
|---|---|
|usda|テキストファイル|
|usd/usdc|バイナリファイル|
|usdz|usdファイルとイメージファイルを1つのファイルにしたもの|
usdaとusd/usdcファイルは、テキストとバイナリで異なりますが同じ内容を記載できます。
バイナリファイルのほうがファイルサイズを小さくできます。
usdファイルはテクスチャとしてイメージファイル(png/jpeg/exrなど)を参照します。
複数のusdファイルやイメージファイルをまとめたものが「usdz」というファイルになります。
これは無圧縮のzip形式です。
## USDの構成
USDは以下のように記述されます。
以下はusdaというテキストファイルです。
```
#usda 1.0
def Xform "World"
{
def Sphere "sphere"
{
color3f[] primvars:displayColor = [(0, 0, 1)]
double radius = 1.0
}
}
```
この場合は、半径1.0(cm)の球を原点の位置に青色で配置します。
```
def Type名 "Prim名"
{
}
```
として1つの要素(Primと呼ばれます)が定義されます。
「Xform」は空のNULLノード相当。
その子として「Sphere」の球が配置されています。
Omniverse上では以下のように表示されました。

このとき、"/World/sphere"が「Path」として表現されます。Stage上での絶対パス指定になります。
このPathはUSD内で重複はできません。
もし、同一Pathで形状を作成した場合は上書きされます。
たとえば以下のようにPythonを書いてみました。
Sphereを生成しそのあとに同一パスでCubeを生成すると、SphereはCubeに置き換えられます。
```python
from pxr import Usd, UsdGeom, UsdPhysics, UsdShade, Sdf, Gf, Tf
# Get stage.
stage = omni.usd.get_context().get_stage()
# Create sphere.
pathName = '/World/xxx'
sphereGeom = UsdGeom.Sphere.Define(stage, pathName)
# Create Cube.
cubeGeom = UsdGeom.Cube.Define(stage, pathName)
# Set cube size.
cubeGeom.CreateSizeAttr(10.0)
```
## Primの名前
Prim名は記載ルールがあります。
* ASCIIの英数字、アンダーバーで構成 (日本語は使用できません)
* 先頭の文字は、数値を指定できません。
* 同一階層に同一Prim名を指定できません。
例えば、「球体」「9ABC」「AB-CD」などはPrim名として指定できません。
C/Pythonプログラムでの変数名のような命名ルールです。
そのため、これに沿っていない形状名をusdに渡したい場合は、Prim名をあらかじめ変更して格納する必要があります。
Omniverseにこれらのルールに沿わない文字を無理やり入れた場合は、無効な文字は「_」(アンダーバー)に置き換えられます。
|
ft-lab/omniverse_sample_scripts/knowledge/dev_info.md | # Omniverseのスクリプトの学習手順
Omniverseのスクリプトでは、大きく3つのアクセス先があるように思います。
* Pythonの既存モジュール (numpy/scipy/Pillow(PIL)など)
* USDへのアクセス
* Omniverseへのアクセス
## Pythonの既存モジュール
「Pythonの既存モジュール」は、一般的なPythonで追加できるモジュールです。
Omniverseでは「[omni.kit.pip_archive](../pip_archive/readme.md)」のExtensionとしてまとまっています。
これらは
```python
import numpy
v1 = numpy.array([0.0, 1.0, 2.0])
v2 = numpy.array([1.2, 1.5, 2.3])
v3 = v1 + v2
print(v3)
```
のように一般的なPythonのプログラムと同じように使用できます。
## USDへのアクセス
Omniverseは、データ構造として「USD」( https://graphics.pixar.com/usd/release/index.html )を採用しています。
Omniverseでも、USD SDKのPython使用時と同じように「from pxr import Usd, UsdGeom, UsdPhysics, UsdShade, Sdf, Gf, Tf」としてインポートして使用します。
```python
from pxr import Usd, UsdGeom, UsdPhysics, UsdShade, Sdf, Gf, Tf
# Get stage.
stage = omni.usd.get_context().get_stage()
# Create sphere.
pathName = '/World/sphere'
sphereGeom = UsdGeom.Sphere.Define(stage, pathName)
# Set radius.
sphereGeom.CreateRadiusAttr(5.0)
```
上記の場合は「omni.usd.get_context().get_stage()」は、「OmniverseからStage情報を取得」する機能となり、これはUSDではなくOmniverseへのアクセス(問い合わせ)になります。
「UsdGeom」「UsdPhysics」「Gf」などがUSDのモジュールです。
どの部分がUSDでどの部分がOmniverseが提供するのものか、というのはこのモジュールの名称で判断できそうです。
USDについては、USDのAPI Documentationですべてのメソッドが網羅されているため、ここをリファレンスにするのがよさそうです。
https://graphics.pixar.com/usd/release/api/index.html
### まずは「Gf」を把握する
Omniverseに限らず、3DCGのエンジンで開発を行う場合はまずはベクトル・行列計算を先に把握するとスムーズに開発が進む場合が多いです。
USDのすべてのベクトル・行列計算は、「Gf」(Graphics Foundations : https://graphics.pixar.com/usd/release/api/gf_page_front.html )というモジュールにまとまっています。
これは非常によく使う部分となります。
本サンプル集では「[Math](../Math/readme.md)」に使い方をまとめていますので、ベクトル・行列計算をどう使えばいいのかはご確認くださいませ。
## Omniverseへのアクセス
Omniverseへのアクセスは「omni.xxx」や「carb」として指定する部分になります。
以下のようなものがあります。
* カレントStageの取得 (omni.usd)
* Stageウィンドウでの選択処理 (どのPrimが選択されているか) (omni.usd)
* UIの表示 (omni.ui)
* キーボードやGamePadの入力 (carb.input)
これらのOmniverseのアクセスは"Omniverse Kit"の"Kit Programming Manual"に情報があります。
Omniverse Createの場合は、メインメニューの[Help]-[Developers Manual]からドキュメントにアクセスできます。

UIについては同じくメインメニューの[Help]-[Omni UI Docs]からアクセスして表示されるドキュメントが参考になります。
## Omniverse上でのスクリプトの学習方法
Omniverseは範囲がすごく広いため、またUSD自身も情報量がすごく多いため、はじめの手ごたえをつかむのが難しいかもしれません。
USD単体については
```python
from pxr import Usd, UsdGeom, UsdPhysics, UsdShade, Sdf, Gf, Tf
# Get stage.
stage = omni.usd.get_context().get_stage()
```
としてStageを取得した後はUSDの操作になるため、そこで試しながら追いかけるのがよさそうです。
また、Physicsのサンプルとドキュメントはビジュアルとしての動きもあって分かりやすいため、そこから入るとスクリプトは理解しやすいかと思います。
Physicsのデモについてはメインメニューの[Window]-[Physics]-[Demo Scenes]を選択。

"Physics Demo Scenes"ウィンドウにサンプルが列挙されます。
ソースコードも見ることができます。

Physicsのドキュメントは、メインメニューの[Window]-[Physics]-[Physics Scripting Manual]を選択。

このドキュメントはPhysicsに絞っているため、USDの使い方も合わせて分かりやすいと思います。
Physics自体はOmniverseの機能というわけではなく、USDのAPIとして「UsdPhysics」でアクセスできるようになっています。
### Extensionを読む
難易度はありますが、既存ExtensionはPythonで書かれているためそれを解読して作法を学ぶというのもよさそうです。
"kit/exts"や"kit/extscore"にExtensionが格納されています。
サンプルExtensionも用意されています。
### Omniverse Kitのドキュメントを読む
Omniverse Kitのドキュメントは、ある程度Omniverseの開発(Python/Extension)に慣れてくると理解が進むように思います。
https://docs.omniverse.nvidia.com/py/kit/index.html
どちらかというと、Kitのシステム的な側面から見たリファレンスという感じ。
ExtensionやOmni.Graphについてかなり詳しい情報があります。
|
ft-lab/omniverse_sample_scripts/pip_archive/readme.md | # omni.kit.pip_archive
Pythonでよく使用するモジュールは、"pip_archive"として用意されています。
これは"omni.kit.pip_archive"のExtensionとして提供されていますが、Pythonのこれらを使ったモジュールと同じ使い方ができます。
いくつか使用してみました。
|サンプル|説明|
|---|---|
|[numpy](./numpy)|ベクトル・行列計算を行う|
|[PIL](./PIL)|2D画像操作を行う : Pillow(Python Imaging Library(PIL)).|
|
ft-lab/omniverse_sample_scripts/pip_archive/numpy/CreateMatrix.py | import numpy
# Create 4x4 matrix (identity matrix).
m = numpy.matrix(numpy.identity(4))
print(m)
# Set a value to a matrix.
m[3,0] = 2.0
m[2] = [50.0, 100.0, -20.0, 1.0]
print(m)
|
ft-lab/omniverse_sample_scripts/pip_archive/numpy/CalcVector.py | import numpy
v1 = numpy.array([0.0, 1.0, 2.0])
v2 = numpy.array([1.2, 1.5, 2.3])
v3 = v1 + v2
print(v3)
v3 = v1 * v2
print(v3)
v2[0] += 0.5
print(v2[0])
print(v2[1])
print(v2[2])
|
ft-lab/omniverse_sample_scripts/pip_archive/numpy/CalcVectorLength.py | import numpy
val = numpy.array([2.5, 1.0, 3.0])
lenV = numpy.linalg.norm(val)
print(str(val) + " : Length = " + str(lenV))
# Normalized.
lenV = numpy.linalg.norm(val)
val2 = val
if lenV != 0.0:
val2 = val / lenV
print("Normalized " + str(val) + " ==> " + str(val2))
|
ft-lab/omniverse_sample_scripts/pip_archive/numpy/readme.md | # numpy
numpyはベクトル・行列計算を行うモジュールです。
高速に数値計算を行うことができます。
USDでは"Gf"のモジュールがベクトル・行列計算で使用され、また3DCGでよく使う計算もここに内包されているため、
別途でnumpyを深く使うということは少ないかもしれません。
|ファイル|説明|
|---|---|
|[CalcVector.py](./CalcVector.py)|ベクトル計算を行う|
|[CalcVectorLength.py](./CalcVectorLength.py)|ベクトルの長さを計算、正規化|
|[CalcVectorDotCross.py](./CalcVectorDotCross.py)|ベクトルの内積、外積を計算|
|[CreateMatrix.py](./CreateMatrix.py)|行列の作成/単位ベクトル|
|[CalcMultiplyMatrix.py](./CalcMultiplyMatrix.py)|行列同士の乗算|
|[CalcMultiplyMatrixVector.py](./CalcMultiplyMatrixVector.py)|行列とベクトルの乗算|
|
ft-lab/omniverse_sample_scripts/pip_archive/numpy/CalcMultiplyMatrix.py | import numpy
# Create 4x4 matrix (identity matrix).
m1 = numpy.matrix(numpy.identity(4))
m2 = numpy.matrix(numpy.identity(4))
m1[3] = [22.3, 15.5, 3.0, 1.0]
m2[3] = [50.0, 100.0, -20.0, 1.0]
# Multiply matrix.
# (Same result for mA and mB)
mA = m1 * m2
mB = numpy.dot(m1, m2)
print(mA)
print(mB)
|
ft-lab/omniverse_sample_scripts/pip_archive/numpy/CalcVectorDotCross.py | import numpy
v1 = numpy.array([0.0, 1.0, 2.0])
v2 = numpy.array([1.2, 1.5, 2.3])
# Calculating the Inner Product.
v = numpy.dot(v1, v2)
print("Inner product : " + str(v))
# Calculating the Outer Product.
v = numpy.cross(v1, v2)
print("Outer product : " + str(v))
|
ft-lab/omniverse_sample_scripts/pip_archive/numpy/CalcMultiplyMatrixVector.py | import numpy
# Create Vector3.
v1 = numpy.array([0.0, 1.0, 2.0])
# Create 4x4 matrix.
m1 = numpy.matrix(numpy.identity(4))
m1[3] = [22.3, 15.5, 3.0, 1.0]
# Make sure that the vector to be multiplied has four elements.
vec4 = numpy.array(v1)
if v1.size == 3:
vec4 = numpy.array([v1[0], v1[1], v1[2], 1.0])
# Vector and matrix multiplication.
retM = numpy.dot(vec4, m1)
print(retM)
# Replace the result with Vector3.
retV = numpy.array([retM[0,0], retM[0,1], retM[0,2]])
print(retV)
|
ft-lab/omniverse_sample_scripts/pip_archive/PIL/readme.md | # Pillow(PIL)
Pillow(PIL)を使用して、2D画像の操作を行います。
|ファイル|説明|
|---|---|
|[LoadImage.py](./LoadImage.py) |画像の読み込み|
|[DrawImage.py](./DrawImage.py) |画像の描画と出力|
|
ft-lab/omniverse_sample_scripts/pip_archive/PIL/DrawImage.py | # PIL exists in "kit/extscore/omni.kit.pip_archive/pip_prebundle".
from PIL import Image, ImageDraw, ImageFont
# Create new image.
im = Image.new("RGBA", (512, 512), (0, 0, 0, 0))
draw = ImageDraw.Draw(im)
# Draw rectangle (fill).
draw.rectangle((100, 100, 200, 200), fill=(255, 0, 0))
# Draw rectangle.
draw.rectangle((100, 220, 200, 320), outline=(0, 0, 255), width=1)
# Draw line.
draw.line((0, 0, im.width, im.height), fill=(0, 255, 0), width=2)
# Draw circle.
draw.ellipse((100, 400, 150, 450), outline=(0, 0, 255), width=2)
# Draw circle (fill).
draw.ellipse((280, 300, 380, 400), fill=(0, 0, 255))
# Polygon.
vers = ((40, 20), (140, 120), (180, 60))
draw.polygon(vers, outline=(128, 0, 0))
# Polygon (fill).
vers = ((240, 20), (340, 120), (380, 60))
draw.polygon(vers, fill=(128, 128, 0))
# Font.
font = None
try:
# The ttf font path should be replaced according to your environment.
basePath = "K:/fonts"
fontPath = basePath + "/SourceHanSansJP-Bold.otf"
font = ImageFont.truetype(fontPath, 48)
except Exception as e:
print(e)
# Draw text.
if font != None:
draw.multiline_text((16, 40), 'Draw Text!', fill=(0, 128, 0))
# Save image.
# Rewrite it to any file path and uncomment the following.
#im.save("K:/NVIDIA_omniverse/images/out.png", quality=95)
|
ft-lab/omniverse_sample_scripts/pip_archive/PIL/LoadImage.py | # PIL exists in "kit/extscore/omni.kit.pip_archive/pip_prebundle".
from PIL import Image
# Load image from file.
path = "K:/NVIDIA_omniverse/images/omniverse_64.png"
im = None
try:
im = Image.open(path)
# Get image size.
wid = im.size[0]
hei = im.size[1]
print("Image size : " + str(wid) + " x " + str(hei))
# Get format (PNG, JPEG, etc).
print("Format : " + str(im.format))
# Get mode (RGB, RGBA, etc.).
print("Mode : " + str(im.mode))
except Exception as e:
print(e)
|
ft-lab/omniverse_sample_scripts/Material/readme.md | # Material
マテリアルの割り当て/取得。
なお、テクスチャファイルについては「[textures](./textures)」をローカルの相対パスの位置に配置してご使用くださいませ。
マテリアルは UsdShade.Material ( https://graphics.pixar.com/usd/release/api/class_usd_shade_material.html )で定義されます。
Primに対して以下のようにバインドすることで、対象形状にマテリアルが反映されます。
```python
UsdShade.MaterialBindingAPI(prim).Bind(material)
```
また、マテリアルはShaderを割り当てる必要があります。
UsdShade.Shader ( https://graphics.pixar.com/usd/release/api/class_usd_shade_shader.html )。
このShaderは、USD標準のUsdPreviewSurfaceを使用するほか、独自のShaderを割り当てることができます。
Omniverseの場合は、MDL ( https://www.nvidia.com/ja-jp/design-visualization/technologies/material-definition-language/ )としてマテリアルを表現します。
|ファイル|説明|
|---|---|
|[UnbindMaterial.py](./UnbindMaterial.py)|選択Primに割り当てられているマテリアルのバインドをクリア|
|サンプル|説明|
|---|---|
|[GetMaterial](./GetMaterial)|マテリアル情報を取得|
|[UsdPreviewSurface](./UsdPreviewSurface)|マテリアルの割り当て (UsdPreviewSurface)|
|[OmniPBR](./OmniPBR)|マテリアルの割り当て (OmniPBR)|
|
ft-lab/omniverse_sample_scripts/Material/UnbindMaterial.py | from pxr import Usd, UsdGeom, UsdPhysics, UsdShade, Sdf, Gf, Tf
# Get stage.
stage = omni.usd.get_context().get_stage()
# Get selection.
selection = omni.usd.get_context().get_selection()
paths = selection.get_selected_prim_paths()
for path in paths:
prim = stage.GetPrimAtPath(path)
if prim.IsValid():
# Unbind Material.
UsdShade.MaterialBindingAPI(prim).UnbindAllBindings()
|
ft-lab/omniverse_sample_scripts/Material/OmniPBR/CreateMaterialWithDiffuseTexture.py | from pxr import Usd, UsdGeom, UsdPhysics, UsdShade, Sdf, Gf, Tf
# Get stage.
stage = omni.usd.get_context().get_stage()
# Create mesh.
meshPath = '/World/mesh'
meshGeom = UsdGeom.Mesh.Define(stage, meshPath)
meshGeom.CreatePointsAttr([(-10, 0, -10), (-10, 0, 10), (10, 0, 10), (10, 0, -10)])
meshGeom.CreateNormalsAttr([(0, 1, 0), (0, 1, 0), (0, 1, 0), (0, 1, 0)])
meshGeom.CreateFaceVertexCountsAttr([4])
meshGeom.CreateFaceVertexIndicesAttr([0, 1, 2, 3])
texCoords = meshGeom.CreatePrimvar("st",
Sdf.ValueTypeNames.TexCoord2fArray,
UsdGeom.Tokens.varying)
texCoords.Set([(0, 1), (0, 0), (1, 0), (1, 1)])
meshPrim = stage.GetPrimAtPath(meshPath)
# Create material scope.
materialScopePath = '/World/Materials'
scopePrim = stage.GetPrimAtPath(materialScopePath)
if scopePrim.IsValid() == False:
UsdGeom.Scope.Define(stage, materialScopePath)
# Create material (omniPBR).
materialPath = '/World/Materials/omniPBR_mat1'
material = UsdShade.Material.Define(stage, materialPath)
shaderPath = materialPath + '/Shader'
shader = UsdShade.Shader.Define(stage, shaderPath)
shader.SetSourceAsset('OmniPBR.mdl', 'mdl')
shader.GetPrim().CreateAttribute('info:mdl:sourceAsset:subIdentifier', Sdf.ValueTypeNames.Token, False, Sdf.VariabilityUniform).Set('OmniPBR')
# Set Diffuse color.
shader.CreateInput('diffuse_color_constant', Sdf.ValueTypeNames.Color3f).Set((1.0, 0.5, 0.4))
# Set Metallic.
shader.CreateInput('metallic_constant', Sdf.ValueTypeNames.Float).Set(0.0)
# Set Roughness.
shader.CreateInput('reflection_roughness_constant', Sdf.ValueTypeNames.Float).Set(0.2)
# Set Diffuse texture.
# Note : Texture files should be specified in the path where they exist.
#textureFilePath = '../textures/tile_image.png'
textureFilePath = 'https://ft-lab.github.io/usd/omniverse/textures/tile_image.png'
diffTexIn = shader.CreateInput('diffuse_texture', Sdf.ValueTypeNames.Asset)
diffTexIn.Set(textureFilePath)
diffTexIn.GetAttr().SetColorSpace('sRGB')
# Set Diffuse value.
diffTintIn = shader.CreateInput('diffuse_tint', Sdf.ValueTypeNames.Color3f)
diffTintIn.Set((0.9, 0.9, 0.9))
# Connecting Material to Shader.
mdlOutput = material.CreateSurfaceOutput('mdl')
mdlOutput.ConnectToSource(shader, 'out')
# Bind material.
UsdShade.MaterialBindingAPI(meshPrim).Bind(material)
|
ft-lab/omniverse_sample_scripts/Material/OmniPBR/CreateMaterialWithCommand.py | from pxr import Usd, UsdGeom, UsdPhysics, UsdShade, Sdf, Gf, Tf
import omni.kit.commands
# Get stage.
stage = omni.usd.get_context().get_stage()
# Create new material.
omni.kit.commands.execute('CreateAndBindMdlMaterialFromLibrary', mdl_name='OmniPBR.mdl',
mtl_name='OmniPBR', mtl_created_list=['/World/Looks/OmniPBR'])
# Get selection.
selection = omni.usd.get_context().get_selection()
selectedPaths = selection.get_selected_prim_paths()
# Path of the added material.
selectPrimPath = ""
for path in selectedPaths:
selectPrimPath = path
break
print(selectPrimPath) |
ft-lab/omniverse_sample_scripts/Material/OmniPBR/readme.md | # OmniPBR
OmniPBRのマテリアルを割り当て。
|ファイル|説明|
|---|---|
|[CreateMaterial.py](./CreateMaterial.py)|球にシンプルなマテリアルを割り当て。<br>|
|[CreateMaterialWithCommand.py](./CreateMaterialWithCommand.py)|omni.kit.commandsを使ってOmniPBRの新しいマテリアルを作成|
|[CreateMaterialWithDiffuseTexture.py](./CreateMaterialWithDiffuseTexture.py)|MeshにdiffuseColorテクスチャを割り当てる。<br>|
|[CreateMaterialWithDiffuseNormalTexture.py](./CreateMaterialWithDiffuseNormalTexture.py)|MeshにdiffuseColorテクスチャ/法線マップテクスチャを割り当てる。<br>|
|
ft-lab/omniverse_sample_scripts/Material/OmniPBR/CreateMaterialWithDiffuseNormalTexture.py | from pxr import Usd, UsdGeom, UsdPhysics, UsdShade, Sdf, Gf, Tf
# Get stage.
stage = omni.usd.get_context().get_stage()
# Create mesh.
meshPath = '/World/mesh'
meshGeom = UsdGeom.Mesh.Define(stage, meshPath)
meshGeom.CreatePointsAttr([(-10, 0, -10), (-10, 0, 10), (10, 0, 10), (10, 0, -10)])
meshGeom.CreateNormalsAttr([(0, 1, 0), (0, 1, 0), (0, 1, 0), (0, 1, 0)])
meshGeom.CreateFaceVertexCountsAttr([4])
meshGeom.CreateFaceVertexIndicesAttr([0, 1, 2, 3])
texCoords = meshGeom.CreatePrimvar("st",
Sdf.ValueTypeNames.TexCoord2fArray,
UsdGeom.Tokens.varying)
texCoords.Set([(0, 1), (0, 0), (1, 0), (1, 1)])
meshPrim = stage.GetPrimAtPath(meshPath)
# Create material scope.
materialScopePath = '/World/Materials'
scopePrim = stage.GetPrimAtPath(materialScopePath)
if scopePrim.IsValid() == False:
UsdGeom.Scope.Define(stage, materialScopePath)
# Create material (omniPBR).
materialPath = '/World/Materials/omniPBR_mat1'
material = UsdShade.Material.Define(stage, materialPath)
shaderPath = materialPath + '/Shader'
shader = UsdShade.Shader.Define(stage, shaderPath)
shader.SetSourceAsset('OmniPBR.mdl', 'mdl')
shader.GetPrim().CreateAttribute('info:mdl:sourceAsset:subIdentifier', Sdf.ValueTypeNames.Token, False, Sdf.VariabilityUniform).Set('OmniPBR')
# Set Diffuse color.
shader.CreateInput('diffuse_color_constant', Sdf.ValueTypeNames.Color3f).Set((1.0, 0.5, 0.4))
# Set Metallic.
shader.CreateInput('metallic_constant', Sdf.ValueTypeNames.Float).Set(0.0)
# Set Roughness.
shader.CreateInput('reflection_roughness_constant', Sdf.ValueTypeNames.Float).Set(0.2)
# Set Diffuse texture.
# Note : Texture files should be specified in the path where they exist.
#diffuseTextureFilePath = '../textures/stone_01_diffuse.png'
diffuseTextureFilePath = 'https://ft-lab.github.io/usd/omniverse/textures/stone_01_diffuse.png'
diffTexIn = shader.CreateInput('diffuse_texture', Sdf.ValueTypeNames.Asset)
diffTexIn.Set(diffuseTextureFilePath)
diffTexIn.GetAttr().SetColorSpace('sRGB')
# Set Diffuse value.
diffTintIn = shader.CreateInput('diffuse_tint', Sdf.ValueTypeNames.Color3f)
diffTintIn.Set((0.9, 0.9, 0.9))
# Set normal texture.
# Note : Texture files should be specified in the path where they exist.
#normalTextureFilePath = '../textures/stone_01_normal.png'
normalTextureFilePath = 'https://ft-lab.github.io/usd/omniverse/textures/stone_01_normal.png'
normalTexIn = shader.CreateInput('normalmap_texture', Sdf.ValueTypeNames.Asset)
normalTexIn.Set(normalTextureFilePath)
# The ColorSpace of the Normal map must be raw.
normalTexIn.GetAttr().SetColorSpace('raw')
# Normal strength.
normalStrengthIn = shader.CreateInput('bump_factor', Sdf.ValueTypeNames.Float)
normalStrengthIn.Set(1.0)
# Connecting Material to Shader.
mdlOutput = material.CreateSurfaceOutput('mdl')
mdlOutput.ConnectToSource(shader, 'out')
# Bind material.
UsdShade.MaterialBindingAPI(meshPrim).Bind(material)
|
ft-lab/omniverse_sample_scripts/Material/OmniPBR/CreateMaterial.py | from pxr import Usd, UsdGeom, UsdPhysics, UsdShade, Sdf, Gf, Tf
# Get stage.
stage = omni.usd.get_context().get_stage()
# Create sphere.
spherePath = '/World/sphere'
sphereGeom = UsdGeom.Sphere.Define(stage, spherePath)
sphereGeom.CreateRadiusAttr(20.0)
spherePrim = stage.GetPrimAtPath(spherePath)
spherePrim.CreateAttribute('refinementEnableOverride', Sdf.ValueTypeNames.Bool).Set(True)
spherePrim.CreateAttribute('refinementLevel', Sdf.ValueTypeNames.Int).Set(2)
prim = sphereGeom.GetPrim()
# Create material scope.
materialScopePath = '/World/Materials'
scopePrim = stage.GetPrimAtPath(materialScopePath)
if scopePrim.IsValid() == False:
UsdGeom.Scope.Define(stage, materialScopePath)
# Create material (omniPBR).
materialPath = '/World/Materials/omniPBR_mat1'
material = UsdShade.Material.Define(stage, materialPath)
shaderPath = materialPath + '/Shader'
shader = UsdShade.Shader.Define(stage, shaderPath)
shader.SetSourceAsset('OmniPBR.mdl', 'mdl')
shader.GetPrim().CreateAttribute('info:mdl:sourceAsset:subIdentifier', Sdf.ValueTypeNames.Token, False, Sdf.VariabilityUniform).Set('OmniPBR')
# Set Diffuse color.
shader.CreateInput('diffuse_color_constant', Sdf.ValueTypeNames.Color3f).Set((1.0, 0.5, 0.4))
# Set Metallic.
shader.CreateInput('metallic_constant', Sdf.ValueTypeNames.Float).Set(0.0)
# Set Roughness.
shader.CreateInput('reflection_roughness_constant', Sdf.ValueTypeNames.Float).Set(0.2)
# Connecting Material to Shader.
mdlOutput = material.CreateSurfaceOutput('mdl')
mdlOutput.ConnectToSource(shader, 'out')
# Bind material.
bindAPI = UsdShade.MaterialBindingAPI(prim)
bindAPI.Bind(material)
bindAPI.Apply(prim)
|
ft-lab/omniverse_sample_scripts/Material/GetMaterial/GetMaterial.py | from pxr import Usd, UsdGeom, UsdPhysics, UsdShade, Sdf, Gf, Tf
# Get stage.
stage = omni.usd.get_context().get_stage()
selection = omni.usd.get_context().get_selection()
paths = selection.get_selected_prim_paths()
for path in paths:
prim = stage.GetPrimAtPath(path)
# Get Material.
rel = UsdShade.MaterialBindingAPI(prim).GetDirectBindingRel()
pathList = rel.GetTargets()
print('[ ' + prim.GetName() + ' ]')
for mTargetPath in pathList:
print(' material : ' + mTargetPath.pathString)
material = UsdShade.Material(stage.GetPrimAtPath(mTargetPath))
print(material)
|
ft-lab/omniverse_sample_scripts/Material/GetMaterial/readme.md | # GetMaterial
マテリアル情報を取得。
以下は、形状からマテリアルを取得するサンプルです。
|ファイル|説明|
|---|---|
|[GetMaterial.py](./GetMaterial.py)|選択形状のマテリアル情報を取得|
以下は、マテリアルから情報を取得するサンプルです。
|ファイル|説明|
|---|---|
|[GetMaterialType.py](./GetMaterialType.py)|選択マテリアルの種類を取得(UsdPreviewSurface or MDL)|
|[GetMaterialInputs.py](./GetMaterialInputs.py)|選択マテリアルの入力パラメータを取得|
|[GetMaterialTexturePath.py](./GetMaterialTexturePath.py)|選択マテリアルの入力パラメータからテクスチャ情報のみを取得。<br>Sdf.AssetPathのpathは入力そのまま。resolvedPathはフルパスが入っている。|
|
ft-lab/omniverse_sample_scripts/Material/GetMaterial/GetMaterialTexturePath.py | from pxr import Usd, UsdGeom, UsdPhysics, UsdShade, Sdf, Gf, Tf
# Get stage.
stage = omni.usd.get_context().get_stage()
selection = omni.usd.get_context().get_selection()
paths = selection.get_selected_prim_paths()
for path in paths:
prim = stage.GetPrimAtPath(path)
if prim.GetTypeName() != "Material":
continue
# List textures referenced by Material.
pChildren = prim.GetChildren()
for cPrim in pChildren:
if cPrim.GetTypeName() == "Shader":
shaderPrim = UsdShade.Shader(cPrim)
print(f"[{shaderPrim.GetPath().pathString}]")
mInputs = shaderPrim.GetInputs()
for inputV in mInputs:
baseName = inputV.GetBaseName()
typeName = inputV.GetTypeName()
if typeName == "asset":
v = inputV.Get() # Sdf.AssetPath
if v.path != "":
# v.path ... display path.
# v.resolvedPath ... absolute path.
print(f" {baseName}")
print(f" path [ {v.path} ]")
print(f" resolvedPath [ {v.resolvedPath} ]")
|
ft-lab/omniverse_sample_scripts/Material/GetMaterial/GetMaterialType.py | from pxr import Usd, UsdGeom, UsdPhysics, UsdShade, Sdf, Gf, Tf
# Get stage.
stage = omni.usd.get_context().get_stage()
selection = omni.usd.get_context().get_selection()
paths = selection.get_selected_prim_paths()
# Get material type (UsdPreviewSurface/OmniPBR/CustomMDL etc.)
def GetMaterialType (path : str):
prim = stage.GetPrimAtPath(path)
if prim.GetTypeName() != "Material":
return ""
materialTypeName = ""
pChildren = prim.GetChildren()
for cPrim in pChildren:
if cPrim.GetTypeName() == "Shader":
shaderPrim = UsdShade.Shader(cPrim)
# In the case of UsdPreviewSurface, ImplementationSource is "id".
# In the case of MDL, the ImplementationSource is "sourceAsset".
sourceV = shaderPrim.GetImplementationSource()
if sourceV == "id":
attr = shaderPrim.GetIdAttr()
idValue = attr.Get() # "UsdPreviewSurface"
if idValue == "UsdPreviewSurface":
materialTypeName = idValue
# Get MDL information.
if sourceV == "sourceAsset":
# Sdf.AssetPath
# assetPath.path ... display path.
# assetPath.resolvedPath ... absolute path.
assetPath = shaderPrim.GetSourceAsset("mdl")
# MDL name.
subIdentifier = shaderPrim.GetSourceAssetSubIdentifier("mdl")
if subIdentifier != "":
materialTypeName = subIdentifier
else:
materialTypeName = assetPath.resolvedPath
if materialTypeName != "":
break
return materialTypeName
# -----------------------------------.
for path in paths:
materialTypeName = GetMaterialType(path)
if materialTypeName != "":
print(f"{path} : {materialTypeName}")
|
ft-lab/omniverse_sample_scripts/Material/GetMaterial/GetMaterialInputs.py | from pxr import Usd, UsdGeom, UsdPhysics, UsdShade, Sdf, Gf, Tf
# Get stage.
stage = omni.usd.get_context().get_stage()
selection = omni.usd.get_context().get_selection()
paths = selection.get_selected_prim_paths()
for path in paths:
prim = stage.GetPrimAtPath(path)
if prim.GetTypeName() != "Material":
continue
print("[" + prim.GetPath().pathString + "]")
# Get Shader of Material and input parameters.
pChildren = prim.GetChildren()
for cPrim in pChildren:
if cPrim.GetTypeName() == "Shader":
shaderPrim = UsdShade.Shader(cPrim)
mInputs = shaderPrim.GetInputs()
for inputV in mInputs:
baseName = inputV.GetBaseName()
typeName = inputV.GetTypeName()
print(" [" + baseName + "] (" + str(typeName) + ")")
v = inputV.Get()
print(" " + str(type(v)) + " ==> " + str(v))
|
ft-lab/omniverse_sample_scripts/Material/UsdPreviewSurface/CreateMaterialWithDiffuseTexture.py | from pxr import Usd, UsdGeom, UsdPhysics, UsdShade, Sdf, Gf, Tf
# Get stage.
stage = omni.usd.get_context().get_stage()
# Create mesh.
meshPath = '/World/mesh'
meshGeom = UsdGeom.Mesh.Define(stage, meshPath)
meshGeom.CreatePointsAttr([(-10, 0, -10), (-10, 0, 10), (10, 0, 10), (10, 0, -10)])
meshGeom.CreateNormalsAttr([(0, 1, 0), (0, 1, 0), (0, 1, 0), (0, 1, 0)])
meshGeom.CreateFaceVertexCountsAttr([4])
meshGeom.CreateFaceVertexIndicesAttr([0, 1, 2, 3])
texCoords = meshGeom.CreatePrimvar("st",
Sdf.ValueTypeNames.TexCoord2fArray,
UsdGeom.Tokens.varying)
texCoords.Set([(0, 1), (0, 0), (1, 0), (1, 1)])
meshPrim = stage.GetPrimAtPath(meshPath)
# Create material scope.
materialScopePath = '/World/Materials'
scopePrim = stage.GetPrimAtPath(materialScopePath)
if scopePrim.IsValid() == False:
UsdGeom.Scope.Define(stage, materialScopePath)
# Create material (UsdPreviewSurface).
materialPath = '/World/Materials/mat1'
material = UsdShade.Material.Define(stage, materialPath)
pbrShader = UsdShade.Shader.Define(stage, materialPath + '/PBRShader')
pbrShader.CreateIdAttr("UsdPreviewSurface")
pbrShader.CreateInput("diffuseColor", Sdf.ValueTypeNames.Color3f).Set((1.0, 0.2, 0.0))
pbrShader.CreateInput("roughness", Sdf.ValueTypeNames.Float).Set(0.4)
pbrShader.CreateInput("metallic", Sdf.ValueTypeNames.Float).Set(0.0)
# Set diffuse texture.
stReader = UsdShade.Shader.Define(stage, materialPath + '/stReader')
stReader.CreateIdAttr('UsdPrimvarReader_float2')
diffuseTextureSampler = UsdShade.Shader.Define(stage, materialPath + '/diffuseTexture')
diffuseTextureSampler.CreateIdAttr('UsdUVTexture')
# Note : Texture files should be specified in the path where they exist.
#textureFilePath = '../textures/tile_image.png'
textureFilePath = 'https://ft-lab.github.io/usd/omniverse/textures/tile_image.png'
diffuseTextureSampler.CreateInput('file', Sdf.ValueTypeNames.Asset).Set(textureFilePath)
diffuseTextureSampler.CreateInput("st", Sdf.ValueTypeNames.Float2).ConnectToSource(stReader.ConnectableAPI(), 'result')
diffuseTextureSampler.CreateOutput('rgb', Sdf.ValueTypeNames.Float3)
pbrShader.CreateInput("diffuseColor", Sdf.ValueTypeNames.Color3f).ConnectToSource(diffuseTextureSampler.ConnectableAPI(), 'rgb')
stInput = material.CreateInput('frame:stPrimvarName', Sdf.ValueTypeNames.Token)
stInput.Set('st')
stReader.CreateInput('varname',Sdf.ValueTypeNames.Token).ConnectToSource(stInput)
# Connect PBRShader to Material.
material.CreateSurfaceOutput().ConnectToSource(pbrShader.ConnectableAPI(), "surface")
# Bind material.
UsdShade.MaterialBindingAPI(meshPrim).Bind(material)
|
ft-lab/omniverse_sample_scripts/Material/UsdPreviewSurface/readme.md | # UsdPreviewSurface
UsdPreviewSurfaceのマテリアルを割り当て。
|ファイル|説明|
|---|---|
|[CreateMaterial.py](./CreateMaterial.py)|球にシンプルなマテリアルを割り当て。<br>|
|[CreateMaterialWithDiffuseTexture.py](./CreateMaterialWithDiffuseTexture.py) |MeshにdiffuseColorテクスチャを割り当てる。<br>|
|[CreateMaterialWithDiffuseNormalTexture.py](./CreateMaterialWithDiffuseNormalTexture.py)|MeshにdiffuseColorテクスチャ/法線マップテクスチャを割り当てる。<br>|
|
ft-lab/omniverse_sample_scripts/Material/UsdPreviewSurface/CreateMaterialWithDiffuseNormalTexture.py | from pxr import Usd, UsdGeom, UsdPhysics, UsdShade, Sdf, Gf, Tf
# Get stage.
stage = omni.usd.get_context().get_stage()
# Create mesh.
meshPath = '/World/mesh'
meshGeom = UsdGeom.Mesh.Define(stage, meshPath)
meshGeom.CreatePointsAttr([(-10, 0, -10), (-10, 0, 10), (10, 0, 10), (10, 0, -10)])
meshGeom.CreateNormalsAttr([(0, 1, 0), (0, 1, 0), (0, 1, 0), (0, 1, 0)])
meshGeom.CreateFaceVertexCountsAttr([4])
meshGeom.CreateFaceVertexIndicesAttr([0, 1, 2, 3])
texCoords = meshGeom.CreatePrimvar("st",
Sdf.ValueTypeNames.TexCoord2fArray,
UsdGeom.Tokens.varying)
texCoords.Set([(0, 1), (0, 0), (1, 0), (1, 1)])
meshPrim = stage.GetPrimAtPath(meshPath)
# Create material scope.
materialScopePath = '/World/Materials'
scopePrim = stage.GetPrimAtPath(materialScopePath)
if scopePrim.IsValid() == False:
UsdGeom.Scope.Define(stage, materialScopePath)
# Create material (UsdPreviewSurface).
materialPath = '/World/Materials/mat1'
material = UsdShade.Material.Define(stage, materialPath)
pbrShader = UsdShade.Shader.Define(stage, materialPath + '/PBRShader')
pbrShader.CreateIdAttr("UsdPreviewSurface")
pbrShader.CreateInput("diffuseColor", Sdf.ValueTypeNames.Color3f).Set((1.0, 0.2, 0.0))
pbrShader.CreateInput("roughness", Sdf.ValueTypeNames.Float).Set(0.4)
pbrShader.CreateInput("metallic", Sdf.ValueTypeNames.Float).Set(0.0)
# Set diffuse texture.
stReader = UsdShade.Shader.Define(stage, materialPath + '/stReader')
stReader.CreateIdAttr('UsdPrimvarReader_float2')
diffuseTextureSampler = UsdShade.Shader.Define(stage, materialPath + '/diffuseTexture')
diffuseTextureSampler.CreateIdAttr('UsdUVTexture')
# Note : Texture files should be specified in the path where they exist.
#diffuseTextureFilePath = '../textures/stone_01_diffuse.png'
diffuseTextureFilePath = 'https://ft-lab.github.io/usd/omniverse/textures/stone_01_diffuse.png'
diffuseTextureSampler.CreateInput('file', Sdf.ValueTypeNames.Asset).Set(diffuseTextureFilePath)
diffuseTextureSampler.CreateInput("st", Sdf.ValueTypeNames.Float2).ConnectToSource(stReader.ConnectableAPI(), 'result')
diffuseTextureSampler.CreateOutput('rgb', Sdf.ValueTypeNames.Float3)
pbrShader.CreateInput("diffuseColor", Sdf.ValueTypeNames.Color3f).ConnectToSource(diffuseTextureSampler.ConnectableAPI(), 'rgb')
# Set normal texture.
normalTextureSampler = UsdShade.Shader.Define(stage, materialPath + '/normalTexture')
normalTextureSampler.CreateIdAttr('UsdUVTexture')
# Note : Texture files should be specified in the path where they exist.
#normalTextureFilePath = '../textures/stone_01_normal.png'
normalTextureFilePath = 'https://ft-lab.github.io/usd/omniverse/textures/stone_01_normal.png'
normalTextureSampler.CreateInput('file', Sdf.ValueTypeNames.Asset).Set(normalTextureFilePath)
normalTextureSampler.CreateInput("st", Sdf.ValueTypeNames.Float2).ConnectToSource(stReader.ConnectableAPI(), 'result')
normalTextureSampler.CreateOutput('rgb', Sdf.ValueTypeNames.Normal3f)
pbrShader.CreateInput("normal", Sdf.ValueTypeNames.Normal3f).ConnectToSource(normalTextureSampler.ConnectableAPI(), 'rgb')
stInput = material.CreateInput('frame:stPrimvarName', Sdf.ValueTypeNames.Token)
stInput.Set('st')
stReader.CreateInput('varname',Sdf.ValueTypeNames.Token).ConnectToSource(stInput)
# Connect PBRShader to Material.
material.CreateSurfaceOutput().ConnectToSource(pbrShader.ConnectableAPI(), "surface")
# Bind material.
UsdShade.MaterialBindingAPI(meshPrim).Bind(material)
|
ft-lab/omniverse_sample_scripts/Material/UsdPreviewSurface/CreateMaterial.py | from pxr import Usd, UsdGeom, UsdPhysics, UsdShade, Sdf, Gf, Tf
# Get stage.
stage = omni.usd.get_context().get_stage()
# Create sphere.
spherePath = '/World/sphere'
sphereGeom = UsdGeom.Sphere.Define(stage, spherePath)
sphereGeom.CreateRadiusAttr(20.0)
spherePrim = stage.GetPrimAtPath(spherePath)
spherePrim.CreateAttribute('refinementEnableOverride', Sdf.ValueTypeNames.Bool).Set(True)
spherePrim.CreateAttribute('refinementLevel', Sdf.ValueTypeNames.Int).Set(2)
# Create material scope.
materialScopePath = '/World/Materials'
scopePrim = stage.GetPrimAtPath(materialScopePath)
if scopePrim.IsValid() == False:
UsdGeom.Scope.Define(stage, materialScopePath)
# Create material (UsdPreviewSurface).
materialPath = '/World/Materials/mat1'
material = UsdShade.Material.Define(stage, materialPath)
pbrShader = UsdShade.Shader.Define(stage, materialPath + '/PBRShader')
pbrShader.CreateIdAttr("UsdPreviewSurface")
pbrShader.CreateInput("diffuseColor", Sdf.ValueTypeNames.Color3f).Set((1.0, 0.2, 0.0))
pbrShader.CreateInput("roughness", Sdf.ValueTypeNames.Float).Set(0.4)
pbrShader.CreateInput("metallic", Sdf.ValueTypeNames.Float).Set(0.0)
# Connect PBRShader to Material.
material.CreateSurfaceOutput().ConnectToSource(pbrShader.ConnectableAPI(), "surface")
# Bind material.
UsdShade.MaterialBindingAPI(spherePrim).Bind(material)
|
ft-lab/omniverse_sample_scripts/Python/readme.md | # Python
Pythonの標準的な機能の覚書きです。
## サンプル
|ファイル|説明|
|---|---|
|[string](./string)|文字列処理|
|[Class](./Class)|クラスの使用|
|[Web](./Web)|Webブラウザへのアクセス|
|
ft-lab/omniverse_sample_scripts/Python/Class/readme.md | # Class
Classのサンプル。
## サンプル
|ファイル|説明|
|---|---|
|[SimpleClass.py](./SimpleClass.py)|簡単なクラス。<br>コンストラクタとデストラクタ。|
|
ft-lab/omniverse_sample_scripts/Python/Class/SimpleClass.py | # -----------------------------------------------.
# Simple class.
# -----------------------------------------------.
class ClassFoo:
_name = ""
# Constructor
def __init__(self, name : str):
self.name = name
print("Constructor")
# Destructor
def __del__(self):
print("Destructor")
def printName (self):
print("name = " + self.name)
def add (self, a : float, b : float):
return (a + b)
# -----------------------------------------------.
# Create new class.
foo = ClassFoo("test")
foo.printName()
print(foo.add(12.5, 8.2))
# Destroying a class.
foo = None
|
ft-lab/omniverse_sample_scripts/Python/string/NumToStr.py | v = 0.25364
# number to string.
# ==> "0.25364"
print("Value = " + str(v))
# Digit number specification.
# ==> "0000.25364"
print("Value : {:#010}".format(v))
print("Value : " + format(v, '#010'))
# Specify the number of decimal places.
# ==> "0.254"
print("Value : {:.3f}".format(v))
print("Value : " + format(v, '.3f'))
# Replaced by hexadecimal.
# ==> "0x7fff"
v2 = 32767
print(hex(v2))
# Replaced by a binary number.
# ==> "0b101"
v2 = 5
print(bin(v2))
|
ft-lab/omniverse_sample_scripts/Python/string/readme.md | # string
文字列処理。
## サンプル
|ファイル|説明|
|---|---|
|[NumToStr.py](./NumToStr.py)|数値を文字列に変換|
|[StringTest.py](./StringTest.py)|文字列指定時に変数を埋め込む|
|
ft-lab/omniverse_sample_scripts/Python/string/StringTest.py | from pxr import Usd, UsdGeom, UsdPhysics, UsdShade, Sdf, Gf, Tf
v = 25.3674
print("Value = " + str(v))
print(f"Value = {v}")
print(f"Type = {type(v)}")
# Specify the number of decimal places.
# ==> "25.367"
print(f"Value = {'{:.3f}'.format(v)}")
vec3 = Gf.Vec3f(1.2, 5.6, 90)
print(f"vec3 = {vec3}")
array = [1.2, "test", True]
print(f"array = {array}")
|
ft-lab/omniverse_sample_scripts/Python/Web/readme.md | # Web
Webブラウザへのアクセス。
|サンプル|説明|
|---|---|
|[WebOpen](./WebOpen.py)|指定のURLをWebブラウザで開く。|
|
ft-lab/omniverse_sample_scripts/Python/Web/WebOpen.py | import webbrowser
url = "https://docs.omniverse.nvidia.com/"
webbrowser.open(url)
|
ft-lab/omniverse_sample_scripts/AssetConverter/readme.md | # Asset Converter
obj/fbx/glTFなどのファイルをUSDにコンバートします。
|ファイル|説明|
|---|---|
|[importObjToUSD.py](./importObjToUSD.py)|指定のobjファイルをUSDファイルにコンバートします。<br>「[simple_obj.obj](./simple_obj/simple_obj.obj)」を入力のobjファイルの参考にしてくださいませ。|
|
ft-lab/omniverse_sample_scripts/AssetConverter/importObjToUSD.py | # --------------------------------------------------.
# obj to usd conversion.
# See : https://docs.omniverse.nvidia.com/app_create/prod_extensions/ext_asset-converter.html
# --------------------------------------------------.
import carb
import omni
import asyncio
import omni.kit.asset_converter
# Progress of processing.
def progress_callback (current_step: int, total: int):
# Show progress
print(f"{current_step} of {total}")
# Convert asset file(obj/fbx/glTF, etc) to usd.
async def convert_asset_to_usd (input_asset: str, output_usd: str):
# Input options are defaults.
converter_context = omni.kit.asset_converter.AssetConverterContext()
converter_context.ignore_materials = False
converter_context.ignore_camera = False
converter_context.ignore_animations = False
converter_context.ignore_light = False
converter_context.export_preview_surface = False
converter_context.use_meter_as_world_unit = False
converter_context.create_world_as_default_root_prim = True
converter_context.embed_textures = True
converter_context.convert_fbx_to_y_up = False
converter_context.convert_fbx_to_z_up = False
converter_context.merge_all_meshes = False
converter_context.use_double_precision_to_usd_transform_op = False
converter_context.ignore_pivots = False
converter_context.keep_all_materials = True
converter_context.smooth_normals = True
instance = omni.kit.asset_converter.get_instance()
task = instance.create_converter_task(input_asset, output_usd, progress_callback, converter_context)
# Wait for completion.
success = await task.wait_until_finished()
if not success:
carb.log_error(task.get_status(), task.get_detailed_error())
print("converting done")
# Rewrite it to suit your environment.
input_obj = "K:/Modeling/obj/simple_obj2/simple_obj.obj"
output_usd = "K:/Modeling/obj/simple_obj2/simple_obj/simple_obj.usd"
# Convert to USD (obj to USD).
asyncio.ensure_future(
convert_asset_to_usd(input_obj, output_usd)
)
|
ft-lab/omniverse_sample_scripts/Event/UpdateInterval.py |
import omni.ui
import omni.kit.app
import carb.events
import time
import asyncio
class UpdateInterval:
_viewportWindow = None
_subs = None
_visible = True
_time = None
_vTime = None
def __init__(self):
pass
# Update event.
def on_update (self, e: carb.events.IEvent):
if self._viewportWindow == None:
return
curTime = time.time()
diffTime = curTime - self._time
self._time = curTime
if self._vTime == None:
self._vTime = curTime
if curTime < self._vTime + 0.5 and self._visible:
return
self._vTime = curTime
# Update UI.
with self._viewportWindow.frame:
with omni.ui.VStack(height=0):
with omni.ui.Placer(offset_x=20, offset_y=30):
# Set label.
fpsV = 1.0 / diffTime
msgStr = "Update interval(sec) : {:.5f} sec, {:.2f} fps".format(diffTime, fpsV)
f = omni.ui.Label(msgStr)
f.visible = self._visible
f.set_style({"color": 0xff00ffff, "font_size": 32})
def startup (self):
# Get main window viewport.
self._viewportWindow = omni.ui.Window('Viewport')
self._time = time.time()
self._visible = True
# Register for update event.
self._subs = omni.kit.app.get_app().get_update_event_stream().create_subscription_to_pop(self.on_update)
def shutdown (self):
# Release the update event.
async def _exitUpdateEvent ():
self._visible = False
await omni.kit.app.get_app().next_update_async()
self._subs = None
self._vTime = None
asyncio.ensure_future(_exitUpdateEvent())
# -----------------------------------------.
updateI = UpdateInterval()
updateI.startup()
# Finish the process below.
#updateI.shutdown()
|
ft-lab/omniverse_sample_scripts/Event/readme.md | # Event
イベント処理を行います。
## 更新イベント
以下のように更新イベントを登録すると、コールバックとして更新処理が呼ばれます。
```python
import omni.kit.app
import carb.events
def on_update(e: carb.events.IEvent):
pass
subs = omni.kit.app.get_app().get_update_event_stream().create_subscription_to_pop(on_update)
```
## サンプル
|ファイル|説明|
|---|---|
|[UpdateInterval.py](./UpdateInterval.py)|update_event_streamの更新間隔をビューポートに表示|
|
ft-lab/omniverse_sample_scripts/System/readme.md | # System
システムの情報を取得します。
|ファイル|説明|
|---|---|
|[GetPythonVersion.py](./GetPythonVersion.py)|Pythonのバージョンを取得|
|[GetSysPath.py](./GetSysPath.py)|Pythonの検索パスの取得と追加|
|[GetUSDVersion.py](./GetUSDVersion.py)|USDのバージョンを取得|
|
ft-lab/omniverse_sample_scripts/System/GetUSDVersion.py | from pxr import Usd, UsdGeom, UsdPhysics, UsdShade, Sdf, Gf, Tf
print(Usd.GetVersion())
|
ft-lab/omniverse_sample_scripts/System/GetPythonVersion.py | import sys
print(sys.version)
|
ft-lab/omniverse_sample_scripts/System/GetSysPath.py | import sys
import os
# Append path.
def appendSysPath (newPath):
existF = False
for path in sys.path:
if path == newPath:
existF = True
break
if existF:
return
sys.path.append(newPath)
for path in sys.path:
print(path)
|
ft-lab/omniverse_sample_scripts/Geometry/readme.md | # Geometry
ジオメトリを作成するためのサンプルです。
## primvarの仕様変更
USD 20.08からUSD 22.11にかけて、primvarの仕様が変更されました。
「[UsdGeom.PrimvarsAPI](https://openusd.org/release/api/class_usd_geom_primvars_a_p_i.html)」を使用してprimvarを操作する必要があります。
## Samples
|サンプル|説明|
|---|---|
|[CreateSphere](./CreateSphere)|球を作成<br>UsdGeom.Sphere ( https://graphics.pixar.com/usd/release/api/class_usd_geom_sphere.html )を使用。|
|[CreateCube](./CreateCube)|直方体を作成<br>UsdGeom.Cube ( https://graphics.pixar.com/usd/release/api/class_usd_geom_cube.html )を使用。|
|[CreateMesh](./CreateMesh)|Meshを作成/Mesh情報を取得<br>UsdGeom.Mesh ( https://graphics.pixar.com/usd/release/api/class_usd_geom_mesh.html )を使用。|
|ファイル|説明|
|---|---|
|[GetMeshPrimvars.py](./GetMeshPrimvars.py)|選択Meshの「primvars:xxx」の情報を取得。|
|[SetMeshPrimvars.py](./SetMeshPrimvars.py)|選択Meshにprimvarを追加/削除。|
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.