file_path
stringlengths 20
207
| content
stringlengths 5
3.85M
| size
int64 5
3.85M
| lang
stringclasses 9
values | avg_line_length
float64 1.33
100
| max_line_length
int64 4
993
| alphanum_fraction
float64 0.26
0.93
|
---|---|---|---|---|---|---|
AkaneFoundation/Omni/app/src/main/res/drawable/ic_warning.xml | <vector xmlns:android="http://schemas.android.com/apk/res/android"
android:width="24dp"
android:height="24dp"
android:viewportWidth="960"
android:viewportHeight="960"
android:tint="?attr/colorControlNormal">
<path
android:fillColor="@android:color/white"
android:pathData="M40,840L480,80L920,840L40,840ZM178,760L782,760L480,240L178,760ZM480,720Q497,720 508.5,708.5Q520,697 520,680Q520,663 508.5,651.5Q497,640 480,640Q463,640 451.5,651.5Q440,663 440,680Q440,697 451.5,708.5Q463,720 480,720ZM440,600L520,600L520,400L440,400L440,600ZM480,500L480,500L480,500L480,500Z"/>
</vector>
| 611 | XML | 54.636359 | 317 | 0.757774 |
AkaneFoundation/Omni/app/src/main/res/drawable/ic_conversion_path.xml | <vector xmlns:android="http://schemas.android.com/apk/res/android"
android:width="24dp"
android:height="24dp"
android:viewportWidth="960"
android:viewportHeight="960"
android:tint="?attr/colorControlNormal">
<path
android:fillColor="@android:color/white"
android:pathData="M760,840Q721,840 690,817.5Q659,795 647,760L440,760Q374,760 327,713Q280,666 280,600Q280,534 327,487Q374,440 440,440L520,440Q553,440 576.5,416.5Q600,393 600,360Q600,327 576.5,303.5Q553,280 520,280L313,280Q300,315 269.5,337.5Q239,360 200,360Q150,360 115,325Q80,290 80,240Q80,190 115,155Q150,120 200,120Q239,120 269.5,142.5Q300,165 313,200L520,200Q586,200 633,247Q680,294 680,360Q680,426 633,473Q586,520 520,520L440,520Q407,520 383.5,543.5Q360,567 360,600Q360,633 383.5,656.5Q407,680 440,680L647,680Q660,645 690.5,622.5Q721,600 760,600Q810,600 845,635Q880,670 880,720Q880,770 845,805Q810,840 760,840ZM200,280Q217,280 228.5,268.5Q240,257 240,240Q240,223 228.5,211.5Q217,200 200,200Q183,200 171.5,211.5Q160,223 160,240Q160,257 171.5,268.5Q183,280 200,280Z"/>
</vector>
| 1,070 | XML | 96.363628 | 776 | 0.76729 |
AkaneFoundation/Omni/app/src/main/res/drawable/ic_explorer.xml | <vector xmlns:android="http://schemas.android.com/apk/res/android"
android:width="24dp"
android:height="24dp"
android:viewportWidth="960"
android:viewportHeight="960"
android:tint="?attr/colorControlNormal">
<path
android:fillColor="@android:color/white"
android:pathData="M260,700L560,560L700,260L400,400L260,700ZM480,520Q463,520 451.5,508.5Q440,497 440,480Q440,463 451.5,451.5Q463,440 480,440Q497,440 508.5,451.5Q520,463 520,480Q520,497 508.5,508.5Q497,520 480,520ZM480,880Q397,880 324,848.5Q251,817 197,763Q143,709 111.5,636Q80,563 80,480Q80,397 111.5,324Q143,251 197,197Q251,143 324,111.5Q397,80 480,80Q563,80 636,111.5Q709,143 763,197Q817,251 848.5,324Q880,397 880,480Q880,563 848.5,636Q817,709 763,763Q709,817 636,848.5Q563,880 480,880ZM480,800Q614,800 707,707Q800,614 800,480Q800,346 707,253Q614,160 480,160Q346,160 253,253Q160,346 160,480Q160,614 253,707Q346,800 480,800ZM480,480Q480,480 480,480Q480,480 480,480Q480,480 480,480Q480,480 480,480Q480,480 480,480Q480,480 480,480Q480,480 480,480Q480,480 480,480Z"/>
</vector>
| 1,064 | XML | 95.818173 | 770 | 0.771617 |
AkaneFoundation/Omni/app/src/main/res/drawable/ic_grid_view.xml | <vector xmlns:android="http://schemas.android.com/apk/res/android"
android:width="24dp"
android:height="24dp"
android:viewportWidth="960"
android:viewportHeight="960"
android:tint="?attr/colorControlNormal">
<path
android:fillColor="@android:color/white"
android:pathData="M120,440L120,120L440,120L440,440L120,440ZM120,840L120,520L440,520L440,840L120,840ZM520,440L520,120L840,120L840,440L520,440ZM520,840L520,520L840,520L840,840L520,840ZM200,360L360,360L360,200L200,200L200,360ZM600,360L760,360L760,200L600,200L600,360ZM600,760L760,760L760,600L600,600L600,760ZM200,760L360,760L360,600L200,600L200,760ZM600,360L600,360L600,360L600,360L600,360ZM600,600L600,600L600,600L600,600L600,600ZM360,600L360,600L360,600L360,600L360,600ZM360,360L360,360L360,360L360,360L360,360Z"/>
</vector>
| 813 | XML | 72.999993 | 519 | 0.805658 |
AkaneFoundation/Omni/app/src/main/res/drawable/ic_location_on.xml | <vector xmlns:android="http://schemas.android.com/apk/res/android"
android:width="24dp"
android:height="24dp"
android:viewportWidth="960"
android:viewportHeight="960"
android:tint="?attr/colorControlNormal">
<path
android:fillColor="@android:color/white"
android:pathData="M480,480Q513,480 536.5,456.5Q560,433 560,400Q560,367 536.5,343.5Q513,320 480,320Q447,320 423.5,343.5Q400,367 400,400Q400,433 423.5,456.5Q447,480 480,480ZM480,774Q602,662 661,570.5Q720,479 720,408Q720,299 650.5,229.5Q581,160 480,160Q379,160 309.5,229.5Q240,299 240,408Q240,479 299,570.5Q358,662 480,774ZM480,880Q319,743 239.5,625.5Q160,508 160,408Q160,258 256.5,169Q353,80 480,80Q607,80 703.5,169Q800,258 800,408Q800,508 720.5,625.5Q641,743 480,880ZM480,400Q480,400 480,400Q480,400 480,400Q480,400 480,400Q480,400 480,400Q480,400 480,400Q480,400 480,400Q480,400 480,400Q480,400 480,400Z"/>
</vector>
| 906 | XML | 81.454538 | 612 | 0.759382 |
AkaneFoundation/Omni/gradle/libs.versions.toml | [versions]
agp = "8.4.1"
kotlin = "1.9.0"
coreKtx = "1.13.1"
junit = "4.13.2"
junitVersion = "1.1.5"
espressoCore = "3.5.1"
appcompat = "1.6.1"
material = "1.12.0"
activity = "1.9.0"
constraintlayout = "2.1.4"
preferenceKtx = "1.2.1"
coreSplashscreen = "1.0.1"
[libraries]
androidx-core-ktx = { group = "androidx.core", name = "core-ktx", version.ref = "coreKtx" }
androidx-preference-ktx = { module = "androidx.preference:preference-ktx", version.ref = "preferenceKtx" }
junit = { group = "junit", name = "junit", version.ref = "junit" }
androidx-junit = { group = "androidx.test.ext", name = "junit", version.ref = "junitVersion" }
androidx-espresso-core = { group = "androidx.test.espresso", name = "espresso-core", version.ref = "espressoCore" }
androidx-appcompat = { group = "androidx.appcompat", name = "appcompat", version.ref = "appcompat" }
material = { group = "com.google.android.material", name = "material", version.ref = "material" }
androidx-activity = { group = "androidx.activity", name = "activity", version.ref = "activity" }
androidx-constraintlayout = { group = "androidx.constraintlayout", name = "constraintlayout", version.ref = "constraintlayout" }
androidx-core-splashscreen = { group = "androidx.core", name = "core-splashscreen", version.ref = "coreSplashscreen" }
[plugins]
android-application = { id = "com.android.application", version.ref = "agp" }
jetbrains-kotlin-android = { id = "org.jetbrains.kotlin.android", version.ref = "kotlin" }
| 1,476 | TOML | 46.64516 | 128 | 0.687669 |
move-ai/omniverse-public-asset-library/README.md | # omniverse-public-asset-library
Omniverse extension which allows to import free animations that have been captured by the move.ai team
# Overview
This extension is designed to let you test animations processed by the Move.ai team. All of the animations are free to use allowing you to check the quality of our data.
We will continue to add new animations, stay tuned!
# How to use
- Set your `Assets Path` to where you'd like to store animations
- Click `Update Preview`
- It will take some time to update animation previews. When it's done you'll be able to import animations simply by clicking a `Import animation` button
- Activate `Skeleton Joint` extension to be able to view skeleton animations in the viewport
More info [here](https://docs.move.ai/nvidia-omniverse-extension)
| 790 | Markdown | 42.944442 | 169 | 0.78481 |
move-ai/omniverse-public-asset-library/moveai/assets/extension/extension.py | from ctypes import alignment
import omni.ext
from .window import MoveaiAssetsMarketlaceWindow
class MoveaiAssetsMarketlace(omni.ext.IExt):
# ext_id is current extension id. It can be used with extension manager to query additional information, like where
# this extension is located on filesystem.
def on_startup(self, ext_id):
print("[moveai.assets] Move.ai Public Asset Library startup")
self._window = MoveaiAssetsMarketlaceWindow(ext_id)
def on_shutdown(self):
if self._window is not None:
self._window.destroy()
self._window = None
print("[moveai.assets] Move.ai Public Asset Library shutdown")
| 679 | Python | 36.777776 | 119 | 0.702504 |
move-ai/omniverse-public-asset-library/moveai/assets/extension/__init__.py | from .extension import *
| 25 | Python | 11.999994 | 24 | 0.76 |
move-ai/omniverse-public-asset-library/moveai/assets/extension/utils.py | from urllib import request
import json
import cv2
import random
import carb
import omni.kit.asset_converter
import omni.kit.commands
import omni.usd
from PIL import Image
from pathlib import Path
def get_data(url: str):
f = request.urlopen(url)
data_json = json.loads(f.read())
return data_json
def get_random_frame(videofile: str):
vidcap = cv2.VideoCapture(videofile)
# get total number of frames
total_frames = vidcap.get(cv2.CAP_PROP_FRAME_COUNT)
random_frame_number = random.randint(60, total_frames)
# set frame position
vidcap.set(cv2.CAP_PROP_POS_FRAMES, random_frame_number)
success, image = vidcap.read()
if success:
suffix = Path(videofile).suffix
img_path = f"{videofile.split(suffix)[0]}.jpg"
cv2.imwrite(img_path, image)
return img_path
# Progress of processing.
def progress_callback(current_step: int, total: int):
# Show progress
print(f"{current_step} of {total}")
# Convert asset file(obj/fbx/glTF, etc) to usd.
async def convert_asset_to_usd(input_asset: str, output_usd: str):
# Input options are defaults.
converter_context = omni.kit.asset_converter.AssetConverterContext()
converter_context.ignore_materials = False
converter_context.ignore_camera = False
converter_context.ignore_animations = False
converter_context.ignore_light = False
converter_context.export_preview_surface = False
converter_context.use_meter_as_world_unit = False
converter_context.create_world_as_default_root_prim = True
converter_context.embed_textures = True
converter_context.convert_fbx_to_y_up = False
converter_context.convert_fbx_to_z_up = False
converter_context.merge_all_meshes = False
converter_context.use_double_precision_to_usd_transform_op = False
converter_context.ignore_pivots = False
converter_context.keep_all_materials = True
converter_context.smooth_normals = True
instance = omni.kit.asset_converter.get_instance()
task = instance.create_converter_task(input_asset, output_usd, progress_callback, converter_context)
# Wait for completion.
success = await task.wait_until_finished()
if not success:
carb.log_error(task.get_status(), task.get_detailed_error())
else:
print("converting done")
def download_file(url: str, download_path: Path):
request.urlretrieve(url, download_path)
def import_file_to_scene(usd_path: Path):
stage = omni.usd.get_context().get_stage()
if not stage:
return
name = usd_path.stem
prim_path = omni.usd.get_stage_next_free_path(stage, "/" + name, True)
omni.kit.commands.execute(
"CreateReferenceCommand", path_to=prim_path, asset_path=str(usd_path), usd_context=omni.usd.get_context()
)
def get_img_size(img_path: Path):
im = Image.open(img_path)
width, height = im.size
return width, height
def download_motion(asset_path: Path, name: str, file_type: str = "fbx"):
from .window import MoveaiAssetsMarketlaceWindow
download_dir = asset_path / "anim_files" / file_type
download_dir.mkdir(parents=True, exist_ok=True)
download_path = download_dir / f"{name}.{file_type}"
for motion in MoveaiAssetsMarketlaceWindow.data["motions"]:
if name == motion["title"]:
download_file(motion["files"][f"{file_type}_url"], download_path)
import_file_to_scene(download_path)
return
| 3,448 | Python | 31.847619 | 113 | 0.697506 |
move-ai/omniverse-public-asset-library/moveai/assets/extension/window.py | from functools import partial
import omni.ui as ui
import omni.kit
from urllib import request
from pathlib import Path
from .utils import get_data, get_random_frame, get_img_size, download_motion
import webbrowser
IMG_SIZE_DEVISOR = 2
class MoveaiAssetsMarketlaceWindow(ui.Window):
data = get_data("https://molibapi.move.ai/motions")
def __init__(self, ext_id):
super().__init__("Move.ai Public Asset Library", width=500, height=600, visible=True)
self.frame.set_build_fn(self._build_ui)
self.deferred_dock_in("Content", ui.DockPolicy.CURRENT_WINDOW_IS_ACTIVE)
self.asset_path_default: str = (
omni.kit.app.get_app().get_extension_manager().get_extension_path(ext_id) + "/data"
)
self.asset_path_current: str = None
def _set_path_current(self, path: str):
self.asset_path_current = path
def _build_ui(self):
self.image_preview_width: int = None
self.image_preview_height: int = None
with self.frame:
# Assets path and get previews button
with ui.VStack():
with ui.CollapsableFrame("Settings", height=0):
with ui.VStack():
with ui.HStack(height=20):
ui.Spacer(width=3)
ui.Label("Assets Path", width=70, height=0)
self.asset_field = ui.StringField(name="asset_path")
if not self.asset_path_current:
self.asset_field.model.set_value(self.asset_path_default)
else:
self.asset_field.model.set_value(self.asset_path_current)
self.asset_field.model.add_value_changed_fn(
lambda m: self._set_path_current(m.get_value_as_string())
)
ui.Button("Update Preview", width=0, height=0, clicked_fn=lambda: self._build_ui())
# Grid with previews and import buttons
with ui.CollapsableFrame("Preview"):
self.get_preview()
with ui.HStack(height=20, style={"Button":{"background_color": "0xFFFF7E09"}}):
ui.Button("Join iPhone beta", width=0, height=0, clicked_fn=partial(
webbrowser.open,
"https://www.move.ai/mobile-device"
))
def get_preview(self):
self.asset_path = Path(self.asset_field.model.get_value_as_string())
previews_path = self.asset_path / "previews"
previews_path.mkdir(parents=True, exist_ok=True)
with ui.HStack():
with ui.ScrollingFrame(
horizontal_scrollbar_policy=ui.ScrollBarPolicy.SCROLLBAR_ALWAYS_OFF,
vertical_scrollbar_policy=ui.ScrollBarPolicy.SCROLLBAR_ALWAYS_ON,
):
self.asset_grid = ui.VGrid(style={"margin": 3})
with self.asset_grid:
for motion in self.data["motions"]:
preview_path = previews_path / f"{motion['title']}.mp4"
preview = request.urlretrieve(motion["files"]["preview_url"], preview_path)
img_preview = get_random_frame(str(preview_path))
if not self.image_preview_width:
self.image_preview_width, self.image_preview_height = get_img_size(img_preview)
self.asset_grid.column_width = self.image_preview_width / IMG_SIZE_DEVISOR
with ui.VStack():
image = ui.Image(
img_preview,
fill_policy=ui.FillPolicy.PRESERVE_ASPECT_FIT,
alignment=ui.Alignment.CENTER,
height=self.image_preview_height / IMG_SIZE_DEVISOR,
)
with ui.HStack():
ui.Label(motion["title"], alignment=ui.Alignment.LEFT)
button = ui.Button(
text="Import motion",
name=motion["title"],
alignment=ui.Alignment.RIGHT,
width=0,
height=0,
asset_path=self.asset_path,
clicked_fn=partial(
download_motion,
Path(self.asset_field.model.get_value_as_string()),
motion["title"],
),
)
| 4,930 | Python | 42.637168 | 107 | 0.48357 |
move-ai/omniverse-public-asset-library/config/extension.toml | [package]
# Semantic Versionning is used: https://semver.org/
version = "1.0.0"
# The title and description fields are primarily for displaying extension info in UI
title = "Move.ai Public Asset Library"
description="Move.ai Public Asset Library"
# Path (relative to the root) or content of readme markdown file for UI.
readme = "docs/README.md"
icon = "data/icon.jpeg"
preview_image = "data/preview.png"
# URL of the extension source repository.
repository = ""
# One of categories for UI.
category = "Animation"
# Keywords for the extension
keywords = ["kit", "animation", "move"]
feature = true
# Use omni.ui to build simple UI
[dependencies]
"omni.kit.uiapp" = {}
"omni.kit.asset_converter" = {}
# Main python module this extension provides, it will be publicly available as "import moveai.assets".
[[python.module]]
name = "moveai.assets.extension"
[python.pipapi]
# # List of additional directories with pip achives to be passed into pip using ``--find-links`` arg.
# # Relative paths are relative to extension root. Tokens can be used.
# archiveDirs = ["path/to/pip_archive"]
# Commands passed to pip install before extension gets enabled. Can also contain flags, like `--upgrade`, `--no--index`, etc.
# Refer to: https://pip.pypa.io/en/stable/reference/pip_install/#requirements-file-format
requirements = [
"opencv-python"
]
# Allow going to online index if package can't be found locally (not recommended)
use_online_index = true
# Use this to specify a list of additional repositories if your pip package is hosted somewhere other
# than the default repo(s) configured in pip. Will pass these to pip with "--extra-index-url" argument
# repositories = ["https://my.additional.pip_repo.com/"]
# [settings]
| 1,733 | TOML | 31.716981 | 125 | 0.735141 |
move-ai/omniverse-public-asset-library/docs/README.md | # Overview
This extension is designed to let you test animations processed by the Move.ai team. All of the animations are free to use allowing you to check the quality of our data.
We will continue to add new animations, stay tuned!
# How to use
- Set your `Assets Path` to where you'd like to store animations
- Click `Update Preview`
- It will take some time to update animation previews. When it's done you'll be able to import animations simply by clicking a `Import animation` button
- Activate `Skeleton Joint` extension to be able to view skeleton animations in the viewport | 585 | Markdown | 47.833329 | 169 | 0.779487 |
cadop/siborg-simulate-walk/README.md | # Python Extension [siborg.simulate.walk]
This is a simple extension that lets users select characters and assign them a goal xform to follow (while doing a walk animation).
It was initially done as a test, and the code may be useful to others. Since this was created a few days after the Beta release of the people plugin, its very likely to break soon. Please open an issue or make a PR on github if you find problems in the future.

| 466 | Markdown | 50.888883 | 262 | 0.770386 |
cadop/siborg-simulate-walk/tools/scripts/link_app.py | import argparse
import json
import os
import sys
import packmanapi
import urllib3
def find_omniverse_apps():
http = urllib3.PoolManager()
try:
r = http.request("GET", "http://127.0.0.1:33480/components")
except Exception as e:
print(f"Failed retrieving apps from an Omniverse Launcher, maybe it is not installed?\nError: {e}")
sys.exit(1)
apps = {}
for x in json.loads(r.data.decode("utf-8")):
latest = x.get("installedVersions", {}).get("latest", "")
if latest:
for s in x.get("settings", []):
if s.get("version", "") == latest:
root = s.get("launch", {}).get("root", "")
apps[x["slug"]] = (x["name"], root)
break
return apps
def create_link(src, dst):
print(f"Creating a link '{src}' -> '{dst}'")
packmanapi.link(src, dst)
APP_PRIORITIES = ["code", "create", "view"]
if __name__ == "__main__":
parser = argparse.ArgumentParser(description="Create folder link to Kit App installed from Omniverse Launcher")
parser.add_argument(
"--path",
help="Path to Kit App installed from Omniverse Launcher, e.g.: 'C:/Users/bob/AppData/Local/ov/pkg/create-2021.3.4'",
required=False,
)
parser.add_argument(
"--app", help="Name of Kit App installed from Omniverse Launcher, e.g.: 'code', 'create'", required=False
)
args = parser.parse_args()
path = args.path
if not path:
print("Path is not specified, looking for Omniverse Apps...")
apps = find_omniverse_apps()
if len(apps) == 0:
print(
"Can't find any Omniverse Apps. Use Omniverse Launcher to install one. 'Code' is the recommended app for developers."
)
sys.exit(0)
print("\nFound following Omniverse Apps:")
for i, slug in enumerate(apps):
name, root = apps[slug]
print(f"{i}: {name} ({slug}) at: '{root}'")
if args.app:
selected_app = args.app.lower()
if selected_app not in apps:
choices = ", ".join(apps.keys())
print(f"Passed app: '{selected_app}' is not found. Specify one of the following found Apps: {choices}")
sys.exit(0)
else:
selected_app = next((x for x in APP_PRIORITIES if x in apps), None)
if not selected_app:
selected_app = next(iter(apps))
print(f"\nSelected app: {selected_app}")
_, path = apps[selected_app]
if not os.path.exists(path):
print(f"Provided path doesn't exist: {path}")
else:
SCRIPT_ROOT = os.path.dirname(os.path.realpath(__file__))
create_link(f"{SCRIPT_ROOT}/../../app", path)
print("Success!")
| 2,814 | Python | 32.117647 | 133 | 0.562189 |
cadop/siborg-simulate-walk/tools/packman/config.packman.xml | <config remotes="cloudfront">
<remote2 name="cloudfront">
<transport actions="download" protocol="https" packageLocation="d4i3qtqj3r0z5.cloudfront.net/${name}@${version}" />
</remote2>
</config>
| 211 | XML | 34.333328 | 123 | 0.691943 |
cadop/siborg-simulate-walk/tools/packman/bootstrap/install_package.py | # Copyright 2019 NVIDIA CORPORATION
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
# http://www.apache.org/licenses/LICENSE-2.0
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import logging
import shutil
import sys
import tempfile
import zipfile
__author__ = "hfannar"
logging.basicConfig(level=logging.WARNING, format="%(message)s")
logger = logging.getLogger("install_package")
class TemporaryDirectory:
def __init__(self):
self.path = None
def __enter__(self):
self.path = tempfile.mkdtemp()
return self.path
def __exit__(self, type, value, traceback):
# Remove temporary data created
shutil.rmtree(self.path)
def install_package(package_src_path, package_dst_path):
with zipfile.ZipFile(package_src_path, allowZip64=True) as zip_file, TemporaryDirectory() as temp_dir:
zip_file.extractall(temp_dir)
# Recursively copy (temp_dir will be automatically cleaned up on exit)
try:
# Recursive copy is needed because both package name and version folder could be missing in
# target directory:
shutil.copytree(temp_dir, package_dst_path)
except OSError as exc:
logger.warning("Directory %s already present, packaged installation aborted" % package_dst_path)
else:
logger.info("Package successfully installed to %s" % package_dst_path)
install_package(sys.argv[1], sys.argv[2])
| 1,844 | Python | 33.166666 | 108 | 0.703362 |
cadop/siborg-simulate-walk/exts/siborg.simulate.walk/siborg/simulate/walk/cust_go.py | from omni.anim.people.scripts.commands.goto import GoTo
class CustomGo(GoTo):
def __init__(self, character, command, navigation_manager):
super().__init__(character, command, navigation_manager)
def update_path(self, new_command):
''' update the path on the goto command by generating a new one
check that the current position was broadcast
Note: This is NOT related to the navigation_manager update_path
'''
self.navigation_manager.generate_goto_path(new_command)
| 533 | Python | 34.599998 | 71 | 0.681051 |
cadop/siborg-simulate-walk/exts/siborg.simulate.walk/siborg/simulate/walk/extension.py | import omni.ext
import omni.ui as ui
import omni.usd
import os
import omni.kit.commands
from pxr import Sdf
class SiborgSimulateWalkExtension(omni.ext.IExt):
def on_startup(self, ext_id):
print("[siborg.simulate.walk] siborg simulate walk startup")
self._window = ui.Window("Walk to Goal Behavior", width=300, height=100)
self.stage = omni.usd.get_context().get_stage()
with self._window.frame:
with ui.VStack():
def add_walk_to_prim():
# Could also Create/Get/Set Attribute
# self._person_prim.SetCustomDataByKey("target_goal", (0,0,0,0))
# Get the selections from the stage
self._usd_context = omni.usd.get_context()
self._selection = self._usd_context.get_selection()
selected_paths = self._selection.get_selected_prim_paths()
# Get them as prims
prims = [self.stage.GetPrimAtPath(x) for x in selected_paths]
dir_path = os.path.dirname(os.path.realpath(__file__))
behavior_script = os.path.join(dir_path, 'cust_behavior.py')
for prim_path in selected_paths:
add_animation_graph(prim_path)
for prim in prims:
add_behavior_script(prim, behavior_script)
ui.Button("Add Walk", clicked_fn=add_walk_to_prim)
def on_shutdown(self):
print("[siborg.simulate.walk] siborg simulate walk shutdown")
def add_animation_graph(prim_path):
omni.kit.commands.execute('ApplyAnimationGraphAPICommand',
paths=[Sdf.Path(prim_path)],
animation_graph_path=Sdf.Path('/World/Biped_Setup/CharacterAnimation/AnimationGraph'))
def add_behavior_script(prim, script):
omni.kit.commands.execute('ApplyScriptingAPICommand', paths=[Sdf.Path(prim.GetPath())])
omni.kit.commands.execute('RefreshScriptingPropertyWindowCommand')
attr = prim.GetAttribute("omni:scripting:scripts")
val = attr.Get()
if val:
scripts = list(val)
scripts.append(scripts)
attr.Set(scripts)
else:
attr.Set([script])
| 2,250 | Python | 34.730158 | 94 | 0.599556 |
cadop/siborg-simulate-walk/exts/siborg.simulate.walk/siborg/simulate/walk/__init__.py | from .extension import *
| 25 | Python | 11.999994 | 24 | 0.76 |
cadop/siborg-simulate-walk/exts/siborg.simulate.walk/siborg/simulate/walk/cust_behavior.py |
from __future__ import annotations
from pxr import Gf, UsdGeom, Usd, Sdf
import omni.usd
from omni.anim.people.scripts.character_behavior import CharacterBehavior
from .cust_go import CustomGo as GoTo
class CustomBehavior(CharacterBehavior):
def __init__(self, prim_path: Sdf.Path):
super().__init__(prim_path)
def on_init(self):
super().on_init()
# This could be simply in renew_character_state, but this is easier to follow
self.assign_goal()
def assign_goal(self):
# # Create an xform
newpath = self.prim_path.AppendPath('Goal')
# check if there is already a Goal (and if there is,
# whoever added better have a transform)
prim: Usd.Prim = self.stage.GetPrimAtPath(newpath)
# Need to set all of these to make transforms work can't just use translate
if not prim:
xform_faster = UsdGeom.Xform.Define(self.stage, newpath)
prim_trans = xform_faster.AddTranslateOp()
prim_trans.Set(Gf.Vec3f(0.0, 0.0, 0.0))
prim_rot = xform_faster.AddOrientOp()
prim_rot.Set(Gf.Quatf(0.0, 0.0, 0.0, 1.0))
prim_scale = xform_faster.AddScaleOp()
prim_scale.Set(Gf.Vec3f(1.0, 1.0, 1.0))
self.goal_prim = self.stage.GetPrimAtPath(newpath)
def on_play(self):
# Make sure we have a goal (incase someone deleted it after creating character)
super().on_play()
self.assign_goal()
def get_command(self, command):
if command[0] == "GoTo":
return GoTo(self.character, command, self.navigation_manager)
# We don't really need this right now, but just a reminder of other possible commands
return super().get_command(command)
# def read_commands_from_file(self):
# ''' Overwritten method to skip the file reading part '''
# # The command parser creates this format, so we just use it for now
# return [['GoTo', '0', '0', '0', '0']]
def get_simulation_commands(self):
''' Overwritten method to skip the file reading part '''
# The command parser creates this format, so we just use it for now
return [['GoTo', '0', '0', '0', '0']]
def on_update(self, current_time: float, delta_time: float):
"""
Called on every update. Initializes character at start,
publishes character positions and executes character commands.
:param float current_time: current time in seconds.
:param float delta_time: time elapsed since last update.
"""
if self.character is None:
if not self.init_character():
return
# Make sure we have an active goal
if not self.goal_prim.IsValid():
# This should only happen if goal prim was deleted during Play
# The existing goal will still be in memory and animation continues there
return
if self.avoidanceOn:
self.navigation_manager.publish_character_positions(delta_time, 0.5)
if self.commands:
if self.current_command:
# First get where the character currently is
# Get the current goal attribute
goal_position = omni.usd.get_world_transform_matrix(self.goal_prim).ExtractTranslation()
new_goal = (goal_position[0], goal_position[1], goal_position[2], 0)
# Two options to try `query_navmesh_path` and `validate_navmesh_point`
# For now, we pre-query the path to check if it will work, and if not, just skip trying to update
cur_pos = self.navigation_manager.character_manager.get_character_current_pos(self.prim_path.pathString)
test_path = self.navigation_manager.navigation_interface.query_navmesh_path(cur_pos, new_goal)
# If there is no path, don't go there
if test_path is None:
return
self.current_command.update_path(new_goal)
self.execute_command(self.commands, delta_time)
| 4,105 | Python | 37.018518 | 120 | 0.61827 |
cadop/siborg-simulate-walk/exts/siborg.simulate.walk/siborg/simulate/walk/tests/__init__.py | from .test_hello_world import * | 31 | Python | 30.999969 | 31 | 0.774194 |
cadop/siborg-simulate-walk/exts/siborg.simulate.walk/siborg/simulate/walk/tests/test_hello_world.py | # NOTE:
# omni.kit.test - std python's unittest module with additional wrapping to add suport for async/await tests
# For most things refer to unittest docs: https://docs.python.org/3/library/unittest.html
import omni.kit.test
# Extnsion for writing UI tests (simulate UI interaction)
import omni.kit.ui_test as ui_test
# Import extension python module we are testing with absolute import path, as if we are external user (other extension)
import siborg.simulate.walk
# Having a test class dervived from omni.kit.test.AsyncTestCase declared on the root of module will make it auto-discoverable by omni.kit.test
class Test(omni.kit.test.AsyncTestCase):
# Before running each test
async def setUp(self):
pass
# After running each test
async def tearDown(self):
pass
# Actual test, notice it is "async" function, so "await" can be used if needed
async def test_hello_public_function(self):
result = siborg.simulate.walk.some_public_function(4)
self.assertEqual(result, 256)
async def test_window_button(self):
# Find a label in our window
label = ui_test.find("My Window//Frame/**/Label[*]")
# Find buttons in our window
add_button = ui_test.find("My Window//Frame/**/Button[*].text=='Add'")
reset_button = ui_test.find("My Window//Frame/**/Button[*].text=='Reset'")
# Click reset button
await reset_button.click()
self.assertEqual(label.widget.text, "empty")
await add_button.click()
self.assertEqual(label.widget.text, "count: 1")
await add_button.click()
self.assertEqual(label.widget.text, "count: 2")
| 1,676 | Python | 34.68085 | 142 | 0.682578 |
cadop/siborg-simulate-walk/exts/siborg.simulate.walk/config/extension.toml | [package]
# Semantic Versioning is used: https://semver.org/
version = "0.0.2"
# Lists people or organizations that are considered the "authors" of the package.
authors = ["Siborg Lab"]
# The title and description fields are primarily for displaying extension info in UI
title = "siborg simulate walk"
description="A simple extension to make walking agents follow a goal."
# Path (relative to the root) or content of readme markdown file for UI.
readme = "docs/README.md"
# URL of the extension source repository.
repository = "https://github.com/cadop/siborg-simulate-walk"
# One of categories for UI.
category = "Simulate"
# Keywords for the extension
keywords = ["Following", "peopl", "agents", "walk", "behavior"]
# Location of change log file in target (final) folder of extension, relative to the root.
# More info on writing changelog: https://keepachangelog.com/en/1.0.0/
changelog="docs/CHANGELOG.md"
# Preview image and icon. Folder named "data" automatically goes in git lfs (see .gitattributes file).
# Preview image is shown in "Overview" of Extensions window. Screenshot of an extension might be a good preview image.
preview_image = "data/preview.png"
# Icon is shown in Extensions window, it is recommended to be square, of size 256x256.
icon = "data/icon.png"
# Use omni.ui to build simple UI
[dependencies]
"omni.kit.uiapp" = {}
"omni.kit.window.viewport" = {}
"omni.anim.navigation.bundle" = {}
"omni.anim.people" = {}
# Main python module this extension provides, it will be publicly available as "import siborg.simulate.walk".
[[python.module]]
name = "siborg.simulate.walk"
[[test]]
# Extra dependencies only to be used during test run
dependencies = [
"omni.kit.ui_test" # UI testing extension
]
| 1,736 | TOML | 33.058823 | 118 | 0.739631 |
cadop/siborg-simulate-walk/exts/siborg.simulate.walk/docs/CHANGELOG.md | # Changelog
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/).
## [1.0.0] - 2021-04-26
- Initial version of extension UI template with a window
| 178 | Markdown | 18.888887 | 80 | 0.702247 |
cadop/siborg-simulate-walk/exts/siborg.simulate.walk/docs/README.md | # Python Extension [siborg.simulate.walk]
This is a simple extension that lets users select characters and assign them a goal xform to follow (while doing a walk animation).
It was initially done as a test, and the code may be useful to others. Since this was created a few days after the Beta release of the people plugin, its very likely to break soon. Please open an issue or make a PR on github if you find problems in the future.
| 440 | Markdown | 72.499988 | 262 | 0.777273 |
cadop/siborg-simulate-walk/exts/siborg.simulate.walk/docs/index.rst | siborg.simulate.walk
#############################
Example of Python only extension
.. toctree::
:maxdepth: 1
README
CHANGELOG
.. automodule::"siborg.simulate.walk"
:platform: Windows-x86_64, Linux-x86_64
:members:
:undoc-members:
:show-inheritance:
:imported-members:
:exclude-members: contextmanager
| 341 | reStructuredText | 15.285714 | 43 | 0.621701 |
cadop/ov_dhart/README.md | # DHART for Omniverse
If you have feature requests or need help with generating graphs, running algorithms, etc. please visit the main repo https://github.com/cadop/dhart. This repo is only for the omniverse extension part.
| 229 | Markdown | 37.333327 | 203 | 0.781659 |
cadop/ov_dhart/tools/scripts/link_app.py | import os
import argparse
import sys
import json
import packmanapi
import urllib3
def find_omniverse_apps():
http = urllib3.PoolManager()
try:
r = http.request("GET", "http://127.0.0.1:33480/components")
except Exception as e:
print(f"Failed retrieving apps from an Omniverse Launcher, maybe it is not installed?\nError: {e}")
sys.exit(1)
apps = {}
for x in json.loads(r.data.decode("utf-8")):
latest = x.get("installedVersions", {}).get("latest", "")
if latest:
for s in x.get("settings", []):
if s.get("version", "") == latest:
root = s.get("launch", {}).get("root", "")
apps[x["slug"]] = (x["name"], root)
break
return apps
def create_link(src, dst):
print(f"Creating a link '{src}' -> '{dst}'")
packmanapi.link(src, dst)
APP_PRIORITIES = ["code", "create", "view"]
if __name__ == "__main__":
parser = argparse.ArgumentParser(description="Create folder link to Kit App installed from Omniverse Launcher")
parser.add_argument(
"--path",
help="Path to Kit App installed from Omniverse Launcher, e.g.: 'C:/Users/bob/AppData/Local/ov/pkg/create-2021.3.4'",
required=False,
)
parser.add_argument(
"--app", help="Name of Kit App installed from Omniverse Launcher, e.g.: 'code', 'create'", required=False
)
args = parser.parse_args()
path = args.path
if not path:
print("Path is not specified, looking for Omniverse Apps...")
apps = find_omniverse_apps()
if len(apps) == 0:
print(
"Can't find any Omniverse Apps. Use Omniverse Launcher to install one. 'Code' is the recommended app for developers."
)
sys.exit(0)
print("\nFound following Omniverse Apps:")
for i, slug in enumerate(apps):
name, root = apps[slug]
print(f"{i}: {name} ({slug}) at: '{root}'")
if args.app:
selected_app = args.app.lower()
if selected_app not in apps:
choices = ", ".join(apps.keys())
print(f"Passed app: '{selected_app}' is not found. Specify one of the following found Apps: {choices}")
sys.exit(0)
else:
selected_app = next((x for x in APP_PRIORITIES if x in apps), None)
if not selected_app:
selected_app = next(iter(apps))
print(f"\nSelected app: {selected_app}")
_, path = apps[selected_app]
if not os.path.exists(path):
print(f"Provided path doesn't exist: {path}")
else:
SCRIPT_ROOT = os.path.dirname(os.path.realpath(__file__))
create_link(f"{SCRIPT_ROOT}/../../app", path)
print("Success!")
| 2,813 | Python | 32.5 | 133 | 0.562389 |
cadop/ov_dhart/tools/packman/config.packman.xml | <config remotes="cloudfront">
<remote2 name="cloudfront">
<transport actions="download" protocol="https" packageLocation="d4i3qtqj3r0z5.cloudfront.net/${name}@${version}" />
</remote2>
</config>
| 211 | XML | 34.333328 | 123 | 0.691943 |
cadop/ov_dhart/tools/packman/bootstrap/install_package.py | # Copyright 2019 NVIDIA CORPORATION
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
# http://www.apache.org/licenses/LICENSE-2.0
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import logging
import zipfile
import tempfile
import sys
import shutil
__author__ = "hfannar"
logging.basicConfig(level=logging.WARNING, format="%(message)s")
logger = logging.getLogger("install_package")
class TemporaryDirectory:
def __init__(self):
self.path = None
def __enter__(self):
self.path = tempfile.mkdtemp()
return self.path
def __exit__(self, type, value, traceback):
# Remove temporary data created
shutil.rmtree(self.path)
def install_package(package_src_path, package_dst_path):
with zipfile.ZipFile(
package_src_path, allowZip64=True
) as zip_file, TemporaryDirectory() as temp_dir:
zip_file.extractall(temp_dir)
# Recursively copy (temp_dir will be automatically cleaned up on exit)
try:
# Recursive copy is needed because both package name and version folder could be missing in
# target directory:
shutil.copytree(temp_dir, package_dst_path)
except OSError as exc:
logger.warning(
"Directory %s already present, packaged installation aborted" % package_dst_path
)
else:
logger.info("Package successfully installed to %s" % package_dst_path)
install_package(sys.argv[1], sys.argv[2])
| 1,888 | Python | 31.568965 | 103 | 0.68697 |
cadop/ov_dhart/exts/siborg.analysis.dhart/siborg/analysis/dhart/usd_utils.py | import numpy as np
from pxr import UsdGeom, Gf, Usd
def traverse_instanced_children(prim):
"""Get every Prim child beneath `prim`, even if `prim` is instanced.
Important:
If `prim` is instanced, any child that this function yields will
be an instance proxy.
Args:
prim (`pxr.Usd.Prim`): Some Prim to check for children.
Yields:
`pxr.Usd.Prim`: The children of `prim`.
"""
for child in prim.GetFilteredChildren(Usd.TraverseInstanceProxies()):
yield child
for subchild in traverse_instanced_children(child):
yield subchild
def parent_and_children_as_mesh(parent_prim):
if parent_prim.IsA(UsdGeom.Mesh):
points, faces = get_mesh(parent_prim)
return points, faces
found_meshes = []
for x in traverse_instanced_children(parent_prim):
if x.IsA(UsdGeom.Mesh):
found_meshes.append(x)
# children = parent_prim.GetAllChildren()
# children = [child.GetPrimPath() for child in children]
# points, faces = get_mesh(children)
points, faces = get_mesh(found_meshes)
return points, faces
def children_as_mesh(stage, parent_prim):
children = parent_prim.GetAllChildren()
children = [child.GetPrimPath() for child in children]
points, faces = get_mesh(stage, children)
return points, faces
def get_all_stage_mesh(stage):
found_meshes = []
# Traverse the scene graph and print the paths of prims, including instance proxies
for x in Usd.PrimRange(stage.GetPseudoRoot(), Usd.TraverseInstanceProxies()):
if x.IsA(UsdGeom.Mesh):
found_meshes.append(x)
points, faces = get_mesh(found_meshes)
return points, faces
def get_mesh(objs):
points, faces = [],[]
for obj in objs:
f_offset = len(points)
f, p = meshconvert(obj)
if len(p) == 0: continue
points.extend(p)
faces.extend(f+f_offset)
return points, faces
def meshconvert(prim):
# Create an XformCache object to efficiently compute world transforms
xform_cache = UsdGeom.XformCache()
# Get the mesh schema
mesh = UsdGeom.Mesh(prim)
# Get verts and triangles
tris = mesh.GetFaceVertexIndicesAttr().Get()
if not tris:
return [], []
tris_cnt = mesh.GetFaceVertexCountsAttr().Get()
# Get the vertices in local space
points_attr = mesh.GetPointsAttr()
local_points = points_attr.Get()
# Convert the VtVec3fArray to a NumPy array
points_np = np.array(local_points, dtype=np.float64)
# Add a fourth component (with value 1.0) to make the points homogeneous
num_points = len(local_points)
ones = np.ones((num_points, 1), dtype=np.float64)
points_np = np.hstack((points_np, ones))
# Compute the world transform for this prim
world_transform = xform_cache.GetLocalToWorldTransform(prim)
# Convert the GfMatrix to a NumPy array
matrix_np = np.array(world_transform, dtype=np.float64).reshape((4, 4))
# Transform all vertices to world space using matrix multiplication
world_points = np.dot(points_np, matrix_np)
tri_list = convert_to_triangle_mesh(tris, tris_cnt)
# tri_list = tri_list.flatten()
world_points = world_points[:,:3]
return tri_list, world_points
def convert_to_triangle_mesh(FaceVertexIndices, FaceVertexCounts):
"""
Convert a list of vertices and a list of faces into a triangle mesh.
A list of triangle faces, where each face is a list of indices of the vertices that form the face.
"""
# Parse the face vertex indices into individual face lists based on the face vertex counts.
faces = []
start = 0
for count in FaceVertexCounts:
end = start + count
face = FaceVertexIndices[start:end]
faces.append(face)
start = end
# Convert all faces to triangles
triangle_faces = []
for face in faces:
if len(face) < 3:
newface = [] # Invalid face
elif len(face) == 3:
newface = [face] # Already a triangle
else:
# Fan triangulation: pick the first vertex and connect it to all other vertices
v0 = face[0]
newface = [[v0, face[i], face[i + 1]] for i in range(1, len(face) - 1)]
triangle_faces.extend(newface)
return np.array(triangle_faces)
| 4,394 | Python | 28.3 | 102 | 0.643605 |
cadop/ov_dhart/exts/siborg.analysis.dhart/siborg/analysis/dhart/extension.py | import omni.ext
import omni.ui as ui
from . import core
from . import render
from . import window
# Any class derived from `omni.ext.IExt` in top level module (defined in `python.modules` of `extension.toml`) will be
# instantiated when extension gets enabled and `on_startup(ext_id)` will be called. Later when extension gets disabled
# on_shutdown() is called.
class DhartExtension(omni.ext.IExt):
# ext_id is current extension id. It can be used with extension manager to query additional information, like where
# this extension is located on filesystem.
def on_startup(self, ext_id):
print("[ov_dhart] DHART is startingup")
# Initialize DHART class and event subscription
self.initialize()
# Setup GUI
self.show_window()
def show_window(self):
self._window = window.populate_window(self.DI, render)
def initialize(self):
''' Initialization and any setup needed '''
self.DI = core.DhartInterface()
# ### Subscribe to events
# self._usd_context = omni.usd.get_context()
# self._selection = self._usd_context.get_selection()
# self._events = self._usd_context.get_stage_event_stream()
# self._stage_event_sub = self._events.create_subscription_to_pop(self._on_stage_event,
# name='my stage update'
# )
def _on_stage_event(self, event):
''' subscription to an event on the stage '''
# When a selection is changed, call our function
if event.type == int(omni.usd.StageEventType.SELECTION_CHANGED):
self._on_selection_changed()
def _on_selection_changed(self):
''' where we do stuff on the event that notified us a stage selection changed '''
# Gets the selected prim paths
selection = self._selection.get_selected_prim_paths()
stage = self._usd_context.get_stage()
# Empty list to be filled of selection prims
prim_selections = []
# Check if there is a valid selection and stage
if selection and stage:
# Make a list of the selection prims
for selected_path in selection:
prim = stage.GetPrimAtPath(selected_path)
prim_selections.append(prim)
if prim_selections:
core.DhartInterface.active_selection = prim_selections
print(f'Set DI to {prim_selections}')
def on_shutdown(self):
print("[ov_dhart] DHART is shutting down")
| 2,650 | Python | 36.871428 | 119 | 0.604906 |
cadop/ov_dhart/exts/siborg.analysis.dhart/siborg/analysis/dhart/__init__.py | from .extension import *
import os
def package_dir():
''' Helper to get directory of this pacckage '''
return os.path.dirname(os.path.realpath(__file__)) | 163 | Python | 22.428568 | 54 | 0.680982 |
cadop/ov_dhart/exts/siborg.analysis.dhart/siborg/analysis/dhart/core.py | from pxr import Usd, UsdGeom, UsdPhysics, UsdShade, Sdf, Gf, Tf, PhysxSchema, Vt
try:
from omni.usd.utils import get_world_transform_matrix
except:
from omni.usd import get_world_transform_matrix
import omni.physx
import numpy as np
from scipy.interpolate import splprep, splev
import dhart
import dhart.geometry
import dhart.raytracer
import dhart.graphgenerator
from dhart import pathfinding
from dhart.visibilitygraph import VisibilityGraphAllToAll
from dhart.visibilitygraph import VisibilityGraphUndirectedAllToAll
from dhart.visibilitygraph import VisibilityGraphGroupToGroup
from dhart.spatialstructures.cost_algorithms import CalculateEnergyExpenditure, CostAlgorithmKeys
from dhart.spatialstructures import Graph, Direction
from . import usd_utils
import time
class DhartInterface():
# Global class variable
active_selection = None
def __init__(self):
# BVH for DHART
self.bvh = None
self.vis_bvh = None # Separate BVH for storing opaque objects
self.VG = None
self.VG_group = None
self.graph = None
# Selected Starting Location
self.start_prim = None
self.node_size = 15
self.path_size = 20
# Set 0 start
self.start_point = [0,0,0]
# Set max nodes
self.max_nodes = 400
self.grid_spacing = [20,20]
self.height = 80
self.upstep = 30
self.downstep = 30
self.upslope = 20
self.downslope = 20
self.targ_vis_path = '/World/TargetNodes'
self.path_start_path = '/World/StartPath'
self.path_end_path = '/World/EndPath'
# Track
self.gui_start = []
self.gui_end = []
def set_as_start(self):
''' Sets the DhartInterface.active_selection to the start prim '''
self.start_point = self.get_selected_as_point()
self.gui_start[0].model.set_value(self.start_point[0])
self.gui_start[1].model.set_value(self.start_point[1])
self.gui_start[2].model.set_value(self.start_point[2])
def set_as_end(self):
''' Sets the DhartInterface.active_selection to the end prim '''
self.end_point = self.get_selected_as_point()
self.gui_end[0].model.set_value(self.end_point[0])
self.gui_end[1].model.set_value(self.end_point[1])
self.gui_end[2].model.set_value(self.end_point[2])
def get_selected_as_point(self):
''' Sets the DhartInterface.active_selection to the start prim '''
# Get the current active selection of the stage
self.stage = omni.usd.get_context().get_stage()
# Get the selections from the stage
self._usd_context = omni.usd.get_context()
self._selection = self._usd_context.get_selection()
selected_paths = self._selection.get_selected_prim_paths()
# Expects a list, so take first selection
prim = [self.stage.GetPrimAtPath(x) for x in selected_paths][0]
# try:
# selected_point = get_world_transform_matrix(prim).ExtractTranslation()
# except:
# selected_point = omni.usd.get_world_transform_matrix(prim).ExtractTranslation()
selected_point = get_world_transform_matrix(prim).ExtractTranslation()
return selected_point
def modify_start(self,x=None,y=None,z=None):
if x: self.start_point[0] = x
if y: self.start_point[1] = y
if z: self.start_point[2] = z
print(f'START IS: {self.start_point}')
def modify_end(self,x=None,y=None,z=None):
if x: self.end_point[0] = x
if y: self.end_point[1] = y
if z: self.end_point[2] = z
print(f'END IS: {self.end_point}')
def set_as_bvh(self):
# Set the graph bvh
self.set_bvh(vis=False)
def set_as_vis_bvh(self):
# Set the visibility-based bvh
self.set_bvh(vis=True)
def set_bvh(self, vis=False):
# Get the current active selection of the stage
self.stage = omni.usd.get_context().get_stage()
# Get the selections from the stage
self._usd_context = omni.usd.get_context()
self._selection = self._usd_context.get_selection()
selected_paths = self._selection.get_selected_prim_paths()
# Expects a list, so take first selection
prims = [self.stage.GetPrimAtPath(x) for x in selected_paths]
# Record if a BVH was generated
made_bvh = False
for prim in prims:
MI = self.convert_to_mesh(prim)
if MI is None:
print("BVH FAILED")
continue
if not made_bvh:
if vis:
self.vis_bvh = dhart.raytracer.EmbreeBVH(MI)
print(f'VIS BVH is: {self.vis_bvh}')
else:
self.bvh = dhart.raytracer.EmbreeBVH(MI)
# self.bvh = dhart.raytracer.EmbreeBVH(MI, use_precise=True)
print(f'BVH is: {self.bvh}')
made_bvh = True
else:
if vis:
self.vis_bvh.AddMesh(MI)
print('Added to VIS BVH')
else:
self.bvh.AddMesh(MI)
print('Added to BVH')
# for prim in prims:
# prim_type = prim.GetTypeName()
# # Only add if its a mesh
# if prim_type == 'Mesh':
# MI = self.convert_to_mesh_old(prim)
# # MI = self.convert_to_mesh(prim)
# if MI is None:
# print("BVH FAILED")
# continue
# if not made_bvh:
# if vis:
# self.vis_bvh = dhart.raytracer.EmbreeBVH(MI)
# print(f'VIS BVH is: {self.vis_bvh}')
# else:
# self.bvh = dhart.raytracer.EmbreeBVH(MI)
# print(f'BVH is: {self.bvh}')
# made_bvh = True
# else:
# if vis:
# self.vis_bvh.AddMesh(MI)
# print('Added to VIS BVH')
# else:
# self.bvh.AddMesh(MI)
# print('Added to BVH')
def set_max_nodes(self, m):
self.max_nodes = m
def set_spacing(self, xy):
self.grid_spacing = [xy,xy]
def set_height(self, z):
self.height = z
def set_upstep(self, u):
self.upstep = u
def set_upslope(self, us):
self.upslope = us
def set_downstep(self, d):
self.downstep = d
def set_downslope(self, ds):
self.downslope = ds
def set_nodesize(self, s):
self.node_size = s
def set_pathsize(self, s):
self.path_size = s
def generate_graph(self):
''' use dhart to generate a graph '''
if not self.bvh:
print("No BVH")
return
self.scene_setup()
spacing = (self.grid_spacing[0], self.grid_spacing[1], self.height)
max_nodes = self.max_nodes
self.graph = dhart.graphgenerator.GenerateGraph(self.bvh,
self.start_point,
spacing,
max_nodes,
up_step = self.upstep,
down_step = self.downstep,
up_slope = self.upslope,
down_slope=self.downslope,
cores=-1)
if self.graph:
self.graph.CompressToCSR()
self.nodes = self.graph.getNodes().array[['x','y','z']]
print(f'Got {len(self.nodes)} Nodes')
else:
print("FAILED")
return
self.create_geompoints(self.nodes.tolist())
def get_to_nodes(self):
parent_prim = self.stage.GetPrimAtPath(self.targ_vis_path)
children = parent_prim.GetAllChildren()
b_nodes = []
for child in children:
t = get_world_transform_matrix(child).ExtractTranslation()
b_nodes.append(np.asarray(t))
return b_nodes
def visibility_graph_groups(self):
start_t = time.time()
nodes_a = self.nodes # Define points as the graph nodes
nodes_b = self.get_to_nodes()
self.VG_group = VisibilityGraphGroupToGroup(self.vis_bvh, nodes_a, nodes_b, self.height) # Calculate the visibility graph
if self.VG_group is None:
print('VG Failed')
return
# visibility_graph = VG.CompressToCSR() # Convert to a CSR (matrix)
scores = self.VG_group.AggregateEdgeCosts(2, True) # Aggregate the visibility graph scores
scores = scores[:-len(nodes_b)] # remove b nodes
print(f'VG group time = {time.time()-start_t}')
# add scores to node attributes
attr = "vg_group"
ids = self.graph.getNodes().array['id']
str_scores = [str(1.0/(x+0.01)) for x in scores] # we need scores to be a string for dhart. was to encode any type of node data
self.graph.add_node_attributes(attr, ids, str_scores)
self.score_vg(scores)
def visibility_graph(self):
start_t = time.time()
points = self.graph.getNodes() # Define points as the graph nodes
self.VG = VisibilityGraphUndirectedAllToAll(self.vis_bvh, points, self.height) # Calculate the visibility graph
# VG = VisibilityGraphAllToAll(self.bvh, points, self.height) # Calculate the visibility graph
scores = self.VG.AggregateEdgeCosts(2, True) # Aggregate the visibility graph scores
print(f'VG time = {time.time()-start_t}')
# add scores to node attributes
attr = "vg_all"
ids = self.graph.getNodes().array['id']
str_scores = [str(x) for x in scores] # we need scores to be a string for dhart. was to encode any type of node data
self.graph.add_node_attributes(attr, ids, str_scores)
self.score_vg(scores)
def reset_endpoints(self):
s_prim = self.stage.GetPrimAtPath(self.path_start_path)
self.start_point = get_world_transform_matrix(s_prim).ExtractTranslation()
e_prim = self.stage.GetPrimAtPath(self.path_end_path)
self.end_point = get_world_transform_matrix(e_prim).ExtractTranslation()
def get_path(self):
''' Get the shortest path by distance '''
# DHART requires passing the desired nodes (not the positions)
# So, we will allow users to select an arbitrary position and get the closest node ids to it
#### !!!! This was screwing up the graph generation because the start point was a bunch of decimals
self.reset_endpoints()
self.start_point = [int(x) for x in self.start_point]
p_desired = np.array([self.start_point, self.end_point])
closest_nodes = self.graph.get_closest_nodes(p_desired)
# nodes = self.graph.getNodes()
# matching_items = nodes[np.isin(nodes['id'], closest_nodes)]
# print(f'Start/End Nodes {matching_items}')
# self.show_nodes(matching_items[['x','y','z']].tolist())
path = pathfinding.DijkstraShortestPath(self.graph, closest_nodes[0], closest_nodes[1])
# print(f'Path Nodes: {path}')
if path is None:
print("No PATH Found")
return
path_xyz = np.take(self.nodes[['x','y','z']], path['id'])
print(len(path_xyz.tolist()))
path_list = path_xyz.tolist()
path_nodes = self.smooth_path(path_list)
self.create_curve(path_nodes)
# self.show_nodes(path_xyz.tolist())
def smooth_path(self, input_points):
'''
Interpolate the path and smooth the verts to be shown
'''
def interpolate_curve(points, num_points=100):
"""Interpolate the curve to produce a denser set of points."""
tck, u = splprep([[p[0] for p in points], [p[1] for p in points], [p[2] for p in points]], s=0)
u_new = np.linspace(0, 1, num_points)
x_new, y_new, z_new = splev(u_new, tck)
return list(zip(x_new, y_new, z_new))
# Re-define the moving_average function as provided by you
def moving_average(points, window_size=3):
"""Smoothen the curve using a moving average."""
if window_size < 3:
return points # Too small window, just return original points
extended_points = points[:window_size-1] + points + points[-(window_size-1):]
smoothed_points = []
for i in range(len(points)):
window = extended_points[i:i+window_size]
avg_x = sum(pt[0] for pt in window) / window_size
avg_y = sum(pt[1] for pt in window) / window_size
avg_z = sum(pt[2] for pt in window) / window_size
smoothed_points.append((avg_x, avg_y, avg_z))
return smoothed_points
# Smooth the original input points
smoothed_points = moving_average(input_points, window_size=4)
# Interpolate the smoothed curve to produce a denser set of points
interpolated_points = interpolate_curve(smoothed_points, num_points=500)
# Smooth the denser set of points
smoothed_interpolated_points = moving_average(interpolated_points, window_size=6)
return smoothed_interpolated_points
def show_nodes(self, nodes):
stage = omni.usd.get_context().get_stage()
prim = UsdGeom.Points.Define(stage, "/World/Graph/Closest")
prim.CreatePointsAttr(nodes)
width_attr = prim.CreateWidthsAttr()
width_attr.Set([self.node_size*2])
# prim.CreateDisplayColorAttr()
# For RTX renderers, this only works for UsdGeom.Tokens.constant
color_primvar = prim.CreateDisplayColorPrimvar(UsdGeom.Tokens.constant)
color_primvar.Set([(0,0,1)])
def get_energy_path(self):
# Get the key
energy_cost_key = CostAlgorithmKeys.ENERGY_EXPENDITURE
CalculateEnergyExpenditure(self.graph)
self.reset_endpoints()
p_desired = np.array([self.start_point, self.end_point])
closest_nodes = self.graph.get_closest_nodes(p_desired)
# Call the shortest path again, with the optional cost type
energy_path = pathfinding.DijkstraShortestPath(self.graph, closest_nodes[0], closest_nodes[1], energy_cost_key)
path_xyz = np.take(self.nodes[['x','y','z']], energy_path['id'])
self.create_curve(path_xyz.tolist())
# As the cost array is numpy, simple operations to sum the total cost can be calculated
path_sum = np.sum(energy_path['cost_to_next'])
print('Total path cost: ', path_sum)
def get_visibility_path(self):
# make sure visibility graph was made
# get node ids and attrs of vg
self.reset_endpoints()
# assign new node attrs for visibility
csr = self.graph.CompressToCSR()
# Get attribute scores from the graph
# out_attrs = self.graph.get_node_attributes(attr)
self.graph.attrs_to_costs("vg_group", "vg_group_cost", Direction.INCOMING)
# self.graph.GetEdgeCost(1, 2, "vg_group_cost")
# get custom path based on vg
p_desired = np.array([self.start_point, self.end_point])
closest_nodes = self.graph.get_closest_nodes(p_desired)
# Call the shortest path again, with the optional cost type
visibility_path = pathfinding.DijkstraShortestPath(self.graph, closest_nodes[0], closest_nodes[1], 'vg_group_cost')
path_xyz = np.take(self.nodes[['x','y','z']], visibility_path['id'])
self.create_curve(path_xyz.tolist())
def get_vg_path(self):
# make sure visibility graph was made
# get node ids and attrs of vg
self.reset_endpoints()
# assign new node attrs for visibility
csr = self.graph.CompressToCSR()
# Get attribute scores from the graph
# out_attrs = self.graph.get_node_attributes(attr)
self.graph.attrs_to_costs("vg_all", "vg_all_cost", Direction.INCOMING)
# self.graph.GetEdgeCost(1, 2, "vg_group_cost")
# get custom path based on vg
p_desired = np.array([self.start_point, self.end_point])
closest_nodes = self.graph.get_closest_nodes(p_desired)
# Call the shortest path again, with the optional cost type
visibility_path = DijkstraShortestPath(self.graph, closest_nodes[0], closest_nodes[1], 'vg_all_cost')
path_xyz = np.take(self.nodes[['x','y','z']], visibility_path['id'])
self.create_curve(path_xyz.tolist())
def scene_setup(self):
# Get stage.
self.stage = omni.usd.get_context().get_stage()
def score_vg(self, scores):
scores = np.asarray(scores)
colors = calc_colors(scores)
self.create_colored_geompoints(self.nodes.tolist(), colors)
def create_colored_geompoints(self, nodes, colors=None):
stage = omni.usd.get_context().get_stage()
prim = UsdGeom.Points.Define(stage, "/World/Graph/VGPoints")
prim.CreatePointsAttr(nodes)
width_attr = prim.CreateWidthsAttr()
width_attr.Set([self.node_size])
color_primvar = prim.CreateDisplayColorPrimvar(UsdGeom.Tokens.vertex)
color_primvar.Set(colors)
def create_geompoints(self, nodes):
stage = omni.usd.get_context().get_stage()
prim = UsdGeom.Points.Define(stage, "/World/Graph/Points")
prim.CreatePointsAttr(nodes)
width_attr = prim.CreateWidthsAttr()
width_attr.Set([self.node_size])
color_primvar = prim.CreateDisplayColorPrimvar(UsdGeom.Tokens.constant)
color_primvar.Set([(1,0,0)])
def create_curve(self, nodes):
'''Create and draw a BasisCurve on the stage following the nodes'''
stage = omni.usd.get_context().get_stage()
prim = UsdGeom.BasisCurves.Define(stage, "/World/Path")
prim.CreatePointsAttr(nodes)
# Set the number of curve verts to be the same as the number of points we have
curve_verts = prim.CreateCurveVertexCountsAttr()
curve_verts.Set([len(nodes)])
# Set the curve type to linear so that each node is connected to the next
type_attr = prim.CreateTypeAttr()
type_attr.Set('linear')
type_attr = prim.GetTypeAttr().Get()
# Set the width of the curve
width_attr = prim.CreateWidthsAttr()
# width_attr = prim.CreateWidthsAttr(UsdGeom.Tokens.varying)
width_attr.Set([self.path_size for x in range(len(nodes))])
color_primvar = prim.CreateDisplayColorPrimvar(UsdGeom.Tokens.constant)
color_primvar.Set([(0,1,0)])
return
def convert_to_mesh(self,prim):
vert_list, tri_list = usd_utils.parent_and_children_as_mesh(prim)
# vert_list, tri_list = usd_utils.get_mesh([prim])
tri_list = np.array(tri_list).flatten()
vert_list = np.array(vert_list).flatten()
try:
MI = dhart.geometry.MeshInfo(tri_list, vert_list, "testmesh", 0)
return MI
except:
print(prim)
return None
def convert_to_mesh_old(self, prim):
''' convert a prim to BVH '''
# Get mesh name (prim name)
m = UsdGeom.Mesh(prim)
# Get verts and triangles
tris = m.GetFaceVertexIndicesAttr().Get()
tris_cnt = m.GetFaceVertexCountsAttr().Get()
verts = m.GetPointsAttr().Get()
tri_list = np.array(tris)
vert_list = np.array(verts)
xform = UsdGeom.Xformable(prim)
time = Usd.TimeCode.Default() # The time at which we compute the bounding box
world_transform: Gf.Matrix4d = xform.ComputeLocalToWorldTransform(time)
translation: Gf.Vec3d = world_transform.ExtractTranslation()
rotation: Gf.Rotation = world_transform.ExtractRotationMatrix()
scale: Gf.Vec3d = Gf.Vec3d(*(v.GetLength() for v in world_transform.ExtractRotationMatrix()))
vert_rotated = np.dot(vert_list, rotation) # Rotate points
vert_translated = vert_rotated + translation
vert_scaled = vert_translated
vert_scaled[:,0] *= scale[0]
vert_scaled[:,1] *= scale[1]
vert_scaled[:,2] *= scale[2]
vert_list = vert_scaled
vert_list = vert_translated.flatten()
# Check if the face counts are 4, if so, reshape and turn to triangles
if tris_cnt[0] == 4:
quad_list = tri_list.reshape(-1,4)
tri_list = quad_to_tri(quad_list)
tri_list = tri_list.flatten()
try:
MI = dhart.geometry.MeshInfo(tri_list, vert_list, "testmesh", 0)
return MI
except:
print(prim)
return None
def quad_to_tri(a):
idx = np.flatnonzero(a[:,-1] == 0)
out0 = np.empty((a.shape[0],2,3),dtype=a.dtype)
out0[:,0,1:] = a[:,1:-1]
out0[:,1,1:] = a[:,2:]
out0[...,0] = a[:,0,None]
out0.shape = (-1,3)
mask = np.ones(out0.shape[0],dtype=bool)
mask[idx*2+1] = 0
return out0[mask]
def calc_colors(scores):
filtered_scores = [score for score in scores if score>=0]
max_v = max(filtered_scores)
min_v = min(filtered_scores)
print('maxmin')
print(max_v)
print(min_v)
print('')
if (max_v == 0):
print("Max is zero!")
exit()
elif(max_v - min_v == 0):
print("All values are the same!")
return [colorbar(1.0)] * len(scores)
return [
colorbar((point-min_v)/(max_v-min_v))
if point >= 0
else None
for point in scores
]
def colorbar(val):
r = min(max(0, 1.5-abs(1-4*(val-0.5))),1)
g = min(max(0, 1.5-abs(1-4*(val-0.25))),1)
b = min(max(0, 1.5-abs(1-4*val)),1)
return np.asarray([r,g,b], dtype=float)
| 22,274 | Python | 34.07874 | 135 | 0.582203 |
cadop/ov_dhart/exts/siborg.analysis.dhart/siborg/analysis/dhart/render.py |
from pxr import Sdf, Usd, UsdGeom
import omni
def create_perspective_camera(stage: Usd.Stage, prim_path: str="/World/MyPerspCam") -> UsdGeom.Camera:
camera_path = Sdf.Path(prim_path)
usd_camera: UsdGeom.Camera = UsdGeom.Camera.Define(stage, camera_path)
usd_camera.CreateProjectionAttr().Set(UsdGeom.Tokens.perspective)
return usd_camera
def assign_camera():
''' insert actiongraph to stage (if not already there) and make a camera '''
stage = omni.usd.get_context().get_stage()
cam_path = "/World/FlyCam"
camera = create_perspective_camera(stage, cam_path)
| 596 | Python | 30.421051 | 102 | 0.713087 |
cadop/ov_dhart/exts/siborg.analysis.dhart/siborg/analysis/dhart/ext_with_layout.py | import os
import omni.ext
import omni.ui as ui
from omni.kit.quicklayout import QuickLayout
from . import core
# Any class derived from `omni.ext.IExt` in top level module (defined in `python.modules` of `extension.toml`) will be
# instantiated when extension gets enabled and `on_startup(ext_id)` will be called. Later when extension gets disabled
# on_shutdown() is called.
class DhartExtension2():
# class DhartExtension(omni.ext.IExt):
# ext_id is current extension id. It can be used with extension manager to query additional information, like where
# this extension is located on filesystem.
MENU_PATH = "Analysis/DHART"
_instance = None
def on_startup(self, ext_id):
print("[omni.dhart] MyExtension startup")
# Add a window menu item so we can easily find the package
self._window = None
try:
self._menu = omni.kit.ui.get_editor_menu().add_item(
DhartExtension.MENU_PATH, self.show_window, toggle=True, value=True
)
except Exception as e:
self._menu = None
self.initialize()
### Subscribe to events
self._usd_context = omni.usd.get_context()
self._selection = self._usd_context.get_selection()
self._events = self._usd_context.get_stage_event_stream()
self._stage_event_sub = self._events.create_subscription_to_pop(self._on_stage_event,
name='my stage update'
)
DhartExtension._instance = self
def _visiblity_changed_fn(self, visible):
if self._menu:
omni.kit.ui.get_editor_menu().set_value(DhartExtension.MENU_PATH, visible)
def show_window(self, menu, value):
print('Passed Class instantiation')
if value:
# self._clean_up_window()
self.initialize()
self._window = ui.Window("DHART", width=300, height=300)
with self._window.frame:
with ui.VStack():
ui.Label("Some Label")
ui.Button("Generate BVH", clicked_fn=lambda: self.DI.convert_mesh())
ui.Button("Generate Graph", clicked_fn=lambda: self.DI.graph())
with ui.HStack():
ui.Label("timesteps: ")
dt = ui.IntField(height=20)
dt.model.set_value(60)
dt.model.add_value_changed_fn(lambda m: self.Sim.set_sim_steps(m.get_value_as_int()))
# Just for fun, does it automatically
with ui.HStack():
# with ui.HStack(width=100):
workspace_filename = omni.dhart.package_dir()
workspace_filename = os.path.join(workspace_filename, 'layout.json')
print(workspace_filename)
ui.Button("Save Layout", clicked_fn=lambda: QuickLayout.save_file(workspace_filename))
ui.Button("Load Layout", clicked_fn=lambda: QuickLayout.load_file(workspace_filename))
# Load workspace layout
workspace_filename = omni.dhart.package_dir()
workspace_filename = os.path.join(workspace_filename, 'layout.json')
QuickLayout.load_file(workspace_filename)
if self._menu:
print("Setting menu")
omni.kit.ui.get_editor_menu().set_value(DhartExtension.MENU_PATH, True)
else:
print("Couldn't setup ")
def initialize(self):
''' Initializer for setting up the class reference to our other functions '''
self.DI = core.DhartInterface()
def _on_stage_event(self, event):
''' subscription to an event on the stage '''
# When a selection is changed, call our function
if event.type == int(omni.usd.StageEventType.SELECTION_CHANGED):
self._on_selection_changed()
def _on_selection_changed(self):
''' where we do stuff on the event that notified us a stage selection changed '''
# Gets the selected prim paths
selection = self._selection.get_selected_prim_paths()
stage = self._usd_context.get_stage()
print(f'== selection changed with {len(selection)} items')
prim_selections = [] # Empty list to be filled of selection prims
# Check if there is a valid selection and stage
if selection and stage:
# Make a list of the selection prims
for selected_path in selection:
print(f' item {selected_path}:')
prim = stage.GetPrimAtPath(selected_path)
prim_type = prim.GetTypeName()
print(prim_type)
if prim_type == 'Mesh':
prim_selections.append(prim)
# Call our meshinfo conversion if we have data in selection
if prim_selections:
self.DI.set_active_mesh(prim_selections)
def on_shutdown(self):
print("[omni.dhart] MyExtension shutdown")
# Save current scene layout
workspace_filename = omni.dhart.package_dir()
workspace_filename = os.path.join(workspace_filename, 'layout.json')
QuickLayout.save_file(workspace_filename)
try:
self._window = None
self._stage_event_sub = None
# Set the dhart interface instance to None
self.DI = None
except: pass
self._menu = None
# Run some extra cleanup for the window
self._clean_up_window()
# set this class to none as the last thing we do so it can be newly instantiated later
DhartExtension._instance = None
# print('Cleaned up')
def _clean_up_window(self):
''' make sure we cleanup the window '''
if self._window is not None:
self._window.destroy()
self._window = None | 6,041 | Python | 38.233766 | 119 | 0.577057 |
cadop/ov_dhart/exts/siborg.analysis.dhart/siborg/analysis/dhart/ui.py |
### Place object to set starting point
### Click to select start point
### Grid spacing, meshes to use, etc. | 117 | Python | 9.727272 | 38 | 0.65812 |
cadop/ov_dhart/exts/siborg.analysis.dhart/siborg/analysis/dhart/window.py | import omni.ui as ui
def populate_window(DI, render):
_window = ui.Window("DHART", width=600, height=600)
with _window.frame:
with ui.VStack():
with ui.HStack(height=5):
ui.Button("Set Start Position", clicked_fn=lambda: DI.set_as_start(), height=5)
# start_pos = ui.MultiIntField(0,0,0)
with ui.HStack():
x = ui.IntField(height=5)
x.model.add_value_changed_fn(lambda m : DI.modify_start(x=m.get_value_as_int()))
y = ui.IntField(height=5)
y.model.add_value_changed_fn(lambda m : DI.modify_start(y=m.get_value_as_int()))
z = ui.IntField(height=5)
z.model.add_value_changed_fn(lambda m : DI.modify_start(z=m.get_value_as_int()))
DI.gui_start = [x,y,z]
with ui.HStack(height=5):
ui.Button("Set End Position", clicked_fn=lambda: DI.set_as_end(),height=5)
# end_pos = ui.MultiIntField(0,0,0)
with ui.HStack():
x = ui.IntField(height=5)
x.model.add_value_changed_fn(lambda m : DI.modify_end(x=m.get_value_as_int()))
y = ui.IntField(height=5)
y.model.add_value_changed_fn(lambda m : DI.modify_end(y=m.get_value_as_int()))
z = ui.IntField(height=5)
z.model.add_value_changed_fn(lambda m : DI.modify_end(z=m.get_value_as_int()))
DI.gui_end = [x,y,z]
with ui.HStack(height=5):
ui.Label(" Max Nodes: ")
max_nodes = ui.IntField(height=5)
max_nodes.model.add_value_changed_fn(lambda m : DI.set_max_nodes(m.get_value_as_int()))
max_nodes.model.set_value(DI.max_nodes)
with ui.VStack(height=5):
with ui.HStack(height=5):
ui.Label(" Grid Spacing: ")
grid_spacing = ui.FloatField(height=5)
grid_spacing.model.add_value_changed_fn(lambda m : DI.set_spacing(m.get_value_as_float()))
grid_spacing.model.set_value(DI.grid_spacing[0])
ui.Label(" Height Spacing: ")
height_space = ui.FloatField(height=5)
height_space.model.add_value_changed_fn(lambda m : DI.set_height(m.get_value_as_float()))
height_space.model.set_value(DI.height)
with ui.HStack(height=5):
ui.Label(" Upstep: ")
upstep = ui.FloatField(height=5)
upstep.model.add_value_changed_fn(lambda m : DI.set_upstep(m.get_value_as_float()))
upstep.model.set_value(DI.upstep)
ui.Label(" Upslope: ")
upslope = ui.FloatField(height=5)
upslope.model.add_value_changed_fn(lambda m : DI.set_upslope(m.get_value_as_float()))
upslope.model.set_value(DI.upslope)
with ui.HStack(height=5):
ui.Label(" Downstep: ")
downstep = ui.FloatField(height=5)
downstep.model.add_value_changed_fn(lambda m : DI.set_downstep(m.get_value_as_float()))
downstep.model.set_value(DI.downstep)
ui.Label(" Downslope: ")
downslope = ui.FloatField(height=5)
downslope.model.add_value_changed_fn(lambda m : DI.set_downslope(m.get_value_as_float()))
downslope.model.set_value(DI.downslope)
with ui.HStack(height=5):
ui.Label(" Node Size: ")
node_size = ui.FloatField(height=5)
node_size.model.add_value_changed_fn(lambda m : DI.set_nodesize(m.get_value_as_float()))
node_size.model.set_value(DI.node_size)
ui.Label(" Path Size: ")
path_size = ui.FloatField(height=5)
path_size.model.add_value_changed_fn(lambda m : DI.set_pathsize(m.get_value_as_float()))
path_size.model.set_value(DI.path_size)
with ui.HStack(height=5):
ui.Button("Set Mesh for BVH", clicked_fn=lambda: DI.set_as_bvh(), height=50)
ui.Button("Set Mesh for Visibility BVH", clicked_fn=lambda: DI.set_as_vis_bvh(), height=50)
ui.Button("Generate Graph", clicked_fn=lambda: DI.generate_graph(), height=50)
with ui.HStack(height=5):
ui.Button("Visibility Graph", clicked_fn=lambda: DI.visibility_graph(), height=50)
ui.Button("Visibility Graph to Points", clicked_fn=lambda: DI.visibility_graph_groups(), height=50)
with ui.HStack(height=5):
ui.Button("Find Path", clicked_fn=lambda: DI.get_path(), height=50)
ui.Button("Find Energy Path", clicked_fn=lambda: DI.get_energy_path(), height=50)
ui.Button("Find Visibility Path", clicked_fn=lambda: DI.get_visibility_path(), height=50)
ui.Button("Find VG Path", clicked_fn=lambda: DI.get_vg_path(), height=50)
ui.Button("Set Camera on Path", clicked_fn=lambda: render.assign_camera(), height=30)
return _window | 5,499 | Python | 50.401869 | 115 | 0.519549 |
cadop/ov_dhart/exts/siborg.analysis.dhart/config/extension.toml | [package]
# Semantic Versionning is used: https://semver.org/
version = "0.0.4"
preview_image = "preview.jpg"
# The title and description fields are primarily for displaying extension info in UI
title = "DHART for Omniverse"
description="An omniverse extension for DHART using the python API."
# Path (relative to the root) or content of readme markdown file for UI.
readme = "docs/README.md"
icon = "icon.jpg"
# URL of the extension source repository.
repository = "github.com/cadop/ov_dhart"
# One of categories for UI.
category = "Analysis"
# Keywords for the extension
keywords = ["kit", "design","robotics"]
# Use omni.ui to build simple UI
[dependencies]
"omni.kit.uiapp" = {}
"omni.physx" = {}
# Main python module this extension provides, it will be publicly available as "import SiBoRG.analysis.dhart".
[[python.module]]
name = "siborg.analysis.dhart"
[python.pipapi]
use_online_index = true
# Use this to specify a list of additional repositories if your pip package is hosted somewhere other
# than the default repo(s) configured in pip. Will pass these to pip with "--extra-index-url" argument
# repositories = ["https://test.pypi.org/simple/"]
requirements = ["dhart"] | 1,196 | TOML | 26.837209 | 110 | 0.735786 |
cadop/curvedistribute/README.md | # curvedistribute
| 20 | Markdown | 5.999998 | 17 | 0.75 |
cadop/curvedistribute/tools/scripts/link_app.py | import argparse
import json
import os
import sys
import packmanapi
import urllib3
def find_omniverse_apps():
http = urllib3.PoolManager()
try:
r = http.request("GET", "http://127.0.0.1:33480/components")
except Exception as e:
print(f"Failed retrieving apps from an Omniverse Launcher, maybe it is not installed?\nError: {e}")
sys.exit(1)
apps = {}
for x in json.loads(r.data.decode("utf-8")):
latest = x.get("installedVersions", {}).get("latest", "")
if latest:
for s in x.get("settings", []):
if s.get("version", "") == latest:
root = s.get("launch", {}).get("root", "")
apps[x["slug"]] = (x["name"], root)
break
return apps
def create_link(src, dst):
print(f"Creating a link '{src}' -> '{dst}'")
packmanapi.link(src, dst)
APP_PRIORITIES = ["code", "create", "view"]
if __name__ == "__main__":
parser = argparse.ArgumentParser(description="Create folder link to Kit App installed from Omniverse Launcher")
parser.add_argument(
"--path",
help="Path to Kit App installed from Omniverse Launcher, e.g.: 'C:/Users/bob/AppData/Local/ov/pkg/create-2021.3.4'",
required=False,
)
parser.add_argument(
"--app", help="Name of Kit App installed from Omniverse Launcher, e.g.: 'code', 'create'", required=False
)
args = parser.parse_args()
path = args.path
if not path:
print("Path is not specified, looking for Omniverse Apps...")
apps = find_omniverse_apps()
if len(apps) == 0:
print(
"Can't find any Omniverse Apps. Use Omniverse Launcher to install one. 'Code' is the recommended app for developers."
)
sys.exit(0)
print("\nFound following Omniverse Apps:")
for i, slug in enumerate(apps):
name, root = apps[slug]
print(f"{i}: {name} ({slug}) at: '{root}'")
if args.app:
selected_app = args.app.lower()
if selected_app not in apps:
choices = ", ".join(apps.keys())
print(f"Passed app: '{selected_app}' is not found. Specify one of the following found Apps: {choices}")
sys.exit(0)
else:
selected_app = next((x for x in APP_PRIORITIES if x in apps), None)
if not selected_app:
selected_app = next(iter(apps))
print(f"\nSelected app: {selected_app}")
_, path = apps[selected_app]
if not os.path.exists(path):
print(f"Provided path doesn't exist: {path}")
else:
SCRIPT_ROOT = os.path.dirname(os.path.realpath(__file__))
create_link(f"{SCRIPT_ROOT}/../../app", path)
print("Success!")
| 2,814 | Python | 32.117647 | 133 | 0.562189 |
cadop/curvedistribute/tools/packman/config.packman.xml | <config remotes="cloudfront">
<remote2 name="cloudfront">
<transport actions="download" protocol="https" packageLocation="d4i3qtqj3r0z5.cloudfront.net/${name}@${version}" />
</remote2>
</config>
| 211 | XML | 34.333328 | 123 | 0.691943 |
cadop/curvedistribute/tools/packman/bootstrap/install_package.py | # Copyright 2019 NVIDIA CORPORATION
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
# http://www.apache.org/licenses/LICENSE-2.0
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import logging
import shutil
import sys
import tempfile
import zipfile
__author__ = "hfannar"
logging.basicConfig(level=logging.WARNING, format="%(message)s")
logger = logging.getLogger("install_package")
class TemporaryDirectory:
def __init__(self):
self.path = None
def __enter__(self):
self.path = tempfile.mkdtemp()
return self.path
def __exit__(self, type, value, traceback):
# Remove temporary data created
shutil.rmtree(self.path)
def install_package(package_src_path, package_dst_path):
with zipfile.ZipFile(package_src_path, allowZip64=True) as zip_file, TemporaryDirectory() as temp_dir:
zip_file.extractall(temp_dir)
# Recursively copy (temp_dir will be automatically cleaned up on exit)
try:
# Recursive copy is needed because both package name and version folder could be missing in
# target directory:
shutil.copytree(temp_dir, package_dst_path)
except OSError as exc:
logger.warning("Directory %s already present, packaged installation aborted" % package_dst_path)
else:
logger.info("Package successfully installed to %s" % package_dst_path)
install_package(sys.argv[1], sys.argv[2])
| 1,844 | Python | 33.166666 | 108 | 0.703362 |
cadop/curvedistribute/exts/siborg.create.curvedistribute/siborg/create/curvedistribute/extension.py | import omni.ext
import omni.ui as ui
from omni.ui import color as cl
from pxr import Usd, UsdGeom, Gf, Sdf
import numpy as np
from scipy.interpolate import BSpline
import omni.usd
from . import utils
from .core import CurveManager, GeomCreator
AXIS = ["+X", "+Y", "+Z", "-X", "-Y", "-Z"] # taken from motion path
CURVES = ["Bezier", "BSpline"]
# Any class derived from `omni.ext.IExt` in top level module (defined in `python.modules` of `extension.toml`) will be
# instantiated when extension gets enabled and `on_startup(ext_id)` will be called. Later when extension gets disabled
# on_shutdown() is called.
class SiborgCreateCurvedistributeExtension(omni.ext.IExt):
def __init__(self, delegate=None, **kwargs):
super().__init__(**kwargs)
# ext_id is current extension id. It can be used with extension manager to query additional information, like where
# this extension is located on filesystem.
def on_startup(self, ext_id):
print("[siborg.create.curvedistribute] siborg create curvedistribute startup")
#Models
self._source_prim_model = ui.SimpleStringModel()
self._source_curve_model = ui.SimpleStringModel()
self._use_instance_model = ui.SimpleBoolModel()
#Defaults
self._count = 0
self._source_prim_model.as_string = ""
self._source_curve_model.as_string = ""
self._sampling_resolution = 0
self._use_instance_model = False
self._use_orient_model = False
self._forward_axis = [1,0,0]
self._curve_type = utils.CURVE.Bezier
#Grab Prim in Stage on Selection
def _get_prim():
self._source_prim_model.as_string = ", ".join(utils.get_selection())
def _get_curve():
self._source_curve_model.as_string = ", ".join(utils.get_selection())
self._window = ui.Window("Distribute Along Curve", width=280, height=390)
with self._window.frame:
with ui.VStack(height=10, width=260, spacing=10):
select_button_style ={"Button":{"background_color": cl.cyan,
"border_color": cl.white,
"border_width": 2.0,
"padding": 4,
"margin_height": 1,
"border_radius": 10,
"margin_width":2},
"Button.Label":{"color": cl.black},
"Button:hovered":{"background_color": cl("#E5F1FB")}}
ui.Spacer()
ui.Label("Select Curve From Stage", tooltip="Select a BasisCurves type")
with ui.HStack():
ui.StringField(height=2, model=self._source_curve_model)
ui.Button("S", width=20, height=20, style=select_button_style, clicked_fn=_get_curve)
ui.Spacer()
ui.Label("Get Prims From Stage", width=65, tooltip="Select multiple prims to distribute in sequence")
with ui.HStack():
ui.StringField(height=2, model=self._source_prim_model)
ui.Button("S", width=20, height=20, style=select_button_style, clicked_fn=_get_prim)
ui.Spacer()
with ui.HStack():
ui.Label("Copies", tooltip="Number of copies to distribute. Endpoints are included in the count.")
x = ui.IntField(height=5)
x.model.add_value_changed_fn(lambda m, self=self: setattr(self, '_count', m.get_value_as_int()))
x.model.set_value(3)
ui.Label(" Subsamples", tooltip="A sampling parameter, don't touch if you don't understand")
x = ui.IntField(height=5)
x.model.add_value_changed_fn(lambda m, self=self: setattr(self, '_sampling_resolution', m.get_value_as_int()))
x.model.set_value(1000)
with ui.HStack():
# ui.StringField(height=2, model=self._source_prim_model)
# ui.Button("S", width=20, height=20, style=select_button_style, clicked_fn=_get_prim)
ui.Label(" Use instances ", width=65, tooltip="Select to use instances when copying a prim")
instancer = ui.CheckBox(width=30)
instancer.model.add_value_changed_fn(lambda m : setattr(self, '_use_instance_model', m.get_value_as_bool()))
instancer.model.set_value(False)
ui.Label(" Follow Orientation ", width=65)
instancer = ui.CheckBox(width=30)
instancer.model.add_value_changed_fn(lambda m : setattr(self, '_use_orient_model', m.get_value_as_bool()))
instancer.model.set_value(False)
with ui.HStack():
ui.Label("Spline Type",
name="label",
width=160,
tooltip="Type of curve to use for interpolating control points")
ui.Spacer(width=13)
widget = ui.ComboBox(0, *CURVES).model
widget.add_item_changed_fn(lambda m, i: setattr(self, '_curve_type',
m.get_item_value_model().get_value_as_int()
)
)
with ui.HStack():
ui.Label("Forward Axis",
name="label",
width=160,
tooltip="Forward axis of target Object")
ui.Spacer(width=13)
widget = ui.ComboBox(0, *AXIS).model
widget.add_item_changed_fn(lambda m, i: setattr(self, '_forward_axis',
utils.index_to_axis(m.get_item_value_model().get_value_as_int())
)
)
with ui.VStack():
distribute_button_style = {"Button":{"background_color": cl.cyan,
"border_color": cl.white,
"border_width": 2.0,
"padding": 10,
"margin_height": 10,
"border_radius": 10,
"margin_width":5},
"Button.Label":{"color": cl.black},
"Button:hovered":{"background_color": cl("#E5F1FB")}}
ui.Button("Distribute", clicked_fn=lambda: GeomCreator.duplicate(self._count,
self._sampling_resolution,
self._source_curve_model,
self._source_prim_model,
self._use_instance_model,
self._use_orient_model,
self._forward_axis,
self._curve_type),
style=distribute_button_style)
def on_shutdown(self):
print("[siborg.create.curvedistribute] siborg create curvedistribute shutdown")
| 8,448 | Python | 54.585526 | 136 | 0.4375 |
cadop/curvedistribute/exts/siborg.create.curvedistribute/siborg/create/curvedistribute/__init__.py | from .extension import *
| 25 | Python | 11.999994 | 24 | 0.76 |
cadop/curvedistribute/exts/siborg.create.curvedistribute/siborg/create/curvedistribute/core.py | from pxr import Usd, UsdGeom, Gf, Sdf, Vt
import numpy as np
from scipy.interpolate import BSpline, CubicSpline
import omni.usd
from scipy.interpolate import splprep, splev
from . import utils
class CurveManager():
def __init__(self):
pass
@classmethod
def cubic_bezier(cls, p0, p1, p2, p3, t):
'''Calculate position on a cubic Bezier curve given four control points.'''
return ((1 - t)**3) * p0 + 3 * ((1 - t)**2) * t * p1 + 3 * (1 - t) * t**2 * p2 + t**3 * p3
@classmethod
def create_bezier(cls, control_points, sampling_resolution):
'''Create a continuous cubic Bezier curve from a list of control points.'''
curve_points = []
t = np.linspace(0, 1, sampling_resolution) # defaulted to 100
for i in range(0, len(control_points) - 3, 3): # Step strides 3, bezier continous shared handles with neighbors
p0, p1, p2, p3 = control_points[i], control_points[i + 1], control_points[i + 2], control_points[i + 3]
bezier_segment = np.array([CurveManager.cubic_bezier(p0, p1, p2, p3, t_) for t_ in t])
curve_points.extend(bezier_segment)
return curve_points
@classmethod
def create_bspline(cls, control_points, sampling_resolution):
'''Create a continuous cubic Bezier curve from a list of control points.'''
# Create a BSpline object
k = 3 # degree of the spline
t = np.linspace(0, 1, len(control_points) - k + 1, endpoint=True)
t = np.append(np.zeros(k), t)
t = np.append(t, np.ones(k))
spl = BSpline(t, control_points, k)
#### If not using evenly distributed points, can just return this
# tnew = np.linspace(0, 1, num_points)
# interpolated_points = spl(tnew)
# return interpolated_points
# Calculate the total arc length of the spline
fine_t = np.linspace(0, 1, sampling_resolution)
curve_points = spl(fine_t)
return curve_points
@classmethod
def interpcurve(cls, stage, curve_path, num_points, sampling_resolution, curve_type=utils.CURVE.Bspline):
'''Interpolates a bezier curve based on the input points on the usd'''
# Get the curve prim and points that define it
curveprim = stage.GetPrimAtPath(curve_path)
points = curveprim.GetAttribute('points').Get()
control_points = np.array(points)
if sampling_resolution == 0: sampling_resolution = num_points
if curve_type == utils.CURVE.Bezier:
fine_points = CurveManager.create_bezier(control_points, sampling_resolution)
elif curve_type == utils.CURVE.Bspline:
fine_points = CurveManager.create_bspline(control_points, sampling_resolution)
else:
print("CURVE TYPE NOT IMPLEMENTED")
return
distances = np.sqrt(np.sum(np.diff(fine_points, axis=0)**2, axis=1))
total_length = np.sum(distances)
# Calculate the length of each segment
segment_length = total_length / (num_points - 1)
# Create an array of target lengths
target_lengths = np.array([i * segment_length for i in range(num_points)])
# Find the points at the target lengths
spaced_points = [control_points[0]] # Start with the first control point
point_dirs = [fine_points[1]- fine_points[0]] # Store the direction for each point
current_length = 0
j = 1 # Start from the second target length
for i in range(1, len(fine_points)):
segment_length = distances[i-1]
# Create strides to find when the next point should be accepted
while j < num_points - 1 and current_length + segment_length >= target_lengths[j]:
# Assign points
point = fine_points[i]
spaced_points.append(point)
# Get directions
direction = fine_points[i + 1] - point
# Normalize the direction vector
direction /= np.linalg.norm(direction)
point_dirs.append(direction)
j += 1
current_length += segment_length
# End with the last control point
spaced_points.append(control_points[-1])
last_dir = control_points[-1] - control_points[-2]
last_dir /= np.linalg.norm(last_dir)
point_dirs.append(last_dir)
return np.array(spaced_points), np.array(point_dirs)
@classmethod
def copy_to_points(cls, stage, target_points, target_dirs, ref_prims, path_to, _forward_axis, make_instance=False,
rand_order=False, use_orient=False, follow_curve=False):
'''
path_to: str, prefix to the prim path. automatically appends Copy
TODO: rand_order =True, use randomness to determine which prim to place
TODO: follow_curve=True, set rotation axis to match curve (different than orientation when curve is 3d)
'''
# Define a path for the new scope prim
scope_name = 'Copies'
scope_path = f"/World/{scope_name}"
# Create the scope prim at the specified path
scope_prim = UsdGeom.Scope.Define(stage, scope_path)
# Get index of prims that are not None and keep track
prim_set = [p for p in ref_prims if p != None]
# print(prim_set)
# print(f'isntance? : {make_instance}')
new_prims = []
if make_instance:
# Mark the original prims as instanceable if it has no children (like for a mesh)
for prim_path in prim_set:
# print(f'{prim_path=}')
original_prim = stage.GetPrimAtPath(prim_path)
# print(f'{original_prim=}')
# If this prim is not wrapped in an xform
if not original_prim.GetChildren():
ref_prim = original_prim
ref_prim_suffix = str(ref_prim.GetPath()).split('/')[-1]
# Create a new xform inside the scope
primpath_to = f"{scope_prim.GetPath()}/{ref_prim_suffix}_Source"
new_prim_xform_wrapper = stage.DefinePrim(primpath_to, "Xform")
# Make this new xform instanceable
new_prim_xform_wrapper.SetInstanceable(True)
# print(f'xform wrap path {new_prim_xform_wrapper}')
new_ref_prim = f"{new_prim_xform_wrapper.GetPath()}/{ref_prim_suffix}"
# Duplicate the prim and put it under a new xform
omni.usd.duplicate_prim(stage, ref_prim.GetPath(), new_ref_prim)
xform = UsdGeom.Xformable(new_prim_xform_wrapper)
# Get the list of xformOps
xform_ops = xform.GetOrderedXformOps()
# Check if translate op exists
has_translate_op = any(op.GetOpType() == UsdGeom.XformOp.TypeTranslate for op in xform_ops)
if not has_translate_op:
xform.AddTranslateOp()
has_Orient_op = any(op.GetOpType() == UsdGeom.XformOp.TypeOrient for op in xform_ops)
if not has_Orient_op:
xform.AddOrientOp()
ref_prim= str(new_prim_xform_wrapper.GetPath())
original_prim = stage.GetPrimAtPath(ref_prim)
# print("finished the xform wrapper")
original_prim.SetInstanceable(True)
new_prims.append(original_prim)
prim_set = new_prims
num_prims = len(prim_set)
cur_idx = 0
# Place the prims
for i, target_point in enumerate(target_points):
ref_prim = prim_set[cur_idx]
if make_instance:
prim_type = ref_prim.GetTypeName()
ref_prim_suffix = str(ref_prim.GetPath()).split('/')[-1]
primpath_to = f"{scope_prim.GetPath()}/{ref_prim_suffix}_{i}"
# Create a new prim and add a reference to the original prim
instance_prim = stage.DefinePrim(primpath_to, prim_type)
references = instance_prim.GetReferences()
references.AddInternalReference(ref_prim.GetPath())
# Move prim to desired location
cur_prim = instance_prim
else:
# Directly duplicate the prim
ref_prim_suffix = str(ref_prim).split('/')[-1]
primpath_to = f"{scope_prim.GetPath()}/{ref_prim_suffix}_{i}"
omni.usd.duplicate_prim(stage, ref_prim, primpath_to)
new_prim = stage.GetPrimAtPath(primpath_to)
cur_prim = new_prim
# Move prim to desired location
target_pos = Gf.Vec3d(tuple(target_point))
cur_prim.GetAttribute('xformOp:translate').Set(target_pos)
if use_orient:
# Make the forward vector face desired direction
target_direction = tuple(target_dirs[i])
# Ensure the target direction is a normalized Gf.Vec3f
target_direction = Gf.Vec3f(target_direction).GetNormalized()
target_direction = np.asarray(target_direction)
# Forward vector, assuming -Z is forward; change as per your convention
forward_vector = np.array(_forward_axis)
# Compute the cross product (rotation axis)
rotation_axis = np.cross(forward_vector, target_direction)
# Compute the dot product and then the angle
dot_product = np.dot(forward_vector, target_direction)
rotation_angle = np.arccos(np.clip(dot_product, -1.0, 1.0)) # Clipping for numerical stability
rot_ax = Vt.Vec3fArray.FromNumpy(rotation_axis)[0]
# Create a rotation quaternion
rotation_quat = Gf.Quatf(rotation_angle, rot_ax).GetNormalized()
# @TODO fix stupid hack
# Apply the rotation
try: cur_prim.GetAttribute('xformOp:orient').Set(Gf.Quatd(rotation_quat))
except: cur_prim.GetAttribute('xformOp:orient').Set(Gf.Quatf(rotation_quat))
if cur_idx < num_prims-1: cur_idx +=1
else: cur_idx = 0
class GeomCreator():
def __init__(self):
pass
@classmethod
def duplicate(cls, _count, _sampling_resolution, _source_curve_model, _source_prim_model,
_use_instance, _use_orient, _forward_axis, _curve_type):
'''
## All of these should work (assuming the named prim is there)
# ref_prims = ['/World/Cube']
# ref_prims = ['/World/Cube', None]
# ref_prims = ['/World/Cube', '/World/Cone']
'''
stage = omni.usd.get_context().get_stage()
curve_path = _source_curve_model.as_string
ref_prims = [_source_prim_model.as_string]
ref_prims = _source_prim_model.as_string.replace(' ','').split(',')
# _use_instance = _use_instance.as_bool
path_to = f'/Copy'
sampling_resolution = _sampling_resolution
num_points = _count
# Default to 3x the number of points to distribute? Actually might be handled already by interp
num_samples = _count
# TODO: make this setting for the resolution to sample the curve defined by user
interpolated_points, target_dirs = CurveManager.interpcurve(stage, curve_path, num_samples, sampling_resolution, _curve_type)
indices = np.linspace(0, len(interpolated_points) - 1, num_points, dtype=int)
target_points = interpolated_points[indices]
CurveManager.copy_to_points(stage, target_points, target_dirs, ref_prims, path_to, _forward_axis,
make_instance=_use_instance, use_orient=_use_orient)
| 12,324 | Python | 43.334532 | 133 | 0.566375 |
cadop/curvedistribute/exts/siborg.create.curvedistribute/siborg/create/curvedistribute/utils.py | import omni.usd
from typing import List
from pxr import Sdf
from enum import IntEnum
class CURVE(IntEnum):
Bezier = 0
Bspline = 1
Linear = 2
def get_selection() -> List[str]:
"""Get the list of currently selected prims"""
return omni.usd.get_context().get_selection().get_selected_prim_paths()
def index_to_axis(idx):
# AXIS = ["+X", "+Y", "+Z", "-X", "-Y", "-Z"] # taken from motion path
xp = [1,0,0]
yp = [0,1,0]
zp = [0,0,1]
xn = [-1,0,0]
yn = [0,-1,0]
zn = [0,0,-1]
axis_vecs = [xp,yp,zp,xn,yn,zn]
return axis_vecs[idx] | 598 | Python | 21.185184 | 75 | 0.556856 |
cadop/curvedistribute/exts/siborg.create.curvedistribute/siborg/create/curvedistribute/tests/__init__.py | from .test_hello_world import * | 31 | Python | 30.999969 | 31 | 0.774194 |
cadop/curvedistribute/exts/siborg.create.curvedistribute/siborg/create/curvedistribute/tests/test_hello_world.py | # NOTE:
# omni.kit.test - std python's unittest module with additional wrapping to add suport for async/await tests
# For most things refer to unittest docs: https://docs.python.org/3/library/unittest.html
import omni.kit.test
# Extnsion for writing UI tests (simulate UI interaction)
import omni.kit.ui_test as ui_test
# Import extension python module we are testing with absolute import path, as if we are external user (other extension)
import siborg.create.curvedistribute
# Having a test class dervived from omni.kit.test.AsyncTestCase declared on the root of module will make it auto-discoverable by omni.kit.test
class Test(omni.kit.test.AsyncTestCase):
# Before running each test
async def setUp(self):
pass
# After running each test
async def tearDown(self):
pass
# Actual test, notice it is "async" function, so "await" can be used if needed
async def test_hello_public_function(self):
result = siborg.create.curvedistribute.some_public_function(4)
self.assertEqual(result, 256)
async def test_window_button(self):
# Find a label in our window
label = ui_test.find("My Window//Frame/**/Label[*]")
# Find buttons in our window
add_button = ui_test.find("My Window//Frame/**/Button[*].text=='Add'")
reset_button = ui_test.find("My Window//Frame/**/Button[*].text=='Reset'")
# Click reset button
await reset_button.click()
self.assertEqual(label.widget.text, "empty")
await add_button.click()
self.assertEqual(label.widget.text, "count: 1")
await add_button.click()
self.assertEqual(label.widget.text, "count: 2")
| 1,694 | Python | 35.063829 | 142 | 0.68595 |
cadop/curvedistribute/exts/siborg.create.curvedistribute/config/extension.toml | [package]
# Semantic Versioning is used: https://semver.org/
version = "1.0.0"
# Lists people or organizations that are considered the "authors" of the package.
authors = ["SiBORG"]
# The title and description fields are primarily for displaying extension info in UI
title = "siborg create curvedistribute"
description="A tool to make copies of a prim along a curve (distribute/array)"
# Path (relative to the root) or content of readme markdown file for UI.
readme = "docs/README.md"
# URL of the extension source repository.
repository = ""
# One of categories for UI.
category = "Tools"
# Keywords for the extension
keywords = ["curve", "distribute", "array"]
# Location of change log file in target (final) folder of extension, relative to the root.
# More info on writing changelog: https://keepachangelog.com/en/1.0.0/
changelog="docs/CHANGELOG.md"
# Preview image and icon. Folder named "data" automatically goes in git lfs (see .gitattributes file).
# Preview image is shown in "Overview" of Extensions window. Screenshot of an extension might be a good preview image.
preview_image = "data/preview.png"
# Icon is shown in Extensions window, it is recommended to be square, of size 256x256.
icon = "data/icon.png"
# Use omni.ui to build simple UI
[dependencies]
"omni.kit.uiapp" = {}
"omni.pip.compute" = {}
# Main python module this extension provides, it will be publicly available as "import siborg.create.curvedistribute".
[[python.module]]
name = "siborg.create.curvedistribute"
[[test]]
# Extra dependencies only to be used during test run
dependencies = [
"omni.kit.ui_test" # UI testing extension
]
| 1,632 | TOML | 32.32653 | 118 | 0.744485 |
cadop/curvedistribute/exts/siborg.create.curvedistribute/docs/CHANGELOG.md | # Changelog
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/).
## [1.0.0] - 2021-04-26
- Initial version of extension UI template with a window
| 178 | Markdown | 18.888887 | 80 | 0.702247 |
cadop/curvedistribute/exts/siborg.create.curvedistribute/docs/README.md | # Python Extension Example [siborg.create.curvedistribute]
This is an example of pure python Kit extension. It is intended to be copied and serve as a template to create new extensions.
| 188 | Markdown | 36.799993 | 126 | 0.797872 |
cadop/curvedistribute/exts/siborg.create.curvedistribute/docs/index.rst | siborg.create.curvedistribute
#############################
Example of Python only extension
.. toctree::
:maxdepth: 1
README
CHANGELOG
.. automodule::"siborg.create.curvedistribute"
:platform: Windows-x86_64, Linux-x86_64
:members:
:undoc-members:
:show-inheritance:
:imported-members:
:exclude-members: contextmanager
| 359 | reStructuredText | 16.142856 | 46 | 0.640669 |
jshrake-nvidia/kit-image-sequence/README.md | # kit-image-sequence
Omniverse Kit extension to import and layout image sequences.

