file_path
stringlengths
21
202
content
stringlengths
12
1.02M
size
int64
12
1.02M
lang
stringclasses
9 values
avg_line_length
float64
3.33
100
max_line_length
int64
10
993
alphanum_fraction
float64
0.27
0.93
ft-lab/omniverse_sample_scripts/Extensions/knowledge/config_info.md
# extension.tomlでの記述内容 "extension.toml"に記載する内容の覚書です。 ## 他のExtensionを使用し、機能を呼び出したい 他のExtensionの機能を使用したい場合、[dependencies]にExtension名を追加します。 ``` [dependencies] "omni.audioplayer" = {} ``` この場合は「omni.audioplayer」を有効にします。 こうすることで、Pythonで「import omni.audioplayer」が使用できるようになります。 なお、参照で記載するExtension名は [[python.module]] に記載しているものと同じになります。 以下は「omni.audioplayer」内の"extension.toml"の記載です。 ``` [[python.module]] name = "omni.audioplayer" ``` ここで記載しているExtensionがOnになっていない場合は、対象のExtensionを起動した時に自動的にOnになります。 ## 外部のC/C++モジュールを呼び出す Windows環境の場合、dllの形で外部関数を作成します。 これをExtensionから呼び出すことができます。 ``` [[native.library]] path = "bin/win/x64/OmniverseSimpleDLL.dll" ``` DLL呼び出しのサンプルExtensionは「[ft_lab.sample.callDLL](../ft_lab.sample.callDLL)」をご参照くださいませ。
784
Markdown
21.428571
89
0.743622
ft-lab/omniverse_sample_scripts/Extensions/ft_lab.sample.widgets/ft_lab/sample/widgets/extension.py
import omni.ext import omni.ui from pathlib import Path import os.path import carb.tokens # ----------------------------------------------------------. class WidgetsExtension(omni.ext.IExt): _window = None _sField = None _label0 = None _radioCollection = None _label1 = None _checkbox = None _label2 = None _combobox = None _label3 = None _slider = None _label4 = None # ------------------------------------------------. # Init window. # ------------------------------------------------. def init_window (self): imagesPath = Path(__file__).parent.joinpath("images") # Create new window. self._window = omni.ui.Window("Widgets Window", width=300, height=400) # Radio Button Style. style = { "": {"background_color": 0x0, "image_url": f"{imagesPath}/radio_off.svg"}, ":checked": {"image_url": f"{imagesPath}/radio_on.svg"}, } def onButtonClicked (uiFieldModel, uiLabel): if not uiFieldModel or not uiLabel: return v = uiFieldModel.model.get_value_as_string() uiLabel.text = "Input : " + v def onRadioValueChanged (uiFieldModel, uiLabel): if not uiFieldModel or not uiLabel: return v = uiFieldModel.get_value_as_int() uiLabel.text = "Select Radio : " + str(v) def onCheckBoxValueChanged (uiFieldModel, uiLabel): if not uiFieldModel or not uiLabel: return b = uiFieldModel.get_value_as_bool() uiLabel.text = "CheckBox : " + str(b) def onComboBoxValueChanged (uiFieldModel, uiLabel): if not uiFieldModel or not uiLabel: return v = uiFieldModel.get_value_as_int() uiLabel.text = "ComboBox : " + str(v) def onSliderValueChanged (uiFieldModel, uiLabel): if not uiFieldModel or not uiLabel: return v = uiFieldModel.get_value_as_float() uiLabel.text = "Slider : " + str(v) # ------------------------------------------. with self._window.frame: # Create window UI. with omni.ui.VStack(height=0): # ------------------------------------------. # StringField & Button. # ------------------------------------------. omni.ui.Spacer(height=4) self._sField = omni.ui.StringField(width=120, height=14, style={"color": 0xffffffff}) self._sField.model.set_value("xxx") omni.ui.Spacer(height=4) omni.ui.Spacer(height=4) btn = omni.ui.Button(" Button ") omni.ui.Spacer(height=4) # Label. with omni.ui.HStack(width=0): omni.ui.Spacer(width=8) self._label0 = omni.ui.Label("") btn.set_clicked_fn(lambda s = self._sField, l = self._label0: onButtonClicked(s, l)) # Separator. omni.ui.Spacer(height=4) omni.ui.Line(style={"border_width":2, "color":0xff202020}) omni.ui.Spacer(height=4) # ------------------------------------------. # Radio Button. # ------------------------------------------. # Radio button. self._radioCollection = omni.ui.RadioCollection() radioLBtnList = [] with omni.ui.HStack(width=0): for i in range(3): with omni.ui.HStack(style=style): radio = omni.ui.RadioButton(radio_collection=self._radioCollection, width=30, height=30) omni.ui.Label(f"Radio {i} ", name="text") radioLBtnList.append(radio) # Label. with omni.ui.HStack(width=0): omni.ui.Spacer(width=8) self._label1 = omni.ui.Label("") # Update label. onRadioValueChanged(self._radioCollection.model, self._label1) for radio in radioLBtnList: radio.set_clicked_fn(lambda f = self._radioCollection.model, l = self._label1: onRadioValueChanged(f, l)) # Separator. omni.ui.Spacer(height=4) omni.ui.Line(style={"border_width":2, "color":0xff202020}) omni.ui.Spacer(height=4) # ------------------------------------------. # CheckBox. # ------------------------------------------. # CheckBox omni.ui.Spacer(height=4) with omni.ui.HStack(width=0): self._checkbox = omni.ui.CheckBox() omni.ui.Label(" CheckBox") omni.ui.Spacer(height=4) # Label. with omni.ui.HStack(width=0): omni.ui.Spacer(width=8) self._label2 = omni.ui.Label("") # Update label. onCheckBoxValueChanged(self._checkbox.model, self._label2) self._checkbox.model.add_value_changed_fn(lambda f = self._checkbox.model, l = self._label2: onCheckBoxValueChanged(f, l)) # Separator. omni.ui.Spacer(height=4) omni.ui.Line(style={"border_width":2, "color":0xff202020}) omni.ui.Spacer(height=4) # ------------------------------------------. # ComboBox. # ------------------------------------------. # ComboBox omni.ui.Spacer(height=4) self._combobox = omni.ui.ComboBox(1, "Item1", "Item2", "Item3") omni.ui.Spacer(height=4) # Label. with omni.ui.HStack(width=0): omni.ui.Spacer(width=8) self._label3 = omni.ui.Label("") # Update label. onComboBoxValueChanged(self._combobox.model.get_item_value_model(), self._label3) cModel = self._combobox.model.get_item_value_model() cModel.add_value_changed_fn(lambda f = cModel, l = self._label3: onComboBoxValueChanged(f, l)) # Separator. omni.ui.Spacer(height=4) omni.ui.Line(style={"border_width":2, "color":0xff202020}) omni.ui.Spacer(height=4) # ------------------------------------------. # Slider. # ------------------------------------------. # Slider. omni.ui.Spacer(height=4) self._slider = omni.ui.FloatSlider(min=0.0, max=10.0) self._slider.model.set_value(1.2) omni.ui.Spacer(height=4) # Label. with omni.ui.HStack(width=0): omni.ui.Spacer(width=8) self._label4 = omni.ui.Label("") onSliderValueChanged(self._slider.model, self._label4) self._slider.model.add_value_changed_fn(lambda f = self._slider.model, l = self._label4: onSliderValueChanged(f, l)) # Separator. omni.ui.Spacer(height=4) omni.ui.Line(style={"border_width":2, "color":0xff202020}) omni.ui.Spacer(height=4) # ------------------------------------------. # Image. # ------------------------------------------. # 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" omni.ui.Image(imagePath, width=64, height=64) # ------------------------------------------------. # Term window. # ------------------------------------------------. def term_window (self): if self._window != None: self._window = None # ------------------------------------------------. # Startup. # ------------------------------------------------. def on_startup(self, ext_id): self.init_window() # ------------------------------------------------. # Shutdown. # ------------------------------------------------. def on_shutdown(self): self.term_window()
8,726
Python
36.294872
138
0.43273
ft-lab/omniverse_sample_scripts/Extensions/ft_lab.sample.widgets/docs/CHANGELOG.md
# CHANGELOG This document records all notable changes to ``ft_lab.sample.widgets`` extension.
97
Markdown
15.333331
81
0.762887
ft-lab/omniverse_sample_scripts/Extensions/ft_lab.sample.widgets/docs/README.md
# Python Extension Example [ft_lab.sample.widgets] sample extension.
75
Markdown
14.199997
50
0.733333
ft-lab/omniverse_sample_scripts/Extensions/ft_lab.sample.uiSceneViewportOverlay/ft_lab/sample/uiSceneViewportOverlay/extension.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 from pathlib import Path import math # Kit104 : changed from omni.kit.viewport_legacy to omni.kit.viewport.utility.get_active_viewport_window import omni.kit.viewport.utility # Reference : https://github.com/NVIDIA-Omniverse/kit-extension-sample-ui-scene # ----------------------------------------------------------. class UISceneViewportOverlayExtension(omni.ext.IExt): _scene_view = None _stage = None _viewport_api = None _active_vp_window = None # ------------------------------------------------. # Init window. # ------------------------------------------------. def init_window (self, ext_id : str): imagesPath = Path(__file__).parent.joinpath("images") # Get current stage. self._stage = omni.usd.get_context().get_stage() # Kit104 : Get active viewport window. self._active_vp_window = omni.kit.viewport.utility.get_active_viewport_window() self._viewport_api = self._active_vp_window.viewport_api with self._active_vp_window.get_frame(ext_id): self._scene_view = sc.SceneView() with self._scene_view.scene: # Edges of cube cubeSize = 100.0 sc.Line([-cubeSize, -cubeSize, -cubeSize], [cubeSize, -cubeSize, -cubeSize]) sc.Line([-cubeSize, cubeSize, -cubeSize], [cubeSize, cubeSize, -cubeSize]) sc.Line([-cubeSize, -cubeSize, cubeSize], [cubeSize, -cubeSize, cubeSize]) sc.Line([-cubeSize, cubeSize, cubeSize], [cubeSize, cubeSize, cubeSize]) sc.Line([-cubeSize, -cubeSize, -cubeSize], [-cubeSize, cubeSize, -cubeSize]) sc.Line([cubeSize, -cubeSize, -cubeSize], [cubeSize, cubeSize, -cubeSize]) sc.Line([-cubeSize, -cubeSize, cubeSize], [-cubeSize, cubeSize, cubeSize]) sc.Line([cubeSize, -cubeSize, cubeSize], [cubeSize, cubeSize, cubeSize]) sc.Line([-cubeSize, -cubeSize, -cubeSize], [-cubeSize, -cubeSize, cubeSize]) sc.Line([-cubeSize, cubeSize, -cubeSize], [-cubeSize, cubeSize, cubeSize]) sc.Line([cubeSize, -cubeSize, -cubeSize], [cubeSize, -cubeSize, cubeSize]) sc.Line([cubeSize, cubeSize, -cubeSize], [cubeSize, cubeSize, cubeSize]) # Use Transform to change position. moveT = sc.Matrix44.get_translation_matrix(0, 0, 0) with sc.Transform(transform=moveT): sc.Label("Hello Omniverse !!", alignment = omni.ui.Alignment.CENTER, color=cl("#ffff00a0"), size=20) # Register the SceneView with the Viewport to get projection and view updates self._viewport_api.add_scene_view(self._scene_view) # ------------------------------------------------. # Term window. # ------------------------------------------------. def term_window (self): if self._scene_view: # Empty the SceneView of any elements it may have self._scene_view.scene.clear() # Be a good citizen, and un-register the SceneView from Viewport updates if self._active_vp_window: self._active_vp_window.viewport_api.remove_scene_view(self._scene_view) self._active_vp_window = None # ------------------------------------------------. # Startup. # ------------------------------------------------. def on_startup(self, ext_id): self.init_window(ext_id) # ------------------------------------------------. # Shutdown. # ------------------------------------------------. def on_shutdown(self): self.term_window()
3,851
Python
42.772727
120
0.538302
ft-lab/omniverse_sample_scripts/Extensions/ft_lab.sample.uiSceneViewportOverlay/docs/CHANGELOG.md
# CHANGELOG This document records all notable changes to ``ft_lab.sample.uiSceneViewportOverlay`` extension.
112
Markdown
17.83333
96
0.794643
ft-lab/omniverse_sample_scripts/Extensions/ft_lab.sample.uiSceneViewportOverlay/docs/README.md
# Python Extension Example [ft_lab.sample.uiSceneViewportOverlay] sample extension.
90
Markdown
17.199997
65
0.777778
ft-lab/omniverse_sample_scripts/Extensions/ft_lab.sample.uiSceneShowPrimName/ft_lab/sample/uiSceneShowPrimName/extension.py
from pxr import Usd, UsdGeom, CameraUtil, UsdShade, UsdSkel, 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 import omni.kit.app import carb.events from pathlib import Path import time # Kit104 : changed from omni.kit.viewport_legacy to omni.kit.viewport.utility.get_active_viewport_window import omni.kit.viewport.utility # Reference : https://github.com/NVIDIA-Omniverse/kit-extension-sample-ui-scene # -------------------------------------. # Scene draw process. # -------------------------------------. 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) # ----------------------------------------------------------. class UISceneShowPrimNameExtension(omni.ext.IExt): _scene_view = None _stage = None _sceneDraw = None _time = 0 _selectedPrimPaths = None _active_vp_window = None _viewport_api = None _active_viewport_name = "" _ext_id = "" # ------------------------------------------------. # Update event. # Update when selection shape changes. # Update when the active viewport is switched. # ------------------------------------------------. def on_update (self, e: carb.events.IEvent): # Check every 0.2 seconds. curTime = time.time() diffTime = curTime - self._time if diffTime > 0.2: self._time = curTime # Get selection. selection = omni.usd.get_context().get_selection() paths = selection.get_selected_prim_paths() # Selection changed. if self._selectedPrimPaths == None or self._selectedPrimPaths != paths: self._selectedPrimPaths = paths # Update drawing. if self._sceneDraw != None: self._sceneDraw.invalidate() # If the active viewport name has changed. active_vp_window = omni.kit.viewport.utility.get_active_viewport_window() if active_vp_window != None and active_vp_window.name != self._active_viewport_name: # Rebuild overlay. self.term_window() self.init_window(self._ext_id) # ------------------------------------------------. # Init window. # ------------------------------------------------. def init_window (self, ext_id : str): self._ext_id = ext_id # Get current stage. self._stage = omni.usd.get_context().get_stage() self._time = time.time() # Kit104 : Get active viewport window. self._active_vp_window = omni.kit.viewport.utility.get_active_viewport_window() # Get viewport API. self._viewport_api = self._active_vp_window.viewport_api # Register a callback to be called when the camera in the viewport is changed. self._subs_viewport_change = self._viewport_api.subscribe_to_view_change(self._viewport_changed) with self._active_vp_window.get_frame(ext_id): self._scene_view = sc.SceneView() # Add the manipulator into the SceneView's scene with self._scene_view.scene: ObjectInfoManipulator(model=ObjectInfoModel()) # Register the SceneView with the Viewport to get projection and view updates self._viewport_api.add_scene_view(self._scene_view) # ------------------------------------------------. # Term window. # ------------------------------------------------. def term_window (self): if self._scene_view: # Empty the SceneView of any elements it may have self._scene_view.scene.clear() # Be a good citizen, and un-register the SceneView from Viewport updates if self._active_vp_window: self._active_vp_window.viewport_api.remove_scene_view(self._scene_view) self._active_vp_window = None # ------------------------------------------------. # Startup. # ------------------------------------------------. def on_startup(self, ext_id): self.init_window(ext_id) # ------------------------------------------------. # Shutdown. # ------------------------------------------------. def on_shutdown(self): self.term_window()
5,705
Python
35.113924
114
0.522524
ft-lab/omniverse_sample_scripts/Extensions/ft_lab.sample.uiSceneShowPrimName/docs/CHANGELOG.md
# CHANGELOG This document records all notable changes to ``ft_lab.sample.uiSceneShowPrimName`` extension.
109
Markdown
17.33333
93
0.788991
ft-lab/omniverse_sample_scripts/Extensions/ft_lab.sample.uiSceneShowPrimName/docs/README.md
# Python Extension Example [ft_lab.sample.uiSceneShowPrimName] sample extension.
87
Markdown
16.599997
62
0.770115
ft-lab/omniverse_sample_scripts/Extensions/ft_lab.sample.uiScene/ft_lab/sample/uiScene/extension.py
import omni.ext import omni.ui from omni.ui import color as cl from omni.ui import scene as sc from pathlib import Path # ----------------------------------------------------------. class UISceneExtension(omni.ext.IExt): _window = None _scene_view = None # ------------------------------------------------. # Init window. # ------------------------------------------------. def init_window (self): imagesPath = Path(__file__).parent.joinpath("images") # Create new window. self._window = omni.ui.Window("UI Scene Window", width=300, height=400) # ------------------------------------------. with self._window.frame: # Create window UI. with omni.ui.VStack(height=0): omni.ui.Spacer(height=4) omni.ui.Label("Use omni.ui.scene for custom drawing.") omni.ui.Spacer(height=4) self._scene_view = sc.SceneView( aspect_ratio_policy=sc.AspectRatioPolicy.PRESERVE_ASPECT_FIT, height=200 ) with self._scene_view.scene: sc.Line([-1.0, -1.0, 0], [1.0, 1.0, 0], color=cl.red, thickness=2) sc.Line([-1.0, 1.0, 0], [1.0, -1.0, 0], color=cl.green, thickness=1) sc.Arc(0.5, color=cl("#5040ff")) sc.Rectangle(0.3, 0.3, wireframe=False, color=cl("#c0ff00")) # Use Transform to change position. moveT = sc.Matrix44.get_translation_matrix(0.0, -0.8, 0) with sc.Transform(transform=moveT): sc.Label("Test", alignment = omni.ui.Alignment.CENTER, color=cl.black, size=20) # ------------------------------------------------. # Term window. # ------------------------------------------------. def term_window (self): if self._window != None: self._window = None # ------------------------------------------------. # Startup. # ------------------------------------------------. def on_startup(self, ext_id): self.init_window() # ------------------------------------------------. # Shutdown. # ------------------------------------------------. def on_shutdown(self): self.term_window()
2,341
Python
36.174603
103
0.408372
ft-lab/omniverse_sample_scripts/Extensions/ft_lab.sample.uiScene/docs/README.md
# Python Extension Example [ft_lab.sample.uiScene] sample extension.
75
Markdown
14.199997
50
0.733333
ft-lab/omniverse_sample_scripts/Rendering/readme.md
# Rendering レンダリング画像を取得します。 |サンプル|説明| |---|---| |[Capture](./Capture)|レンダリング画像を取得|
109
Markdown
11.222221
39
0.495413
ft-lab/omniverse_sample_scripts/Rendering/Capture/CaptureRenderingColorToBuffer.py
from pxr import Usd, UsdGeom, UsdPhysics, UsdShade, Sdf, Gf, Tf import asyncio from PIL import Image import ctypes import carb from omni.kit.viewport.utility import get_active_viewport, capture_viewport_to_buffer # See also : https://forums.developer.nvidia.com/t/how-to-get-the-backbuffer-of-omniverses-current-viewport/236825 # -------------------------------------------. # Capture LDR. # -------------------------------------------. async def capture(): # Get active viewport. active_viewport = get_active_viewport() await active_viewport.wait_for_rendered_frames() # Called when capture is complete. callbackExit = False def capture_callback(buffer, buffer_size, width, height, format): nonlocal callbackExit print(f"Buffer size : {buffer_size}") print(f"Resolution : {width} x {height} ") print(f"TextureFormat : {format}") # TextureFormat.RGBA8_UNORM # Get capture image. if str(format) == "TextureFormat.RGBA8_UNORM": # Get buffer from void *. try: ctypes.pythonapi.PyCapsule_GetPointer.restype = ctypes.POINTER(ctypes.c_byte * buffer_size) ctypes.pythonapi.PyCapsule_GetPointer.argtypes = [ctypes.py_object, ctypes.c_char_p] content = ctypes.pythonapi.PyCapsule_GetPointer(buffer, None) except Exception as e: carb.log_error(f"Failed to get capture buffer: {e}") callbackExit = True return # Create image. # content.contents is RGBA buffers. image = Image.frombytes("RGBA", (width, height), content.contents) # Show. image.show() callbackExit = True # Capturing. cap_obj = capture_viewport_to_buffer(active_viewport, capture_callback) await omni.kit.app.get_app_interface().next_update_async() # Wait for a callback to return from a callback. while callbackExit == False: await asyncio.sleep(0.05) print(f"Capture complete.") # -------------------------------------------. asyncio.ensure_future( capture() )
2,141
Python
32.999999
114
0.602522
ft-lab/omniverse_sample_scripts/Rendering/Capture/CaptureRenderingColorToFile.py
from pxr import Usd, UsdGeom, UsdPhysics, UsdShade, Sdf, Gf, Tf import asyncio import carb import carb.settings from omni.kit.viewport.utility import get_active_viewport, capture_viewport_to_file # See also : omni.kit.capture. # -------------------------------------------. # Capture LDR/HDR. # -------------------------------------------. async def capture(filePath : str, hdr : bool = False): # Assign ldr/hdr in settings. settings = carb.settings.get_settings() prevAsyncRendering = settings.get("/app/asyncRendering") prevAsyncRenderingLowLatency = settings.get("/app/asyncRenderingLowLatency") prevHdr = settings.get("/app/captureFrame/hdr") settings.set("/app/asyncRendering", False) settings.set("/app/asyncRenderingLowLatency", False) settings.set("/app/captureFrame/hdr", hdr) # Get active viewport. active_viewport = get_active_viewport() await active_viewport.wait_for_rendered_frames() # Capturing. cap_obj = capture_viewport_to_file(active_viewport, filePath) await omni.kit.app.get_app_interface().next_update_async() # awaiting completion. result = await cap_obj.wait_for_result(completion_frames=30) settings.set("/app/asyncRendering", prevAsyncRendering) settings.set("/app/asyncRenderingLowLatency", prevAsyncRenderingLowLatency) settings.set("/app/captureFrame/hdr", prevHdr) print(f"Capture complete [{filePath}].") # -------------------------------------------. asyncio.ensure_future( capture("K:/temp/output.png") ) # HDR capture not working? asyncio.ensure_future( capture("K:/temp/output.exr", True) )
1,619
Python
32.749999
83
0.665843
ft-lab/omniverse_sample_scripts/Rendering/Capture/readme.md
# Capture レンダリング画像を取得。 Kit.104で動作するように確認。 "omni.kit.viewport.utility"を使用したキャプチャ。 |サンプル|説明| |---|---| |[CaptureRenderingColorToFile.py](./CaptureRenderingColorToFile.py) |レンダリング画像をファイルに保存。| |[CaptureRenderingColorToBuffer.py](./CaptureRenderingColorToBuffer.py) |レンダリング画像をバッファ(RGBA)で取得し、PILのImageで表示。| |[CaptureCameraRenderingColorToBuffer.py](./CaptureCameraRenderingColorToBuffer.py) |指定のカメラからのレンダリングを行い、PILのImageで表示。<br>レンダリングのViewportは非表示にして、オフラインレンダリングを行う。| ## 古い実装 キャプチャを行うには、Extensionの"omni.syntheticdata"をOnにして使用する必要があります。 |サンプル|説明| |---|---| |[CaptureRenderingDepth.py](./CaptureRenderingDepth.py)|Synthetic Data Sensorを使用して、レンダリングのDepthをファイル保存。<br>また、Viewportで"Synthetic Data Sensor"の"Depth"をOnにしておく必要があります。<br>![capture_SyntheticDataSensor_1.jpg](./images/capture_SyntheticDataSensor_1.jpg)|
872
Markdown
35.374999
256
0.75344
ft-lab/omniverse_sample_scripts/Rendering/Capture/CaptureRenderingDepth.py
""" Use "Synthetic Data Sensor". This requires that Extension "omni.syntheticdata" be enabled. Set "Depth" of "Synthetic Data Sensor" to On. """ from pxr import Usd, UsdGeom, UsdPhysics, UsdShade, Sdf, Gf, Tf import omni.ui import omni.kit.app import omni.syntheticdata # Use omni.syntheticdata extension. import numpy as np from PIL import Image import itertools # Colorize Helpers (ref : omni.syntheticdata) def colorize_depth(depth_image): height, width = depth_image.shape[:2] colorized_image = np.zeros((height, width, 4)) depth_image[depth_image == 0.0] = 1e-5 depth_image = np.clip(depth_image, 0, 255) depth_image -= np.min(depth_image) depth_image /= np.max(depth_image) + 1e-8 colorized_image[:, :, 0] = depth_image colorized_image[:, :, 1] = depth_image colorized_image[:, :, 2] = depth_image colorized_image[:, :, 3] = 1 colorized_image = (colorized_image * 255).astype(int) return colorized_image # Get main window viewport. window = omni.ui.Window('Viewport') viewportI = omni.kit.viewport_legacy.acquire_viewport_interface() vWindow = viewportI.get_viewport_window(None) iface = omni.syntheticdata._syntheticdata.acquire_syntheticdata_interface() sensor_list = iface.get_sensor_list(vWindow) for sensorD in sensor_list: if iface.get_sensor_type(sensorD) == omni.syntheticdata._syntheticdata.SensorType.DepthLinear: # Get viewport image. data = iface.get_sensor_host_float_texture_array(sensorD) # Get size. hei, wid = data.shape[:2] # Store data (buff[hei][wid]). buff = np.frombuffer(data, np.float32).reshape(hei, wid, -1) buff[buff == buff.max()] = 0 # Save the Viewport image as a file. # The path should be rewritten to match your environment. filePath = "K:/temp/output_depth.png" # Convert float32 to RGBA. rgbaBuff = colorize_depth(buff.squeeze()) rgbaBuff2 = list(itertools.chain.from_iterable(rgbaBuff)) rgbaBuff3 = [] for item in rgbaBuff2: rgbaBuff3.append((item[0], item[1], item[2], item[3])) # Create new image (with PIL). im = Image.new("RGBA", (wid, hei), (0, 0, 0, 0)) im.putdata(rgbaBuff3) # store rgba. im.save(filePath, quality=95)
2,301
Python
32.852941
98
0.659713
ft-lab/omniverse_sample_scripts/Rendering/Capture/CaptureCameraRenderingColorToBuffer.py
from pxr import Usd, UsdGeom, UsdPhysics, UsdShade, Sdf, Gf, Tf import asyncio from PIL import Image import ctypes import carb from omni.kit.viewport.utility import get_active_viewport, capture_viewport_to_buffer, create_viewport_window, get_viewport_from_window_name from omni.kit.viewport.utility.camera_state import ViewportCameraState # See also : https://forums.developer.nvidia.com/t/how-to-get-the-backbuffer-of-omniverses-current-viewport/236825 # -------------------------------------------. # Search for viewport with specified name. # -------------------------------------------. def SearchViewportWindow(window_name : str): try: from omni.kit.viewport.window import get_viewport_window_instances for window in get_viewport_window_instances(None): if window.title == window_name: return window except ImportError: pass return None # -------------------------------------------. # Capture LDR. # -------------------------------------------. async def captureCamera(cameraPrimPath : str): if cameraPrimPath == None or cameraPrimPath == "": carb.log_error("Camera path is not specified.") return stage = omni.usd.get_context().get_stage() prim = stage.GetPrimAtPath(cameraPrimPath) if prim.IsValid() == False: carb.log_error(f"[{cameraPrimPath}] could not be found.") return # Create a Viewport corresponding to the camera. # If a Viewport already exists, reuse it. viewportName = "Viewport Camera" #viewport_api = get_viewport_from_window_name(viewportName) viewport_api = None viewportWindow = SearchViewportWindow(viewportName) if viewportWindow != None: viewport_api = viewportWindow.viewport_api if viewport_api == None: # Create new viewport. viewportWindow = create_viewport_window(viewportName, width=800, height=600) viewport_api = viewportWindow.viewport_api # Hide Viewport viewportWindow.visible = False if viewport_api == None: carb.log_error("Viewport could not be created.") return viewport_api.set_active_camera(cameraPrimPath) await viewport_api.wait_for_rendered_frames() # Called when capture is complete. cImage = None callbackExit = False def capture_callback(buffer, buffer_size, width, height, format): nonlocal cImage nonlocal callbackExit print(f"Buffer size : {buffer_size}") print(f"Resolution : {width} x {height} ") print(f"TextureFormat : {format}") # TextureFormat.RGBA8_UNORM if str(format) != "TextureFormat.RGBA8_UNORM": callbackExit = True return # Get capture image. try: ctypes.pythonapi.PyCapsule_GetPointer.restype = ctypes.POINTER(ctypes.c_byte * buffer_size) ctypes.pythonapi.PyCapsule_GetPointer.argtypes = [ctypes.py_object, ctypes.c_char_p] content = ctypes.pythonapi.PyCapsule_GetPointer(buffer, None) except Exception as e: carb.log_error(f"Failed to get capture buffer: {e}") callbackExit = True return # Create image. # content.contents is RGBA buffers. cImage = Image.frombytes("RGBA", (width, height), content.contents) callbackExit = True # Capturing. cap_obj = capture_viewport_to_buffer(viewport_api, capture_callback) await omni.kit.app.get_app_interface().next_update_async() # Wait for a callback to return from a callback. while callbackExit == False: await asyncio.sleep(0.05) # Destroy Viewport window. # Note that Viewport must be discarded completely or it will consume the GPU. viewportWindow.destroy() viewportWindow = None print(f"Capture complete.") # Show image. if cImage != None: cImage.show() # -------------------------------------------. asyncio.ensure_future( captureCamera("/World/Camera") )
3,992
Python
32.554622
140
0.634269
ft-lab/omniverse_sample_scripts/Camera/GetCurrentCamera.py
from pxr import Usd, UsdGeom, CameraUtil, UsdShade, Sdf, Gf, Tf import omni.kit # Get viewport. # Kit103 : changed from omni.kit.viewport to omni.kit.viewport_legacy #viewport = omni.kit.viewport_legacy.get_viewport_interface() #viewportWindow = viewport.get_viewport_window() # Kit104 : changed from omni.kit.viewport_legacy to omni.kit.viewport.utility.get_active_viewport_window import omni.kit.viewport.utility # Get active viewport window. active_vp_window = omni.kit.viewport.utility.get_active_viewport_window() viewport_api = active_vp_window.viewport_api # Get camera path ("/OmniverseKit_Persp" etc). cameraPath = viewport_api.camera_path.pathString print("Active camera path : " + cameraPath) # Get stage. stage = omni.usd.get_context().get_stage() #time_code = omni.timeline.get_timeline_interface().get_current_time() * stage.GetTimeCodesPerSecond() time_code = Usd.TimeCode.Default() # Get active camera. cameraPrim = stage.GetPrimAtPath(cameraPath) if cameraPrim.IsValid(): camera = UsdGeom.Camera(cameraPrim) # UsdGeom.Camera cameraV = camera.GetCamera(time_code) # Gf.Camera print("Aspect : " + str(cameraV.aspectRatio)) print("fov(H) : " + str(cameraV.GetFieldOfView(Gf.Camera.FOVHorizontal))) print("fov(V) : " + str(cameraV.GetFieldOfView(Gf.Camera.FOVVertical))) print("FocalLength : " + str(cameraV.focalLength)) print("World to camera matrix : " + str(cameraV.transform)) viewMatrix = cameraV.frustum.ComputeViewMatrix() print("View matrix : {viewMatrix}") viewInv = viewMatrix.GetInverse() # Camera position(World). cameraPos = viewInv.Transform(Gf.Vec3f(0, 0, 0)) print(f"Camera position(World) : {cameraPos}") # Camera vector(World). cameraVector = viewInv.TransformDir(Gf.Vec3f(0, 0, -1)) print(f"Camera vector(World) : {cameraVector}") projectionMatrix = cameraV.frustum.ComputeProjectionMatrix() print(f"Projection matrix : {projectionMatrix}") #cv = CameraUtil.ScreenWindowParameters(cameraV) #print(cv.screenWindow)
2,055
Python
35.714285
104
0.725061
ft-lab/omniverse_sample_scripts/Camera/readme.md
# Camera カメラ操作を行います。 カメラはUsdGeom.Camera ( https://graphics.pixar.com/usd/release/api/class_usd_geom_camera.html ) を使用します。 Omniverse Kit.102では「omni.kit.viewport」を使っていましたが、kit.103では「omni.kit.viewport_legacy」となりました(とりあえずの変更)。 kit.104では「omni.kit.viewport_legacy」は廃止になっています。 ```python import omni.kit.viewport.utility # Get active viewport window. active_vp_window = omni.kit.viewport.utility.get_active_viewport_window() viewport_api = active_vp_window.viewport_api # Get camera path ("/OmniverseKit_Persp" etc). cameraPath = viewport_api.camera_path.pathString ``` としてviewport_apiからカメラのPrimパスを取得します。 kit.104は"Viewport 2.0"となっており、複数のViewportを持つことができます。 そのため、アクティブなビューポートを"omni.kit.viewport.utility.get_active_viewport_window()"から取得してきています。 ## サンプル Kit104以上で動作。 |ファイル|説明| |---|---| |[CreateCamera.py](./CreateCamera.py)|カメラを作成| |[GetCurrentCamera.py](./GetCurrentCamera.py)|カレントのカメラを情報を取得| |[CalcPanoramaCameraVector.py](./CalcPanoramaCameraVector.py)|立体視用の2つのカメラを作成|
1,043
Markdown
30.636363
107
0.732502
ft-lab/omniverse_sample_scripts/Camera/CalcPanoramaCameraVector.py
from pxr import Usd, UsdGeom, CameraUtil, UsdShade, Sdf, Gf, Tf import omni.kit # IPD (cm). ipdValue = 6.4 # Get viewport. # Kit103 : changed from omni.kit.viewport to omni.kit.viewport_legacy #viewport = omni.kit.viewport_legacy.get_viewport_interface() #viewportWindow = viewport.get_viewport_window() # Kit104 : changed from omni.kit.viewport_legacy to omni.kit.viewport.utility.get_active_viewport_window import omni.kit.viewport.utility # Get active viewport window. active_vp_window = omni.kit.viewport.utility.get_active_viewport_window() viewport_api = active_vp_window.viewport_api # Get camera path ("/OmniverseKit_Persp" etc). cameraPath = viewport_api.camera_path.pathString # Get stage. stage = omni.usd.get_context().get_stage() #time_code = omni.timeline.get_timeline_interface().get_current_time() * stage.GetTimeCodesPerSecond() time_code = Usd.TimeCode.Default() # ---------------------------------. # Create new camera. # ---------------------------------. def createNewCamera (orgCamera : Gf.Camera, pathName : str, position : Gf.Vec3f, direction : Gf.Vec3f): cameraGeom = UsdGeom.Camera.Define(stage, pathName) cameraGeom.CreateFocusDistanceAttr(orgCamera.GetFocusDistanceAttr().Get()) cameraGeom.CreateFocalLengthAttr(orgCamera.GetFocalLengthAttr().Get()) cameraGeom.CreateFStopAttr(orgCamera.GetFStopAttr().Get()) # Set position. UsdGeom.XformCommonAPI(cameraGeom).SetTranslate((position[0], position[1], position[2])) # Set rotation(Y-Up (0, 1, 0)). m = Gf.Matrix4f().SetLookAt(Gf.Vec3f(0, 0, 0), direction, Gf.Vec3f(0, 1, 0)) rV = -m.ExtractRotation().Decompose(Gf.Vec3d(1, 0, 0), Gf.Vec3d(0, 1, 0), Gf.Vec3d(0, 0, 1)) UsdGeom.XformCommonAPI(cameraGeom).SetRotate((rV[0], rV[1], rV[2]), UsdGeom.XformCommonAPI.RotationOrderXYZ) # Set scale. UsdGeom.XformCommonAPI(cameraGeom).SetScale((1, 1, 1)) # ---------------------------------. # Get active camera. cameraPrim = stage.GetPrimAtPath(cameraPath) if cameraPrim.IsValid(): camera = UsdGeom.Camera(cameraPrim) # UsdGeom.Camera cameraV = camera.GetCamera(time_code) # Gf.Camera # Get view matrix. viewMatrix = cameraV.frustum.ComputeViewMatrix() # Two camera positions in the view. ipdH = ipdValue * 0.5 leftVPos = Gf.Vec3f(-ipdH, 0, 0) rightVPos = Gf.Vec3f( ipdH, 0, 0) # Camera vector(World). viewInv = viewMatrix.GetInverse() vVector = viewInv.TransformDir(Gf.Vec3f(0, 0, -1)) # Convert to camera position in world coordinates. leftWPos = viewInv.Transform(leftVPos) rightWPos = viewInv.Transform(rightVPos) # Create camera. pathStr = '/World' leftPathStr = pathStr + '/camera_left' createNewCamera(camera, leftPathStr, leftWPos, vVector) rightPathStr = pathStr + '/camera_right' createNewCamera(camera, rightPathStr, rightWPos, vVector)
2,877
Python
34.097561
112
0.68926
ft-lab/omniverse_sample_scripts/Camera/CreateCamera.py
from pxr import Usd, UsdGeom, UsdPhysics, UsdShade, Sdf, Gf, Tf # Get stage. stage = omni.usd.get_context().get_stage() # Create camera. pathName = '/World/camera' cameraGeom = UsdGeom.Camera.Define(stage, pathName) cameraGeom.CreateFocalLengthAttr(24.0) cameraGeom.CreateFocusDistanceAttr(400.0) cameraGeom.CreateFStopAttr(0.0) cameraGeom.CreateProjectionAttr('perspective') # Set position. UsdGeom.XformCommonAPI(cameraGeom).SetTranslate((0.0, 20.0, 40.0)) # Set rotation. UsdGeom.XformCommonAPI(cameraGeom).SetRotate((-20, 15.0, 0.0), UsdGeom.XformCommonAPI.RotationOrderXYZ) # Set scale. UsdGeom.XformCommonAPI(cameraGeom).SetScale((1, 1, 1)) # Change active camera. # Kit103 : changed from omni.kit.viewport to omni.kit.viewport_legacy #viewport = omni.kit.viewport_legacy.get_viewport_interface() #viewport.get_viewport_window().set_active_camera(pathName) # Kit104 : changed from omni.kit.viewport_legacy to omni.kit.viewport.utility.get_active_viewport_window import omni.kit.viewport.utility # Get active viewport window. active_vp_window = omni.kit.viewport.utility.get_active_viewport_window() viewport_api = active_vp_window.viewport_api viewport_api.set_active_camera(pathName)
1,203
Python
29.871794
104
0.78138
ft-lab/omniverse_sample_scripts/Samples/readme.md
# Samples 実用的に使えそうなスクリプトのサンプルです。 |サンプル|説明| |---|---| |[CreateSimpleCurve](./CreateSimpleCurve)|複数のSphereをつなぐチューブ形状を生成| |[UnitsToCentimeters](./UnitsToCentimeters)|Stageの単位をセンチメートルに統一(MetersPerUnitを0.01にする)|
231
Markdown
24.777775
91
0.714286
ft-lab/omniverse_sample_scripts/Samples/CreateSimpleCurve/readme.md
# CreateSimpleCurve Xform内の複数のSphereを使用し、Spbereをスプライン補間したチューブ形状を作成します。 ## 使い方 複数のSphereを配置します。 このSphereをつなぐようにスプラインでチューブ形状がMeshとして作成されることになります。 ![createSimpleCurve_01.jpg](./images/createSimpleCurve_01.jpg) また、Xformに対してマテリアルを割り当てておきます。 Xformを選択した状態でScript Editorで「[CreateSimpleCurve.py](./CreateSimpleCurve.py)」を実行します。 Create Curveウィンドウが表示されました。 ![createSimpleCurve_02.png](./images/createSimpleCurve_02.png) "Number of divisions"で分割数を指定して"Create"ボタンを押します。 Sphereを曲線上でつないだチューブ形状がMeshとして生成されます。 ![createSimpleCurve_03.png](./images/createSimpleCurve_03.png) ![createSimpleCurve_04.png](./images/createSimpleCurve_04.png)
685
Markdown
27.583332
87
0.766423
ft-lab/omniverse_sample_scripts/Samples/CreateSimpleCurve/CreateSimpleCurve.py
# ----------------------------------------------------------. # SplineのCurveを作成するスクリプト. # ----------------------------------------------------------. from pxr import Usd, UsdGeom, UsdPhysics, UsdShade, UsdSkel, Sdf, Gf, Tf from scipy import interpolate import numpy as np import math import omni.ui # Get stage. stage = omni.usd.get_context().get_stage() rootPath = '/World' # --------------------------------------------------------. # 3Dの頂点座標より、スプラインとして細分割した頂点を返す. # @param[in] vList Gf.Vec3fの配列.4つ以上であること. # @param[in] divCou 分割数。len(vList)よりも大きい値のこと. # @return 再分割されたGf.Vec3fの配列. # --------------------------------------------------------. def curveInterpolation (vList, divCou : int): # XYZを配列に分離. xList = [] yList = [] zList = [] for p in vList: xList.append(p[0]) yList.append(p[1]) zList.append(p[2]) retVList = [] tck,u = interpolate.splprep([xList, yList, zList], k=3, s=0) u = np.linspace(0, 1, num=divCou, endpoint=True) spline = interpolate.splev(u, tck) for i in range(divCou): retVList.append(Gf.Vec3f(spline[0][i], spline[1][i], spline[2][i])) return retVList # --------------------------------------------------------. # 選択Primの子で球の座標を配列に格納. # @return Gf.Vec3fの配列, 半径(cm), マテリアル. # --------------------------------------------------------. def getSelectedSpheresPoint (): selection = omni.usd.get_context().get_selection() paths = selection.get_selected_prim_paths() if len(paths) == 0: return None xformCache = UsdGeom.XformCache(0) prim = stage.GetPrimAtPath(paths[0]) # retRに半径(cm)が入る。vPosList[]に頂点座標が入る. retR = -1.0 vPosList = [] pChildren = prim.GetChildren() for cPrim in pChildren: typeName = cPrim.GetTypeName() if typeName == 'Sphere': globalPose = xformCache.GetLocalToWorldTransform(cPrim) # Decompose transform. translate, rotation, scale = UsdSkel.DecomposeTransform(globalPose) # 半径を取得. if retR < 0.0: sphereGeom = UsdGeom.Sphere(cPrim) r = sphereGeom.GetRadiusAttr().Get() retR = r * scale[0] vPosList.append(translate) if len(vPosList) == 0: return None # primに割り当てられているマテリアルを取得. material = None rel = UsdShade.MaterialBindingAPI(prim).GetDirectBindingRel() pathList = rel.GetTargets() if len(pathList) > 0: materialPath = pathList[0] material = UsdShade.Material(stage.GetPrimAtPath(materialPath)) return vPosList, retR, material # --------------------------------------------------------. # 外積の計算. # --------------------------------------------------------. def calcCross (v1 : Gf.Vec3f, v2 : Gf.Vec3f): v1_2 = Gf.Vec4f(v1[0], v1[1], v1[2], 1.0) v2_2 = Gf.Vec4f(v2[0], v2[1], v2[2], 1.0) v3 = Gf.HomogeneousCross(v1_2, v2_2) return Gf.Vec3f(v3[0], v3[1], v3[2]) # --------------------------------------------------------. # 進行方向からベクトルを計算. # @param[in] vDir 進行方向のベクトル. # @return 4x4行列. # --------------------------------------------------------. def calcDirToMatrix (vDir : Gf.Vec3f): vDir0 = vDir.GetNormalized() m = Gf.Matrix4f() vX = Gf.Vec3f(1.0, 0.0, 0.0) vY = Gf.Vec3f(0.0, 1.0, 0.0) dirY = vY angleV = Gf.Dot(vDir0, vY) if math.fabs(angleV) > 0.999: dirY = vX dirX = calcCross(vDir0, dirY) dirX = dirX.GetNormalized() dirY = calcCross(dirX, vDir0) dirY = dirY.GetNormalized() m[0, 0] = dirX[0] m[0, 1] = dirX[1] m[0, 2] = dirX[2] m[1, 0] = dirY[0] m[1, 1] = dirY[1] m[1, 2] = dirY[2] m[2, 0] = vDir0[0] m[2, 1] = vDir0[1] m[2, 2] = vDir0[2] return m # --------------------------------------------------------. # 頂点の配列と半径、分割数により、チューブ状のMeshを作成. # @param[in] name 形状名. # @param[in] vList Gf.Vec3fの配列. # @param[in] radiusV 半径. # @param[in] divUCou 円の分割数. # @param[in] divVCou 進行方向での分割数. # @param[in] material 割り当てるマテリアル. # --------------------------------------------------------. def createTubeMesh (name : str, vList, radiusV : float, divUCou : int, divVCou : int, material : UsdShade.Material): pathStr = rootPath + '/cables' prim = stage.GetPrimAtPath(pathStr) if prim.IsValid() == False: UsdGeom.Xform.Define(stage, pathStr) prim = stage.GetPrimAtPath(pathStr) # 子形状に同一名がある場合は連番を付ける. newName = name index = 0 pChildren = prim.GetChildren() if pChildren != None: while True: chkF = False for cPrim in pChildren: name2 = cPrim.GetName() if name2 == newName: index += 1 newName = name + '_' + str(index) chkF = True break if chkF == False: break name = newName meshName = pathStr + '/' + name meshGeom = UsdGeom.Mesh.Define(stage, meshName) # Bind material. if material != None: UsdShade.MaterialBindingAPI(meshGeom).Bind(material) # +Zを中心とした半径radiusVのポイントを計算. circleV = [] dd = (math.pi * 2.0) / ((float)(divUCou)) dPos = 0.0 for i in range(divUCou): circleV.append(Gf.Vec3f(math.cos(dPos), math.sin(dPos), 0.0)) dPos += dd # ポリゴンメッシュのポイントと法線. m = Gf.Matrix4f() vDir0 = Gf.Vec3f(0.0, 0.0, 1.0) newVList = [] newVNList = [] vListCou = len(vList) for i in range(vListCou): if i + 1 >= vListCou: p1 = vList[i] else: p1 = vList[i] p2 = vList[(i + 1) % vListCou] vDir = (p2 - p1).GetNormalized() if i == 0: m = calcDirToMatrix(p2 - p1) vDir0 = vDir else: mInv = m.GetInverse() pV0 = mInv.TransformDir(vDir0) pV1 = mInv.TransformDir(vDir) m0 = calcDirToMatrix(pV0) m1 = calcDirToMatrix(pV1) m = (m1.GetInverse() * m0).GetInverse() * m for j in range(divUCou): p = circleV[j] p = m.Transform(Gf.Vec3f(p[0] * radiusV, p[1] * radiusV, p[2] * radiusV)) pp = p + p1 newVList.append([pp[0], pp[1], pp[2]]) pN = p.GetNormalized() newVNList.append([pN[0], pN[1], pN[2]]) vDir0 = vDir meshGeom.CreatePointsAttr(newVList) meshGeom.CreateNormalsAttr(newVNList) # 面の頂点数の配列を格納. facesCou = (vListCou - 1) * divUCou faceVCouList = [int] * (facesCou) for i in range(facesCou): faceVCouList[i] = 4 meshGeom.CreateFaceVertexCountsAttr(faceVCouList) # ポリゴンメッシュの面を配置. faceIndexList = [] iPos = 0 vCou = vListCou - 1 for i in range(vCou): for j in range(divUCou): i0 = iPos + j i1 = iPos + ((j + 1) % divUCou) if i + 1 >= vListCou: i2 = ((j + 1) % divUCou) i3 = j else: i2 = iPos + divUCou + ((j + 1) % divUCou) i3 = iPos + divUCou + j faceIndexList.append(i3) faceIndexList.append(i2) faceIndexList.append(i1) faceIndexList.append(i0) iPos += divUCou meshGeom.CreateFaceVertexIndicesAttr(faceIndexList) # ------------------------------------------. # Clicked button event. # ------------------------------------------. def onButtonClick(hDivCouIntField): hDivCou = hDivCouIntField.model.get_value_as_int() if hDivCou < 4: hDivCou = 4 # 選択Primの子で球の座標を配列に格納. retV = getSelectedSpheresPoint() if retV == None: print("Select an XForm that contains spheres.") else: vPosList, retR, material = retV # 頂点座標の配置から、細分化した頂点を計算. newVPosList = curveInterpolation(vPosList, hDivCou) # チューブ形状を作成. createTubeMesh('cable', newVPosList, retR, 12, hDivCou, material) # --------------------------------------------------------. # メイン部. # --------------------------------------------------------. # ------------------------------------------. # Create new window. my_window = omni.ui.Window("Create Curve", width=300, height=200) with my_window.frame: with omni.ui.VStack(height=0): hDivCouIntField = None with omni.ui.Placer(offset_x=8, offset_y=8): # Set label. f = omni.ui.Label("Select a Prim with multiple spheres as children.") with omni.ui.Placer(offset_x=8, offset_y=4): with omni.ui.HStack(width=300): omni.ui.Label("Number of divisions : ", width=50) hDivCouIntField = omni.ui.IntField(width=200, height=0) hDivCouIntField.model.set_value(50) with omni.ui.Placer(offset_x=8, offset_y=4): # Set button. btn = omni.ui.Button("Create", width=200, height=0) btn.set_clicked_fn(lambda f = hDivCouIntField: onButtonClick(f))
8,972
Python
28.613861
116
0.509362
ft-lab/omniverse_sample_scripts/Samples/UnitsToCentimeters/readme.md
# UnitsToCentimeters Stageの単位をセンチメートルに統一します。 [UnitsToCentimeters.py](./UnitsToCentimeters.py) は、 metersPerUnitを0.01に変換するスクリプトです。 ## 使い方 このスクリプトは、StageのmetersPerUnitが0.01(センチメートル)でない場合に DefaultPrimのscaleを調整し、metersPerUnitを0.01に置き換えます。 ルートPrimがXformで「DefaultPrim」の指定がされているのが必要条件になります。 なお、Nucleus上のusdファイルの場合はmetersPerUnitの変更が許可されないことがありました。 そのため、このスクリプトはローカルのusdに対して行うようにしてください。 なお、このスクリプトはファイル保存は行いません。 必要であれば、処理後にusdファイルを保存してご使用くださいませ。
479
Markdown
24.263157
59
0.810021
ft-lab/omniverse_sample_scripts/Samples/UnitsToCentimeters/UnitsToCentimeters.py
from pxr import Usd, UsdGeom, UsdPhysics, UsdShade, Sdf, Gf, Tf # Get stage. stage = omni.usd.get_context().get_stage() # Get metersPerUnit (default : 0.01). metersPerUnit = UsdGeom.GetStageMetersPerUnit(stage) # ----------------------------------------------------------------------. # Convert the scale of Mesh and Xform so that metersPerUnit is 0.01. # ----------------------------------------------------------------------. def ConvPrimScale (_metersPerUnit, path): prim = stage.GetPrimAtPath(path) if prim.IsValid() == False: return False # Set xformOpOrder (Xform/Mesh). transformOrder = prim.GetAttribute('xformOpOrder') typeName = prim.GetTypeName() if typeName == 'Xform' or typeName == 'Mesh': tV = prim.GetAttribute('xformOp:scale') if tV.IsValid() == False: if prim.GetAttribute('xformOp:translate').IsValid() == False: prim.CreateAttribute("xformOp:translate", Sdf.ValueTypeNames.Float3, False).Set(Gf.Vec3f(0, 0, 0)) if prim.GetAttribute('xformOp:scale').IsValid() == False: prim.CreateAttribute("xformOp:scale", Sdf.ValueTypeNames.Float3, False).Set(Gf.Vec3f(1, 1, 1)) if prim.GetAttribute('xformOp:rotateXYZ').IsValid() == False: prim.CreateAttribute("xformOp:rotateXYZ", Sdf.ValueTypeNames.Float3, False).Set(Gf.Vec3f(0, 0, 0)) transformOrder = prim.CreateAttribute("xformOpOrder", Sdf.ValueTypeNames.String, False) transformOrder.Set(["xformOp:translate", "xformOp:rotateXYZ", "xformOp:scale"]) if transformOrder.IsValid() and transformOrder.Get() != None: tV = prim.GetAttribute('xformOp:scale') if tV.IsValid(): scaleV = tV.Get() scale = _metersPerUnit / 0.01 tV.Set(scaleV * scale) return True return False # ----------------------------------------------------------------------. if abs(metersPerUnit - 0.01) < 1e-5: print("The units of Stage are already centimeters.") else: # Get default prim. defaultPrim = stage.GetDefaultPrim() if defaultPrim == None or defaultPrim.IsValid() == False: print("DefaultPrim does not exist.") else: path = defaultPrim.GetPath().pathString if ConvPrimScale(metersPerUnit, path) == False: print("Failed to change DefaultPrim.") else: # Set metersPerUnit. try: UsdGeom.SetStageMetersPerUnit(stage, 0.01) print("DefaultPrim has been successfully changed.") except Exception as e: print(e)
2,631
Python
40.777777
114
0.578867
ft-lab/omniverse_sample_scripts/Samples/FlipMeshNormals/FlipMeshNormals.py
from pxr import Usd, UsdGeom, UsdPhysics, UsdShade, UsdSkel, Sdf, Gf, Tf # Get stage. stage = omni.usd.get_context().get_stage() # ------------------------------------------------------------. # Flip mesh normals. # ------------------------------------------------------------. def FlipMeshNormals (prim): if prim.GetTypeName() == 'Mesh': m = UsdGeom.Mesh(prim) # If it is displayed. if m.ComputeVisibility() == 'inherited': # Get prim path. path = prim.GetPath().pathString print(prim.GetName()) pChildren = prim.GetChildren() for cPrim in pChildren: FlipMeshNormals(cPrim) # ------------------------------------------------------------. # 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(): FlipMeshNormals(prim)
952
Python
24.078947
72
0.506303
ft-lab/omniverse_sample_scripts/Settings/GetRenderingSize.py
from pxr import Usd, UsdGeom, UsdPhysics, UsdShade, Sdf, Gf, Tf import carb.settings # Get rendering size. # If Render Resolution is "Viewport", -1 will be set. settings = carb.settings.get_settings() width = settings.get('/app/renderer/resolution/width') height = settings.get('/app/renderer/resolution/height') print("Rendering size : " + str(width) + " x " + str(height)) # Set rendering size. #settings.set('/app/renderer/resolution/width', 1280) #settings.set('/app/renderer/resolution/height', 720)
509
Python
32.999998
63
0.72888
ft-lab/omniverse_sample_scripts/Settings/GetKitPath.py
import os.path import carb.tokens kitPath = os.path.abspath(carb.tokens.get_tokens_interface().resolve("${kit}")) print(kitPath)
130
Python
20.83333
79
0.753846
ft-lab/omniverse_sample_scripts/Settings/readme.md
# Settings carb.settingsより、設定を取得します。 これは"/kit/config/kit-core.json"の情報を読み取ります。 |ファイル|説明| |---|---| |[GetKitVersion.py](./GetKitVersion.py)|Omniverse Kitのバージョンを取得| |[GetKitPath.py](./GetKitPath.py)|Omniverse Kitの絶対パスを取得| |[GetRenderingSize.py](./GetRenderingSize.py)|レンダリングサイズを取得| |[GetRenderMode.py](./GetRenderMode.py)|Render Mode(RTX Real-time/RTX Path-traced)を取得、設定<br>Render Modeは、コルーチン内で「await omni.kit.app.get_app().next_update_async()」で1フレーム待ってから変更したほうが安全。|
509
Markdown
35.428569
189
0.701375
ft-lab/omniverse_sample_scripts/Settings/GetKitVersion.py
import omni.kit # Get Omniverse Kit version. kitVersion = omni.kit.app.get_app_interface().get_build_version() # 102.1.2+release.xxxx print("Kit Version : " + str(kitVersion)) # 102.1.2 print(str(" ") + kitVersion.split("+")[0])
235
Python
18.666665
65
0.67234
ft-lab/omniverse_sample_scripts/Settings/GetRenderMode.py
import omni.kit import carb.settings import asyncio # Get Render Mode. settings = carb.settings.get_settings() renderMode = settings.get('/rtx/rendermode') # rtx, iray activeRender = settings.get('/renderer/active') if activeRender == 'iray': print("Render Mode : Iray") else: if renderMode == 'RaytracedLighting': print("Render Mode : RTX Real-time") else: if renderMode == 'PathTracing': print("Render Mode : RTX Path-traced") else: print("Render Mode : " + renderMode) # Set Render mode. # It is safe to wait for one frame in the coroutine to change the RenderMode. async def SetRenderMode (modeName : str): await omni.kit.app.get_app().next_update_async() settings.set('/rtx/rendermode', modeName) # Set "RTX Real-time" asyncio.ensure_future(SetRenderMode('RaytracedLighting')) # Set "RTX Path-traced" asyncio.ensure_future(SetRenderMode('PathTracing'))
933
Python
25.685714
77
0.687031
ft-lab/omniverse_sample_scripts/Scene/OpenUSDFile.py
from pxr import Usd, UsdGeom, UsdShade, Sdf, Gf, Tf try: # Open USD File. ret = omni.usd.get_context().open_stage("xxx.usd") print("open_stage : " + str(ret)) except Exception as e: print(e)
209
Python
19.999998
54
0.626794
ft-lab/omniverse_sample_scripts/Scene/CloseStage.py
from pxr import Usd, UsdGeom, UsdShade, Sdf, Gf, Tf omni.usd.get_context().close_stage()
90
Python
21.749995
51
0.722222
ft-lab/omniverse_sample_scripts/Scene/StageUpAxis.py
from pxr import Usd, UsdGeom, UsdPhysics, UsdShade, Sdf, Gf, Tf # Get stage. stage = omni.usd.get_context().get_stage() # Get UpAxis. upAxis = UsdGeom.GetStageUpAxis(stage) if upAxis == UsdGeom.Tokens.x: print("UpAxis : X") elif upAxis == UsdGeom.Tokens.y: print("UpAxis : Y") elif upAxis == UsdGeom.Tokens.z: print("UpAxis : Z") # Set UpAxis (Y-Up). try: UsdGeom.SetStageUpAxis(stage, UsdGeom.Tokens.y) except Exception as e: print(e)
461
Python
19.999999
63
0.67679
ft-lab/omniverse_sample_scripts/Scene/GetResolvedPath.py
from pxr import Usd, UsdGeom, UsdPhysics, UsdShade, Sdf, Gf, Tf try: # Open USD File. usdPath = "https://ft-lab.github.io/usd/omniverse/usd/cyawan/cyawan.usdc" ret = omni.usd.get_context().open_stage(usdPath) if ret == True: # Get stage. stage = omni.usd.get_context().get_stage() # Convert relative paths to absolute paths from Stage. # It is necessary to specify the relative path where the texture name, Reference, etc. exists on the Stage. absPath = stage.ResolveIdentifierToEditTarget("./cyawan_mat_albedo.png") # "https://ft-lab.github.io/usd/omniverse/usd/cyawan/cyawan_mat_albedo.png" print(absPath) except Exception as e: print(e)
721
Python
33.380951
115
0.667129
ft-lab/omniverse_sample_scripts/Scene/readme.md
# Scene シーン(Stage)の情報を取得/操作します。 |ファイル|説明| |---|---| |[StageUpAxis.py](./StageUpAxis.py)|Stageのアップベクトルの取得/設定| |[CreateHierarchy.py](./CreateHierarchy.py)|Xformを使って階層構造を作って形状を配置<br>![createHierarchy_img.jpg](./images/createHierarchy_img.jpg)| |[GetAllFacesCount.py](./GetAllFacesCount.py)|シーン内のすべてのMeshの面数を合計して表示。<br>対象はMesh/PointInstancer。| |[TraverseHierarchy.py](./TraverseHierarchy.py)|シーンの階層構造をたどってPrim名を表示。<br>Meshの場合はMeshの面数も表示。| |[Traverse_mesh.py](./Traverse_mesh.py)|Usd.PrimRangeを使ってPrimを取得し、Meshのみを格納| |[GetMetersPerUnit.py](./GetMetersPerUnit.py)|metersPerUnitの取得/設定| |[NewStage.py](./NewStage.py)|何も配置されていない新しいStageを作成します。<br>なお、直前のStageの変更は保存されません。| |[CloseStage.py](./CloseStage.py)|現在のStageを閉じます。<br>なお、直前のStageの変更は保存されません。| |[OpenUSDFile.py](./OpenUSDFile.py)|指定のUSDファイルを開きます。<br>なお、直前のStageの変更は保存されません。| |[GetResolvedPath.py](./GetResolvedPath.py)|カレントStageで指定されている相対パス(テクスチャやReferenceとして参照しているusdファイルなど)を絶対パスに変換。<br>存在しないパスを指定した場合は空文字が返る。| ## レイヤ関連 |ファイル|説明| |---|---| |[GetRealPath.py](./Layers/GetRealPath.py)|読み込んだStageのパスを取得| |[GetSublayers.py](./Layers/GetSublayers.py)|SubLayerのパスを取得|
1,197
Markdown
51.086954
141
0.729323
ft-lab/omniverse_sample_scripts/Scene/NewStage.py
from pxr import Usd, UsdGeom, UsdShade, Sdf, Gf, Tf omni.usd.get_context().new_stage() print("New Stage !")
109
Python
20.999996
51
0.697248
ft-lab/omniverse_sample_scripts/Scene/GetAllFacesCount.py
from pxr import Usd, UsdGeom, UsdPhysics, UsdShade, Sdf, Gf, Tf # ---------------------------------------. # Get the number of faces used by PointInstancer. # ---------------------------------------. def TraversePointInstancer (prim): typeName = prim.GetTypeName() allCou = 0 if typeName == 'Mesh': m = UsdGeom.Mesh(prim) # If it is displayed. if m.ComputeVisibility() == 'inherited': # Get the number of faces of Mesh. allCou += len(m.GetFaceVertexCountsAttr().Get()) # Recursively traverse the hierarchy. pChildren = prim.GetChildren() for cPrim in pChildren: allCou += TraversePointInstancer(cPrim) return allCou # ---------------------------------------. # traverse the hierarchy. # ---------------------------------------. def TraverseHierarchy_number (depth, prim): if prim.IsValid() == None: return 0 typeName = prim.GetTypeName() allCou = 0 if typeName == 'PointInstancer': m = UsdGeom.PointInstancer(prim) # If it is displayed. if m.ComputeVisibility() == 'inherited': # Get the number of faces used by PointInstancer. facesCou = TraversePointInstancer(prim) piCou = 0 positionsA = m.GetPositionsAttr().Get() if positionsA != None: piCou = len(positionsA) allCou += facesCou * piCou return allCou if typeName == 'Mesh': m = UsdGeom.Mesh(prim) # If it is displayed. if m.ComputeVisibility() == 'inherited': # Get the number of faces of Mesh. allCou += len(m.GetFaceVertexCountsAttr().Get()) # Recursively traverse the hierarchy. pChildren = prim.GetChildren() for cPrim in pChildren: allCou += TraverseHierarchy_number(depth + 1, cPrim) return allCou # ---------------------------------------. # Get stage. stage = omni.usd.get_context().get_stage() # Get default prim. defaultPrim = stage.GetDefaultPrim() # Get root path. rootPath = '/' if defaultPrim.IsValid(): rootPath = defaultPrim.GetPath().pathString # traverse the hierarchy. tPrim = stage.GetPrimAtPath(rootPath) allFacesCou = TraverseHierarchy_number(0, tPrim) print("Number of all faces : " + str(allFacesCou))
2,313
Python
26.879518
63
0.57112
ft-lab/omniverse_sample_scripts/Scene/CreateHierarchy.py
from pxr import Usd, UsdGeom, UsdPhysics, UsdShade, Sdf, Gf, Tf # Get stage. stage = omni.usd.get_context().get_stage() # Get default prim. defaultPrim = stage.GetDefaultPrim() # Get root path. rootPath = '' if defaultPrim.IsValid(): rootPath = defaultPrim.GetPath().pathString # Create empty node(Xform). UsdGeom.Xform.Define(stage, rootPath + '/node1') # Create empty node(Xform). UsdGeom.Xform.Define(stage, rootPath + '/node1/node1_2') # Create sphere. pathName = rootPath + '/node1/sphere' sphereGeom = UsdGeom.Sphere.Define(stage, pathName) # Set radius. sphereGeom.CreateRadiusAttr(1.0) # Set position. UsdGeom.XformCommonAPI(sphereGeom).SetTranslate((-3, 0, 0)) # Create cube. pathName = rootPath + '/node1/cube' cubeGeom = UsdGeom.Cube.Define(stage, pathName) # Set position. UsdGeom.XformCommonAPI(cubeGeom).SetTranslate((0, 0, 0))
856
Python
22.805555
63
0.731308
ft-lab/omniverse_sample_scripts/Scene/GetMetersPerUnit.py
from pxr import Usd, UsdGeom, UsdPhysics, UsdShade, Sdf, Gf, Tf # Get stage. stage = omni.usd.get_context().get_stage() # Get metersPerUnit (default : 0.01). metersPerUnit = UsdGeom.GetStageMetersPerUnit(stage) print("MetersPerUnit : " + str(metersPerUnit)) # Set metersPerUnit. try: UsdGeom.SetStageMetersPerUnit(stage, 0.01) except Exception as e: print(e)
370
Python
23.733332
63
0.732432
ft-lab/omniverse_sample_scripts/Scene/TraverseHierarchy.py
from pxr import Usd, UsdGeom, UsdPhysics, UsdShade, Sdf, Gf, Tf # ---------------------------------------. # traverse the hierarchy. # ---------------------------------------. def TraverseHierarchy (depth, prim): if prim.IsValid() == None: return indentStr = '' for i in range(depth): indentStr += ' ' # Print Prim information. name = prim.GetName() typeName = prim.GetTypeName() s = indentStr + '[ ' + name + ' ]' s += ' type : ' + typeName # If hidden. if UsdGeom.Imageable(prim).ComputeVisibility() == 'invisible': s += ' ** Hide **' print(s) if typeName == 'Mesh': # Get the number of faces of Mesh. m = UsdGeom.Mesh(prim) faceCount = len(m.GetFaceVertexCountsAttr().Get()) print(indentStr + ' Face count : ' + str(faceCount)) # Recursively traverse the hierarchy. pChildren = prim.GetChildren() for cPrim in pChildren: TraverseHierarchy(depth + 1, cPrim) # ---------------------------------------. # Get stage. stage = omni.usd.get_context().get_stage() # Get default prim. print("--- Default prim ---") defaultPrim = stage.GetDefaultPrim() if defaultPrim.IsValid(): print("DefaultPrim(Name) : " + defaultPrim.GetName()) print("DefaultPrim(Path) : " + defaultPrim.GetPath().pathString) else: print("Default Prim does not exist.") print("") # Get root path. rootPath = '/' if defaultPrim.IsValid(): rootPath = defaultPrim.GetPath().pathString print("Root path : " + rootPath) print("") # traverse the hierarchy. tPrim = stage.GetPrimAtPath(rootPath) print("--- Hierarchy ---") TraverseHierarchy(0, tPrim) print("")
1,683
Python
24.515151
68
0.57754
ft-lab/omniverse_sample_scripts/Scene/Traverse_mesh.py
from pxr import Usd, UsdGeom, UsdPhysics, UsdShade, Sdf, Gf, Tf # Get stage. stage = omni.usd.get_context().get_stage() defaultPrim = stage.GetDefaultPrim() if defaultPrim.IsValid(): prims = [] for prim in Usd.PrimRange(defaultPrim): if prim.IsA(UsdGeom.Mesh): # For Mesh. prims.append(prim) for prim in prims: print(prim.GetName() + " (" + prim.GetPath().pathString + ")")
423
Python
25.499998
70
0.628842
ft-lab/omniverse_sample_scripts/Scene/Layers/GetSublayers.py
from pxr import Usd, UsdGeom, UsdPhysics, UsdShade, Sdf, Gf, Tf # Get stage. stage = omni.usd.get_context().get_stage() # Get root layer. rootLayer = stage.GetRootLayer() # Get subLayer paths. sublayerPaths = rootLayer.subLayerPaths for path in sublayerPaths: print(" " + path)
287
Python
19.571427
63
0.71777
ft-lab/omniverse_sample_scripts/Scene/Layers/GetRealPath.py
from pxr import Usd, UsdGeom, UsdPhysics, UsdShade, Sdf, Gf, Tf # Get stage. stage = omni.usd.get_context().get_stage() # Get root layer. rootLayer = stage.GetRootLayer() # Get real path. realPath = rootLayer.realPath print("realPath : " + realPath)
254
Python
18.615383
63
0.712598
ft-lab/omniverse_sample_scripts/Audio/PlaySound.py
import omni.audioplayer # need "omni.audioplayer" extension. import time import asyncio # ----------------------------------------------. # AudioPlayer. # ----------------------------------------------. class AudioPlayer: _player = None _filePath = None _loadSuccess = False _loadBusy = False def __init__(self): pass def startup (self): self._player = omni.audioplayer.create_audio_player() def shutdown (self): self.stop() self._player = None def _file_loaded (self, success : bool): self._loadSuccess = success if success: print("load success!") soundLength = self._player.get_sound_length() print(f"sound length : {soundLength} sec") else: print("load failed...") self._loadBusy = False # Load sound from file. def loadFromFile (self, filePath : str): self._loadSuccess = False if self._player == None: return self._filePath = filePath self._loadBusy = True self._player.load_sound(filePath, self._file_loaded) # Wait for it to finish loading. def isLoad (self): while self._loadBusy: time.sleep(0.1) return self._loadSuccess # Called when playback is finished. def _play_finished (self): print("play finished.") # Play sound. def play (self): if self._player == None: return False self._player.play_sound(self._filePath, None, self._play_finished, 0.0) # Stop sound. def stop (self): if self._player != None: self._player.stop_sound() # ----------------------------------------------. # Initialize AudioPlayer. audio = AudioPlayer() audio.startup() # Load sound file. # Specify an Audio file name that matches your environment. audio.loadFromFile("./audio/HitWall.ogg") if audio.isLoad(): for i in range(3): # Play sound. audio.play() # Wait one seconds. time.sleep(1.0) # Terminate AudioPlayer. audio.shutdown()
2,093
Python
23.348837
79
0.548973
ft-lab/omniverse_sample_scripts/Audio/readme.md
# Audio Audioファイルを読み込んで再生します。 Audio自身はUSDでPrimとして指定することができます。 UsdAudio Proposal https://graphics.pixar.com/usd/release/wp_usdaudio.html また、OmniverseでもUIとしてAudioのStageへのインポートができます。 https://docs.omniverse.nvidia.com/app_create/prod_extensions/ext_audio.html Audioファイルフォーマットは、wav/ogg/mp3が再生できるのを確認しています。 USDファイルにAudioを指定でき、この場合はTimelineの指定の位置での再生が可能です。 Pythonスクリプトから任意のタイミングでの再生するにはExtensionの「omni.audioplayer」を使用します。 Audioファイルは [HitWall.ogg](./audio/HitWall.ogg) をサンプルとしてアップしているため、 スクリプトから検索できる位置に配置してご利用くださいませ。 |ファイル|説明| |---|---| |[PlaySound.py](./PlaySound.py)|Audioファイルを読み込んで再生<br>"omni.audioplayer" ExtensionをOnにする必要があります。|
704
Markdown
26.115384
101
0.75142
ft-lab/omniverse_sample_scripts/Prim/IsValid.py
from pxr import Usd, UsdGeom, UsdPhysics, UsdShade, Sdf, Gf, Tf # Get stage. stage = omni.usd.get_context().get_stage() path = "/World" # Get prim. prim = stage.GetPrimAtPath(path) # Use IsValid to check if the specified Prim exists. print(path + " : " + str(prim.IsValid()))
280
Python
20.615383
63
0.685714
ft-lab/omniverse_sample_scripts/Prim/GetSingleSided.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: # Get prim. prim = stage.GetPrimAtPath(path) if prim.IsValid() == False: continue try: singleSidedAttr = prim.GetAttribute("singleSided") if singleSidedAttr != None and singleSidedAttr.IsValid(): # Get singleSided (True/False). if singleSidedAttr.Get() != None: print("[" + prim.GetName() + "] singleSided : " + str(singleSidedAttr.Get())) # Set singleSided. #if prim.GetTypeName() == 'Mesh': # singleSidedAttr = prim.CreateAttribute("singleSided", Sdf.ValueTypeNames.Bool) # singleSidedAttr.Set(True) except Exception as e: print(e)
929
Python
29.999999
93
0.620022
ft-lab/omniverse_sample_scripts/Prim/CreateXform.py
from pxr import Usd, UsdGeom, UsdPhysics, UsdShade, Sdf, Gf, Tf # Get stage. stage = omni.usd.get_context().get_stage() # Get default prim. defaultPrim = stage.GetDefaultPrim() defaultPrimPath = defaultPrim.GetPath().pathString path = defaultPrimPath + '/xform' # Create empty node(Xform). UsdGeom.Xform.Define(stage, path)
329
Python
20.999999
63
0.741641
ft-lab/omniverse_sample_scripts/Prim/readme.md
# Prim USDのPrim(ノード相当)を操作します。 Primの操作は「[CommandsExecute](../Operation/CommandsExecute)」も便利に使用できます。 |ファイル|説明| |---|---| |[IsValid.py](./IsValid.py)|指定のパスのPrimが存在するかチェック(IsValid)| |[GetPrimNamePath.py](./GetPrimNamePath.py)|指定のPrimの名前とパスを取得| |[GetDefaultPrim.py](./GetDefaultPrim.py)|StageのルートとなるPrim(DefaultPrim)を取得| |[SetDefaultPrim.py](./SetDefaultPrim.py)|StageのルートとなるPrim(DefaultPrim)を指定| |[CreateXform.py](./CreateXform.py)|空のノード(Nullノード相当)を作成。<br>USDではこれを"Xform"と呼んでいます。<br>UsdGeom.Xform ( https://graphics.pixar.com/usd/release/api/class_usd_geom_xform.html )を使用します。| |[CreateScope.py](./CreateScope.py)|Scopeを作成。<br>Scopeは移動/回転/スケール要素を持ちません。単純なグルーピング向けです。<br>UsdGeom.Scope ( https://graphics.pixar.com/usd/release/api/class_usd_geom_scope.html )を使用します。| |[GetDoubleSided.py](./GetDoubleSided.py)|ジオメトリでのDoubleSided指定の取得、設定| |[GetSingleSided.py](./GetSingleSided.py)|ジオメトリでのSingleSided指定の取得、設定<br>これはOmniverseでの独自の属性| |[GetParent.py](./GetParent.py)|選択パスの親のPrimを取得| |[GetChildren.py](./GetChildren.py)|選択パスの子のPrimを取得| |[CalcWorldBoundingBox.py](./CalcWorldBoundingBox.py)|選択形状のワールド座標でのバウンディングボックスを計算| |[RemovePrim.py](./RemovePrim.py)|指定のパスのPrimを削除。<br>Sdf.NamespaceEdit.Removeを使用する。| |[RenamePrim.py](./RenamePrim.py)|指定のパスのPrim名を変更。<br>Sdf.NamespaceEdit.Renameを使用する。| |サンプル|説明| |---|---| |[Visibility](./Visibility)|Primの表示/非表示| |[Kind](./Kind)|PrimのKindを取得/設定| |[Transform](./Transform)|Transform(scale/rotate/translate)の取得/設定| |[TypeName](./TypeName)|PrimのTypeName(Xform/Mesh/DistantLightなど)を取得| |[Skeleton](./Skeleton)|Skeletonでの情報を取得| |[Reference](./Reference)|参照(Reference/Payload)を使った複製/参照のチェック| |[PointInstancer](./PointInstancer)|アセット(USDで指定)を複数の位置/回転/スケールで複製配置(PointInstancer)| |[Variant](./Variant)|Variantを使ったPrimの切り替え|
1,873
Markdown
51.055554
191
0.722904
ft-lab/omniverse_sample_scripts/Prim/GetParent.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: # Get prim. prim = stage.GetPrimAtPath(path) if prim.IsValid() == False: continue # Get parent prim. parentPrim = prim.GetParent() if parentPrim.IsValid(): print("[ " + prim.GetPath().pathString + " ]") print(" Parent : " + parentPrim.GetPath().pathString)
561
Python
25.761904
63
0.645276
ft-lab/omniverse_sample_scripts/Prim/CreateScope.py
from pxr import Usd, UsdGeom, UsdPhysics, UsdShade, Sdf, Gf, Tf # Get stage. stage = omni.usd.get_context().get_stage() # Get default prim. defaultPrim = stage.GetDefaultPrim() defaultPrimPath = defaultPrim.GetPath().pathString path = defaultPrimPath + '/scope' # Create scope. UsdGeom.Scope.Define(stage, path)
317
Python
20.199999
63
0.741325
ft-lab/omniverse_sample_scripts/Prim/SetDefaultPrim.py
from pxr import Usd, UsdGeom, UsdPhysics, UsdShade, Sdf, Gf, Tf # Get stage. stage = omni.usd.get_context().get_stage() # Create empty node(Xform). path = "/NewWorld" UsdGeom.Xform.Define(stage, path) prim = stage.GetPrimAtPath(path) # Set default prim. stage.SetDefaultPrim(prim)
285
Python
19.42857
63
0.729825
ft-lab/omniverse_sample_scripts/Prim/GetPrimNamePath.py
from pxr import Usd, UsdGeom, UsdPhysics, UsdShade, Sdf, Gf, Tf # Get stage. stage = omni.usd.get_context().get_stage() # Get prim. orgPath = "/World/defaultLight" prim = stage.GetPrimAtPath(orgPath) if prim.IsValid(): # Get Prim name. name = prim.GetName() print("Name : " + str(name)) # Get Prim path. path = prim.GetPath() print("Path : " + str(path))
383
Python
20.333332
63
0.634465
ft-lab/omniverse_sample_scripts/Prim/RemovePrim.py
from pxr import Usd, UsdGeom, UsdPhysics, UsdShade, Sdf, Gf, Tf # Get stage. stage = omni.usd.get_context().get_stage() # Get prim. path = "/World/Sphere" prim = stage.GetPrimAtPath(path) if prim.IsValid(): # Remove prim. # See here : https://graphics.pixar.com/usd/release/api/class_usd_stage.html#ac605faad8fc2673263775b1eecad2955 # For example, if Prim is used in a layer, RemovePrim will not remove it completely. #stage.RemovePrim(path) # Prepare specified paths as candidates for deletion. edit = Sdf.NamespaceEdit.Remove(path) batchE = Sdf.BatchNamespaceEdit() batchE.Add(edit) # Execute Deletion. stage.GetEditTarget().GetLayer().Apply(batchE)
702
Python
28.291665
114
0.709402
ft-lab/omniverse_sample_scripts/Prim/GetDefaultPrim.py
from pxr import Usd, UsdGeom, UsdPhysics, UsdShade, Sdf, Gf, Tf # Get stage. stage = omni.usd.get_context().get_stage() # Get default prim. defaultPrim = stage.GetDefaultPrim() # Default prim path. defaultPrimPath = defaultPrim.GetPath().pathString print("DefaultPrim : " + defaultPrimPath)
294
Python
23.583331
63
0.744898
ft-lab/omniverse_sample_scripts/Prim/GetChildren.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: # Get prim. prim = stage.GetPrimAtPath(path) if prim.IsValid() == False: continue # Get children. pChildren = prim.GetChildren() if len(pChildren) >= 1: print("[ " + prim.GetPath().pathString + " ]") for cPrim in pChildren: print(" " + cPrim.GetPath().pathString)
585
Python
24.47826
63
0.623932
ft-lab/omniverse_sample_scripts/Prim/GetDoubleSided.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: # Get prim. prim = stage.GetPrimAtPath(path) if prim.IsValid() == False: continue try: gprim = UsdGeom.Gprim(prim) doubleSidedAttr = gprim.GetDoubleSidedAttr() if doubleSidedAttr != None and doubleSidedAttr.IsValid(): # Get doubleSided (True/False). # The Omniverse Viewport does not reflect "doubleSided", but "singleSided". if doubleSidedAttr.Get() != None: print("[" + prim.GetName() + "] doubleSided : " + str(doubleSidedAttr.Get())) # Set DoubleSided. #doubleSidedAttr.Set(True) except Exception as e: print(e)
937
Python
30.266666
93
0.602988
ft-lab/omniverse_sample_scripts/Prim/CalcWorldBoundingBox.py
from pxr import Usd, UsdGeom, UsdPhysics, UsdShade, Sdf, Gf, Tf import omni.usd # Get stage. stage = omni.usd.get_context().get_stage() # Get selection. selection = omni.usd.get_context().get_selection() paths = selection.get_selected_prim_paths() # -------------------------------------------------. # Calculate bounding box in world coordinates. # -------------------------------------------------. def _calcWorldBoundingBox (prim : Usd.Prim): # Calc world boundingBox. bboxCache = UsdGeom.BBoxCache(Usd.TimeCode.Default(), ["default"]) bboxD = bboxCache.ComputeWorldBound(prim).ComputeAlignedRange() bb_min = Gf.Vec3f(bboxD.GetMin()) bb_max = Gf.Vec3f(bboxD.GetMax()) return bb_min, bb_max # -------------------------------------------------. for path in paths: # Get prim. prim = stage.GetPrimAtPath(path) if prim.IsValid() == False: continue print("[ " + str(prim.GetName()) + "] ") bbMin, bbMax = _calcWorldBoundingBox(prim) print(" BoundingBox : " + str(bbMin) + " - " + str(bbMax)) sx = bbMax[0] - bbMin[0] sy = bbMax[1] - bbMin[1] sz = bbMax[2] - bbMin[2] print(" BoundingBoxSize : " + str(sx) + " x " + str(sy) + " x " + str(sz))
1,225
Python
31.263157
79
0.553469
ft-lab/omniverse_sample_scripts/Prim/RenamePrim.py
from pxr import Usd, UsdGeom, UsdPhysics, UsdShade, Sdf, Gf, Tf # Get stage. stage = omni.usd.get_context().get_stage() # Get prim. path = "/World/Sphere" prim = stage.GetPrimAtPath(path) if prim.IsValid(): # Rename prim. # Prepare specified paths as candidates for rename. # "/World/Sphere" to "/World/Sphere2" edit = Sdf.NamespaceEdit.Rename(path, "Sphere2") batchE = Sdf.BatchNamespaceEdit() batchE.Add(edit) # Execute rename. stage.GetEditTarget().GetLayer().Apply(batchE)
519
Python
22.636363
63
0.676301
ft-lab/omniverse_sample_scripts/Prim/Reference/InternalReferenceTest.py
from pxr import Usd, UsdGeom, UsdPhysics, UsdShade, Sdf, Gf, Tf # Get stage. stage = omni.usd.get_context().get_stage() # Get default prim. defaultPrim = stage.GetDefaultPrim() defaultPrimPath = defaultPrim.GetPath().pathString # Create sphere. orgPath = defaultPrimPath + '/org' UsdGeom.Xform.Define(stage, orgPath) spherePath = orgPath + '/sphere' sphereGeom = UsdGeom.Sphere.Define(stage, spherePath) # Set radius. sphereGeom.CreateRadiusAttr(2.0) # Set color. sphereGeom.CreateDisplayColorAttr([(1.0, 0.0, 0.0)]) # Create empty node(Xform). path = defaultPrimPath + '/refShape' UsdGeom.Xform.Define(stage, path) prim = stage.GetPrimAtPath(path) # Set position. UsdGeom.XformCommonAPI(prim).SetTranslate((5.0, 0.0, 0.0)) # Remove references. prim.GetReferences().ClearReferences() # Add a internal reference. # The Path to be added must be an Xform. prim.GetReferences().AddInternalReference(orgPath)
913
Python
24.388888
63
0.751369
ft-lab/omniverse_sample_scripts/Prim/Reference/ReferenceTest2.py
from pxr import Usd, UsdGeom, UsdPhysics, UsdShade, Sdf, Gf, Tf # Get stage. stage = omni.usd.get_context().get_stage() # Get default prim. defaultPrim = stage.GetDefaultPrim() defaultPrimPath = defaultPrim.GetPath().pathString # Create empty node(Xform). path = defaultPrimPath + '/refShape' UsdGeom.Xform.Define(stage, path) prim = stage.GetPrimAtPath(path) # Remove references. prim.GetReferences().ClearReferences() # Add a reference. #usdPath = "./cyawan/cyawan.usdc" usdPath = "https://ft-lab.github.io/usd/omniverse/usd/cyawan/cyawan.usdc" prim.GetReferences().AddReference(usdPath)
595
Python
26.090908
73
0.754622
ft-lab/omniverse_sample_scripts/Prim/Reference/readme.md
# Reference 参照の処理を行います。 ## ReferenceとPayload USDでは、他のUSDを参照する構造として"Reference"と"Payload"があります。 Payload は「弱い参照」となります。 Payload としてインポートした場合は、見た目上は参照と変わりません。 以下はOmniverse Createでのパラメータです(USD自身がこの構造を持っています)。 ![usd_reference_payload.png](./images/usd_reference_payload.png) Payload したUSDはアンロードすることができ、これによりメモリ解放できます。 また、必要な時にロードできます。 対してReferenceの場合は参照のロード/アンロード機能はありません。 Payloadのほうが利便性があるため、基本的にはPayloadで参照を指定するほうがよいかもしれません。 ## サンプル |ファイル|説明| |---|---| |[ReferenceTest.py](./ReferenceTest.py)|作成したXformに対して外部のusdファイルを参照として追加。<br>このサンプルでは、"ft-lab.github.io/usd/omniverse" 内を参照しています。<br>適宜「[sphere.usda](./usd/sphere.usda)」を相対パスとして検索できる位置に配置して試すようにしてください。<br>![usd_prim_reference_00.jpg](./images/usd_prim_reference_00.jpg)| |[PayloadTest.py](./PayloadTest.py)|作成したXformに対して外部のusdファイルを参照(Payload)として追加。<br>このサンプルでは、"ft-lab.github.io/usd/omniverse" 内を参照しています。<br>適宜「[sphere.usda](./usd/sphere.usda)」を相対パスとして検索できる位置に配置して試すようにしてください。<br>![usd_prim_reference_00.jpg](./images/usd_prim_reference_00.jpg)| |[ReferenceTest2.py](./ReferenceTest2.py)|作成したXformに対して外部のテクスチャ付きのusdファイルを参照として追加。<br>このサンプルでは、"ft-lab.github.io/usd/omniverse" 内を参照しています。<br>適宜「[./cyawan/cyawan.usdc](./usd/cyawan/cyawan.usdc)」を相対パスとして検索できる位置に配置して試すようにしてください。<br>![usd_prim_reference_02.jpg](./images/usd_prim_reference_02.jpg)| |[InternalReferenceTest.py](./InternalReferenceTest.py)|作成したXformに対して同一Stage内のPrimを参照として追加<br>![usd_prim_reference_01.jpg](./images/usd_prim_reference_01.jpg)| |[HasReference.py](./HasReference.py)|選択した形状が参照を持つかチェック| |[HasPayload.py](./HasPayload.py)|選択した形状がPayloadを持つかチェック| |[GetReferencePayload.py](./GetReferencePayload.py)|選択した形状がReferenceまたはPayloadの場合に、参照先のパスを取得| ----
1,749
Markdown
52.030301
299
0.765009
ft-lab/omniverse_sample_scripts/Prim/Reference/GetReferencePayload.py
# "Pcp" added below. from pxr import Usd, UsdGeom, UsdPhysics, UsdShade, Sdf, Gf, Tf, Pcp # 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(): # If Prim has Reference or Payload. if prim.HasAuthoredReferences() or prim.HasPayload(): query = Usd.PrimCompositionQuery.GetDirectRootLayerArcs(prim) qList = query.GetCompositionArcs() if qList != None: for arc in qList: arcType = arc.GetArcType() if arcType != Pcp.ArcTypeReference and arcType != Pcp.ArcTypePayload: continue # Get AssetPath. editorProxy, reference = arc.GetIntroducingListEditor() assetPath = reference.assetPath if arcType == Pcp.ArcTypeReference: print("[" + prim.GetName() + "] has reference > " + assetPath) if arcType == Pcp.ArcTypePayload: print("[" + prim.GetName() + "] has payload. > " + assetPath)
1,256
Python
32.972972
89
0.565287
ft-lab/omniverse_sample_scripts/Prim/Kind/readme.md
# Kind PrimのKindを取得/設定。 |ファイル|説明| |---|---| |[SetComponent.py](./SetComponent.py)|選択PrimのKindをComponentに変更| |[GetKind.py](./GetKind.py)|選択PrimのKindを取得|
177
Markdown
13.833332
67
0.610169
ft-lab/omniverse_sample_scripts/Prim/Kind/SetComponent.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: # Get prim. prim = stage.GetPrimAtPath(path) if prim.IsValid() == False: continue # Change the value of Kind in Prim to Component. Usd.ModelAPI(prim).SetKind(Kind.Tokens.component)
464
Python
24.833332
63
0.69181
ft-lab/omniverse_sample_scripts/Prim/Skeleton/GetJoints.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() # -------------------------------------------------------------------. # Traverse. # -------------------------------------------------------------------. def Traverse (prim): if prim.IsValid() == None: return # For Skeleton, get the Joints information. if prim.GetTypeName() == 'Skeleton': jointAttr = prim.GetAttribute("joints") bindTransformsAttr = prim.GetAttribute("bindTransforms") restTransformsAttr = prim.GetAttribute("restTransforms") if jointAttr.IsValid() and bindTransformsAttr.IsValid() and restTransformsAttr.IsValid(): jCou = len(jointAttr.Get()) print("[ " + prim.GetPath().pathString + " ]") for i in range(jCou): jointName = jointAttr.Get()[i] bindTransform = bindTransformsAttr.Get()[i] restTransform = restTransformsAttr.Get()[i] print(str(i) + " : " + jointName) print(" bindTransform : " + str(bindTransform)) print(" restTransform : " + str(restTransform)) # Recursively traverse the hierarchy. pChildren = prim.GetChildren() for cPrim in pChildren: Traverse(cPrim) # -------------------------------------------------------------------. for path in paths: # Get prim. prim = stage.GetPrimAtPath(path) Traverse(prim)
1,621
Python
30.192307
97
0.530537
ft-lab/omniverse_sample_scripts/Prim/Skeleton/GetSkeletonTransforms.py
from pxr import Usd, UsdGeom, UsdPhysics, UsdShade, UsdSkel, Sdf, Gf, Tf import omni.kit # Get stage. stage = omni.usd.get_context().get_stage() # Get selection. selection = omni.usd.get_context().get_selection() paths = selection.get_selected_prim_paths() skel_cache = UsdSkel.Cache() #time_code = omni.timeline.get_timeline_interface().get_current_time() * stage.GetTimeCodesPerSecond() time_code = Usd.TimeCode.Default() for path in paths: # Get prim. prim = stage.GetPrimAtPath(path) if prim.IsValid() and prim.GetTypeName() == 'Skeleton': # Get transform from cache. skel_query = skel_cache.GetSkelQuery(UsdSkel.Skeleton(prim)) transforms = skel_query.ComputeJointLocalTransforms(time_code) # joints name. jointNames = skel_query.GetJointOrder() # joints matrix to translate, rotations, scales. translates, rotations, scales = UsdSkel.DecomposeTransforms(transforms) print(jointNames) print(" Translates : " + str(translates)) print(" Rotations : " + str(rotations)) print(" Scales : " + str(scales))
1,122
Python
31.085713
102
0.674688
ft-lab/omniverse_sample_scripts/Prim/Skeleton/readme.md
# Skeleton Skeletonでの情報を取得。 |ファイル|説明| |---|---| |[GetJoints.py](./GetJoints.py)|選択Primの中に"Skeleton"がある場合に、ジョイント名/バインドの行列/リセットの行列を表示| |[GetSkeletonTransforms.py](./GetSkeletonTransforms.py)|選択Primが"Skeleton"の場合に、ジョイント名と移動/回転/スケールのリストを取得|
261
Markdown
22.81818
107
0.704981
ft-lab/omniverse_sample_scripts/Prim/Visibility/readme.md
# Visibility Primの表示/非表示。 |ファイル|説明| |---|---| |[GetShowHidePrim.py](./GetShowHidePrim.py)|選択Primの表示/非表示を取得| |[ShowHidePrim.py](./ShowHidePrim.py)|選択Primの表示/非表示を切り替え|
190
Markdown
16.363635
65
0.631579
ft-lab/omniverse_sample_scripts/Prim/PointInstancer/PointInstancer_01.py
from pxr import Usd, UsdGeom, UsdPhysics, UsdShade, Sdf, Gf, Tf import random # Get stage. stage = omni.usd.get_context().get_stage() # Get default prim. defaultPrim = stage.GetDefaultPrim() defaultPrimPath = defaultPrim.GetPath().pathString # Create empty node(Xform). path = defaultPrimPath + '/trees' UsdGeom.Xform.Define(stage, path) prim = stage.GetPrimAtPath(path) # Create PointInstancer. pointInstancerPath = path + '/pointInstancer' pointInstancer = UsdGeom.PointInstancer.Define(stage, pointInstancerPath) # Create Reference. refPath = pointInstancerPath + '/asset' UsdGeom.Xform.Define(stage, refPath) prim = stage.GetPrimAtPath(refPath) # Set Kind. #Usd.ModelAPI(prim).SetKind(Kind.Tokens.component) Usd.ModelAPI(prim).SetKind("component") # Set the asset to be referenced. pointInstancer.CreatePrototypesRel().AddTarget(refPath) # Remove references. prim.GetReferences().ClearReferences() # Add a reference. #usdPath = "./simpleTree.usda" usdPath = "https://ft-lab.github.io/usd/omniverse/usd/simpleTree.usda" prim.GetReferences().AddReference(usdPath) # Points data. positions = [] scales = [] protoIndices = [] orientations = [] areaSize = 1000.0 treesCou = 50 for i in range(treesCou): px = random.random() * areaSize - (areaSize * 0.5) pz = random.random() * areaSize - (areaSize * 0.5) scale = random.random() * 0.5 + 0.8 positions.append(Gf.Vec3f(px, 0.0, pz)) # Position. orientations.append(Gf.Quath()) # Rotation. scales.append(Gf.Vec3f(scale, scale, scale)) # Scale. protoIndices.append(0) # asset index. pointInstancer.CreatePositionsAttr(positions) pointInstancer.CreateOrientationsAttr(orientations) pointInstancer.CreateScalesAttr(scales) pointInstancer.CreateProtoIndicesAttr(protoIndices)
1,807
Python
28.16129
73
0.729386
ft-lab/omniverse_sample_scripts/Prim/PointInstancer/readme.md
# PointInstancer 指定のアセット(USDファイルで指定)をPointInstancerを使って、位置/回転/スケールを指定して複製。 UsdGeom.PointInstancer ( https://graphics.pixar.com/usd/release/api/class_usd_geom_point_instancer.html ) を使用します。 |ファイル|説明| |---|---| |[PointInstancer_01.py](./PointInstancer_01.py)|木の"simpleTree.usda"をアセットとして、ランダムな位置/スケールで複製。<br>木のusdは[simpleTree.usda](./usd/simpleTree.usda)を使用しています。<br>![usd_pointinstancer_01.jpg](./images/usd_pointinstancer_01.jpg)|
453
Markdown
44.399996
224
0.739514
ft-lab/omniverse_sample_scripts/Prim/TypeName/readme.md
# TypeName PrimのTypeName(Xform/Mesh/DistantLightなど)を取得。 |ファイル|説明| |---|---| |[GetTypeName.py](./GetTypeName.py)|PrimのTypeNameを取得|
151
Markdown
12.818181
57
0.629139
ft-lab/omniverse_sample_scripts/Prim/Variant/Variant_01.py
from pxr import Usd, UsdGeom, UsdPhysics, UsdShade, Sdf, Gf, Tf # Reference : https://github.com/PixarAnimationStudios/USD/blob/release/extras/usd/tutorials/authoringVariants/authorVariants.py # Get stage. stage = omni.usd.get_context().get_stage() # Get default prim. defaultPrim = stage.GetDefaultPrim() defaultPrimPath = defaultPrim.GetPath().pathString # Create empty node(Xform). path = defaultPrimPath + '/Chair' UsdGeom.Xform.Define(stage, path) prim = stage.GetPrimAtPath(path) # Set VariantSet. variantSet = prim.GetVariantSet('variantGroup') variantSet.AddVariant('chair1') variantSet.AddVariant('chair2') variantSet.AddVariant('chair3') # -----------------------------------------------. # Set Chair. # -----------------------------------------------. def SetChair (index : int, path : str, colorV): # Create reference. # The USD file to be referenced should be changed to suit your environment. usdPath = "https://ft-lab.github.io/usd/omniverse/usd/simple_chair.usda" path2 = path + '/simple_chair_' + str(index) UsdGeom.Xform.Define(stage, path2) prim2 = stage.GetPrimAtPath(path2) prim2.GetReferences().AddReference(usdPath) path3 = path2 + '/simple_chair' targetPrim = UsdGeom.Gprim.Get(stage, path3) try: # Clear Material. UsdShade.MaterialBindingAPI(targetPrim).UnbindAllBindings() # Set Display Color. colorAttr = targetPrim.GetDisplayColorAttr() colorAttr.Set([colorV]) except Exception as e: pass # -----------------------------------------------. # Set 'chair1'. variantSet.SetVariantSelection("chair1") with variantSet.GetVariantEditContext(): SetChair(1, path, (1,0,0)) # Set 'chair2'. variantSet.SetVariantSelection("chair2") with variantSet.GetVariantEditContext(): SetChair(2, path, (0,1,0)) # Set 'chair3'. variantSet.SetVariantSelection("chair3") with variantSet.GetVariantEditContext(): SetChair(3, path, (0,0,1)) # Select current variant. variantSet.SetVariantSelection("chair1")
2,026
Python
30.184615
128
0.670286
ft-lab/omniverse_sample_scripts/Prim/Variant/readme.md
# Variant PrimのGetVariant( https://graphics.pixar.com/usd/release/api/class_usd_prim.html#a607da249e11bc4f5f3b4bf0db99861ab )を使用して、1つのPrim内で複数のPrimを「VariantSet」として登録します。 この例の場合は椅子のusdファイル([simple_chair.usda](../Reference/usd/simple_chair.usda))を参照し、色を変えて3つの形状としています。 ![prim_variant_01.jpg](./images/prim_variant_01.jpg) 表示されるのはVariantで指定された1つの形状のみです。 |ファイル|説明| |---|---| |[Variant_01.py](./Variant_01.py)|Variantを使ったPrimの切り替えのテスト|
467
Markdown
32.428569
163
0.734475
ft-lab/omniverse_sample_scripts/Prim/Transform/SetRotate.py
from pxr import Usd, UsdGeom, UsdPhysics, UsdShade, Sdf, Gf, Tf import omni.usd import omni.timeline # Get stage. stage = omni.usd.get_context().get_stage() # Get selection. selection = omni.usd.get_context().get_selection() paths = selection.get_selected_prim_paths() # --------------------------------------------------. # Set Rotate. # --------------------------------------------------. def _setRotate (prim : Usd.Prim, rV : Gf.Vec3f): if prim == None: return # Get rotOrder. # If rotation does not exist, rotOrder = UsdGeom.XformCommonAPI.RotationOrderXYZ. xformAPI = UsdGeom.XformCommonAPI(prim) time_code = Usd.TimeCode.Default() translation, rotation, scale, pivot, rotOrder = xformAPI.GetXformVectors(time_code) # Convert rotOrder to "xformOp:rotateXYZ" etc. t = xformAPI.ConvertRotationOrderToOpType(rotOrder) rotateAttrName = "xformOp:" + UsdGeom.XformOp.GetOpTypeToken(t) # Set rotate. rotate = prim.GetAttribute(rotateAttrName).Get() if rotate != None: # Specify a value for each type. if type(rotate) == Gf.Vec3f: prim.GetAttribute(rotateAttrName).Set(Gf.Vec3f(rV)) elif type(rotate) == Gf.Vec3d: prim.GetAttribute(rotateAttrName).Set(Gf.Vec3d(rV)) else: # xformOpOrder is also updated. xformAPI.SetRotate(Gf.Vec3f(rV), rotOrder) for path in paths: prim = stage.GetPrimAtPath(path) if prim.IsValid() == True: # Print prim name. print(f"[ {prim.GetName()} ]") rV = Gf.Vec3f(10.0, 25.0, 12.0) _setRotate(prim, rV)
1,599
Python
30.999999
87
0.61601
ft-lab/omniverse_sample_scripts/Prim/Transform/GetTransformOrder.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() == True: # Print prim name. print(f"[ {prim.GetName()} ]") # Order of Transform elements. transformOrder = prim.GetAttribute('xformOpOrder').Get() for sV in transformOrder: print(f" {sV}")
558
Python
24.40909
64
0.636201
ft-lab/omniverse_sample_scripts/Prim/Transform/SetTransform.py
from pxr import Usd, UsdGeom, UsdPhysics, UsdShade, Sdf, Gf, Tf # Get stage. stage = omni.usd.get_context().get_stage() # Create cube. pathName = '/World/cube' cubeGeom = UsdGeom.Cube.Define(stage, pathName) # Set cube size. cubeGeom.CreateSizeAttr(10.0) # Set color. cubeGeom.CreateDisplayColorAttr([(0.0, 1.0, 0.0)]) # Set transform. prim = stage.GetPrimAtPath(pathName) prim.CreateAttribute("xformOp:translate", Sdf.ValueTypeNames.Float3, False).Set(Gf.Vec3f(0, 10, 0)) prim.CreateAttribute("xformOp:scale", Sdf.ValueTypeNames.Float3, False).Set(Gf.Vec3f(1, 2, 1)) prim.CreateAttribute("xformOp:rotateXYZ", Sdf.ValueTypeNames.Float3, False).Set(Gf.Vec3f(120, 45, 0)) transformOrder = prim.CreateAttribute("xformOpOrder", Sdf.ValueTypeNames.String, False) transformOrder.Set(["xformOp:translate", "xformOp:rotateXYZ", "xformOp:scale"])
844
Python
34.208332
101
0.75237
ft-lab/omniverse_sample_scripts/Prim/Transform/SetPivot.py
from pxr import Usd, UsdGeom, UsdPhysics, UsdShade, Sdf, Gf, Tf import omni.usd import omni.timeline # Get stage. stage = omni.usd.get_context().get_stage() # Get selection. selection = omni.usd.get_context().get_selection() paths = selection.get_selected_prim_paths() # --------------------------------------------------. # Set pivot. # --------------------------------------------------. def _setPivot (prim : Usd.Prim, pV : Gf.Vec3f): pivot = prim.GetAttribute("xformOp:translate:pivot").Get() if pivot != None: # Specify a value for each type. if type(pivot) == Gf.Vec3f: prim.GetAttribute("xformOp:translate:pivot").Set(Gf.Vec3f(pV)) elif type(pivot) == Gf.Vec3d: prim.GetAttribute("xformOp:translate:pivot").Set(Gf.Vec3d(pV)) else: # xformOpOrder is also updated. # ["xformOp:translate", "xformOp:translate:pivot", "xformOp:rotateXYZ", "xformOp:scale", "!invert!xformOp:translate:pivot"] # The following do not work correctly? #xformAPI = UsdGeom.XformCommonAPI(prim) #xformAPI.SetPivot(Gf.Vec3f(pV)) prim.CreateAttribute("xformOp:translate:pivot", Sdf.ValueTypeNames.Float3, False).Set(Gf.Vec3f(pV)) # ["xformOp:translate", "xformOp:rotateXYZ", "xformOp:scale", "xformOp:translate:pivot", "!invert!xformOp:translate:pivot"] transformOrder = prim.GetAttribute("xformOpOrder").Get() orderList = [] for sV in transformOrder: orderList.append(sV) orderList.append("xformOp:translate:pivot") orderList.append("!invert!xformOp:translate:pivot") prim.GetAttribute("xformOpOrder").Set(orderList) # --------------------------------------------------. for path in paths: prim = stage.GetPrimAtPath(path) if prim.IsValid() == True: # Print prim name. print(f"[ {prim.GetName()} ]") pV = Gf.Vec3f(10.0, 20.0, 0.0) _setPivot(prim, pV)
1,953
Python
37.313725
131
0.596518
ft-lab/omniverse_sample_scripts/Prim/Transform/readme.md
# Transform Transform(scale/rotate/translate)情報の取得/設定。 |ファイル|説明| |---|---| |[GetTransform.py](./GetTransform.py)|選択された形状のTransform要素を取得| |[GetTransformOrder.py](./GetTransformOrder.py)|選択された形状のxformOpOrder(Transformの変換順)を取得| |[SetTransform.py](./SetTransform.py)|Cubeを作成し、Transformを指定| |[GetWorldTransform.py](./GetWorldTransform.py)|選択形状のTransformをワールド変換して表示| |[GetLocalMatrix.py](./GetLocalMatrix.py)|選択形状のローカル座標での4x4変換行列を取得| |[GetTransformVectors.py](./GetTransformVectors.py)|UsdGeom.XformCommonAPIを使用して、選択形状の移動/回転/スケール/Pivot/回転を取得| |[SetTranslate.py](./SetTranslate.py)|選択形状の移動を指定。存在しなければxformOpOrderも考慮して追加| |[SetScale.py](./SetScale.py)|選択形状のスケールを指定。存在しなければxformOpOrderも考慮して追加| |[SetRotate.py](./SetRotate.py)|選択形状の回転を指定。存在しなければxformOpOrderも考慮して追加| |[SetRotateWithQuat.py](./SetRotateWithQuat.py)|選択形状の回転をQuatで指定| |[SetPivot.py](./SetPivot.py)|選択形状のPivotを指定。存在しなければxformOpOrderも考慮して追加| |[DeletePivot.py](./DeletePivot.py)|選択形状のPivotを削除。一部 omni.kit.commands.execute('RemoveProperty') を使用|
1,041
Markdown
53.842102
112
0.772334
ft-lab/omniverse_sample_scripts/Prim/Transform/GetWorldTransform.py
from pxr import Usd, UsdGeom, UsdPhysics, UsdShade, UsdSkel, Sdf, Gf, Tf import omni.kit # Get stage. stage = omni.usd.get_context().get_stage() # Get selection. selection = omni.usd.get_context().get_selection() paths = selection.get_selected_prim_paths() xformCache = UsdGeom.XformCache(0) for path in paths: prim = stage.GetPrimAtPath(path) if prim.IsValid(): # Get world Transform. globalPose = xformCache.GetLocalToWorldTransform(prim) print(globalPose) # Decompose transform. translate, rotation, scale = UsdSkel.DecomposeTransform(globalPose) # Conv Quat to eular angles. # Rotate XYZ. rV = Gf.Rotation(rotation).Decompose(Gf.Vec3d(0, 0, 1), Gf.Vec3d(0, 1, 0), Gf.Vec3d(1, 0, 0)) rV = Gf.Vec3d(rV[2], rV[1], rV[0]) print(f"==> translate : {translate}") print(f"==> rotation : {rV}") print(f"==> scale : {scale}")
932
Python
28.156249
101
0.631974
ft-lab/omniverse_sample_scripts/Prim/Transform/GetTransform.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() == True: # Print prim name. print('[ ' + prim.GetName() + ' ]') # Order of Transform elements. transformOrder = prim.GetAttribute('xformOpOrder') if transformOrder.IsValid() and transformOrder.Get() != None: print(f" TransformOrder : {transformOrder.Get()}") for transV in transformOrder.Get(): # 'xformOp:scale', 'xformOp:rotateXYZ', 'xformOp:translate', etc. tV = prim.GetAttribute(transV) if tV.IsValid(): print(f" {transV} ( {tV.GetTypeName()} ) : {tV.Get()}")
921
Python
30.793102
81
0.592834
ft-lab/omniverse_sample_scripts/Prim/Transform/SetScale.py
from pxr import Usd, UsdGeom, UsdPhysics, UsdShade, Sdf, Gf, Tf import omni.usd import omni.timeline # Get stage. stage = omni.usd.get_context().get_stage() # Get selection. selection = omni.usd.get_context().get_selection() paths = selection.get_selected_prim_paths() # --------------------------------------------------. # Set scale. # --------------------------------------------------. def _setScale (prim : Usd.Prim, sV : Gf.Vec3f): if prim == None: return scale = prim.GetAttribute("xformOp:scale").Get() if scale != None: # Specify a value for each type. if type(scale) == Gf.Vec3f: prim.GetAttribute("xformOp:scale").Set(Gf.Vec3f(sV)) elif type(scale) == Gf.Vec3d: prim.GetAttribute("xformOp:scale").Set(Gf.Vec3d(sV)) else: # xformOpOrder is also updated. xformAPI = UsdGeom.XformCommonAPI(prim) xformAPI.SetScale(Gf.Vec3f(sV)) # --------------------------------------------------. for path in paths: prim = stage.GetPrimAtPath(path) if prim.IsValid() == True: # Print prim name. print(f"[ {prim.GetName()} ]") sV = Gf.Vec3f(1.1, 1.2, 1.3) _setScale(prim, sV)
1,211
Python
28.560975
64
0.535095
ft-lab/omniverse_sample_scripts/Prim/Transform/GetTransformVectors.py
from pxr import Usd, UsdGeom, UsdPhysics, UsdShade, Sdf, Gf, Tf import omni.usd import omni.timeline # Get stage. 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() for path in paths: prim = stage.GetPrimAtPath(path) if prim.IsValid() == True: # Print prim name. print(f"[ {prim.GetName()} ]") # Get transform. # However, the type that can be obtained here is different from the actual Type. xformAPI = UsdGeom.XformCommonAPI(prim) translation, rotation, scale, pivot, rotOrder = xformAPI.GetXformVectors(time_code) print("** GetXformVectors **") print(f"translation : {type(translation)} {translation}") print(f"rotation : {type(rotation)} {rotation}") print(f"scale : {type(scale)} {scale}") print(f"pivot : {type(pivot)} {pivot}") print(f"rotOrder : {type(rotOrder)} {rotOrder}") print("** prim.GetAttribute **") trans = prim.GetAttribute("xformOp:translate").Get() print(f"trans : {type(trans)} {trans}") # Convert rotOrder to "xformOp:rotateXYZ" etc. t = xformAPI.ConvertRotationOrderToOpType(rotOrder) rotateAttrName = "xformOp:" + UsdGeom.XformOp.GetOpTypeToken(t) rotate = prim.GetAttribute(rotateAttrName).Get() print(f"rotate ({rotateAttrName}) : {type(rotate)} {rotate}") scale = prim.GetAttribute("xformOp:scale").Get() print(f"scale : {type(scale)} {scale}") pivot = prim.GetAttribute("xformOp:translate:pivot").Get() print(f"pivot : {type(pivot)} {pivot}")
1,731
Python
33.639999
91
0.635471
ft-lab/omniverse_sample_scripts/Prim/Transform/SetTranslate.py
from pxr import Usd, UsdGeom, UsdPhysics, UsdShade, Sdf, Gf, Tf import omni.usd import omni.timeline # Get stage. stage = omni.usd.get_context().get_stage() # Get selection. selection = omni.usd.get_context().get_selection() paths = selection.get_selected_prim_paths() # --------------------------------------------------. # Set translate. # --------------------------------------------------. def _setTranslate (prim : Usd.Prim, tV : Gf.Vec3f): if prim == None: return trans = prim.GetAttribute("xformOp:translate").Get() if trans != None: # Specify a value for each type. if type(trans) == Gf.Vec3f: prim.GetAttribute("xformOp:translate").Set(Gf.Vec3f(tV)) elif type(trans) == Gf.Vec3d: prim.GetAttribute("xformOp:translate").Set(Gf.Vec3d(tV)) else: # xformOpOrder is also updated. xformAPI = UsdGeom.XformCommonAPI(prim) xformAPI.SetTranslate(Gf.Vec3d(tV)) # -------------------------------------------------. for path in paths: prim = stage.GetPrimAtPath(path) if prim.IsValid() == True: # Print prim name. print('[ ' + prim.GetName() + ' ]') tV = Gf.Vec3f(10, 20, 30) _setTranslate(prim, tV)
1,239
Python
29.999999
68
0.544794
ft-lab/omniverse_sample_scripts/Prim/Transform/DeletePivot.py
from pxr import Usd, UsdGeom, UsdPhysics, UsdShade, Sdf, Gf, Tf import omni.usd import omni.kit.commands # Get stage. stage = omni.usd.get_context().get_stage() # Get selection. selection = omni.usd.get_context().get_selection() paths = selection.get_selected_prim_paths() # --------------------------------------------------. # Delete pivot. # --------------------------------------------------. def _deletePivot (prim : Usd.Prim): if prim == None: return path = prim.GetPath().pathString + ".xformOp:translate:pivot" omni.kit.commands.execute('RemoveProperty', prop_path=path) transformOrder = prim.GetAttribute("xformOpOrder").Get() if transformOrder != None: orderList = [] for sV in transformOrder: if sV == "xformOp:translate:pivot" or sV == "!invert!xformOp:translate:pivot": continue orderList.append(sV) prim.GetAttribute("xformOpOrder").Set(orderList) # --------------------------------------------------. for path in paths: prim = stage.GetPrimAtPath(path) if prim.IsValid() == True: # Print prim name. print('[ ' + prim.GetName() + ' ]') # Delete pivot. _deletePivot(prim)
1,226
Python
28.214285
90
0.553018
ft-lab/omniverse_sample_scripts/Prim/Transform/GetLocalMatrix.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() xformCache = UsdGeom.XformCache(0) for path in paths: prim = stage.GetPrimAtPath(path) if prim.IsValid() == True: # Print prim name. print(f"[ {prim.GetName()} ]") # Calc local matrix. matrix = xformCache.GetLocalTransformation(prim)[0] print(matrix) # Decompose matrix. # If the result is False, then reduce the value of eps and call Factor again. eps = 1e-10 result = matrix.Factor(eps) if result[0]: scale = result[2] rotate = result[3].ExtractRotation() translation = result[4] # Convert Rotate to Euler. # Rotate XYZ. rotateE = rotate.Decompose(Gf.Vec3d(0, 0, 1), Gf.Vec3d(0, 1, 0), Gf.Vec3d(1, 0, 0)) rotateE = Gf.Vec3d(rotateE[2], rotateE[1], rotateE[0]) print(f"Translation : {translation}") print(f"rotate : {rotateE}") print(f"scale : {scale}")
1,205
Python
28.414633
95
0.585062
ft-lab/omniverse_sample_scripts/Operation/FocusPrim.py
# "omni.kit.viewport_legacy" is no longer available in kit104. #import omni.kit.viewport_legacy from pxr import Usd, UsdGeom, UsdPhysics, UsdShade, Sdf, Gf, Tf import omni.kit.commands # Kit104 : changed from omni.kit.viewport_legacy to omni.kit.viewport.utility.get_active_viewport_window import omni.kit.viewport.utility # Get active viewport window. active_vp_window = omni.kit.viewport.utility.get_active_viewport_window() viewport_api = active_vp_window.viewport_api # Get camera path ("/OmniverseKit_Persp" etc). cameraPath = viewport_api.camera_path.pathString # Get stage. stage = omni.usd.get_context().get_stage() #time_code = omni.timeline.get_timeline_interface().get_current_time() * stage.GetTimeCodesPerSecond() time_code = Usd.TimeCode() # Get active camera. cameraPrim = stage.GetPrimAtPath(cameraPath) if cameraPrim.IsValid(): camera = UsdGeom.Camera(cameraPrim) # UsdGeom.Camera cameraV = camera.GetCamera(time_code) # Gf.Camera # Aspect ratio. aspect = cameraV.aspectRatio # Taret prim path. targetPrimPath = "/World/Sphere" prim = stage.GetPrimAtPath(targetPrimPath) if prim.IsValid(): # Set focus. omni.kit.commands.execute('FramePrimsCommand', prim_to_move=Sdf.Path(cameraPath), prims_to_frame=[targetPrimPath], time_code=time_code, usd_context_name='', aspect_ratio=aspect)
1,431
Python
30.822222
104
0.703704
ft-lab/omniverse_sample_scripts/Operation/readme.md
# Operation Ominverseの操作/イベント処理を行います。 |ファイル|説明| |---|---| |[FocusPrim.py](./FocusPrim.py)|Kit104以上で動作。<br>指定のPrim(ここでは"/World/Sphere")にフォーカスを合わせる<br>(キーボードの[F]をプッシュした時と同じ動作)| |サンプル|説明| |---|---| |[Selection](./Selection)|Stageウィンドウでの選択を取得| |[GamePad](./GamePad)|GamePadの入力イベント取得| |[Keyboard](./Keyboard)|Keyboardの入力イベント取得| |[UNDO](./UNDO)|UNDO処理| |[CommandsExecute](./CommandsExecute)|omni.kit.commandsを使用したコマンド実行|
473
Markdown
26.882351
121
0.638478
ft-lab/omniverse_sample_scripts/Operation/GamePad/GamePad_moveSelectPrim.py
from pxr import Usd, UsdGeom, UsdSkel, UsdPhysics, UsdShade, Sdf, Gf, Tf import carb import carb.input import omni.kit.app import omni.ext # Reference : kit/exts/omni.kit.debug.input # Get stage. stage = omni.usd.get_context().get_stage() # ------------------------------------------. # Move the selected Prim. # ------------------------------------------. def moveSelectedPrim (mV : Gf.Vec3f): # Get selection. selection = omni.usd.get_context().get_selection() paths = selection.get_selected_prim_paths() for path in paths: prim = stage.GetPrimAtPath(path) Gf.Vec3f(0, 0, 0) if prim.IsValid() == True: # Get translate. transformOrder = prim.GetAttribute('xformOpOrder') if transformOrder.IsValid(): tV = prim.GetAttribute("xformOp:translate") if tV.IsValid(): pos = Gf.Vec3f(tV.Get()) # Update translate. pos += mV tV.Set(pos) # ------------------------------------------. # Gamepad discription. # ------------------------------------------. class GamepadDesc: def _cleanup(self): self.name = None self.guid = None self.gamepad_device = None self.input_device = None self.is_connected = False self.input_val = {} def __init__(self): self._cleanup() def __del__(self): self._cleanup() # ------------------------------------------. # Input with GamePad. # ------------------------------------------. class InputGamePad: _gamepads = None _input = None _input_provider = None _gamepad_connection_subs = None _gamepad_inputs = None _app = None _pre_update_sub = None def __init__(self): pass def _update_gamepad_connection_state(self, gamepad_device, connection_state): for gamepad_desc in self._gamepads: if gamepad_desc.gamepad_device == gamepad_device: gamepad_desc.is_connected = connection_state # gamepad connection event. def _gamepad_connection_event(self, event): # Gamepad created. if event.type == carb.input.GamepadConnectionEventType.CREATED: gamepad_desc = GamepadDesc() gamepad_desc.name = self._input.get_gamepad_name(event.gamepad) gamepad_desc.guid = self._input.get_gamepad_guid(event.gamepad) gamepad_desc.gamepad_device = event.gamepad gamepad_desc.input_device = event.device self._gamepads.append(gamepad_desc) print("carb.input.GamepadConnectionEventType.CREATED") print("name : " + str(gamepad_desc.name)) print("guid : " + str(gamepad_desc.guid)) # Gamepad destroyed. elif event.type == carb.input.GamepadConnectionEventType.DESTROYED: for gamepad_desc in self._gamepads: if gamepad_desc.gamepad_device == event.gamepad: self._gamepads.remove(gamepad_desc) print("carb.input.GamepadConnectionEventType.DESTROYED") # Gamepad connected. elif event.type == carb.input.GamepadConnectionEventType.CONNECTED: self._update_gamepad_connection_state(event.gamepad, True) print(" carb.input.GamepadConnectionEventType.CONNECTED") # Gamepad disconnected. elif event.type == carb.input.GamepadConnectionEventType.DISCONNECTED: self._update_gamepad_connection_state(event.gamepad, False) print(" carb.input.GamepadConnectionEventType.DISCONNECTED") # gamepad update event. def _update_gamepads_data(self, event): gamepad_descD = None for gamepad_desc in self._gamepads: gamepad_descD = gamepad_desc for gamepad_input in self._gamepad_inputs: # Store value. val = self._input.get_gamepad_value(gamepad_descD.gamepad_device, gamepad_input) gamepad_descD.input_val[gamepad_input] = float(val) # gamepad_input : DPAD (0.0 or 1.0). # carb.input.GamepadInput.DPAD_DOWN # carb.input.GamepadInput.DPAD_UP # carb.input.GamepadInput.DPAD_LEFT # carb.input.GamepadInput.DPAD_RIGHT # gamepad_input : buttons (0.0 or 1.0). # carb.input.GamepadInput.X # carb.input.GamepadInput.Y # carb.input.GamepadInput.A # carb.input.GamepadInput.B # carb.input.GamepadInput.MENU1 (Back) # carb.input.GamepadInput.MENU2 (Start) # gamepad_input : stick (0.0 - 1.0). # carb.input.GamepadInput.LEFT_STICK_DOWN # carb.input.GamepadInput.LEFT_STICK_UP # carb.input.GamepadInput.LEFT_STICK_LEFT # carb.input.GamepadInput.LEFT_STICK_RIGHT # carb.input.GamepadInput.RIGHT_STICK_DOWN # carb.input.GamepadInput.RIGHT_STICK_UP # carb.input.GamepadInput.RIGHT_STICK_LEFT # carb.input.GamepadInput.RIGHT_STICK_RIGHT # gamepad_input : stick push (0.0 or 1.0). # carb.input.GamepadInput.LEFT_STICK # carb.input.GamepadInput.RIGHT_STICK # gamepad_input : trigger (0.0 - 1.0). # carb.input.GamepadInput.LEFT_TRIGGER # carb.input.GamepadInput.RIGHT_TRIGGER # gamepad_input : shoulder (0.0 or 1.0). # carb.input.GamepadInput.LEFT_SHOULDER # carb.input.GamepadInput.RIGHT_SHOULDER if gamepad_descD == None: return # Move the selected Prim. mV = Gf.Vec3f(0, 0, 0) scaleV = 2.0 minV = 0.3 if gamepad_desc.input_val[carb.input.GamepadInput.LEFT_STICK_DOWN] > minV: mV[2] += scaleV * gamepad_desc.input_val[carb.input.GamepadInput.LEFT_STICK_DOWN] if gamepad_desc.input_val[carb.input.GamepadInput.LEFT_STICK_UP] > minV: mV[2] -= scaleV * gamepad_desc.input_val[carb.input.GamepadInput.LEFT_STICK_UP] if gamepad_desc.input_val[carb.input.GamepadInput.LEFT_STICK_LEFT] > minV: mV[0] -= scaleV * gamepad_desc.input_val[carb.input.GamepadInput.LEFT_STICK_LEFT] if gamepad_desc.input_val[carb.input.GamepadInput.LEFT_STICK_RIGHT] > minV: mV[0] += scaleV * gamepad_desc.input_val[carb.input.GamepadInput.LEFT_STICK_RIGHT] moveSelectedPrim(mV) def startup (self): self._gamepads = [] self._input = carb.input.acquire_input_interface() self._input_provider = carb.input.acquire_input_provider() self._gamepad_connection_subs = self._input.subscribe_to_gamepad_connection_events(self._gamepad_connection_event) # Creating a dict of processed GamepadInput enumeration for convenience def filter_gamepad_input_attribs(attr): return not callable(getattr(carb.input.GamepadInput, attr)) and not attr.startswith("__") and attr != "name" and attr != "COUNT" self._gamepad_inputs = dict((getattr(carb.input.GamepadInput, attr), attr) for attr in dir(carb.input.GamepadInput) if filter_gamepad_input_attribs(attr)) self._app = omni.kit.app.get_app() self._pre_update_sub = self._app.get_pre_update_event_stream().create_subscription_to_pop( self._update_gamepads_data, name="GamePad test" ) def shutdown (self): self._input.unsubscribe_to_gamepad_connection_events(self._gamepad_connection_subs) self._gamepad_connection_subs = None self._gamepad_inputs = None self._gamepads = None self._app = None self._pre_update_sub = None self._input_provider = None self._input = None gamePadV = InputGamePad() gamePadV.startup() # stop. #gamePadV.shutdown()
8,017
Python
38.112195
162
0.583385
ft-lab/omniverse_sample_scripts/Operation/GamePad/readme.md
# GamePad GamePadでの操作を取得します。 XBOX Controllerの場合は以下のような入力になります。 ![gamepad_image_01.jpg](./images/gamepad_image_01.jpg) |入力|値| |---|---| |carb.input.GamepadInput.LEFT_SHOULDER|0 or 1| |carb.input.GamepadInput.RIGHT_SHOULDER|0 or 1| |carb.input.GamepadInput.LEFT_TRIGGER|0 - 1| |carb.input.GamepadInput.RIGHT_TRIGGER|0 - 1| |carb.input.GamepadInput.DPAD_DOWN<br>carb.input.GamepadInput.DPAD_UP<br>carb.input.GamepadInput.DPAD_LEFT<br>carb.input.GamepadInput.DPAD_RIGHT|0 or 1| |carb.input.GamepadInput.X|0 or 1| |carb.input.GamepadInput.Y|0 or 1| |carb.input.GamepadInput.A|0 or 1| |carb.input.GamepadInput.B|0 or 1| |carb.input.GamepadInput.MENU1|0 or 1| |carb.input.GamepadInput.MENU2|0 or 1| |carb.input.GamepadInput.LEFT_STICK_DOWN<br>carb.input.GamepadInput.LEFT_STICK_UP<br>carb.input.GamepadInput.LEFT_STICK_LEFT<br>carb.input.GamepadInput.LEFT_STICK_RIGHT|0 - 1| |carb.input.GamepadInput.RIGHT_STICK_DOWN<br>carb.input.GamepadInput.RIGHT_STICK_UP<br>carb.input.GamepadInput.RIGHT_STICK_LEFT<br>carb.input.GamepadInput.RIGHT_STICK_RIGHT|0 - 1| |carb.input.GamepadInput.LEFT_STICK |0 or 1| |carb.input.GamepadInput.RIGHT_STICK |0 or 1| ## サンプル |ファイル|説明| |---|---| |[GamePad.py](./GamePad.py)|GamePad情報を取得(特定のボタンのみ)| |[GamePad_moveSelectPrim.py](./GamePad_moveSelectPrim.py)|GamePadのLeftStick操作で選択形状を移動|
1,345
Markdown
42.419353
179
0.751673
ft-lab/omniverse_sample_scripts/Operation/CommandsExecute/SelectNone.py
import omni.kit omni.kit.commands.execute("SelectNone")
57
Python
13.499997
39
0.789474
ft-lab/omniverse_sample_scripts/Operation/CommandsExecute/GetCommandsList.py
import omni.kit # Get commands list (dict). listA = omni.kit.commands.get_commands() keys = listA.keys() print(str(keys))
124
Python
14.624998
40
0.709677
ft-lab/omniverse_sample_scripts/Operation/CommandsExecute/readme.md
# Execute omni.kit.commandsを使用して、Omniverseのコマンドを実行します。 ## サンプル |ファイル|説明| |---|---| |[GetCommandsList.py](./GetCommandsList.py)|コマンドのリストを一覧。| |[SelectNone.py](./SelectNone.py)|Stageウィンドウでの選択を解除| |[CopyPrim.py](./CopyPrim.py)|選択されたPrimの複製を作成| |[DeletePrims.py](./DeletePrims.py)|選択されたPrimを削除| |[MovePrim.py](./MovePrim.py)|選択されたPrimのパスを変更。<br>/World/Xform 内に選択されたPrimを移動する。| |[RenamePrim.py](./RenamePrim.py)|選択されたPrimの名前を変更。<br>"MovePrim"でPrimの名前変更できる。|
500
Markdown
32.399998
86
0.682
ft-lab/omniverse_sample_scripts/Operation/CommandsExecute/CopyPrim.py
from pxr import Usd, UsdGeom, UsdPhysics, UsdShade, Sdf, Gf, Tf import omni.kit # Get stage. stage = omni.usd.get_context().get_stage() # Get selection. selection = omni.usd.get_context().get_selection() selectedPaths = selection.get_selected_prim_paths() newPrimPathList = [] for path in selectedPaths: # Duplicate Prim from specified path. omni.kit.commands.execute("CopyPrim", path_from=path) # Stores the path of the newly duplicated Prim. selection = omni.usd.get_context().get_selection() paths = selection.get_selected_prim_paths() if len(paths) >= 1: newPrimPathList.append(paths[0]) # Show the path of the newly duplicated Prim. print(newPrimPathList)
698
Python
28.124999
63
0.719198
ft-lab/omniverse_sample_scripts/Operation/CommandsExecute/DeletePrims.py
from pxr import Usd, UsdGeom, UsdPhysics, UsdShade, Sdf, Gf, Tf import omni.kit # Get stage. stage = omni.usd.get_context().get_stage() # Get selection. selection = omni.usd.get_context().get_selection() selectedPaths = selection.get_selected_prim_paths() # Delete prims. omni.kit.commands.execute("DeletePrims", paths=selectedPaths)
337
Python
24.999998
63
0.750742
ft-lab/omniverse_sample_scripts/Operation/CommandsExecute/RenamePrim.py
from pxr import Usd, UsdGeom, UsdPhysics, UsdShade, Sdf, Gf, Tf import omni.kit # Get stage. stage = omni.usd.get_context().get_stage() # Get selection. selection = omni.usd.get_context().get_selection() selectedPaths = selection.get_selected_prim_paths() for path in selectedPaths: # Get prim. prim = stage.GetPrimAtPath(path) if prim.IsValid() == False: continue newPathName = path + "_rename" # Rename Prim name. omni.kit.commands.execute("MovePrim", path_from=path, path_to=newPathName) break
538
Python
23.499999
78
0.689591
ft-lab/omniverse_sample_scripts/Operation/CommandsExecute/MovePrim.py
from pxr import Usd, UsdGeom, UsdPhysics, UsdShade, Sdf, Gf, Tf import omni.kit # Get stage. stage = omni.usd.get_context().get_stage() # Get default prim. defaultPrim = stage.GetDefaultPrim() # Create empty node(Xform). defaultPrimPath = defaultPrim.GetPath().pathString xformPath = defaultPrimPath + '/Xform' UsdGeom.Xform.Define(stage, xformPath) # Get selection. selection = omni.usd.get_context().get_selection() selectedPaths = selection.get_selected_prim_paths() for path in selectedPaths: # Get prim. prim = stage.GetPrimAtPath(path) if prim.IsValid() == False: continue pathTo = xformPath + "/" + str(prim.GetName()) # Change Prim's path. # path_from : Path of the original Prim. # path_to : Path to move to. omni.kit.commands.execute("MovePrim", path_from=path, path_to=pathTo)
839
Python
24.454545
73
0.697259