## Getting Started
1. Install and enable the `omni.kit.imageseq` extension, which can be found in the `Community` (or Third Party) tab of the Extension window.

2. Open the extension window under `Window/Image Sequence Importer` and then click the `Create New Image Sequence` button.
2. Specify a [glob string](https://en.wikipedia.org/wiki/Glob_(programming)) to a directory containing images (for example `C:/Users/You/Documents/Content/*.png`) in the `Asset Path` field and hit enter. You should see your images appear in the viewport, arranged left to right in filename alphabetical order. You can control the layout of the images by making changes to `PPI`, `Gap`, `Curve`, and `Images Per Row` input fields.

4. You can create as many image sequences as you like. Selecting any top-level `ImageSequence{N}` prim will allow you to modify the layout parameters.
5. The resulting USD file is completely standalone. Other users do not need to install this extension in order to view your imported image sequences.
6. You can create image sequences programmatically from Python using the `create_textured_quad_prim` function found in [./exts/omni.kit.imageseq/omni/kit/imageseq/core.py](./exts/omni.kit.imageseq/omni/kit/imageseq/core.py).
## PDF + PPT Support
This extension was built to support users wishing to import PDF or PPT-like documents into Omniverse.
In order to do so, you must first convert your PDF or PPT-like document into a sequence of images. This conversion is outside the scope of this extension, but here are some helpful resources to get you started:
- PDF: [pdftoppm](https://www.xpdfreader.com/download.html)
- PPT: You can export the slides as images or convert the PPT to a PDF and use the above workflow.
- [https://www.adobe.com/acrobat/hub/how-to/export-images-from-ppt#:~:text=Here's%20what%20to%20do%3A,to%20export%20the%20selected%20slide.](https://www.adobe.com/acrobat/hub/how-to/export-images-from-ppt#:~:text=Here's%20what%20to%20do%3A,to%20export%20the%20selected%20slide.)
## Development (Quick Start)
```bash
git clone https://github.com/jshrake/kit-image-sequence
cd kit-imageseq
./link_app.bat --app create
./app/omni.create.bat --ext-folder exts --enable omni.kit.imageseq
```
## Development (Detailed)
### Install Omniverse and some Apps
1. Install *Omniverse Launcher*: [download](https://www.nvidia.com/en-us/omniverse/download)
2. Install and launch one of *Omniverse* apps in the Launcher. For instance: *Code*.
### Add a new extension to your *Omniverse App*
1. Fork and clone this repo, for example in `C:\projects\kit-extension-template`
2. In the *Omniverse App* open extension manager: *Window* → *Extensions*.
3. In the *Extension Manager Window* open a settings page, with a small gear button in the top left bar.
4. In the settings page there is a list of *Extension Search Paths*. Add cloned repo `exts` subfolder there as another search path: `C:\projects\kit-extension-template\exts`

5. Now you can find `omni.hello.world` extension in the top left search bar. Select and enable it.
6. "My Window" window will pop up. *Extension Manager* watches for any file changes. You can try changing some code in this extension and see them applied immediately with a hotreload.
### Few tips
* Now that `exts` folder was added to the search you can add new extensions to this folder and they will be automatically found by the *App*.
* Look at the *Console* window for warnings and errors. It also has a small button to open current log file.
* All the same commands work on linux. Replace `.bat` with `.sh` and `\` with `/`.
* Extension name is a folder name in `exts` folder, in this example: `omni.hello.world`.
* Most important thing extension has is a config file: `extension.toml`, take a peek.
### Next Steps: Alternative way to add a new extension
To get a better understanding and learn a few other things, we recommend following next steps:
1. Remove search path added in the previous section.
1. Open this cloned repo using Visual Studio Code: `code C:\projects\kit-extension-template`. It will suggest installing a few extensions to improve python experience.
2. In the terminal (CTRL + \`) run `link_app.bat` (more in [Linking with an *Omniverse* app](#linking-with-an-omniverse-app) section).
3. Run this app with `exts` folder added as an extensions search path and new extension enabled:
```bash
> app\omni.code.bat --ext-folder exts --enable omni.hello.world
```
- `--ext-folder [path]` - adds new folder to the search path
- `--enable [extension]` - enables an extension on startup.
Use `-h` for help:
```bash
> app\omni.code.bat -h
```
4. After the *App* started you should see:
* new "My Window" window popup.
* extension search paths in *Extensions* window as in the previous section.
* extension enabled in the list of extensions.
5. If you look inside `omni.code.bat` or any other *Omniverse App*, they all run *Omniverse Kit* (`kit.exe`). *Omniverse Kit* is the Omniverse Application runtime that powers *Apps* build out of extensions.
Think of it as `python.exe`. It is a small runtime, that enables all the basics, like settings, python, logging and searches for extensions. **Everything else is an extension.** You can run only this new extension without running any big *App* like *Code*:
```bash
> app\kit\kit.exe --ext-folder exts --enable omni.hello.world
```
It starts much faster and will only have extensions enabled that are required for this new extension (look at `[dependencies]` section of `extension.toml`). You can enable more extensions: try adding `--enable omni.kit.window.extensions` to have extensions window enabled (yes, extension window is an extension too!):
```bash
> app\kit\kit.exe --ext-folder exts --enable omni.hello.world --enable omni.kit.window.extensions
```
You should see a menu in the top left. From here you can enable more extensions from the UI.
### Few tips
* In the *Extensions* window, press *Bread* button near the search bar and select *Show Extension Graph*. It will show how the current *App* comes to be: all extensions and dependencies.
* Extensions system documentation: http://omniverse-docs.s3-website-us-east-1.amazonaws.com/kit-sdk/104.0/docs/guide/extensions.html
### Running Tests
To run tests we run a new process where only the tested extension (and it's dependencies) is enabled. Like in example above + testing system (`omni.kit.test` extension). There are 2 ways to run extension tests:
1. Run: `app\kit\test_ext.bat omni.hello.world --ext-folder exts`
That will run a test process with all tests and exit. For development mode pass `--dev`: that will open test selection window. As everywhere, hotreload also works in this mode, give it a try by changing some code!
2. Alternatively, in *Extension Manager* (*Window → Extensions*) find your extension, click on *TESTS* tab, click *Run Test*
For more information about testing refer to: [testing doc](http://omniverse-docs.s3-website-us-east-1.amazonaws.com/kit-sdk/104.0/docs/guide/ext_testing.html).
### Linking with an *Omniverse* app
For a better developer experience, it is recommended to create a folder link named `app` to the *Omniverse Kit* app installed from *Omniverse Launcher*. A convenience script to use is included.
Run:
```bash
> link_app.bat
```
If successful you should see `app` folder link in the root of this repo.
If multiple Omniverse apps is installed script will select recommended one. Or you can explicitly pass an app:
```bash
> link_app.bat --app create
```
You can also just pass a path to create link to:
```bash
> link_app.bat --path "C:/Users/bob/AppData/Local/ov/pkg/create-2021.3.4"
```
### Adding a new extension
Adding a new extension is as simple as copying and renaming existing one:
1. copy `exts/omni.hello.world` to `exts/[new extension name]`
2. rename python module (namespace) in `exts/[new extension name]/omni/hello/world` to `exts/[new extension name]/[new python module]`
3. update `exts/[new extension name]/config/extension.toml`, most importantly specify new python module to load:
```toml
[[python.module]]
name = "[new python module]"
```
No restart is needed, you should be able to find and enable `[new extension name]` in extension manager.
### Sharing extensions
To make extension available to other users use [Github Releases](https://docs.github.com/en/repositories/releasing-projects-on-github/managing-releases-in-a-repository).
1. Make sure the repo has [omniverse-kit-extension](https://github.com/topics/omniverse-kit-extension) topic set for auto discovery.
2. For each new release increment extension version (in `extension.toml`) and update the changelog (in `docs/CHANGELOG.md`). [Semantic versionning](https://semver.org/) must be used to express severity of API changes.
### Contributing
The source code for this repository is provided as-is and we are not accepting outside contributions. | 9,172 | Markdown | 51.718391 | 429 | 0.752617 |
jshrake-nvidia/kit-image-sequence/tools/scripts/link_app.py | import os
import argparse
import sys
import json
import packmanapi
import urllib3
def find_omniverse_apps():
http = urllib3.PoolManager()
try:
r = http.request("GET", "http://127.0.0.1:33480/components")
except Exception as e:
print(f"Failed retrieving apps from an Omniverse Launcher, maybe it is not installed?\nError: {e}")
sys.exit(1)
apps = {}
for x in json.loads(r.data.decode("utf-8")):
latest = x.get("installedVersions", {}).get("latest", "")
if latest:
for s in x.get("settings", []):
if s.get("version", "") == latest:
root = s.get("launch", {}).get("root", "")
apps[x["slug"]] = (x["name"], root)
break
return apps
def create_link(src, dst):
print(f"Creating a link '{src}' -> '{dst}'")
packmanapi.link(src, dst)
APP_PRIORITIES = ["code", "create", "view"]
if __name__ == "__main__":
parser = argparse.ArgumentParser(description="Create folder link to Kit App installed from Omniverse Launcher")
parser.add_argument(
"--path",
help="Path to Kit App installed from Omniverse Launcher, e.g.: 'C:/Users/bob/AppData/Local/ov/pkg/create-2021.3.4'",
required=False,
)
parser.add_argument(
"--app", help="Name of Kit App installed from Omniverse Launcher, e.g.: 'code', 'create'", required=False
)
args = parser.parse_args()
path = args.path
if not path:
print("Path is not specified, looking for Omniverse Apps...")
apps = find_omniverse_apps()
if len(apps) == 0:
print(
"Can't find any Omniverse Apps. Use Omniverse Launcher to install one. 'Code' is the recommended app for developers."
)
sys.exit(0)
print("\nFound following Omniverse Apps:")
for i, slug in enumerate(apps):
name, root = apps[slug]
print(f"{i}: {name} ({slug}) at: '{root}'")
if args.app:
selected_app = args.app.lower()
if selected_app not in apps:
choices = ", ".join(apps.keys())
print(f"Passed app: '{selected_app}' is not found. Specify one of the following found Apps: {choices}")
sys.exit(0)
else:
selected_app = next((x for x in APP_PRIORITIES if x in apps), None)
if not selected_app:
selected_app = next(iter(apps))
print(f"\nSelected app: {selected_app}")
_, path = apps[selected_app]
if not os.path.exists(path):
print(f"Provided path doesn't exist: {path}")
else:
SCRIPT_ROOT = os.path.dirname(os.path.realpath(__file__))
create_link(f"{SCRIPT_ROOT}/../../app", path)
print("Success!")
| 2,813 | Python | 32.5 | 133 | 0.562389 |
jshrake-nvidia/kit-image-sequence/tools/packman/config.packman.xml | <config remotes="cloudfront">
<remote2 name="cloudfront">
<transport actions="download" protocol="https" packageLocation="d4i3qtqj3r0z5.cloudfront.net/${name}@${version}" />
</remote2>
</config>
| 211 | XML | 34.333328 | 123 | 0.691943 |
jshrake-nvidia/kit-image-sequence/tools/packman/bootstrap/install_package.py | # Copyright 2019 NVIDIA CORPORATION
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
# http://www.apache.org/licenses/LICENSE-2.0
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import logging
import zipfile
import tempfile
import sys
import shutil
__author__ = "hfannar"
logging.basicConfig(level=logging.WARNING, format="%(message)s")
logger = logging.getLogger("install_package")
class TemporaryDirectory:
def __init__(self):
self.path = None
def __enter__(self):
self.path = tempfile.mkdtemp()
return self.path
def __exit__(self, type, value, traceback):
# Remove temporary data created
shutil.rmtree(self.path)
def install_package(package_src_path, package_dst_path):
with zipfile.ZipFile(
package_src_path, allowZip64=True
) as zip_file, TemporaryDirectory() as temp_dir:
zip_file.extractall(temp_dir)
# Recursively copy (temp_dir will be automatically cleaned up on exit)
try:
# Recursive copy is needed because both package name and version folder could be missing in
# target directory:
shutil.copytree(temp_dir, package_dst_path)
except OSError as exc:
logger.warning(
"Directory %s already present, packaged installation aborted" % package_dst_path
)
else:
logger.info("Package successfully installed to %s" % package_dst_path)
install_package(sys.argv[1], sys.argv[2])
| 1,888 | Python | 31.568965 | 103 | 0.68697 |
jshrake-nvidia/kit-image-sequence/exts/omni.kit.imageseq/config/extension.toml | [package]
# Semantic Versionning is used: https://semver.org/
version = "0.0.1"
# The title and description fields are primarily for displaying extension info in UI
title = "Image Sequence Importer"
description = "Import and layout image sequences"
# Path (relative to the root) or content of readme markdown file for UI.
readme = "docs/README.md"
# URL of the extension source repository.
repository = "https://github.com/jshrake-nvidia/kit-image-sequence"
# One of categories for UI.
category = "Example"
# Keywords for the extension
keywords = ["kit", "example"]
# Icon to show in the extension manager
icon = "data/icon.png"
# Preview to show in the extension manager
preview_image = "data/preview.png"
# Use omni.ui to build simple UI
[dependencies]
"omni.kit.uiapp" = {}
"omni.kit.pipapi" = {}
[python.pipapi]
requirements = [
"pillow"
]
use_online_index = true
# Main python module this extension provides, it will be publicly available as "import omni.hello.world".
[[python.module]]
name = "omni.kit.imageseq"
[[test]]
# Extra dependencies only to be used during test run
dependencies = [
"omni.kit.ui_test" # UI testing extension
]
| 1,163 | TOML | 23.25 | 105 | 0.727429 |
jshrake-nvidia/kit-image-sequence/exts/omni.kit.imageseq/omni/kit/imageseq/config.py | import codecs
import pickle
from typing import List
from pxr import Sdf, Usd
class Config:
path_glob: str
expanded_glob: List[str]
ppi: int
gap_pct: float
curve_pct: float
images_per_row: int
def set_config_metadata(prim: Usd.Prim, config: Config) -> None:
if not prim.IsValid():
return
config_str = codecs.encode(pickle.dumps(config), 'base64')
attribute: Usd.Attribute= prim.GetAttribute("imageseq:config")
if not attribute.IsValid():
attribute = prim.CreateAttribute("imageseq:config", Sdf.ValueTypeNames.String)
attribute.Set(config_str)
def get_config_metadata(prim: Usd.Prim) -> Config:
if not prim.IsValid():
raise Exception("programming error")
attribute: Usd.Attribute = prim.GetAttribute("imageseq:config")
if not attribute.IsValid():
return None
config_str = attribute.Get()
config_bytes = codecs.decode(config_str.encode(), 'base64')
config = pickle.loads(config_bytes)
return config
| 1,006 | Python | 26.972221 | 86 | 0.685885 |
jshrake-nvidia/kit-image-sequence/exts/omni.kit.imageseq/omni/kit/imageseq/extension.py | import asyncio
from functools import partial
import omni.ext
import omni.kit.app
import omni.kit.ui
import omni.ui
import omni.usd
from .window import KitImageSequenceWindow
class KitImageSequenceExtension(omni.ext.IExt):
WINDOW_NAME = "Image Sequence Importer"
MENU_PATH = f"Window/{WINDOW_NAME}"
def on_startup(self):
# The ability to show up the window if the system requires it. We use it
# in QuickLayout.
self._window = None
omni.ui.Workspace.set_show_window_fn(KitImageSequenceExtension.WINDOW_NAME, partial(self.show_window, None))
# Put the new menu
editor_menu = omni.kit.ui.get_editor_menu()
if editor_menu:
self._menu = editor_menu.add_item(
KitImageSequenceExtension.MENU_PATH, self.show_window, toggle=True, value=True
)
# Show the window. It will call `self.show_window`
omni.ui.Workspace.show_window(KitImageSequenceExtension.WINDOW_NAME)
def on_shutdown(self):
if self._window:
self._window.destroy()
self._window = None
editor_menu = omni.kit.ui.get_editor_menu()
if editor_menu:
editor_menu.remove_item(KitImageSequenceExtension.MENU_PATH)
self._menu = None
# Deregister the function that shows the window from omni.ui
omni.ui.Workspace.set_show_window_fn(KitImageSequenceExtension.WINDOW_NAME, None)
def _set_menu(self, value):
"""Set the menu to create this window on and off"""
editor_menu = omni.kit.ui.get_editor_menu()
if editor_menu:
editor_menu.set_value(KitImageSequenceExtension.MENU_PATH, value)
async def _destroy_window_async(self):
# wait one frame, this is due to the one frame defer
# in Window::_moveToMainOSWindow()
await omni.kit.app.get_app().next_update_async()
if self._window:
self._window.destroy()
self._window = None
def _visibility_changed_fn(self, visible):
# Called when the user pressed "X"
self._set_menu(visible)
if not visible:
# Destroy the window, since we are creating new window
# in show_window
asyncio.ensure_future(self._destroy_window_async())
def show_window(self, menu, value):
if value:
self._window = KitImageSequenceWindow(KitImageSequenceExtension.WINDOW_NAME, width=300, height=365)
self._window.set_visibility_changed_fn(self._visibility_changed_fn)
elif self._window:
self._window.visible = False
| 2,611 | Python | 34.780821 | 116 | 0.644964 |
jshrake-nvidia/kit-image-sequence/exts/omni.kit.imageseq/omni/kit/imageseq/__init__.py | from .extension import *
| 25 | Python | 11.999994 | 24 | 0.76 |
jshrake-nvidia/kit-image-sequence/exts/omni.kit.imageseq/omni/kit/imageseq/core.py | import math
from pathlib import Path
from typing import Dict, List
import carb
from PIL import Image
from pxr import Gf, Kind, Sdf, Usd, UsdGeom, UsdShade
from .config import Config, set_config_metadata
def create_textured_quad_prim(
stage: Usd.Stage, prim_path: Sdf.Path, translate: Gf.Vec3d, scale: Gf.Vec3d, rotate: Gf.Vec3d, image_path: str
) -> Usd.Prim:
prim: UsdGeom.Xform = UsdGeom.Xform.Define(stage, prim_path)
Usd.ModelAPI(prim).SetKind(Kind.Tokens.subcomponent)
translate_op: UsdGeom.XformOp = prim.AddTranslateOp()
rotate_op: UsdGeom.XformOp = prim.AddRotateXYZOp()
scale_op: UsdGeom.XformOp = prim.AddScaleOp()
translate_op.Set(translate)
rotate_op.Set(rotate)
scale_op.Set(Gf.Vec3d(1, 1, 1))
mesh = create_quad_mesh(stage, scale, prim_path.AppendChild("ImageSequenceMesh"))
material = create_texture_material(stage, prim_path.AppendChild("ImageSequenceMaterial"), image_path)
UsdShade.MaterialBindingAPI(mesh).Bind(material)
return prim
def create_quad_mesh(stage: Usd.Stage, scale: Gf.Vec3d, prim_path: Sdf.Path) -> UsdGeom.Mesh:
# See https://graphics.pixar.com/usd/dev/tut_simple_shading.html#adding-a-mesh-billboard
mesh: UsdGeom.Mesh = UsdGeom.Mesh.Define(stage, prim_path)
translate_op: UsdGeom.XformOp = mesh.AddTranslateOp()
rotate_op: UsdGeom.XformOp = mesh.AddRotateXYZOp()
scale_op: UsdGeom.XformOp = mesh.AddScaleOp()
translate_op.Set(Gf.Vec3d(0, 0, 0))
rotate_op.Set(Gf.Vec3d(0, 0, 0))
scale_op.Set(scale)
mesh.CreatePointsAttr([(-0.5, -0.5, 0.0), (0.5, -0.5, 0.0), (0.5, 0.5, 0.0), (-0.5, 0.5, 0.0)])
mesh.CreateFaceVertexCountsAttr([4])
mesh.CreateFaceVertexIndicesAttr([0, 1, 2, 3])
mesh.CreateExtentAttr([(-0.5, 0.0, -0.5), (0.5, 0.0, 0.5)])
texCoords = mesh.CreatePrimvar("st", Sdf.ValueTypeNames.TexCoord2fArray, UsdGeom.Tokens.varying)
texCoords.Set([(0, 0), (1, 0), (1, 1), (0, 1)])
return mesh
def create_texture_material(stage: Usd.Stage, material_prim_path: Sdf.Path, image_path: str) -> UsdShade.Material:
# See https://graphics.pixar.com/usd/dev/tut_simple_shading.html#adding-a-mesh-billboard
shader_prim_path = material_prim_path.AppendChild("ImageSequenceShader")
material: UsdShade.Material = UsdShade.Material.Define(stage, material_prim_path)
shader: UsdShade.Shader = UsdShade.Shader.Define(stage, shader_prim_path)
shader.CreateImplementationSourceAttr(UsdShade.Tokens.sourceAsset)
shader.SetSourceAsset("OmniPBR.mdl", "mdl")
shader.SetSourceAssetSubIdentifier("OmniPBR", "mdl")
material.CreateSurfaceOutput("mdl").ConnectToSource(shader.ConnectableAPI(), "out")
shader_prim: Usd.Prim = stage.GetPrimAtPath(shader_prim_path)
shader_prim.CreateAttribute("inputs:diffuse_texture", Sdf.ValueTypeNames.Asset).Set(image_path)
shader_prim.CreateAttribute("inputs:emissive_color_texture", Sdf.ValueTypeNames.Asset).Set(image_path)
shader_prim.CreateAttribute("inputs:reflection_roughness_constant", Sdf.ValueTypeNames.Float).Set(1.0)
shader_prim.CreateAttribute("inputs:metallic_constant", Sdf.ValueTypeNames.Float).Set(0.0)
return material
class Transform:
translate: Gf.Vec2d = Gf.Vec3d(0, 0, 0)
scale: Gf.Vec2d = Gf.Vec3d(1, 1, 1)
rotate: Gf.Vec2d = Gf.Vec3d(0, 0, 0)
def calculate_transforms(config: Config) -> Dict[str, Transform]:
INCHES_TO_CM = 1.54
images: List[Image.Image] = [Image.open(image_path_str) for image_path_str in config.expanded_glob]
image_count = len(images)
if image_count == 0:
return {}
# Calculate the largest image width in cm
max_image_width_px = max([image.size[0] for image in images])
max_image_width_in = max_image_width_px / config.ppi
max_image_width_cm = max_image_width_in * INCHES_TO_CM
# Calculate the largest image height in cm
max_image_height_px = max([image.size[1] for image in images])
max_image_height_in = max_image_height_px / config.ppi
max_image_height_cm = max_image_height_in * INCHES_TO_CM
# Calculate the number of images per row
images_per_row = image_count if config.images_per_row < 1 else config.images_per_row
# Calculate the total number of rows
total_rows = math.ceil(image_count / images_per_row)
#print(f"Images per row: {images_per_row}, Total Rows: {total_rows}")
image_gap_cm = config.gap_pct * max_image_width_cm
# Calculate total extents
total_width_cm = max(max_image_width_cm * (images_per_row - 1) + image_gap_cm * max(images_per_row - 1, 0), 0)
total_height_cm = (total_rows - 1) * max_image_height_cm + image_gap_cm * max(total_rows - 1, 0)
#print(f"Total Width: {total_width_cm}, Total Height: {total_height_cm}")
# max_height_px = max([image.size[1] for image in images])
left_most_cm = -0.5 * total_width_cm
top_most_cm = 0.5 * total_height_cm
left_current_cm = left_most_cm
top_current_cm = top_most_cm
transforms: Dict[str, Transform] = {}
seen = 0
for count, image in enumerate(images):
if seen > images_per_row - 1:
left_current_cm = left_most_cm
top_current_cm -= max_image_height_cm + image_gap_cm
seen = 0
image_width_px = image.size[0]
image_height_px = image.size[1]
image_width_in = image_width_px / config.ppi
image_height_in = image_height_px / config.ppi
image_width_cm = image_width_in * INCHES_TO_CM
image_height_cm = image_height_in * INCHES_TO_CM
transform = Transform()
transform.scale = Gf.Vec3d(image_width_cm, image_height_cm, 1)
# Lerp between the line and the arc positioning
t = (left_current_cm - left_most_cm) / total_width_cm if total_width_cm > 0 else 0
turns = 0.5 * math.tau
phase = (1.0 - t) * turns + 0.25 * math.tau
amp = 0.5 * total_width_cm
x = left_current_cm * (1.0 - config.curve_pct) + (config.curve_pct) * amp * math.sin(phase)
z = 0 + config.curve_pct * amp * math.cos(phase)
transform.translate = Gf.Vec3d(x, top_current_cm, z)
angle = -config.curve_pct * math.degrees(-phase + 0.5 * math.tau)
# print(t, phase, angle)
transform.rotate = Gf.Vec3d(0, angle, 0)
transforms[image.filename] = transform
left_current_cm += max_image_width_cm + image_gap_cm
seen += 1
return transforms
def create_image_sequence_group_prim(stage: Usd.Stage, root_prim_path: Sdf.Path, config: Config) -> Usd.Prim:
# Create the root prim
prim: Usd.Prim = stage.GetPrimAtPath(root_prim_path)
if not prim.IsValid():
xform: UsdGeom.Xform = UsdGeom.Xform.Define(stage, root_prim_path)
Usd.ModelAPI(xform).SetKind(Kind.Tokens.component)
translate_op: UsdGeom.XformOp = xform.AddTranslateOp()
rotate_op: UsdGeom.XformOp = xform.AddRotateXYZOp()
scale_op: UsdGeom.XformOp = xform.AddScaleOp()
translate_op.Set(Gf.Vec3d(0, 0, 0))
rotate_op.Set(Gf.Vec3d(0, 0, 0))
scale_op.Set(Gf.Vec3d(1, 1, 1))
# Persist the config data in the top-level USD prim
prim: Usd.Prim = stage.GetPrimAtPath(root_prim_path)
set_config_metadata(prim, config)
# Create a child prim for each image
transforms = calculate_transforms(config)
for asset_path in config.expanded_glob:
image_path = Path(asset_path)
transform: Transform = transforms[asset_path]
# Create the prim
image_prim_path = root_prim_path.AppendChild(make_safe_prim_name(image_path.stem))
create_textured_quad_prim(
stage=stage,
prim_path=image_prim_path,
translate=transform.translate,
scale=transform.scale,
rotate=transform.rotate,
image_path=asset_path,
)
return prim
def update_image_sequence_prims(stage: Usd.Stage, root_prim_path: Sdf.Path, config: Config) -> None:
if stage is None:
carb.log_warn("Unexpected: stage is none")
return
top_prim: Usd.Prim = stage.GetPrimAtPath(root_prim_path)
if not top_prim.IsValid():
carb.log_warn("Unexpected: prim is invalid")
return
set_config_metadata(top_prim, config)
transforms = calculate_transforms(config)
# Create a child prim for each image
for image in config.expanded_glob:
image_path = Path(image)
transform: Transform = transforms[image]
image_prim_path: Sdf.Path = root_prim_path.AppendChild(make_safe_prim_name(image_path.stem))
mesh_prim_path: Sdf.Path = image_prim_path.AppendChild("ImageSequenceMesh")
image_prim: Usd.Prim = stage.GetPrimAtPath(image_prim_path)
mesh_prim: Usd.Prim = stage.GetPrimAtPath(mesh_prim_path)
if not image_prim.IsValid():
carb.log_warn(f"Unexpected: {image_prim_path} is invalid")
return
if not mesh_prim.IsValid():
carb.log_warn(f"Unexpected: {mesh_prim_path} is invalid")
return
image_prim.GetAttribute("xformOp:translate").Set(transform.translate)
mesh_prim.GetAttribute("xformOp:scale").Set(transform.scale)
image_prim.GetAttribute("xformOp:rotateXYZ").Set(transform.rotate)
return
def make_safe_prim_name(name: str, replace: str = "_") -> str:
for c in ["-", ".", "?"]:
name = name.replace(c, replace)
return name
| 9,377 | Python | 44.086538 | 114 | 0.666098 |
jshrake-nvidia/kit-image-sequence/exts/omni.kit.imageseq/omni/kit/imageseq/window.py | # Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
#
__all__ = ["KitImageSequenceWindow"]
import os
from glob import glob
import carb
import omni.ui
from pxr import Usd
from .config import *
from .core import *
class KitImageSequenceWindow(omni.ui.Window):
"""
Extension window
"""
def __init__(self, title: str, delegate=None, **kwargs):
super().__init__(title, **kwargs)
# Set the function that is called to build widgets when the window is
# visible
self._asset_path_model = omni.ui.SimpleStringModel("")
self._ppi_model = omni.ui.SimpleIntModel(100)
self._gap_model = omni.ui.SimpleFloatModel(0.1)
self._curve_model = omni.ui.SimpleFloatModel(0.0)
self._images_per_row_model = omni.ui.SimpleIntModel(1)
self._image_sequence_is_selected = omni.ui.SimpleBoolModel(False)
self._asset_path_model.add_end_edit_fn(lambda _: self._on_asset_path_change())
self._ppi_model.add_value_changed_fn(lambda _: self._on_change())
self._gap_model.add_value_changed_fn(lambda _: self._on_change())
self._curve_model.add_value_changed_fn(lambda _: self._on_change())
self._images_per_row_model.add_value_changed_fn(lambda _: self._on_change())
self._image_sequence_is_selected.add_value_changed_fn(lambda _: self._on_image_seq_selection_change())
self.frame.set_build_fn(self._build_fn)
stage_event_stream = omni.usd.get_context().get_stage_event_stream()
self._stage_event_sub = stage_event_stream.create_subscription_to_pop(self._on_stage_event, name="kit-imageseq-event-stream")
def destroy(self):
super().destroy()
self._stage_event_sub.unsubscribe()
def _on_stage_event(self, event):
stage: Usd.Stage = omni.usd.get_context().get_stage()
if stage is None:
return
SELECTION_CHANGED = int(omni.usd.StageEventType.SELECTION_CHANGED)
if event.type == SELECTION_CHANGED:
self._image_sequence_is_selected.set_value(False)
selection: omni.usd.Selection = omni.usd.get_context().get_selection()
paths = selection.get_selected_prim_paths()
if len(paths) == 0:
return
first_path = paths[0]
first_prim: Usd.Prim = stage.GetPrimAtPath(first_path)
if not first_prim.IsValid():
return
# Populate the UI Model with the config values
config = get_config_metadata(first_prim)
if config is None:
return
self._selected_prim_path = first_path
self._set_models_from_config(config)
def _config_from_models(self) -> Config:
config = Config()
config.path_glob = self._asset_path_model.get_value_as_string()
config.expanded_glob = glob(config.path_glob)
config.expanded_glob.sort()
config.ppi = self._ppi_model.get_value_as_int()
config.gap_pct = self._gap_model.get_value_as_float()
config.curve_pct = self._curve_model.get_value_as_float()
config.images_per_row = self._images_per_row_model.get_value_as_int()
return config
def _set_models_from_config(self, config: Config) -> None:
self._asset_path_model.set_value(config.path_glob)
self._ppi_model.set_value(config.ppi)
self._gap_model.set_value(config.gap_pct)
self._curve_model.set_value(config.curve_pct)
self._images_per_row_model.set_min(0)
self._images_per_row_model.set_max(len(config.expanded_glob))
self._images_per_row_model.set_value(config.images_per_row)
self._image_sequence_is_selected.set_value(True)
def _on_image_seq_selection_change(self) -> None:
self._frame.visible = self._image_sequence_is_selected.get_value_as_bool()
def _on_create_new_image_sequence(self) -> None:
stage: Usd.Stage = omni.usd.get_context().get_stage()
#
root_prim: Usd.Prim = stage.GetDefaultPrim()
root_prim_path: Sdf.Path = root_prim.GetPath()
root_image_seq_prim_path = root_prim_path.AppendChild("ImageSequences")
image_seq_count = 0
root_image_seq_prim: Usd.Prim = stage.GetPrimAtPath(root_image_seq_prim_path)
if root_image_seq_prim.IsValid():
image_seq_count = len(root_image_seq_prim.GetChildren())
while True:
image_seq_prim_path = root_image_seq_prim_path.AppendChild(f"ImageSequence{image_seq_count}")
if not stage.GetPrimAtPath(image_seq_prim_path).IsValid():
break
else:
image_seq_count += 1
# Default config
config = Config()
config.path_glob = ""
config.expanded_glob = []
config.ppi = 300
config.gap_pct = 0.0
config.curve_pct = 0.0
config.images_per_row = 0
prim = create_image_sequence_group_prim(stage, image_seq_prim_path, config)
# Select the created prim
selected_prim_path = str(prim.GetPath())
selection: omni.usd.Selection = omni.usd.get_context().get_selection()
selection.set_selected_prim_paths([selected_prim_path], True)
self._selected_prim_path = selected_prim_path
return
def _on_asset_path_change(self) -> None:
# Validate user input
config = self._config_from_models()
if len(config.expanded_glob) == 0:
carb.log_error(f"No assets found for {config.path_glob}")
for asset_path in config.expanded_glob:
if not os.path.exists(asset_path):
carb.log_error(f"Specified asset {asset_path} does not exist")
return
stage: Usd.Stage = omni.usd.get_context().get_stage()
prim_path = Sdf.Path(self._selected_prim_path)
prim: Usd.Prim = stage.GetPrimAtPath(prim_path)
if prim.IsValid():
children = prim.GetChildren()
for child in children:
child: Usd.Prim
stage.RemovePrim(child.GetPath())
prim: Usd.Prim = create_image_sequence_group_prim(stage, prim_path, config)
selection: omni.usd.Selection = omni.usd.get_context().get_selection()
selection.set_selected_prim_paths([str(prim.GetPath())], True)
self._set_models_from_config(config)
return
def _on_change(self):
selected_prim_path = self._selected_prim_path
config = self._config_from_models()
stage = omni.usd.get_context().get_stage()
update_image_sequence_prims(stage, Sdf.Path(selected_prim_path), config)
def _build_fn(self):
with omni.ui.VStack():
with omni.ui.VStack(height=20):
with omni.ui.HStack():
omni.ui.Button("Create New Image Sequence", width=40, clicked_fn=self._on_create_new_image_sequence)
self._frame = omni.ui.Frame(visible=self._image_sequence_is_selected.get_value_as_bool())
with self._frame:
with omni.ui.VStack(height=20):
with omni.ui.HStack():
omni.ui.Label(
"Asset Path", tooltip="Absolute path to an image asset or a glob like C:\dir\*.png"
)
omni.ui.StringField(self._asset_path_model)
omni.ui.Spacer(height=2)
with omni.ui.HStack():
omni.ui.Label("PPI", tooltip="Desired pixels per inch")
omni.ui.IntField(self._ppi_model)
omni.ui.Spacer(height=2)
with omni.ui.HStack():
omni.ui.Label("Gap", tooltip="In units of percentage of the max image width")
omni.ui.FloatSlider(self._gap_model, min=0.0, max=1.0)
omni.ui.Spacer(height=2)
with omni.ui.HStack():
omni.ui.Label("Curve", tooltip="0.0 -> straight line, 1.0 -> circle")
omni.ui.FloatSlider(self._curve_model, min=0.0, max=1.0)
omni.ui.Spacer(height=2)
with omni.ui.HStack():
omni.ui.Label("Images Per Row", tooltip="Images per row")
omni.ui.IntSlider(self._images_per_row_model, min=1)
omni.ui.Spacer(height=2) | 8,794 | Python | 44.569948 | 133 | 0.602343 |
jshrake-nvidia/kit-image-sequence/exts/omni.kit.imageseq/omni/kit/imageseq/tests/__init__.py | from .test_hello_world import * | 31 | Python | 30.999969 | 31 | 0.774194 |
jshrake-nvidia/kit-image-sequence/exts/omni.kit.imageseq/omni/kit/imageseq/tests/test_hello_world.py | # NOTE:
# omni.kit.test - std python's unittest module with additional wrapping to add suport for async/await tests
# For most things refer to unittest docs: https://docs.python.org/3/library/unittest.html
import omni.kit.test
# Extnsion for writing UI tests (simulate UI interaction)
import omni.kit.ui_test as ui_test
# Import extension python module we are testing with absolute import path, as if we are external user (other extension)
import omni.hello.world
# Having a test class dervived from omni.kit.test.AsyncTestCase declared on the root of module will make it auto-discoverable by omni.kit.test
class Test(omni.kit.test.AsyncTestCase):
# Before running each test
async def setUp(self):
pass
# After running each test
async def tearDown(self):
pass
# Actual test, notice it is "async" function, so "await" can be used if needed
async def test_hello_public_function(self):
result = omni.hello.world.some_public_function(4)
self.assertEqual(result, 256)
async def test_window_button(self):
# Find a label in our window
label = ui_test.find("My Window//Frame/**/Label[*]")
# Find buttons in our window
add_button = ui_test.find("My Window//Frame/**/Button[*].text=='Add'")
reset_button = ui_test.find("My Window//Frame/**/Button[*].text=='Reset'")
# Click reset button
await reset_button.click()
self.assertEqual(label.widget.text, "empty")
await add_button.click()
self.assertEqual(label.widget.text, "count: 1")
await add_button.click()
self.assertEqual(label.widget.text, "count: 2")
| 1,668 | Python | 34.510638 | 142 | 0.681055 |
jshrake-nvidia/kit-image-sequence/exts/omni.kit.imageseq/docs/CHANGELOG.md | # Changelog
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/).
## [0.0.1] - 2022-10-27
- Initial release
| 139 | Markdown | 14.555554 | 80 | 0.669065 |
jshrake-nvidia/kit-image-sequence/exts/omni.kit.imageseq/docs/README.md | # Image Sequence Importer
Omniverse Kit extension to import and layout image sequences. | 88 | Markdown | 28.666657 | 61 | 0.829545 |
alankent/ordinary-consolidator/README.md | # Omniverse Extension to Consolidate vertices on a mesh
This extension lets you pick a mesh in an OpenUSD scene that may not
be using `interpolation = "FaceVerying"` and it generates a new mesh
deduplicating vertices. This is necessary to make Audio2Face happy.
https://youtu.be/vv7vp3O_mh8?si=dHCA3kH3WVFwxXLC
| 314 | Markdown | 33.999996 | 68 | 0.799363 |
alankent/ordinary-consolidator/tools/scripts/link_app.py | import argparse
import json
import os
import sys
import packmanapi
import urllib3
def find_omniverse_apps():
http = urllib3.PoolManager()
try:
r = http.request("GET", "http://127.0.0.1:33480/components")
except Exception as e:
print(f"Failed retrieving apps from an Omniverse Launcher, maybe it is not installed?\nError: {e}")
sys.exit(1)
apps = {}
for x in json.loads(r.data.decode("utf-8")):
latest = x.get("installedVersions", {}).get("latest", "")
if latest:
for s in x.get("settings", []):
if s.get("version", "") == latest:
root = s.get("launch", {}).get("root", "")
apps[x["slug"]] = (x["name"], root)
break
return apps
def create_link(src, dst):
print(f"Creating a link '{src}' -> '{dst}'")
packmanapi.link(src, dst)
APP_PRIORITIES = ["code", "create", "view"]
if __name__ == "__main__":
parser = argparse.ArgumentParser(description="Create folder link to Kit App installed from Omniverse Launcher")
parser.add_argument(
"--path",
help="Path to Kit App installed from Omniverse Launcher, e.g.: 'C:/Users/bob/AppData/Local/ov/pkg/create-2021.3.4'",
required=False,
)
parser.add_argument(
"--app", help="Name of Kit App installed from Omniverse Launcher, e.g.: 'code', 'create'", required=False
)
args = parser.parse_args()
path = args.path
if not path:
print("Path is not specified, looking for Omniverse Apps...")
apps = find_omniverse_apps()
if len(apps) == 0:
print(
"Can't find any Omniverse Apps. Use Omniverse Launcher to install one. 'Code' is the recommended app for developers."
)
sys.exit(0)
print("\nFound following Omniverse Apps:")
for i, slug in enumerate(apps):
name, root = apps[slug]
print(f"{i}: {name} ({slug}) at: '{root}'")
if args.app:
selected_app = args.app.lower()
if selected_app not in apps:
choices = ", ".join(apps.keys())
print(f"Passed app: '{selected_app}' is not found. Specify one of the following found Apps: {choices}")
sys.exit(0)
else:
selected_app = next((x for x in APP_PRIORITIES if x in apps), None)
if not selected_app:
selected_app = next(iter(apps))
print(f"\nSelected app: {selected_app}")
_, path = apps[selected_app]
if not os.path.exists(path):
print(f"Provided path doesn't exist: {path}")
else:
SCRIPT_ROOT = os.path.dirname(os.path.realpath(__file__))
create_link(f"{SCRIPT_ROOT}/../../app", path)
print("Success!")
| 2,814 | Python | 32.117647 | 133 | 0.562189 |
alankent/ordinary-consolidator/tools/packman/config.packman.xml | <config remotes="cloudfront">
<remote2 name="cloudfront">
<transport actions="download" protocol="https" packageLocation="d4i3qtqj3r0z5.cloudfront.net/${name}@${version}" />
</remote2>
</config>
| 211 | XML | 34.333328 | 123 | 0.691943 |
alankent/ordinary-consolidator/tools/packman/bootstrap/install_package.py | # Copyright 2019 NVIDIA CORPORATION
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
# http://www.apache.org/licenses/LICENSE-2.0
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import logging
import shutil
import sys
import tempfile
import zipfile
__author__ = "hfannar"
logging.basicConfig(level=logging.WARNING, format="%(message)s")
logger = logging.getLogger("install_package")
class TemporaryDirectory:
def __init__(self):
self.path = None
def __enter__(self):
self.path = tempfile.mkdtemp()
return self.path
def __exit__(self, type, value, traceback):
# Remove temporary data created
shutil.rmtree(self.path)
def install_package(package_src_path, package_dst_path):
with zipfile.ZipFile(package_src_path, allowZip64=True) as zip_file, TemporaryDirectory() as temp_dir:
zip_file.extractall(temp_dir)
# Recursively copy (temp_dir will be automatically cleaned up on exit)
try:
# Recursive copy is needed because both package name and version folder could be missing in
# target directory:
shutil.copytree(temp_dir, package_dst_path)
except OSError as exc:
logger.warning("Directory %s already present, packaged installation aborted" % package_dst_path)
else:
logger.info("Package successfully installed to %s" % package_dst_path)
install_package(sys.argv[1], sys.argv[2])
| 1,844 | Python | 33.166666 | 108 | 0.703362 |
alankent/ordinary-consolidator/exts/ordinary.consolidator/ordinary/consolidator/extension.py | import omni.ext
import omni.ui as ui
from pxr import Usd, Sdf, Gf, UsdGeom, UsdShade
from .MeshMaker import MeshMaker
# Any class derived from `omni.ext.IExt` in top level module (defined in `python.modules` of `extension.toml`) will be
# instantiated when extension gets enabled and `on_startup(ext_id)` will be called. Later when extension gets disabled
# on_shutdown() is called.
class OrdinaryMeshConsolidatorExtension(omni.ext.IExt):
# ext_id is current extension id. It can be used with extension manager to query additional information, like where
# this extension is located on filesystem.
def on_startup(self, ext_id):
self._window = ui.Window("Mesh Consolidator", width=300, height=300)
with self._window.frame:
# TODO: Clean up the UI... one day.
with ui.VStack():
def on_click():
self.consolidate_prim()
with ui.HStack():
ui.Button("Consolidate", clicked_fn=on_click)
# The main body of the clean up code for VRoid Studio characters.
def consolidate_prim(self):
ctx = omni.usd.get_context()
stage = ctx.get_stage()
selections = ctx.get_selection().get_selected_prim_paths()
# Patch the skeleton structure, if not done already. Add "Root" to the joint list.
for prim_path in selections:
mesh_prim = stage.GetPrimAtPath(prim_path)
if mesh_prim and mesh_prim.IsA(UsdGeom.Mesh):
mesh: UsdGeom.Mesh = UsdGeom.Mesh(mesh_prim)
self.perform_consolidation(stage, mesh, prim_path + "_consolidated")
def perform_consolidation(self, stage: Usd.Stage, old_mesh: UsdGeom.Mesh, new_mesh_path):
faceVertexIndices = old_mesh.GetFaceVertexIndicesAttr().Get()
faceVertexCounts = old_mesh.GetFaceVertexCountsAttr().Get()
points = old_mesh.GetPointsAttr().Get()
normals = old_mesh.GetNormalsAttr().Get()
normalsInterpolation = UsdGeom.Primvar(old_mesh.GetNormalsAttr()).GetInterpolation()
stAttr = old_mesh.GetPrim().GetAttribute('primvars:st0')
stInterpolation = UsdGeom.Primvar(stAttr).GetInterpolation()
st = stAttr.Get()
material = UsdShade.MaterialBindingAPI(old_mesh.GetPrim()).GetDirectBindingRel().GetTargets()
new_mesh = MeshMaker(stage, material)
# Assumes faceVertexCounts are all '3'
for face_index in range(len(faceVertexIndices) // 3):
pi1 = faceVertexIndices[face_index * 3 + 0]
pi2 = faceVertexIndices[face_index * 3 + 1]
pi3 = faceVertexIndices[face_index * 3 + 2]
p1 = points[pi1]
p2 = points[pi2]
p3 = points[pi3]
if normalsInterpolation == UsdGeom.Tokens.faceVarying:
n1 = normals[face_index * 3 + 0]
n2 = normals[face_index * 3 + 1]
n3 = normals[face_index * 3 + 2]
else:
n1 = normals[pi1]
n2 = normals[pi2]
n3 = normals[pi3]
if stInterpolation == UsdGeom.Tokens.faceVarying:
st1 = st[face_index * 3 + 0]
st2 = st[face_index * 3 + 1]
st3 = st[face_index * 3 + 2]
else:
st1 = st[pi1]
st2 = st[pi2]
st3 = st[pi3]
new_mesh.add_face(p1, p2, p3, n1, n2, n3, st1, st2, st3)
new_mesh.create_at_path(new_mesh_path)
| 3,506 | Python | 37.538461 | 119 | 0.599544 |
alankent/ordinary-consolidator/exts/ordinary.consolidator/ordinary/consolidator/__init__.py | from .extension import *
| 25 | Python | 11.999994 | 24 | 0.76 |
alankent/ordinary-consolidator/exts/ordinary.consolidator/ordinary/consolidator/MeshMaker.py | from pxr import Usd, Sdf, Gf, UsdGeom, UsdShade, UsdSkel
# This class creates a new Mesh by adding faces one at a time.
# When don, you ask it to create a new Mesh prim.
class MeshMaker:
def __init__(self, stage: Usd.Stage, material):
self.stage = stage
self.material = material
self.faceVertexCounts = []
self.faceVertexIndices = []
self.normals = []
self.st = []
self.points = []
# Create a Mesh prim at the given prim path.
def create_at_path(self, prim_path) -> UsdGeom.Mesh:
# https://stackoverflow.com/questions/74462822/python-for-usd-map-a-texture-on-a-cube-so-every-face-have-the-same-image
mesh: UsdGeom.Mesh = UsdGeom.Mesh.Define(self.stage, prim_path)
mesh.CreateSubdivisionSchemeAttr().Set(UsdGeom.Tokens.none)
mesh.CreatePointsAttr(self.points)
mesh.CreateExtentAttr(UsdGeom.PointBased(mesh).ComputeExtent(mesh.GetPointsAttr().Get()))
mesh.CreateNormalsAttr(self.normals)
mesh.SetNormalsInterpolation(UsdGeom.Tokens.faceVarying)
mesh.CreateFaceVertexCountsAttr(self.faceVertexCounts)
mesh.CreateFaceVertexIndicesAttr(self.faceVertexIndices)
UsdGeom.PrimvarsAPI(mesh.GetPrim()).CreatePrimvar('st', Sdf.ValueTypeNames.TexCoord2fArray, UsdGeom.Tokens.faceVarying).Set(self.st)
UsdShade.MaterialBindingAPI(mesh).GetDirectBindingRel().SetTargets(self.material)
return mesh
# Add a new face (3 points with normals and mappings to part of the texture)
def add_face(self, p1, p2, p3, normal1, normal2, normal3, st1, st2, st3):
self.faceVertexCounts.append(3)
self.faceVertexIndices.append(self.add_point(p1))
self.faceVertexIndices.append(self.add_point(p2))
self.faceVertexIndices.append(self.add_point(p3))
self.normals.append(normal1)
self.normals.append(normal2)
self.normals.append(normal3)
self.st.append(st1)
self.st.append(st2)
self.st.append(st3)
# Given a point, find an existing points array entry and return its index, otherwise add another point
# and return the index of the new point.
def add_point(self, point):
for i in range(0, len(self.points)):
if self.points[i] == point:
return i
self.points.append(point)
return len(self.points) - 1
| 2,396 | Python | 41.052631 | 140 | 0.674457 |
alankent/ordinary-consolidator/exts/ordinary.consolidator/ordinary/consolidator/tests/__init__.py | from .test_hello_world import * | 31 | Python | 30.999969 | 31 | 0.774194 |
alankent/ordinary-consolidator/exts/ordinary.consolidator/ordinary/consolidator/tests/test_hello_world.py | # NOTE:
# omni.kit.test - std python's unittest module with additional wrapping to add suport for async/await tests
# For most things refer to unittest docs: https://docs.python.org/3/library/unittest.html
import omni.kit.test
# Extnsion for writing UI tests (simulate UI interaction)
import omni.kit.ui_test as ui_test
# Import extension python module we are testing with absolute import path, as if we are external user (other extension)
import ordinary.consolidator
# Having a test class dervived from omni.kit.test.AsyncTestCase declared on the root of module will make it auto-discoverable by omni.kit.test
class Test(omni.kit.test.AsyncTestCase):
# Before running each test
async def setUp(self):
pass
# After running each test
async def tearDown(self):
pass
# Actual test, notice it is "async" function, so "await" can be used if needed
async def test_hello_public_function(self):
result = ordinary.consolidator.some_public_function(4)
self.assertEqual(result, 256)
async def test_window_button(self):
# Find a label in our window
label = ui_test.find("My Window//Frame/**/Label[*]")
# Find buttons in our window
add_button = ui_test.find("My Window//Frame/**/Button[*].text=='Add'")
reset_button = ui_test.find("My Window//Frame/**/Button[*].text=='Reset'")
# Click reset button
await reset_button.click()
self.assertEqual(label.widget.text, "empty")
await add_button.click()
self.assertEqual(label.widget.text, "count: 1")
await add_button.click()
self.assertEqual(label.widget.text, "count: 2")
| 1,678 | Python | 34.723404 | 142 | 0.684148 |
alankent/ordinary-consolidator/exts/ordinary.consolidator/config/extension.toml | [package]
# Semantic Versioning is used: https://semver.org/
version = "1.0.0"
# Lists people or organizations that are considered the "authors" of the package.
authors = ["NVIDIA"]
# The title and description fields are primarily for displaying extension info in UI
title = "ordinary consolidator"
description="A simple python extension example to use as a starting point for your extensions."
# Path (relative to the root) or content of readme markdown file for UI.
readme = "docs/README.md"
# URL of the extension source repository.
repository = ""
# One of categories for UI.
category = "Example"
# Keywords for the extension
keywords = ["kit", "example"]
# Location of change log file in target (final) folder of extension, relative to the root.
# More info on writing changelog: https://keepachangelog.com/en/1.0.0/
changelog="docs/CHANGELOG.md"
# Preview image and icon. Folder named "data" automatically goes in git lfs (see .gitattributes file).
# Preview image is shown in "Overview" of Extensions window. Screenshot of an extension might be a good preview image.
preview_image = "data/preview.png"
# Icon is shown in Extensions window, it is recommended to be square, of size 256x256.
icon = "data/icon.png"
# Use omni.ui to build simple UI
[dependencies]
"omni.kit.uiapp" = {}
# Main python module this extension provides, it will be publicly available as "import ordinary.consolidator".
[[python.module]]
name = "ordinary.consolidator"
[[test]]
# Extra dependencies only to be used during test run
dependencies = [
"omni.kit.ui_test" # UI testing extension
]
| 1,589 | TOML | 32.124999 | 118 | 0.748269 |
alankent/ordinary-consolidator/exts/ordinary.consolidator/docs/CHANGELOG.md | # Changelog
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/).
## [1.0.0] - 2021-04-26
- Initial version of extension UI template with a window
| 178 | Markdown | 18.888887 | 80 | 0.702247 |
alankent/ordinary-consolidator/exts/ordinary.consolidator/docs/README.md | # Python Extension Example [ordinary.consolidator]
This is an example of pure python Kit extension. It is intended to be copied and serve as a template to create new extensions.
| 180 | Markdown | 35.199993 | 126 | 0.794444 |
alankent/ordinary-consolidator/exts/ordinary.consolidator/docs/index.rst | ordinary.consolidator
#############################
Example of Python only extension
.. toctree::
:maxdepth: 1
README
CHANGELOG
.. automodule::"ordinary.consolidator"
:platform: Windows-x86_64, Linux-x86_64
:members:
:undoc-members:
:show-inheritance:
:imported-members:
:exclude-members: contextmanager
| 343 | reStructuredText | 15.380952 | 43 | 0.629738 |
alankent/ordinary-windy-blendshapes/README.md | # Create Blend Shapes for Windy Scenes
This project is designed for foliage such as grass, flowers, or trees so
it can sway in the wind in NVIDIA Omniverse. It is designed for models
that are static (unmoving).
It is a work in progress, but sharing where up to. I will probably potter
along with this in my spare time.
It works by creating blend shapes the move points in the mesh by an amount
proportional (with a bit of a curve) to the height of the point off the ground.
So points at (or below) ground level do not move. Points half way up move a
bit, points at the top move the most.
To use it,
* Create a new empty stage for your model, click the first "create skeleton" button which will define SkelRoot, Skeleton, and SkelAnimation prims.
* Add a reference to your model from under SkelRoot. It must be under this prim for it to animate.
* Click the second button which will create a blendshape for each mesh in the model.
## Plans
* Have 2 blend shapes for the model bending east and south. I want to create an animation graph that has two variables controlling the strength of the two blendshapes.
* I want to create an action graph that given wind direction, strength, sway speed etc animations the east and south weights (with negative values for west and north) so the foliage can sway in a specified direction
* I also want a central "wind" script that updates all of the individual models, so you can set the wind direction and strength centrally and everything in the stage will get updated
* I want to add another blendshape for a slight ripple, to make leaves flutter. This would be applied to selected meshes (leaves, not trunks or branches).
# Extension Project Template
This project was automatically generated.
- `app` - It is a folder link to the location of your *Omniverse Kit* based app.
- `exts` - It is a folder where you can add new extensions. It was automatically added to extension search path. (Extension Manager -> Gear Icon -> Extension Search Path).
Open this folder using Visual Studio Code. It will suggest you to install few extensions that will make python experience better.
Look for "ordinary.windy.blendshapes" extension in extension manager and enable it. Try applying changes to any python files, it will hot-reload and you can observe results immediately.
Alternatively, you can launch your app from console with this folder added to search path and your extension enabled, e.g.:
```
> app\omni.code.bat --ext-folder exts --enable company.hello.world
```
# App Link Setup
If `app` folder link doesn't exist or broken it can be created again. For better developer experience it is recommended to create a folder link named `app` to the *Omniverse Kit* app installed from *Omniverse Launcher*. Convenience script to use is included.
Run:
```
> link_app.bat
```
If successful you should see `app` folder link in the root of this repo.
If multiple Omniverse apps is installed script will select recommended one. Or you can explicitly pass an app:
```
> link_app.bat --app create
```
You can also just pass a path to create link to:
```
> link_app.bat --path "C:/Users/bob/AppData/Local/ov/pkg/create-2021.3.4"
```
# Sharing Your Extensions
This folder is ready to be pushed to any git repository. Once pushed direct link to a git repository can be added to *Omniverse Kit* extension search paths.
Link might look like this: `git://github.com/[user]/[your_repo].git?branch=main&dir=exts`
Notice `exts` is repo subfolder with extensions. More information can be found in "Git URL as Extension Search Paths" section of developers manual.
To add a link to your *Omniverse Kit* based app go into: Extension Manager -> Gear Icon -> Extension Search Path
| 3,719 | Markdown | 45.499999 | 258 | 0.767948 |
alankent/ordinary-windy-blendshapes/tools/scripts/link_app.py | import argparse
import json
import os
import sys
import packmanapi
import urllib3
def find_omniverse_apps():
http = urllib3.PoolManager()
try:
r = http.request("GET", "http://127.0.0.1:33480/components")
except Exception as e:
print(f"Failed retrieving apps from an Omniverse Launcher, maybe it is not installed?\nError: {e}")
sys.exit(1)
apps = {}
for x in json.loads(r.data.decode("utf-8")):
latest = x.get("installedVersions", {}).get("latest", "")
if latest:
for s in x.get("settings", []):
if s.get("version", "") == latest:
root = s.get("launch", {}).get("root", "")
apps[x["slug"]] = (x["name"], root)
break
return apps
def create_link(src, dst):
print(f"Creating a link '{src}' -> '{dst}'")
packmanapi.link(src, dst)
APP_PRIORITIES = ["code", "create", "view"]
if __name__ == "__main__":
parser = argparse.ArgumentParser(description="Create folder link to Kit App installed from Omniverse Launcher")
parser.add_argument(
"--path",
help="Path to Kit App installed from Omniverse Launcher, e.g.: 'C:/Users/bob/AppData/Local/ov/pkg/create-2021.3.4'",
required=False,
)
parser.add_argument(
"--app", help="Name of Kit App installed from Omniverse Launcher, e.g.: 'code', 'create'", required=False
)
args = parser.parse_args()
path = args.path
if not path:
print("Path is not specified, looking for Omniverse Apps...")
apps = find_omniverse_apps()
if len(apps) == 0:
print(
"Can't find any Omniverse Apps. Use Omniverse Launcher to install one. 'Code' is the recommended app for developers."
)
sys.exit(0)
print("\nFound following Omniverse Apps:")
for i, slug in enumerate(apps):
name, root = apps[slug]
print(f"{i}: {name} ({slug}) at: '{root}'")
if args.app:
selected_app = args.app.lower()
if selected_app not in apps:
choices = ", ".join(apps.keys())
print(f"Passed app: '{selected_app}' is not found. Specify one of the following found Apps: {choices}")
sys.exit(0)
else:
selected_app = next((x for x in APP_PRIORITIES if x in apps), None)
if not selected_app:
selected_app = next(iter(apps))
print(f"\nSelected app: {selected_app}")
_, path = apps[selected_app]
if not os.path.exists(path):
print(f"Provided path doesn't exist: {path}")
else:
SCRIPT_ROOT = os.path.dirname(os.path.realpath(__file__))
create_link(f"{SCRIPT_ROOT}/../../app", path)
print("Success!")
| 2,814 | Python | 32.117647 | 133 | 0.562189 |
alankent/ordinary-windy-blendshapes/tools/packman/config.packman.xml | <config remotes="cloudfront">
<remote2 name="cloudfront">
<transport actions="download" protocol="https" packageLocation="d4i3qtqj3r0z5.cloudfront.net/${name}@${version}" />
</remote2>
</config>
| 211 | XML | 34.333328 | 123 | 0.691943 |
alankent/ordinary-windy-blendshapes/tools/packman/bootstrap/install_package.py | # Copyright 2019 NVIDIA CORPORATION
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
# http://www.apache.org/licenses/LICENSE-2.0
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import logging
import shutil
import sys
import tempfile
import zipfile
__author__ = "hfannar"
logging.basicConfig(level=logging.WARNING, format="%(message)s")
logger = logging.getLogger("install_package")
class TemporaryDirectory:
def __init__(self):
self.path = None
def __enter__(self):
self.path = tempfile.mkdtemp()
return self.path
def __exit__(self, type, value, traceback):
# Remove temporary data created
shutil.rmtree(self.path)
def install_package(package_src_path, package_dst_path):
with zipfile.ZipFile(package_src_path, allowZip64=True) as zip_file, TemporaryDirectory() as temp_dir:
zip_file.extractall(temp_dir)
# Recursively copy (temp_dir will be automatically cleaned up on exit)
try:
# Recursive copy is needed because both package name and version folder could be missing in
# target directory:
shutil.copytree(temp_dir, package_dst_path)
except OSError as exc:
logger.warning("Directory %s already present, packaged installation aborted" % package_dst_path)
else:
logger.info("Package successfully installed to %s" % package_dst_path)
install_package(sys.argv[1], sys.argv[2])
| 1,844 | Python | 33.166666 | 108 | 0.703362 |
alankent/ordinary-windy-blendshapes/exts/ordinary.windy.blendshapes/ordinary/windy/blendshapes/extension.py | import omni.ext
import omni.ui as ui
from pxr import Usd, Sdf, Gf, UsdGeom, UsdSkel
# Any class derived from `omni.ext.IExt` in top level module (defined in `python.modules` of `extension.toml`) will be
# instantiated when extension gets enabled and `on_startup(ext_id)` will be called. Later when extension gets disabled
# on_shutdown() is called.
class OrdinaryWindyBlendshapesExtension(omni.ext.IExt):
# ext_id is current extension id. It can be used with extension manager to query additional information, like where
# this extension is located on filesystem.
def on_startup(self, ext_id):
print("[ordinary.windy.blendshapes] ordinary windy blendshapes startup")
self._window = ui.Window("Ordinary Windy Blendshapes", width=300, height=300)
with self._window.frame:
with ui.VStack():
label = ui.Label("Instructions\n\n" +
"- Create a new stage\n" +
"- Click 'Create Skeleton'\n" +
"- Drop your model under SkelRoot\n" +
"- Click 'Add Blend Shapes'\n" +
"- Save and reload the file (to flush the skeleton cache)")
def on_create_skeleton():
self.create_skeleton()
def on_add_blend_shapes():
self.add_blend_shapes()
with ui.HStack():
ui.Button("Create Skeleton", clicked_fn=on_create_skeleton)
ui.Button("Add Blend Shapes", clicked_fn=on_add_blend_shapes)
def on_shutdown(self):
print("[ordinary.windy.blendshapes] ordinary windy blendshapes shutdown")
def create_skeleton(self):
ctx = omni.usd.get_context()
stage: Usd.Stage = ctx.get_stage()
root: Usd.Prim = stage.GetDefaultPrim()
# Create a skeleton under which the user will have to add a reference to the model.
skel_root: UsdSkel.Root = UsdSkel.Root.Define(stage, root.GetPath().AppendChild("SkelRoot"))
skeleton: UsdSkel.Skeleton = UsdSkel.Skeleton.Define(stage, skel_root.GetPath().AppendChild("Skeleton"))
UsdSkel.BindingAPI.Apply(skeleton.GetPrim())
skeleton.CreateBindTransformsAttr().Set([])
skeleton.CreateRestTransformsAttr().Set([])
skeleton.CreateJointsAttr().Set([])
skeleton.CreateJointNamesAttr().Set([])
# Add a SkelAnimation referring to the blend shapes to simplify animation.
default_wind_anim = self.add_skel_animation(stage, skeleton, "defaultWindAnimation", [0, 0, 0, 0])
self.add_skel_animation(stage, skeleton, "noWindAnimation", [0, 0, 0, 0])
self.add_skel_animation(stage, skeleton, "eastWindAnimation", [1, 0, 0, 0])
self.add_skel_animation(stage, skeleton, "westWindAnimation", [0, 1, 0, 0])
self.add_skel_animation(stage, skeleton, "southWindAnimation", [0, 0, 1, 0])
self.add_skel_animation(stage, skeleton, "northWindAnimation", [0, 0, 0, 1])
self.add_skel_animation(stage, skeleton, "testWindAnimation", {
0: [0, 0, 0, 0],
10: [0.2, 0, 0.2, 0],
25: [1, 0, 1, 0],
40: [0.2, 0, 0.2, 0],
50: [0, 0, 0, 0],
60: [0, 0.2, 0, 0.2],
75: [0, 1, 0, 1],
90: [0, 0.2, 0, 0.2],
100: [0, 0, 0, 0],
})
# Point the skeleton to the no wind animation.
skel_binding: UsdSkel.BindingAPI = UsdSkel.BindingAPI(skeleton)
skel_binding.CreateAnimationSourceRel().SetTargets([default_wind_anim.GetPath()])
def add_skel_animation(self, stage: Usd.Stage, skeleton: UsdSkel.Skeleton, animation_name, weights):
print(animation_name)
print(skeleton.GetPath().name)
skel_animation: UsdSkel.Animation = UsdSkel.Animation.Define(stage, skeleton.GetPath().AppendChild(animation_name))
skel_animation.CreateBlendShapesAttr().Set(["eastWindBlendShape", "westWindBlendShape", "southWindBlendShape", "northWindBlendShape"])
skel_animation.CreateJointsAttr().Set([])
skel_animation.CreateRotationsAttr().Set([])
skel_animation.CreateScalesAttr().Set([])
skel_animation.CreateTranslationsAttr().Set([])
x: Usd.Prim = None
UsdSkel.Animation.GetBlendShapeWeightsAttr
if type(weights) is dict:
attr = skel_animation.CreateBlendShapeWeightsAttr()
skel_animation.GetBlendShapeWeightsAttr
for time, value in weights.items():
attr.Set(time=time, value=value)
else:
skel_animation.CreateBlendShapeWeightsAttr().Set(weights)
return skel_animation
def add_blend_shapes(self):
ctx = omni.usd.get_context()
stage: Usd.Stage = ctx.get_stage()
root: Usd.Prim = stage.GetDefaultPrim()
skel_root = root.GetChild("SkelRoot")
if not skel_root.IsValid():
print("SkelRoot not found - did you create the skeleton first?")
return
skeleton = skel_root.GetChild("Skeleton")
if not skeleton.IsValid():
print("Skeleton not found - did you create the skeleton first?")
return
# Cannot use Traverse unfortunately, as it is not restricted to under a specific prim.
#for prim in stage.Traverse():
# if prim.IsA(UsdGeom.Mesh):
# print("Mesh: " + prim.GetPath().pathString)
self.look_for_meshes(stage, root, skeleton)
def look_for_meshes(self, stage, prim, skeleton):
if prim.IsA(UsdGeom.Mesh):
self.add_blend_shapes_for_mesh(stage, prim, skeleton)
for child_prim in prim.GetChildren():
self.look_for_meshes(stage, child_prim, skeleton)
def add_blend_shapes_for_mesh(self, stage: Usd.Stage, meshPrim, skeleton):
# Work out which way is up for the model.
up = "Y"
units_resolve_attr = meshPrim.GetParent().GetAttribute("xformOp:rotateX:unitsResolve")
if units_resolve_attr:
units_resolve = units_resolve_attr.Get()
if units_resolve == 0:
pass
elif units_resolve == -90:
up = "Z"
else:
print("I don't know what up is!")
# Create child blend shapes for +X (east) and +Z (south)
mesh = UsdGeom.Mesh(meshPrim)
east_blend_shape = self.add_blendshape_in_one_direction(stage, up, mesh, "eastWindBlendShape", 1, 0)
west_blend_shape = self.add_blendshape_in_one_direction(stage, up, mesh, "westWindBlendShape", -1, 0)
south_blend_shape = self.add_blendshape_in_one_direction(stage, up, mesh, "southWindBlendShape", 0, 1)
north_blend_shape = self.add_blendshape_in_one_direction(stage, up, mesh, "northWindBlendShape", 0, -1)
# TODO: Add a blend shape for fluttering leaves
# Add skel:blendShapes property to list the blendshape names.
# https://openusd.org/dev/api/class_usd_skel_binding_a_p_i.html
binding: UsdSkel.BindingAPI = UsdSkel.BindingAPI(meshPrim)
binding.CreateBlendShapesAttr().Set(["eastWindBlendShape", "westWindBlendShape", "southWindBlendShape", "northWindBlendShape"])
binding.CreateBlendShapeTargetsRel().SetTargets([east_blend_shape.GetPath(), west_blend_shape.GetPath(), south_blend_shape.GetPath(), north_blend_shape.GetPath()])
UsdSkel.BindingAPI.Apply(meshPrim)
binding.CreateSkeletonRel().SetTargets([skeleton.GetPath()])
def add_blendshape_in_one_direction(self, stage: Usd.Stage, up, mesh: UsdGeom.Mesh, blend_shape_name, east_scale, south_scale):
# Work out how many points in blendshape we need.
# We specify all points (0..n), normal offsets are all zero. Point offsets are the most complex.
mesh_points = mesh.GetPointsAttr().Get()
num_points = len(mesh_points)
point_indices = range(0, num_points)
normal_offsets = [(0, 0, 0) for i in point_indices]
# To work out how far to bend the object, we need to know its height.
height = 0
offsets = []
# TODO: I don't really like this - probably a smarter way to do it by computing a base vector
# then rotating it appropriately. But just get it going for now by duplicating the code.
if up == "Y":
for x, y, z in mesh_points:
if y > height:
height = y
for x, y, z in mesh_points:
if y <= 0:
offsets.append((0, 0, 0))
else:
horizontal_delta = self.compute_horizontal_delta(height, y)
vertical_delta = self.compute_vertical_delta(height, y)
offsets.append((horizontal_delta * east_scale, vertical_delta, horizontal_delta * south_scale))
if up == "Z":
for x, y, z in mesh_points:
if z > height:
height = z
for x, y, z in mesh_points:
if z <= 0:
offsets.append((0, 0, 0))
else:
horizontal_delta = self.compute_horizontal_delta(height, z)
vertical_delta = self.compute_vertical_delta(height, z)
offsets.append((horizontal_delta * east_scale, horizontal_delta * south_scale, vertical_delta))
# Create the blendshape! https://openusd.org/dev/api/class_usd_skel_blend_shape.html
blend_shape: UsdSkel.BlendShape = UsdSkel.BlendShape.Define(stage, mesh.GetPath().AppendChild(blend_shape_name))
blend_shape.CreatePointIndicesAttr().Set(point_indices)
blend_shape.CreateOffsetsAttr().Set(offsets)
blend_shape.CreateNormalOffsetsAttr().Set(normal_offsets)
return blend_shape
def compute_horizontal_delta(self, max, value):
# Scale to 0 to 1 fraction, square it for a curve, then scale to up to sway at most 1/4 height.
return ((value / max) ** 2) * max / 8
def compute_vertical_delta(self, max, value):
# When leaning reduce the height a bit so it does not look like its stretching too much.
# TODO: Would have to do a few inbetweens to do a nice curve, and it jumps badly at the top, so just skip it for now.
return 0
#return -abs(self.compute_horizontal_delta(max, value) / 2) | 10,500 | Python | 48.533019 | 171 | 0.609048 |
alankent/ordinary-windy-blendshapes/exts/ordinary.windy.blendshapes/ordinary/windy/blendshapes/__init__.py | from .extension import *
| 25 | Python | 11.999994 | 24 | 0.76 |
alankent/ordinary-windy-blendshapes/exts/ordinary.windy.blendshapes/ordinary/windy/blendshapes/tests/__init__.py | from .test_hello_world import * | 31 | Python | 30.999969 | 31 | 0.774194 |
alankent/ordinary-windy-blendshapes/exts/ordinary.windy.blendshapes/ordinary/windy/blendshapes/tests/test_hello_world.py | # NOTE:
# omni.kit.test - std python's unittest module with additional wrapping to add suport for async/await tests
# For most things refer to unittest docs: https://docs.python.org/3/library/unittest.html
import omni.kit.test
# Extnsion for writing UI tests (simulate UI interaction)
import omni.kit.ui_test as ui_test
# Import extension python module we are testing with absolute import path, as if we are external user (other extension)
import ordinary.windy.blendshapes
# Having a test class dervived from omni.kit.test.AsyncTestCase declared on the root of module will make it auto-discoverable by omni.kit.test
class Test(omni.kit.test.AsyncTestCase):
# Before running each test
async def setUp(self):
pass
# After running each test
async def tearDown(self):
pass
# Actual test, notice it is "async" function, so "await" can be used if needed
@omni.kit.test.omni_test_registry(guid="f898a949-bacc-41f5-be56-b4eb8923f54e")
async def test_hello_public_function(self):
result = ordinary.windy.blendshapes.some_public_function(4)
self.assertEqual(result, 256)
@omni.kit.test.omni_test_registry(guid="4626d574-659f-4a85-8958-9fa8588fbce3")
async def test_window_button(self):
# Find a label in our window
label = ui_test.find("My Window//Frame/**/Label[*]")
# Find buttons in our window
add_button = ui_test.find("My Window//Frame/**/Button[*].text=='Add'")
reset_button = ui_test.find("My Window//Frame/**/Button[*].text=='Reset'")
# Click reset button
await reset_button.click()
self.assertEqual(label.widget.text, "empty")
await add_button.click()
self.assertEqual(label.widget.text, "count: 1")
await add_button.click()
self.assertEqual(label.widget.text, "count: 2")
| 1,854 | Python | 36.857142 | 142 | 0.691478 |
alankent/ordinary-windy-blendshapes/exts/ordinary.windy.blendshapes/config/extension.toml | [package]
# Semantic Versioning is used: https://semver.org/
version = "1.0.0"
# Lists people or organizations that are considered the "authors" of the package.
authors = ["NVIDIA"]
# The title and description fields are primarily for displaying extension info in UI
title = "ordinary windy blendshapes"
description="A simple python extension example to use as a starting point for your extensions."
# Path (relative to the root) or content of readme markdown file for UI.
readme = "docs/README.md"
# URL of the extension source repository.
repository = ""
# One of categories for UI.
category = "Example"
# Keywords for the extension
keywords = ["kit", "example"]
# Location of change log file in target (final) folder of extension, relative to the root.
# More info on writing changelog: https://keepachangelog.com/en/1.0.0/
changelog="docs/CHANGELOG.md"
# Preview image and icon. Folder named "data" automatically goes in git lfs (see .gitattributes file).
# Preview image is shown in "Overview" of Extensions window. Screenshot of an extension might be a good preview image.
preview_image = "data/preview.png"
# Icon is shown in Extensions window, it is recommended to be square, of size 256x256.
icon = "data/icon.png"
# Use omni.ui to build simple UI
[dependencies]
"omni.kit.uiapp" = {}
# Main python module this extension provides, it will be publicly available as "import ordinary.windy.blendshapes".
[[python.module]]
name = "ordinary.windy.blendshapes"
[[test]]
# Extra dependencies only to be used during test run
dependencies = [
"omni.kit.ui_test" # UI testing extension
]
| 1,604 | TOML | 32.437499 | 118 | 0.748753 |
alankent/ordinary-windy-blendshapes/exts/ordinary.windy.blendshapes/docs/CHANGELOG.md | # Changelog
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/).
## [1.0.0] - 2021-04-26
- Initial version of extension UI template with a window
| 178 | Markdown | 18.888887 | 80 | 0.702247 |
alankent/ordinary-windy-blendshapes/exts/ordinary.windy.blendshapes/docs/README.md | # Python Extension Example [ordinary.windy.blendshapes]
This is an example of pure python Kit extension. It is intended to be copied and serve as a template to create new extensions.
| 185 | Markdown | 36.199993 | 126 | 0.794595 |
alankent/ordinary-windy-blendshapes/exts/ordinary.windy.blendshapes/docs/index.rst | ordinary.windy.blendshapes
#############################
Example of Python only extension
.. toctree::
:maxdepth: 1
README
CHANGELOG
.. automodule::"ordinary.windy.blendshapes"
:platform: Windows-x86_64, Linux-x86_64
:members:
:undoc-members:
:show-inheritance:
:imported-members:
:exclude-members: contextmanager
| 353 | reStructuredText | 15.857142 | 43 | 0.634561 |
alankent/ordinary-depthmap-projection/README.md | # Extension Project Template
This project was automatically generated.
- `app` - It is a folder link to the location of your *Omniverse Kit* based app.
- `exts` - It is a folder where you can add new extensions. It was automatically added to extension search path. (Extension Manager -> Gear Icon -> Extension Search Path).
Open this folder using Visual Studio Code. It will suggest you to install few extensions that will make python experience better.
Look for "ordinary.depthmap.projection" extension in extension manager and enable it. Try applying changes to any python files, it will hot-reload and you can observe results immediately.
Alternatively, you can launch your app from console with this folder added to search path and your extension enabled, e.g.:
```
> app\omni.code.bat --ext-folder exts --enable company.hello.world
```
# App Link Setup
If `app` folder link doesn't exist or broken it can be created again. For better developer experience it is recommended to create a folder link named `app` to the *Omniverse Kit* app installed from *Omniverse Launcher*. Convenience script to use is included.
Run:
```
> link_app.bat
```
If successful you should see `app` folder link in the root of this repo.
If multiple Omniverse apps is installed script will select recommended one. Or you can explicitly pass an app:
```
> link_app.bat --app create
```
You can also just pass a path to create link to:
```
> link_app.bat --path "C:/Users/bob/AppData/Local/ov/pkg/create-2021.3.4"
```
# Sharing Your Extensions
This folder is ready to be pushed to any git repository. Once pushed direct link to a git repository can be added to *Omniverse Kit* extension search paths.
Link might look like this: `git://github.com/[user]/[your_repo].git?branch=main&dir=exts`
Notice `exts` is repo subfolder with extensions. More information can be found in "Git URL as Extension Search Paths" section of developers manual.
To add a link to your *Omniverse Kit* based app go into: Extension Manager -> Gear Icon -> Extension Search Path
| 2,052 | Markdown | 37.735848 | 258 | 0.758285 |
alankent/ordinary-depthmap-projection/tools/scripts/link_app.py | import argparse
import json
import os
import sys
import packmanapi
import urllib3
def find_omniverse_apps():
http = urllib3.PoolManager()
try:
r = http.request("GET", "http://127.0.0.1:33480/components")
except Exception as e:
print(f"Failed retrieving apps from an Omniverse Launcher, maybe it is not installed?\nError: {e}")
sys.exit(1)
apps = {}
for x in json.loads(r.data.decode("utf-8")):
latest = x.get("installedVersions", {}).get("latest", "")
if latest:
for s in x.get("settings", []):
if s.get("version", "") == latest:
root = s.get("launch", {}).get("root", "")
apps[x["slug"]] = (x["name"], root)
break
return apps
def create_link(src, dst):
print(f"Creating a link '{src}' -> '{dst}'")
packmanapi.link(src, dst)
APP_PRIORITIES = ["code", "create", "view"]
if __name__ == "__main__":
parser = argparse.ArgumentParser(description="Create folder link to Kit App installed from Omniverse Launcher")
parser.add_argument(
"--path",
help="Path to Kit App installed from Omniverse Launcher, e.g.: 'C:/Users/bob/AppData/Local/ov/pkg/create-2021.3.4'",
required=False,
)
parser.add_argument(
"--app", help="Name of Kit App installed from Omniverse Launcher, e.g.: 'code', 'create'", required=False
)
args = parser.parse_args()
path = args.path
if not path:
print("Path is not specified, looking for Omniverse Apps...")
apps = find_omniverse_apps()
if len(apps) == 0:
print(
"Can't find any Omniverse Apps. Use Omniverse Launcher to install one. 'Code' is the recommended app for developers."
)
sys.exit(0)
print("\nFound following Omniverse Apps:")
for i, slug in enumerate(apps):
name, root = apps[slug]
print(f"{i}: {name} ({slug}) at: '{root}'")
if args.app:
selected_app = args.app.lower()
if selected_app not in apps:
choices = ", ".join(apps.keys())
print(f"Passed app: '{selected_app}' is not found. Specify one of the following found Apps: {choices}")
sys.exit(0)
else:
selected_app = next((x for x in APP_PRIORITIES if x in apps), None)
if not selected_app:
selected_app = next(iter(apps))
print(f"\nSelected app: {selected_app}")
_, path = apps[selected_app]
if not os.path.exists(path):
print(f"Provided path doesn't exist: {path}")
else:
SCRIPT_ROOT = os.path.dirname(os.path.realpath(__file__))
create_link(f"{SCRIPT_ROOT}/../../app", path)
print("Success!")
| 2,814 | Python | 32.117647 | 133 | 0.562189 |
alankent/ordinary-depthmap-projection/tools/packman/config.packman.xml | <config remotes="cloudfront">
<remote2 name="cloudfront">
<transport actions="download" protocol="https" packageLocation="d4i3qtqj3r0z5.cloudfront.net/${name}@${version}" />
</remote2>
</config>
| 211 | XML | 34.333328 | 123 | 0.691943 |
alankent/ordinary-depthmap-projection/tools/packman/bootstrap/install_package.py | # Copyright 2019 NVIDIA CORPORATION
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
# http://www.apache.org/licenses/LICENSE-2.0
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import logging
import shutil
import sys
import tempfile
import zipfile
__author__ = "hfannar"
logging.basicConfig(level=logging.WARNING, format="%(message)s")
logger = logging.getLogger("install_package")
class TemporaryDirectory:
def __init__(self):
self.path = None
def __enter__(self):
self.path = tempfile.mkdtemp()
return self.path
def __exit__(self, type, value, traceback):
# Remove temporary data created
shutil.rmtree(self.path)
def install_package(package_src_path, package_dst_path):
with zipfile.ZipFile(package_src_path, allowZip64=True) as zip_file, TemporaryDirectory() as temp_dir:
zip_file.extractall(temp_dir)
# Recursively copy (temp_dir will be automatically cleaned up on exit)
try:
# Recursive copy is needed because both package name and version folder could be missing in
# target directory:
shutil.copytree(temp_dir, package_dst_path)
except OSError as exc:
logger.warning("Directory %s already present, packaged installation aborted" % package_dst_path)
else:
logger.info("Package successfully installed to %s" % package_dst_path)
install_package(sys.argv[1], sys.argv[2])
| 1,844 | Python | 33.166666 | 108 | 0.703362 |
alankent/ordinary-depthmap-projection/exts/ordinary.depthmap.projection/ordinary/depthmap/projection/extension.py | from typing import List, Tuple, Callable, Dict
from functools import partial
import os
import math
import carb.settings
import carb.windowing
import omni.appwindow
from carb import log_warn, events
import omni.ext
import omni.ui as ui
#from omni.kit.window.file_importer import get_file_importer
from omni.kit.window.filepicker import FilePickerDialog, UI_READY_EVENT
from omni.kit.widget.filebrowser import FileBrowserItem
from pxr import Usd, UsdShade, UsdGeom, Sdf, Gf
import omni.usd
import numpy as np
from PIL import Image
DEFAULT_FILE_EXTENSION_TYPES = [
("*.png, *.jpg", "Image Files"),
("*.*", "All files"),
]
def default_filter_handler(filename: str, filter_postfix: str, filter_ext: str) -> bool:
if not filename:
return True
# Show only files whose names end with: *<postfix>.<ext>
if filter_ext:
# split comma separated string into a list:
filter_exts = filter_ext.split(",") if isinstance(filter_ext, str) else filter_ext
filter_exts = [x.replace(" ", "") for x in filter_exts]
filter_exts = [x for x in filter_exts if x]
# check if the file extension matches anything in the list:
if not (
"*.*" in filter_exts or
any(filename.endswith(f.replace("*", "")) for f in filter_exts)
):
# match failed:
return False
if filter_postfix:
# strip extension and check postfix:
filename = os.path.splitext(filename)[0]
return filename.endswith(filter_postfix)
return True
def on_filter_item(filter_fn: Callable[[str], bool], dialog: FilePickerDialog, item: FileBrowserItem, show_only_folders: bool = False) -> bool:
if item and not item.is_folder:
# OM-96626: Add show_only_folders option to file importer
if show_only_folders:
return False
if filter_fn:
return filter_fn(item.path or '', dialog.get_file_postfix(), dialog.get_file_extension())
return True
def _save_default_settings(default_settings: Dict):
settings = carb.settings.get_settings()
default_settings_path = settings.get_as_string("/exts/omni.kit.window.file_importer/appSettings")
settings.set_string(f"{default_settings_path}/directory", default_settings['directory'] or "")
def on_import(import_fn: Callable[[str, str, List[str]], None], dialog: FilePickerDialog, filename: str, dirname: str, hide_window_on_import: bool = True):
_save_default_settings({'directory': dirname})
selections = dialog.get_current_selections() or []
if hide_window_on_import:
dialog.hide()
if import_fn:
import_fn(filename, dirname, selections=selections)
# Any class derived from `omni.ext.IExt` in top level module (defined in `python.modules` of `extension.toml`) will be
# instantiated when extension gets enabled and `on_startup(ext_id)` will be called. Later when extension gets disabled
# on_shutdown() is called.
class OrdinaryDepthmapProjectionExtension(omni.ext.IExt):
# ext_id is current extension id. It can be used with extension manager to query additional information, like where
# this extension is located on filesystem.
def on_startup(self, ext_id):
print("[ordinary.depthmap.projection] ordinary depthmap projection startup")
self.stage = omni.usd.get_context().get_stage()
self._window = ui.Window("Ordinary Depth Map Projection", width=300, height=300)
with self._window.frame:
with ui.VStack():
with ui.HStack():
def on_texture_click():
def import_handler(filename, dirname, selections = []):
self.texture_filename = os.path.join(dirname, filename)
self.texture_label.text = self.texture_filename
self.texture_dialog = FilePickerDialog(
'Select texture file',
apply_button_label = 'Open',
click_apply_handler = import_handler,
file_extension_options = DEFAULT_FILE_EXTENSION_TYPES
)
self.texture_dialog.set_item_filter_fn(partial(on_filter_item, default_filter_handler, self.texture_dialog, show_only_folders=False))
self.texture_dialog.set_click_apply_handler(partial(on_import, import_handler, self.texture_dialog, hide_window_on_import=True))
#self.texture_dialog._widget.file_bar.enable_apply_button(enable=show_only_folders)
self.texture_dialog.show()
self.texture_dialog._widget.file_bar.focus_filename_input()
ui.Button("Select Texture File", width=150, clicked_fn=on_texture_click)
self.texture_filename = ''
self.texture_label = ui.Label(self.texture_filename)
with ui.HStack():
def on_depthmap_click():
def import_handler(filename, dirname, selections = []):
self.depthmap_filename = os.path.join(dirname, filename)
self.depthmap_label.text = self.depthmap_filename
self.depthmap_dialog = FilePickerDialog(
'Select depthmap file',
apply_button_label = 'Open',
click_apply_handler = import_handler,
file_extension_options = DEFAULT_FILE_EXTENSION_TYPES
)
self.depthmap_dialog.set_item_filter_fn(partial(on_filter_item, default_filter_handler, self.depthmap_dialog, show_only_folders=False))
self.depthmap_dialog.set_click_apply_handler(partial(on_import, import_handler, self.depthmap_dialog, hide_window_on_import=True))
#self.depthmap_dialog._widget.file_bar.enable_apply_button(enable=show_only_folders)
self.depthmap_dialog.show()
ui.Button("Select Depth Map File", width=150, clicked_fn=on_depthmap_click)
self.depthmap_filename = ''
self.depthmap_label = ui.Label(self.depthmap_filename)
with ui.HStack():
def on_generate_click():
self.generate_new_mesh()
ui.Button("Generate", clicked_fn=on_generate_click)
def generate_new_mesh(self):
print("GENERATE", self.texture_filename, self.depthmap_filename)
# Create the mesh
xform = UsdGeom.Xform.Define(self.stage, "/my_plane")
mesh = UsdGeom.Mesh.Define(self.stage, xform.GetPath().AppendChild("mesh"))
mesh.CreateSubdivisionSchemeAttr().Set(UsdGeom.Tokens.none)
texture_image = Image.open(self.texture_filename)
texture_width, texture_height = texture_image.size
mesh_width = texture_width // 16
mesh_height = texture_height // 16
depthmap_image = Image.open(self.depthmap_filename)
# datatype is optional, but can be useful for type conversion
depthmap_data = np.asarray(depthmap_image, dtype=np.uint8)
depthmap_height, depthmap_width, depthmap_colors = depthmap_data.shape
points = []
normals = []
st = []
normal = (0, 1, 0)
vertex_counts = []
vertex_indicies = []
def clamp(value, min_value, max_value):
return max(min(int(value), max_value), min_value)
for y in range(mesh_height + 1):
for x in range(mesh_width + 1):
dmx = clamp(x / mesh_width * depthmap_width, 0, depthmap_width - 1)
dmy = clamp((mesh_height - y) / mesh_height * depthmap_height, 0, depthmap_height - 1)
distance = depthmap_data[dmy, dmx, 0] / 256 * mesh_height
points.append(Gf.Vec3f(x - mesh_width/2, y - mesh_height/2, distance))
for y in range(mesh_height):
for x in range(mesh_width):
vertex_counts.append(3)
vertex_indicies.append(y * (mesh_width + 1) + x) # LL
vertex_indicies.append(y * (mesh_width + 1) + x + 1) # LR
vertex_indicies.append((y + 1) * (mesh_width + 1) + x) # UL
st.append((x / mesh_width, y / mesh_height)) # LL
st.append(((x + 1) / mesh_width, y / mesh_height)) # LR
st.append((x / mesh_width, (y + 1) / mesh_height)) # UL
normals.append(normal)
normals.append(normal)
normals.append(normal)
vertex_counts.append(3)
vertex_indicies.append(y * (mesh_width + 1) + x + 1) # LR
vertex_indicies.append((y + 1) * (mesh_width + 1) + x + 1) # UR
vertex_indicies.append((y + 1) * (mesh_width + 1) + x) # UL
st.append(((x + 1) / mesh_width, y / mesh_height)) # LR
st.append(((x + 1) / mesh_width, (y + 1) / mesh_height)) # UR
st.append((x / mesh_width, (y + 1) / mesh_height)) # UL
normals.append(normal)
normals.append(normal)
normals.append(normal)
mesh.CreatePointsAttr(points)
mesh.CreateExtentAttr(UsdGeom.PointBased(mesh).ComputeExtent(mesh.GetPointsAttr().Get()))
mesh.CreateFaceVertexCountsAttr(vertex_counts)
mesh.CreateFaceVertexIndicesAttr(vertex_indicies)
mesh.CreateNormalsAttr(normals)
mesh.SetNormalsInterpolation(UsdGeom.Tokens.faceVarying)
primvar_api = UsdGeom.PrimvarsAPI(mesh.GetPrim())
primvar_api.CreatePrimvar('st', Sdf.ValueTypeNames.TexCoord2fArray, UsdGeom.Tokens.faceVarying).Set(st)
# Apply texture to the plane
material = UsdShade.Material.Define(self.stage, xform.GetPath().AppendChild("material"))
shader = UsdShade.Shader.Define(self.stage, material.GetPath().AppendChild("texture_shader"))
shader.CreateIdAttr("UsdPreviewSurface")
shader.CreateInput("diffuseColor", Sdf.ValueTypeNames.Color3f).Set((1.0, 1.0, 1.0))
shader.CreateInput("roughness", Sdf.ValueTypeNames.Float).Set(0.5)
shader.CreateInput("metallic", Sdf.ValueTypeNames.Float).Set(0.0)
diffuse_tx = UsdShade.Shader.Define(self.stage, material.GetPath().AppendChild("DiffuseColorTx"))
diffuse_tx.CreateIdAttr('UsdUVTexture')
diffuse_tx.CreateInput('file', Sdf.ValueTypeNames.Asset).Set(self.texture_filename)
diffuse_tx.CreateOutput('rgb', Sdf.ValueTypeNames.Float3)
shader.CreateInput("diffuseColor", Sdf.ValueTypeNames.Color3f).ConnectToSource(diffuse_tx.ConnectableAPI(), 'rgb')
material.CreateSurfaceOutput().ConnectToSource(shader.ConnectableAPI(), "surface")
#stInput = shader.CreateInput("st", Sdf.ValueTypeNames.TexCoord2fArray)
# Create a texture and connect it to the shader's diffuse color
#diffuseTexture = UsdShade.TextureInput(shader.CreateInput("diffuseColor", Sdf.ValueTypeNames.Color3f))
#diffuseTexture.SetTextureFile(texture_filename)
#stInput.ConnectToSource(diffuseTexture.GetOutput())
#material.CreateSurfaceOutput().ConnectToSource(shader.GetOutput("surface"))
#shader.CreateIdAttr("UsdUVTexture")
#shader.CreateInput("file", Sdf.ValueTypeNames.Asset).Set(self.texture_filename)
#st_input = material.CreateInput("st", Sdf.ValueTypeNames.TexCoord2fArray)
#shader_output = shader.CreateOutput("rgb", Sdf.ValueTypeNames.Float3)
#st_input.ConnectToSource(shader_output)
#shader_connection = material.CreateShaderIdAttr().ConnectToSource(shader.GetIdAttr())
material_binding = UsdShade.MaterialBindingAPI(mesh.GetPrim())
material_binding.Bind(material)
def on_shutdown(self):
print("[ordinary.depthmap.projection] ordinary depthmap projection shutdown")
| 12,030 | Python | 44.57197 | 159 | 0.621031 |
alankent/ordinary-depthmap-projection/exts/ordinary.depthmap.projection/ordinary/depthmap/projection/__init__.py | from .extension import *
| 25 | Python | 11.999994 | 24 | 0.76 |
alankent/ordinary-depthmap-projection/exts/ordinary.depthmap.projection/ordinary/depthmap/projection/tests/__init__.py | from .test_hello_world import * | 31 | Python | 30.999969 | 31 | 0.774194 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.