file_path
stringlengths 21
224
| content
stringlengths 0
80.8M
|
---|---|
timedomain-tech/Timedomain-Ai-Singer-Extension/exts/timedomain.ai.singer/timedomain/ai/singer/utils_io.py | import os
import omni.client
A2F_SERVER_TYPE = "omniverse:"
def is_ov_path(path):
return A2F_SERVER_TYPE in path
def path_join(root, fname):
if A2F_SERVER_TYPE in root:
return f"{root}/{fname}"
else:
return os.path.normpath(os.path.join(root, fname))
def is_folder(path):
result, entry = omni.client.stat(path)
# bitewise operation, folder flags is 4
return entry.flags & omni.client.ItemFlags.CAN_HAVE_CHILDREN
def is_valid_path(path):
result, entry = omni.client.stat(path)
return result == omni.client.Result.OK
def list_folder(path):
items = []
path = path.rstrip("/")
result, entries = omni.client.list(path)
if result != omni.client.Result.OK:
return items
for en in entries:
# Skip if it is a folder
if en.flags & omni.client.ItemFlags.CAN_HAVE_CHILDREN:
continue
name = en.relative_path
items.append(name)
return items
def read_file(fpath):
result, _str, bytes_data = omni.client.read_file(fpath)
if result != omni.client.Result.OK:
raise RuntimeError("Unable to read file: {}".format(fpath))
return bytes_data
def write_file(fpath, bytes_data):
result = omni.client.write_file(fpath, bytes_data)
if result != omni.client.Result.OK:
raise RuntimeError("Unable to write file: {}".format(fpath))
|
timedomain-tech/Timedomain-Ai-Singer-Extension/exts/timedomain.ai.singer/timedomain/ai/singer/styles.py | import os
import omni.ui as ui
from omni.ui import color as cl
ELEM_MARGIN = 4
BORDER_RADIUS = 4
VSPACING = ELEM_MARGIN * 2
RECORDER_BTN_WIDTH = 75
LABEL_WIDTH = 100
BTN_WIDTH = 40
BTN_HEIGHT = 16
WAVEFORM_HEIGHT = 22 * 2 + VSPACING + 10
ERROR_CLR = 0xCC7777FF
WARN_CLR = 0xCC77FFFF
KEYFRAME_CLR = 0xAAAA77FF
IMAGE_SIZE = 25
A2F_SERVER_TYPE = "omniverse:"
EXT_ROOT = os.path.normpath(os.path.join(os.path.dirname(os.path.abspath(__file__)), "../../../"))
DATA_PATH = os.path.join(EXT_ROOT, "icons")
PlayBtnStyle = {"image_url": DATA_PATH + "/timeline_play.svg"}
PauseBtnStyle = {"image_url": DATA_PATH + "/timeline_pause.svg"}
ComposeBtnStyle = {"image_url": DATA_PATH + "/timeline_loop.svg"}
LoadingBtnStyle = {"image_url": DATA_PATH + "/loading.gif"}
LocationBtnStyle = {"image_url": DATA_PATH + "/folder.svg"}
AUDIO_FILE_TYPES = [".ufdata"]
StringFieldStyle = {"margin_height": 0, "margin_width": ELEM_MARGIN, "border_radius": BORDER_RADIUS}
ComboBoxStyle = {"border_radius": BORDER_RADIUS + 2}
HandlePlaybackStyle = {"border_radius": 0, "background_color": 0xFFEEEE33}
HandleRecordingStyle = {"border_radius": 0, "background_color": 0xFF3333EE}
HandleStreamingStyle = {"border_radius": 0, "background_color": 0xFF33EE33}
TrackWaveformStyle = {"margin_height": 0, "margin_width": 0, "border_radius": 0}
RangeStartSpacerStyle = {"border_width": 0, "padding": 0, "border_radius": 0, "margin_width": 0}
BigLableStyle = {"font_size": 16, "color": 0xFFFFFFFF}
SmallLableStyle = {"font_size": 14, "color": 0xFF4B4B4B}
ScrollingFrameStyle = {"background_color": 0xFF323232}
MainWindowStyle = {
"Image::header_frame": {"image_url": DATA_PATH + "/head.png"},
"Line::group_line": {"color": cl("#4B4B4B"), "margin_height": 0, "padding": 0},
"Slider::float_slider": {
"background_color": cl("#FF3300"),
"secondary_color": cl("#24211F"),
"border_radius": 3,
"corner_flag": ui.CornerFlag.ALL,
"draw_mode": ui.SliderDrawMode.FILLED,
},
}
PlaybackSliderBackgroundStyle = {
"background_color": 0xFF24211F,
"margin_height": 0,
"margin_width": 0,
"border_radius": 0,
}
LargeBtnStyle = {
"border_radius": BORDER_RADIUS,
"border_width": 0,
"font_size": 14,
"padding": ELEM_MARGIN * 2,
"margin_width": ELEM_MARGIN,
"margin_height": ELEM_MARGIN,
}
FileBrowseBtnStyle = {
"image_url": DATA_PATH + "/folder.svg",
"background_color": 0xFF333333,
":hovered": {"background_color": 0xFF9E9E9E},
}
ModalBtnStyle = {
"border_radius": BORDER_RADIUS,
"border_width": 0,
"font_size": 14,
"padding": ELEM_MARGIN * 2,
"margin_width": ELEM_MARGIN,
"margin_height": ELEM_MARGIN,
}
TrashBtnStyle = {
"image_url": "${glyphs}/trash.svg",
"background_color": 0xFF333333,
":hovered": {"background_color": 0xFF9E9E9E},
":disabled": {"color": 0x60FFFFFF},
}
TrashDarkBtnStyle = {
"image_url": "${glyphs}/trash.svg",
":hovered": {"background_color": 0xFF9E9E9E},
":disabled": {"color": 0x60FFFFFF},
}
PlusBtnStyle = {
"image_url": "${glyphs}/plus.svg",
"background_color": 0xFF333333,
":hovered": {"background_color": 0xFF9E9E9E},
":disabled": {"color": 0x60FFFFFF},
}
PlusDarkBtnStyle = {
"image_url": "${glyphs}/plus.svg",
":hovered": {"background_color": 0xFF9E9E9E},
":disabled": {"color": 0x60FFFFFF},
}
PlusDarkExcitedBtnStyle = {
"image_url": "${glyphs}/plus.svg",
"color": WARN_CLR,
":hovered": {"background_color": 0xFF9E9E9E},
":disabled": {"color": 0x60FFFFFF},
}
MinusDarkBtnStyle = {
"image_url": "${omni_audio2face_common_resources}/minus.png",
":hovered": {"background_color": 0xFF9E9E9E},
":disabled": {"color": 0x60FFFFFF},
}
AngleLeftDarkBtnStyle = {
"image_url": "${glyphs}/angle_left.svg",
":hovered": {"background_color": 0xFF9E9E9E},
":disabled": {"color": 0x60FFFFFF},
}
AngleRightDarkBtnStyle = {
"image_url": "${glyphs}/angle_right.svg",
":hovered": {"background_color": 0xFF9E9E9E},
":disabled": {"color": 0x60FFFFFF},
}
FileBrowseBtnStyle = {
"image_url": "resources/glyphs/folder.svg",
"background_color": 0xFF333333,
":hovered": {"background_color": 0xFF9E9E9E},
}
RangeRectStyle = {
"background_color": 0x30BBAB58,
"padding": 0,
"margin_width": 0,
"margin_height": 0,
"border_radius": 0,
"border_color": 0x70BBAB58,
"border_width": 1,
}
RangeRectRecordingStyle = {
"background_color": 0x305858BB,
"padding": 0,
"margin_width": 0,
"margin_height": 0,
"border_radius": 0,
"border_color": 0x705858BB,
"border_width": 1,
}
RangeRectStreamingStyle = {
"background_color": 0x3058BB58,
"padding": 0,
"margin_width": 0,
"margin_height": 0,
"border_radius": 0,
"border_color": 0x7058BB58,
"border_width": 1,
}
|
timedomain-tech/Timedomain-Ai-Singer-Extension/exts/timedomain.ai.singer/timedomain/ai/singer/extension.py | from .styles import VSPACING, BigLableStyle, MainWindowStyle
from .ui import (
WAVEFORM_HEIGHT,
ButtonComposing,
ButtonLocation,
ButtonPlayPause,
CategoricalSettingWidgetWithReset,
PathWidgetWithReset,
FemaleEntertainerWidger,
TimecodeWidget,
TimelineWidget,
)
import omni.ext
import omni.ui as ui
import omni.client
class MyExtension(omni.ext.IExt):
def on_startup(self, ext_id):
print("[timedomain.ai.singer] MyExtension startup")
self._window = ui.Window("TIMEDOMAIN AI SINGER", width=840, height=650)
self._window.frame.set_build_fn(self.show_window)
self._window.frame.style = MainWindowStyle
def on_shutdown(self):
print("[timedomain.ai.singer] MyExtension shutdown")
self._root_path_widget = None
self._track_widget = None
self._range_widget = None
self.frame = None
self._btn_loop = None
self._timecode_widget.shutdown()
self._timecode_widget = None
self._btn_play.shutdown()
self._btn_play = None
self._timeline_widget.shutdown()
self._timeline_widget = None
self._btn_recorder = None
if self._window:
self._window.destroy()
self._window = None
def show_window(self):
with self._window.frame:
with ui.VStack(spacing=10):
self._root_path_widget = PathWidgetWithReset()
self._root_path_widget._build_content()
self._track_widget = CategoricalSettingWidgetWithReset()
self._track_widget._build_content()
with ui.VStack(height=5):
ui.Line(name="group_line", alignment=ui.Alignment.CENTER)
self.frame = FemaleEntertainerWidger()
self.frame._build_glyph()
with ui.HStack(height=0):
ui.Line(name="group_line", alignment=ui.Alignment.CENTER)
with ui.VStack(height=20):
ui.Label("Mix Your Voice Style", style=BigLableStyle)
self.frame._build_content()
self._btn_loop = ButtonComposing()
self._btn_loop._build_widget()
with ui.HStack(height=WAVEFORM_HEIGHT):
self._timeline_widget = TimelineWidget()
self._timeline_widget._build_content()
ui.Spacer(width=4)
with ui.VStack(spacing=VSPACING, width=0):
self._timecode_widget = TimecodeWidget()
self._timecode_widget._build_content()
with ui.HStack():
self._btn_play = ButtonPlayPause()
self._btn_play._build_content()
self._btn_recorder = ButtonLocation()
self._btn_recorder._build_widget()
|
timedomain-tech/Timedomain-Ai-Singer-Extension/exts/timedomain.ai.singer/timedomain/ai/singer/__init__.py | from .extension import *
|
timedomain-tech/Timedomain-Ai-Singer-Extension/exts/timedomain.ai.singer/timedomain/ai/singer/settings.py | from typing import TypeVar
from pxr import Sdf
SettingType = TypeVar("SettingType", bound="SettingItem")
class SettingItem:
_val = None
_filename = None
_state = None
_mix_info = {
"duration": [],
"pitch": [],
"air": [],
"falsetto": [],
"tension": [],
"energy": [],
"mel": [],
}
def __init__(self, name):
self._name = name
self._init_fn = None
self._changed_fn = None
self._prim = None
self._default_val = None
self._org_default_val = None
self._initialized = False
def shutdown(self):
self._prim = None
def init(self, default_val=None, init_fn=None, changed_fn=None, prim=None):
self._init_fn = init_fn
self._changed_fn = changed_fn
self._prim = prim
self._default_val = self._check(default_val)
self._org_default_val = self._default_val
SettingItem._val = self._default_val # Required if set_val(val) will fail
if self._prim is not None and self._prim.HasAttribute(self.get_usd_attr_name()):
val = self._prim.GetAttribute(self.get_usd_attr_name()).Get()
else:
val = self._default_val
self.set_val(val, use_callback=True, use_init_fn=True)
self._initialized = True
def initialized(self):
return self._initialized
def get_name(self):
return self._name
def get_ui_name(self):
return self._name.replace("_", " ").title()
def get_usd_attr_name(self):
return f"state:setting_{self._name}"
def get_val(self):
if SettingItem._filename is not None:
SettingItem._state = False
return SettingItem._val
def get_default(self):
return self._default_val
def is_default(self):
return SettingItem._val == self._default_val
def set_val(self, val, use_callback=True, use_init_fn=False):
# val_checked = self._check(val)
# callback_fn = self._init_fn if use_init_fn else self._changed_fn
# val_prev = SettingItem._val
SettingItem._val = val
# if use_callback and callback_fn is not None:
# try:
# callback_fn(val_checked)
# except Exception as e:
# SettingItem._val = val_prev
# print(e)
# raise
# self._update_usd_prim_attr()
def set_default(self, default_val):
self._default_val = self._check(default_val)
def reset_default(self):
self._default_val = self._get_safe_default()
def reset(self):
self.set_val(self._default_val, use_callback=True, use_init_fn=False)
def get_usd_type(self):
raise NotImplementedError
def get_arr_usd_type(self):
raise NotImplementedError # Should be implemented in derived class
def to_arr_usd_data(self, arr):
raise NotImplementedError # Should be implemented in derived class
def from_arr_usd_data(self, arr, arr_len):
raise NotImplementedError # Should be implemented in derived class
def interpolate(self, val1, val2, alpha):
raise NotImplementedError # Should be implemented in derived class
def _update_usd_prim_attr(self):
if self._prim is not None and self._prim.IsValid():
if SettingItem._val is not None:
self._prim.CreateAttribute(self.get_usd_attr_name(), self.get_usd_type()).Set(SettingItem._val)
def _check(self, val):
return val
class CategoricalSetting(SettingItem):
def __init__(self, name, options=[], value=None):
self.options = options
self._value = value
super().__init__(name)
def init(self, default_val, init_fn, changed_fn, prim):
super().init(default_val, init_fn, changed_fn, prim)
def get_options(self):
if len(self._options) > 0:
SettingItem._filename = self._options[0]
return self._options
def set_options_and_keep(self, options):
self._options = options
# if SettingItem._val not in self._options:
# # log_warn(
# # f"Setting [{self.get_name()}]: Old value [{self._val}]
# # is not in the new list [{self._options}], resetting to default"
# # )
# self.reset_default()
# self.reset()
def set_options_and_reset(self, options):
self._options = options
self.reset_default()
self.reset()
def set_value(self, val):
self._value = val
SettingItem._filename = val
SettingItem._state = False
def get_value(self):
return self._value
def set_options_and_val(self, options, val):
self._options = options
self.reset_default()
self.set_value(val, use_callback=True, use_init_fn=False)
def get_index(self):
if self._value is not None:
BoolSetting._filename = self._value
return self._options.index(self._value)
else:
return None
def set_index(self, val_index):
val = self._options[val_index]
self.set_value(val)
def get_usd_type(self):
return Sdf.ValueTypeNames.String
def get_arr_usd_type(self):
return Sdf.ValueTypeNames.StringArray
def to_arr_usd_data(self, arr):
return list(arr)
def from_arr_usd_data(self, arr, arr_len):
return list(arr)
def interpolate(self, val1, val2, alpha):
return val1
def _get_safe_default(self):
if len(self._options) > 0:
return self._options[0]
else:
return None
def _check(self, val):
if val is None:
return self._get_safe_default()
if val not in self._options:
raise AttributeError(
f"Setting [{self.get_name()}]: value '{val}' is not in the list of options {self._options}"
)
return val
class BoolSetting(SettingItem):
def __init__(self, name):
super().__init__(name)
def init(self, default_val, init_fn, changed_fn, prim):
super().init(default_val, init_fn, changed_fn, prim)
def get_usd_type(self):
return Sdf.ValueTypeNames.Bool
def get_arr_usd_type(self):
return Sdf.ValueTypeNames.BoolArray
def to_arr_usd_data(self, arr):
return list(arr)
def from_arr_usd_data(self, arr, arr_len):
return list(arr)
def interpolate(self, val1, val2, alpha):
return val1
def toggle(self, use_callback=True):
pass
def get_state(self):
return SettingItem._state
def _get_safe_default(self):
return False
def _check(self, val):
if val is None:
return self._get_safe_default()
return bool(val)
|
timedomain-tech/Timedomain-Ai-Singer-Extension/exts/timedomain.ai.singer/timedomain/ai/singer/ui.py | import os
import pathlib
import json
import omni.kit.pipapi
from .scripts.ui import BoolSettingWidgetBase, SimpleWidget
from threading import Thread
from .styles import (
A2F_SERVER_TYPE,
AUDIO_FILE_TYPES,
BTN_HEIGHT,
BTN_WIDTH,
DATA_PATH,
EXT_ROOT,
LABEL_WIDTH,
WAVEFORM_HEIGHT,
ComboBoxStyle,
FileBrowseBtnStyle,
HandlePlaybackStyle,
HandleRecordingStyle,
HandleStreamingStyle,
BigLableStyle,
LargeBtnStyle,
LocationBtnStyle,
PauseBtnStyle,
PlayBtnStyle,
PlaybackSliderBackgroundStyle,
RangeRectRecordingStyle,
RangeRectStreamingStyle,
RangeRectStyle,
RangeStartSpacerStyle,
ScrollingFrameStyle,
SmallLableStyle,
StringFieldStyle,
TrackWaveformStyle,
)
from .instance import InstanceManagerBase
import omni.client
import omni.ui as ui
import numpy as np
import scipy.ndimage
os.environ["PATH"] += os.pathsep + os.path.join(EXT_ROOT, "dep/ffmpeg")
omni.kit.pipapi.install("pydub")
omni.kit.pipapi.install("requests")
from pydub import AudioSegment
import requests
from .requestData import GetData
class PathWidgetWithReset(InstanceManagerBase):
def __init__(self):
super().__init__()
self._lbl = None
self._field_model = None
self._field = None
self._browse_btn = None
self._browse_dialog = None
def _on_browse_selected(self, filename, dirname):
if self._field is not None:
self._settings.set_val(dirname, use_callback=True)
if self._browse_dialog is not None:
self._browse_dialog.hide()
self._field_model.set_value(self._settings.get_val())
def _on_browse_canceled(self, filename, dirname):
if self._browse_dialog is not None:
self._browse_dialog.hide()
def _on_browse(self):
if self._browse_dialog is None:
self._browse_dialog = omni.kit.window.filepicker.FilePickerDialog(
"Select Audio Directory",
allow_multi_selection=False,
apply_button_label="Select",
click_apply_handler=self._on_browse_selected,
click_cancel_handler=self._on_browse_canceled,
current_directory=str(pathlib.Path.home()),
enable_filename_input=False,
)
else:
self._browse_dialog.show()
self._browse_dialog.refresh_current_directory()
def _on_changed(self, val):
self._settings.set_val(val, use_callback=True)
self._field_model.set_value(self._settings.get_val())
def _on_begin_edit(self, *_):
pass
def _build_content(self):
with ui.VStack(height=28):
ui.Label("Import Your Score", style=BigLableStyle)
ui.Label("Support format: ufdata", style=SmallLableStyle)
with ui.HStack(height=20):
ui.Label("Score Root Path", width=LABEL_WIDTH)
value = self._settings.get_val()
self._field_model = StringFieldModel(value, self._on_changed)
self._field_model.add_begin_edit_fn(self._on_begin_edit)
self._field_model.set_value(self._settings.get_val())
self._field = ui.StringField(self._field_model, style=StringFieldStyle)
self._browse_btn = ui.Button(
width=BTN_WIDTH, image_height=BTN_HEIGHT, style=FileBrowseBtnStyle, clicked_fn=self._on_browse
)
class CategoricalSettingWidgetWithReset(InstanceManagerBase):
def __init__(self):
super().__init__()
self._lbl = None
self._combo_model = None
self._combo = None
self._update_sub = omni.kit.app.get_app().get_update_event_stream().create_subscription_to_pop(self._on_update)
self._frame = None
def shutdown(self):
self._update_sub = None
self._lbl = None
if self._combo_model is not None:
self._combo_model.shutdown()
self._combo_model = None
self._combo = None
super().shutdown()
def _build_content(self):
self._frame = ui.HStack(height=20)
with self._frame:
self._lbl = ui.Label("Score Name", width=LABEL_WIDTH)
# # options: 列表数组
tracks = self._load_track_list(self.get_abs_track_root_path())
self._setting.set_options_and_keep(tracks)
options = self._setting.get_options()
cur_option = self._setting.get_index()
self._combo_model = ComboBoxMinimalModel(options, cur_option, self._on_changed)
if len(self._setting.get_options()) == 0 or self._setting.get_val() is None:
self._combo = None
ui.Label("No options")
else:
self._combo = ui.ComboBox(self._combo_model, style=ComboBoxStyle)
def _on_changed(self, val_index):
self._setting.set_index(val_index)
def _on_update(self, *_):
if self.get_abs_track_root_path():
tracks = self._load_track_list(self.get_abs_track_root_path())
if tracks != self._setting.get_options():
self._setting.set_options_and_keep(tracks)
if self._combo_model is not None:
if self._setting.get_val() is not None:
self._combo_model.set_index(self._setting.get_index())
if self._combo_model.get_options() != self._setting.get_options():
self._refresh()
def _load_track_list(self, path: str):
# path = path.replace("\\", "/")
if not self.is_folder(path):
print(f"Unable to load list of tracks from {path}")
return []
dir_files = self.list_folder(path)
return [x for x in dir_files if (os.path.splitext(x)[1] in AUDIO_FILE_TYPES)]
def is_folder(self, path):
result, entry = omni.client.stat(path)
# bitewise operation, folder flags is 4
return entry.flags & omni.client.ItemFlags.CAN_HAVE_CHILDREN
def list_folder(self, path):
items = []
# rstrip() 删除 string 字符串末尾的指定字符,默认为空白符,包括空格、换行符、回车符、制表符。
# path = path.rstrip("/")
result, entries = omni.client.list(path)
if result != omni.client.Result.OK:
return items
for en in entries:
# Skip if it is a folder
if en.flags & omni.client.ItemFlags.CAN_HAVE_CHILDREN:
continue
name = en.relative_path
items.append(name)
return items
def is_ov_path(path):
return A2F_SERVER_TYPE in path
def get_abs_track_root_path(self):
"""normpath if it is local path
for ov path not apply normpath
"""
path = self._setting.get_val()
# path = self._setting._val
# if not self.is_ov_path(path):
# if not os.path.isabs(path):
# path = os.path.abspath(os.path.join(PLAYER_DEPS_ROOT, path))
# return os.path.normpath(path).replace("\\", "/")
return path
def _changed_fn(self, model):
index = model.as_int
self._item_changed(None)
if not self._from_set_index:
if self._changed_callback_fn is not None:
self._changed_callback_fn(index)
def _build_content_wrapper(self): # Required for extra UI wrapers in intermediate dervied classes
self._build_content()
def _refresh(self):
if self._frame is not None:
self._frame.clear()
with self._frame:
self._build_content_wrapper()
class StringFieldModel(ui.AbstractValueModel):
def __init__(self, initial_value, changed_callback_fn=None):
super().__init__()
self._value = initial_value
self._changed_callback_fn = changed_callback_fn
self.add_end_edit_fn(self._end_edit_fn)
def shutdown(self):
self._changed_callback_fn = None
def get_value(self):
return self._value
def get_value_as_string(self):
return str(self._value)
def set_value(self, value):
self._value = value
self._value_changed()
def _end_edit_fn(self, model):
value = model.get_value()
if self._changed_callback_fn is not None:
self._changed_callback_fn(value)
class ComboBoxMinimalItem(ui.AbstractItem):
def __init__(self, text):
super().__init__()
self.model = ui.SimpleStringModel(text)
class ComboBoxMinimalModel(ui.AbstractItemModel):
def __init__(self, options, initial_index, changed_callback_fn=None):
super().__init__()
self._options = options
self._changed_callback_fn = changed_callback_fn
self._items = [ComboBoxMinimalItem(text) for text in self._options]
self._current_index = ui.SimpleIntModel()
if initial_index is not None:
self._current_index.as_int = initial_index
self._from_set_index = False
self._current_index.add_value_changed_fn(self._changed_fn)
def shutdown(self):
self._changed_callback_fn = None
self._current_index = None
self._items = None
def get_options(self):
return self._options
def get_item_children(self, item):
return self._items
def get_item_value_model(self, item, column_id):
if item is None:
return self._current_index
return item.model
def get_index(self):
return self._current_index.as_int
def set_index(self, index):
if index is not None:
if index >= 0 and index < len(self._items):
self._from_set_index = True
self._current_index.as_int = index
self._from_set_index = False
def _changed_fn(self, model):
index = model.as_int
self._item_changed(None)
if not self._from_set_index:
if self._changed_callback_fn is not None:
self._changed_callback_fn(index)
class FemaleEntertainerWidger(InstanceManagerBase):
list_array_name = []
list_array_id = []
list_array_float = []
list_array_avatar = []
def __init__(self):
self._btn_create_timedomain_pipeline = None
self._btn_create_audio_palyer = None
self._btn_create_a2f_core = None
self._btn_create_head_template = None
self._frame = None
self._female_entertainer_data = None
self._id = None
def shutdown(self):
self._btn_create_timedomain_pipeline = None
self._btn_create_audio_palyer = None
self._btn_create_a2f_core = None
self._btn_create_head_template = None
self._frame = None
self._female_entertainer_data = None
self._id = None
def _add_menu_item(self, *args, **kwargs):
editor_menu = omni.kit.ui.get_editor_menu()
self._menu_items.append(editor_menu.add_item(*args, **kwargs))
def _build_content(self):
if self._frame is None:
self._frame = ui.ScrollingFrame(height=ui.Percent(35), style=ScrollingFrameStyle)
self._frame.set_build_fn(self._build_fn)
self._frame.rebuild()
def _build_fn(self):
with self._frame:
with ui.VStack(spacing=5):
sliders = [self.create_ui_float_slider(i) for i in range(len(FemaleEntertainerWidger.list_array_name))]
if len(FemaleEntertainerWidger.list_array_name) > 0:
for i in range(len(FemaleEntertainerWidger.list_array_name)):
with ui.HStack(height=25):
IMAGE = FemaleEntertainerWidger.list_array_avatar[i]
ui.Image(IMAGE, width=25, height=25)
ui.Label(
f"{FemaleEntertainerWidger.list_array_name[i]}",
width=ui.Percent(8),
name="text",
)
sliders[i]()
else:
ui.Label("No Voiceseed Selected", alignment=ui.Alignment.CENTER)
def _build_glyph(self):
self._request_female_entertainer_data()
with ui.VStack(height=28):
ui.Label("Choose Your Voice Style (up to 10)", style=BigLableStyle)
ui.Label("Choose one or more voiceseeds to mix a voice", style=SmallLableStyle)
with ui.ScrollingFrame(height=ui.Percent(15)):
with ui.VGrid(column_width=200):
glyph_plus = ui.get_custom_glyph_code("${glyphs}/plus.svg")
if isinstance(self._female_entertainer_data["data"], list):
functions = [
self.create_female_entertainer_clicked(i) for i in range(len(self._female_entertainer_data["data"]))
]
for index in range(len(self._female_entertainer_data["data"])):
_name = self._female_entertainer_data["data"][index]["name_chn"]
_tooltip = self._female_entertainer_data["data"][index]["characteristic"]
with ui.HStack():
ui.Button(
f"{_name} {glyph_plus}",
style=LargeBtnStyle,
clicked_fn=functions[index],
tooltip=_tooltip
)
def _refresh(self):
if self._frame is not None:
self._frame.rebuild()
def _build_content_wrapper(self): # Required for extra UI wrapers in intermediate dervied classes
self._build_content()
def create_ui_float_slider(self, index):
def set_value(value, index):
value = round(value, 2)
FemaleEntertainerWidger.list_array_float[index] = value
def _delete_avatar():
del FemaleEntertainerWidger.list_array_name[index]
del FemaleEntertainerWidger.list_array_id[index]
del FemaleEntertainerWidger.list_array_avatar[index]
del FemaleEntertainerWidger.list_array_float[index]
self._refresh()
def _click_get_model_value():
IMAGE_DELETE = DATA_PATH + "/delete.svg"
slider = ui.FloatSlider(name="float_slider", min=0, max=1).model
slider.set_value(0.5)
FemaleEntertainerWidger.list_array_float[index] = 0.5
slider.add_value_changed_fn(lambda m: set_value(m.get_value_as_float(), index))
ui.Button(width=25, height=25, image_url=IMAGE_DELETE, clicked_fn=_delete_avatar)
return _click_get_model_value
def create_female_entertainer_clicked(self, index):
name = self._female_entertainer_data["data"][index]["name_chn"]
id = self._female_entertainer_data["data"][index]["id"]
avatar = self._female_entertainer_data["data"][index]["avatar"]
def _on_btn_create_female_entertainer_clicked():
if name not in FemaleEntertainerWidger.list_array_name:
FemaleEntertainerWidger.list_array_name.append(name)
FemaleEntertainerWidger.list_array_id.append(id)
FemaleEntertainerWidger.list_array_avatar.append(avatar)
FemaleEntertainerWidger.list_array_float.append([])
self._refresh()
return _on_btn_create_female_entertainer_clicked
def _request_female_entertainer_data(self):
self._female_entertainer_data = GetData._get_female_entertainer_data()
def _get_female_data():
_array = []
for i in range(len(FemaleEntertainerWidger.list_array_name)):
_array.append([])
_array[i] = [FemaleEntertainerWidger.list_array_id[i], FemaleEntertainerWidger.list_array_float[i]]
return _array
class ScalarSliderModel(ui.AbstractValueModel):
def __init__(self, initial_value, min_val, max_val, changed_callback_fn=None, fast_change=True):
super().__init__()
self._value = initial_value
self._min_val = min_val
self._max_val = max_val
self._changed_callback_fn = changed_callback_fn
self._fast_change = fast_change
if not self._fast_change:
self.add_end_edit_fn(self._end_edit_fn)
def shutdown(self):
self._changed_callback_fn = None
def get_value(self):
return self._value
def get_min(self):
return self._min_val
def get_max(self):
return self._max_val
def get_value_as_int(self):
return int(self._value)
def get_value_as_float(self):
return float(self._value)
def set_value(self, value):
self._value = value
self._value_changed()
if self._fast_change and self._changed_callback_fn is not None:
self._changed_callback_fn(self._value)
def set_field(self, value):
if value is not None:
self._value = value
self._value_changed()
def _end_edit_fn(self, model):
value = model.get_value()
if self._changed_callback_fn is not None:
self._changed_callback_fn(value)
class WaveformWidget(SimpleWidget):
def __init__(self, height):
super().__init__()
self._height = height
self._waveform_image_provider = None
self._waveform_image = None
self._canvas = None
self._canvas_width = 1024
self._canvas_height = WAVEFORM_HEIGHT
def shutdown(self):
self._waveform_image_provider = None
self._waveform_image = None
self._canvas = None
super().shutdown()
def update_track_waveform(self, track):
num_samples = track.get_num_samples()
width, height = self._canvas_width, self._canvas_height
ex_factor = 1
width_ex = width * ex_factor
shrink_factor = max(num_samples // width_ex, 1)
if 0:
volume = np.abs(track.data[::shrink_factor][:width_ex])
else:
if num_samples >= shrink_factor * width_ex:
volume = track.data[: shrink_factor * width_ex].reshape(width_ex, shrink_factor)
else:
tmp = np.zeros((shrink_factor * width_ex), np.float32)
tmp[:num_samples] = track.data
volume = tmp.reshape(width_ex, shrink_factor)
volume = np.abs(np.max(volume, axis=1))
# volume /= max(np.max(volume), 1e-8)
# dB logarithmic scale
if 0:
volume = np.maximum(volume, 1e-6)
volume = 20.0 * np.log10(volume / 1.0)
# [-50, 0] dB
volume = np.maximum((volume / 50.0) + 1.0, 0.0)
volume *= 0.7
canvas = np.zeros((height, width_ex, 4), dtype=np.uint8)
print("canvas.shape[1]======>", canvas.shape[1])
for x in range(canvas.shape[1]):
start = int(round((1.0 - volume[x]) * float(height) / 2))
end = int(round((1.0 + volume[x]) * float(height) / 2))
canvas[start:end, x, :] = [255, 255, 255, 130]
if start == end:
canvas[start: end + 1, x, :] = [255, 255, 255, 60]
if ex_factor > 1:
canvas = scipy.ndimage.zoom(canvas.astype(np.float32), (1, 1.0 / ex_factor, 1), order=1).astype(np.uint8)
self._canvas = canvas.flatten().tolist()
if self._waveform_image_provider is not None:
self._waveform_image_provider.set_bytes_data(self._canvas, [self._canvas_width, self._canvas_height])
def _build_content(self):
self._waveform_image_provider = ui.ByteImageProvider()
if self._canvas is not None:
self._waveform_image_provider.set_bytes_data(self._canvas, [self._canvas_width, self._canvas_height])
with ui.HStack():
self._waveform_image = ui.ImageWithProvider(
self._waveform_image_provider,
height=self._height,
style=TrackWaveformStyle,
fill_policy=ui.IwpFillPolicy.IWP_STRETCH,
)
class TimelineRangeWidget(InstanceManagerBase):
def __init__(self, height):
super().__init__()
self._height = height
self._rect_range_start = None
self._rect_range = None
def shutdown(self):
self._rect_range_start = None
self._rect_range = None
super().shutdown()
def set_rect_style(self, style):
if self._rect_range is not None:
self._rect_range.set_style(style)
def update_range_rect(self, range_start, range_end, track_len):
if self._rect_range_start is not None and self._rect_range is not None:
if track_len == 0:
start_perc = 0
rect_perc = 0
else:
start_perc = range_start / track_len * 100.0
rect_perc = (range_end - range_start) / track_len * 100.0
self._rect_range_start.width = ui.Percent(start_perc)
self._rect_range.width = ui.Percent(rect_perc)
def _build_content(self):
with ui.HStack(height=self._height):
self._rect_range_start = ui.Spacer(width=omni.ui.Percent(0), style=RangeStartSpacerStyle)
self._rect_range = ui.Rectangle(width=omni.ui.Percent(100), height=self._height, style=RangeRectStyle)
class PlaybackSliderWidget(SimpleWidget):
def __init__(self, height, on_changed_fn=None, on_changed_from_mouse_fn=None):
super().__init__()
self._height = height
self._on_changed_fn = on_changed_fn
self._on_changed_from_mouse_fn = on_changed_from_mouse_fn
self._max_value = 0.001
self._value = 0.0
self._handle_width = 1
self._pressed = False
self._mouse_catcher = None
self._slider_placer = None
self._handle = None
self._update_sub = omni.kit.app.get_app().get_update_event_stream().create_subscription_to_pop(self._on_update)
def shutdown(self):
self._update_sub = None
self._on_changed_fn = None
self._on_changed_from_mouse_fn = None
self._max_value = 0.001
self._value = 0.0
self._pressed = False
self._mouse_catcher = None
self._slider_placer = None
self._handle = None
super().shutdown()
def set_value(self, value):
if self._pressed:
return # pressed mouse overrides external change of the value
self._value = value
if self._value < 0.0:
self._value = 0.0
elif self._value > self._max_value:
self._value = self._max_value
if self._on_changed_fn is not None:
self._on_changed_fn(self._value)
if self._max_value > 0:
rel_x_perc = self._value / self._max_value
self._set_slider_position(rel_x_perc)
elif self._max_value == 0:
self._set_slider_position(0)
def get_value(self):
return self._value
def set_max(self, max_value):
if max_value < 0:
raise ValueError("Playback Slider max value can't be less than zero")
self._max_value = max_value if max_value > 0 else 0.001
def set_handle_style(self, style):
if self._handle is not None:
self._handle.set_style(style)
def _set_slider_position(self, rel_x_perc):
if self._slider_placer is not None:
self._slider_placer.offset_x = ui.Percent(rel_x_perc * 100.0)
def _on_mouse_moved(self, x, y, _, btn):
if btn is True:
self._update_from_mouse(x)
def _on_mouse_pressed(self, x, y, btn, *args):
if btn == 0:
self._pressed = True
self._update_from_mouse(x)
def _on_mouse_released(self, x, y, btn, *args):
if btn == 0:
self._pressed = False
def _update_from_mouse(self, x):
if self._mouse_catcher is not None and self._slider_placer is not None:
rel_x = x - self._mouse_catcher.screen_position_x
if rel_x < 0:
rel_x = 0
elif rel_x >= self._mouse_catcher.computed_width:
rel_x = self._mouse_catcher.computed_width
rel_x_perc = rel_x / self._mouse_catcher.computed_width
self._set_slider_position(rel_x_perc)
self._value = self._max_value * rel_x_perc
if self._on_changed_fn is not None:
self._on_changed_fn(self._value)
def _build_content(self):
with ui.ZStack():
self._mouse_catcher = ui.Rectangle(
height=self._height,
style={
"background_color": 0x0,
"padding": 0,
"margin_width": 0,
"margin_height": 0,
"border_radius": 0,
"border_color": 0x0,
"border_width": 0,
},
mouse_moved_fn=self._on_mouse_moved,
mouse_pressed_fn=self._on_mouse_pressed,
mouse_released_fn=self._on_mouse_released,
)
with ui.HStack():
self._slider_placer = ui.Placer(draggable=False, stable_size=True)
with self._slider_placer:
with ui.HStack():
self._handle = ui.Rectangle(
width=self._handle_width, height=self._height, style=HandlePlaybackStyle
)
ui.Spacer()
def _on_update(self, *_):
if self._pressed:
if self._on_changed_from_mouse_fn is not None:
self._on_changed_from_mouse_fn(self._value)
class TimelineWidget(BoolSettingWidgetBase):
_frame = None
def __init__(self):
super().__init__()
self._waveform_widget = WaveformWidget(height=WAVEFORM_HEIGHT)
self._timeline_range_widget = TimelineRangeWidget(height=WAVEFORM_HEIGHT)
self._playback_slider_widget = PlaybackSliderWidget(
height=WAVEFORM_HEIGHT, on_changed_fn=None, on_changed_from_mouse_fn=self._on_changed
)
self._update_sub = omni.kit.app.get_app().get_update_event_stream().create_subscription_to_pop(self._on_update)
def shutdown(self):
self._update_sub = None
self._waveform_widget.shutdown()
self._waveform_widget = None
self._timeline_range_widget.shutdown()
self._timeline_range_widget = None
self._playback_slider_widget.shutdown()
self._playback_slider_widget = None
# super().shutdown()
def set_style(self, style):
if style == "regular":
self._playback_slider_widget.set_handle_style(HandlePlaybackStyle)
self._timeline_range_widget.set_rect_style(RangeRectStyle)
elif style == "streaming":
self._playback_slider_widget.set_handle_style(HandleStreamingStyle)
self._timeline_range_widget.set_rect_style(RangeRectStreamingStyle)
elif style == "recording":
self._playback_slider_widget.set_handle_style(HandleRecordingStyle)
self._timeline_range_widget.set_rect_style(RangeRectRecordingStyle)
def update_track_waveform(self):
track = self._audio_player.get_track_ref()
self._waveform_widget.update_track_waveform(track)
def _build_content(self):
TimelineWidget._frame = ui.ZStack()
with TimelineWidget._frame:
ui.Rectangle(style=PlaybackSliderBackgroundStyle)
self._waveform_widget._build_content()
self._timeline_range_widget._build_content()
self._playback_slider_widget._build_content()
def _refresh(self):
if TimelineWidget._frame is not None:
TimelineWidget._frame.clear()
with TimelineWidget._frame:
self._build_content_wrapper()
def _build_content_wrapper(self): # Required for extra UI wrapers in intermediate dervied classes
self._build_content()
def _on_changed(self, t):
if self._track is not None:
track_len = self._track.get_length()
self._playback_slider_widget.set_max(track_len)
self._playback_slider_widget.set_value(t)
seek_sample = self._track.sec_to_sample(t)
self._audio_player.seek(seek_sample)
def _on_update(self, *_):
if self._track is not None and self._audio_player is not None:
self._pressed = False
track_len = self._track.get_length()
self._playback_slider_widget.set_max(track_len)
t = self._audio_player.get_current_time()
self._playback_slider_widget.set_value(t)
# if t == track_len and not self.boolSetting._state:
# self.boolSetting._state = True
# self._on_toggled()
class TimecodeWidget(BoolSettingWidgetBase):
def __init__(self):
super().__init__()
self.ts = None
self._timecode_lbl = None
self._timecode_tms_lbl = None
self._timecode_max_lbl = None
self._timecode_max_tms_lbl = None
self._button_play_pause = ButtonPlayPause()
self._update_sub = omni.kit.app.get_app().get_update_event_stream().create_subscription_to_pop(self._on_update)
def shutdown(self):
self.ts = None
self._update_sub = None
self._timecode_lbl = None
self._timecode_tms_lbl = None
self._timecode_max_lbl = None
self._timecode_max_tms_lbl = None
# super().shutdown()
def _build_content(self):
with ui.HStack(height=22, style={"margin_width": 0}):
ui.Spacer()
self._timecode_lbl = ui.Label("0:00", width=0)
self._timecode_tms_lbl = ui.Label(".00", width=0, style={"color": 0x50FFFFFF})
ui.Label(" | ", style={"color": 0x70FFFFFF})
self._timecode_max_lbl = ui.Label("0:00", width=0)
self._timecode_max_tms_lbl = ui.Label(".00", width=0, style={"color": 0x50FFFFFF})
ui.Spacer()
def _set_timecode(self, t, m_sec_lbl, tms_lbl):
tmss = int(round(t * 100))
secs = tmss // 100
mins = secs // 60
secs_sub = secs % 60
tmss_sub = tmss % 100
m_sec_lbl.text = "{}:{:02d}".format(mins, secs_sub)
tms_lbl.text = ".{:02d}".format(tmss_sub)
if self.ts is not None and t == self.ts:
self._button_play_pause._update_from_state(is_playing=False)
else:
self.ts = t
def _on_update(self, *_):
if self._timecode_lbl is not None and self._timecode_tms_lbl is not None:
t = self._audio_player.get_current_time()
self._set_timecode(t, self._timecode_lbl, self._timecode_tms_lbl)
if self._timecode_max_lbl is not None and self._timecode_max_tms_lbl is not None and self._track is not None:
track_len = self._track.get_length()
self._set_timecode(track_len, self._timecode_max_lbl, self._timecode_max_tms_lbl)
class ButtonPlayPause(BoolSettingWidgetBase):
_btn = None
def __init__(self):
super().__init__()
def shutdown(self):
ButtonPlayPause._btn = None
super().shutdown()
def _build_widget(self):
with ui.HStack(width=BTN_WIDTH, height=30):
ButtonPlayPause._btn = ui.Button(width=BTN_WIDTH, style=PlayBtnStyle, tooltip="Play/Pause (P)")
ButtonPlayPause._btn.set_clicked_fn(self._on_toggled)
def _update_from_state(self, is_playing):
if ButtonPlayPause._btn is not None:
if is_playing is True:
ButtonPlayPause._btn.set_style(PauseBtnStyle)
else:
ButtonPlayPause._btn.set_style(PlayBtnStyle)
class ButtonComposing(BoolSettingWidgetBase):
def __init__(self):
super().__init__()
self._btn = None
self._compose_data = None
self._timeline_widget = TimelineWidget()
def shutdown(self):
self._btn = None
super().shutdown()
def _build_widget(self):
with ui.VStack():
self._btn = ui.Button('Synthesis your song', height=BTN_HEIGHT*2.5, tooltip="Synthesized Voice")
self._btn.set_clicked_fn(self._on_compound)
def _on_compound(self):
thread = Thread(target=self._request_compose_data)
thread.start()
def _update_from_state(self, is_looping):
if self._btn is not None:
self._btn.selected = is_looping
def _request_compose_data(self):
_array = FemaleEntertainerWidger._get_female_data()
path = os.path.join(self.boolSetting._val, self.boolSetting._filename)
files = {"file": open(path, "rb")}
mix_str = json.dumps(
{
"duration": _array,
"pitch": _array,
"air": _array,
"falsetto": _array,
"tension": _array,
"energy": _array,
"mel": _array,
},
)
data_dict = {"flag": 135, "is_male": 1, "mix_info": mix_str}
try:
self._btn.text = 'processing...'
res = GetData._get_compose_data(files, data_dict)
if res["code"] == 200:
r = requests.get(res["data"][-1]["audio"], stream=True)
if not os.path.exists(os.path.join(EXT_ROOT, "voice")):
os.makedirs(os.path.join(EXT_ROOT, "voice"))
memory_address_ogg = os.path.join(EXT_ROOT, "voice\\voice.ogg")
memory_address_wav = os.path.join(EXT_ROOT, "voice\\voice.wav")
with open(memory_address_ogg, "wb") as ace_music:
for chunk in r.iter_content(chunk_size=1024): # 1024 bytes
if chunk:
ace_music.write(chunk)
song = AudioSegment.from_ogg(memory_address_ogg)
song.export(memory_address_wav, format="wav")
self._load_track(memory_address_wav)
self._timeline_widget.update_track_waveform()
self._timeline_widget._refresh()
else:
print(res)
except BaseException as e:
print(e)
self._btn.text = 'Synthesis your song'
self._btn.set_style({})
class ButtonLocation(BoolSettingWidgetBase):
def __init__(self):
self._btn = None
def shutdown(self):
self._btn = None
super().shutdown()
def _build_widget(self):
with ui.HStack(width=BTN_WIDTH, height=30):
self._btn = ui.Button(width=BTN_WIDTH, style=LocationBtnStyle, tooltip="Locate the composite file")
self._btn.set_clicked_fn(self.get_location)
def get_location(self):
# memory_address为需要打开文件夹的路径
if not os.path.exists(os.path.join(EXT_ROOT, "voice")):
os.makedirs(os.path.join(EXT_ROOT, "voice"))
memory_address = os.path.join(EXT_ROOT, "voice")
os.startfile(memory_address)
def _update_from_state(self, recorder_enabled):
if self._btn is not None:
self._btn.selected = recorder_enabled
|
timedomain-tech/Timedomain-Ai-Singer-Extension/exts/timedomain.ai.singer/timedomain/ai/singer/scripts/ui.py | from timedomain.ai.singer.instance import InstanceManagerBase
from timedomain.ai.singer.utils_io import read_file
import omni.ui as ui
import omni.kit.ui
import omni.kit.app
import omni.kit.window.filepicker
import omni.kit.pipapi
a2f_audio = omni.audio2face.player_deps.import_a2f_audio()
class Refreshable:
def __init__(self):
self.__need_refresh = False
self.__update_sub = (
omni.kit.app.get_app().get_update_event_stream().create_subscription_to_pop(self.__on_update)
)
def shutdown(self):
self.__update_sub = None
def refresh(self):
# We can't call self._refresh() directly, since it will clear the UI
# while the caller of this function could be that UI too
self.__need_refresh = True
def __on_update(self, *_):
if self.__need_refresh:
self.__need_refresh = False
self._refresh()
def _refresh(self): # Should be implemented in the derived class
raise NotImplementedError
class SimpleWidget(Refreshable):
def __init__(self):
super().__init__()
self._frame = None
def shutdown(self):
self._frame = None
super().shutdown()
def build(self):
self._frame = ui.VStack(height=0, spacing=0)
with self._frame:
self._build_content_wrapper()
def show(self):
if self._frame is not None:
self._frame.visible = True
def hide(self):
if self._frame is not None:
self._frame.visible = False
def enable(self):
if self._frame is not None:
self._frame.enabled = True
def disable(self):
if self._frame is not None:
self._frame.enabled = False
def clear(self):
if self._frame is not None:
self._frame.clear()
def _refresh(self):
if self._frame is not None:
self._frame.clear()
with self._frame:
self._build_content_wrapper()
def _build_content_wrapper(self): # Required for extra UI wrapers in intermediate dervied classes
self._build_content()
def _build_content(self): # Should be implemented in the derived class
raise NotImplementedError
class BoolSettingWidgetBase(InstanceManagerBase):
_track = None
_audio_player = a2f_audio.AudioPlayer(verbose=True)
def __init__(self):
super().__init__()
self._update_sub = omni.kit.app.get_app().get_update_event_stream().create_subscription_to_pop(self._on_update)
def shutdown(self):
self._update_sub = None
BoolSettingWidgetBase._audio_player.pause()
BoolSettingWidgetBase._audio_player = None
super().shutdown()
def _build_content(self):
self._build_widget()
if self.boolSetting._state is not None:
self._update_from_state(self.boolSetting._state)
def _on_toggled(self):
self.boolSetting._state = not self.boolSetting._state
if self.boolSetting._state:
if self.boolSetting._val is not None and self.boolSetting._filename is not None:
BoolSettingWidgetBase._audio_player.play()
self._update_from_state(True)
self.boolSetting._state = True
else:
self._update_from_state(False)
BoolSettingWidgetBase._audio_player.pause()
self.boolSetting._state = False
else:
self._update_from_state(False)
BoolSettingWidgetBase._audio_player.pause()
def _load_track(self, track_fpath):
bytes_data = read_file(track_fpath)
track = a2f_audio.read_track_from_bytes(bytes_data)
BoolSettingWidgetBase._track = track
BoolSettingWidgetBase._audio_player.set_track(track)
def _on_update(self, *_):
if self.boolSetting._state:
self.boolSetting.toggle()
def _build_widget(self): # Should be implemented in the derived class
raise NotImplementedError
def _update_from_state(self): # Should be implemented in the derived class
raise NotImplementedError |
timedomain-tech/Timedomain-Ai-Singer-Extension/exts/timedomain.ai.singer/timedomain/ai/singer/tests/__init__.py | from .test_hello_world import * |
timedomain-tech/Timedomain-Ai-Singer-Extension/exts/timedomain.ai.singer/timedomain/ai/singer/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 timedomain.ai.singer
# 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 = timedomain.ai.singer.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")
|
timedomain-tech/Timedomain-Ai-Singer-Extension/exts/timedomain.ai.singer/config/extension.toml | [package]
version = "1.0.0"
title = "TIMEDOMAIN AI SINGER"
description="Timedomain Ai Singer is a convenient tool for singing synthesis on the Omniverse platform."
readme = "docs/README.md"
repository = ""
authors = ["timedomAIn"]
category = "Audio"
keywords = ["timedomain", "ai", "singer"]
icon = "data/logo.png"
preview_image = "data/preview.png"
changelog = "docs/CHANGELOG.md"
[dependencies]
"omni.kit.uiapp" = {}
"omni.audio2face.player_deps" = {}
"omni.kit.window.filepicker" = {}
[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 = [
"requests"
]
[[python.module]]
name = "timedomain.ai.singer"
[[test]]
dependencies = [
"omni.kit.ui_test" # UI testing extension
]
|
timedomain-tech/Timedomain-Ai-Singer-Extension/exts/timedomain.ai.singer/docs/CHANGELOG.md | # Changelog
All notable changes to this project will be documented in this file.
## [1.0.0]
- Initial version of Timedomain Ai Singer extension.
|
timedomain-tech/Timedomain-Ai-Singer-Extension/exts/timedomain.ai.singer/docs/README.md | # Timedomain AI Singer Omniverse Extension
Timedomain AI Singer Omniverse Extension is a convenient tool for singing synthesis on the Omniverse platform.
|
yizhouzhao/VRKitchen2.0-IndoorKit/link_app.sh | #!/bin/bash
set -e
SCRIPT_DIR=$(dirname ${BASH_SOURCE})
cd "$SCRIPT_DIR"
exec "tools/packman/python.sh" tools/scripts/link_app.py $@
|
yizhouzhao/VRKitchen2.0-IndoorKit/link_app.bat | @echo off
call "%~dp0tools\packman\python.bat" %~dp0tools\scripts\link_app.py %*
if %errorlevel% neq 0 ( goto Error )
:Success
exit /b 0
:Error
exit /b %errorlevel%
|
yizhouzhao/VRKitchen2.0-IndoorKit/README.md | # Omniverse IndoorKit Extension (#ExtendOmniverse 2022 Contest Overall Winner)

This extension allows to load and record indoor scene tasks for robotics. [Introduction video here.](https://drive.google.com/file/d/1_u2uGuuxoSeeE6WiKhx703ZjQvJQ0ESa/view?usp=sharing)
<div>
<img src='./img/pickup_AdobeExpress.gif' width='320px'>
<img src='./img/drawer_AdobeExpress.gif' width='320px'>
<img src='./img/rotate_AdobeExpress.gif' width='320px'>
<img src='./img/water_AdobeExpress.gif' width='320px'>
</div>
In the field of robotics, it requires a lot of effort to set up even a simple task (e,g. picking up an object) for a robot in a real scene. At present, with the help of Omniverse, not only can we set up tasks for robots in a photo-realistic and physics-reliable manner, but we build this extension to bring high-quality content with a wide range of variability and randomness.
Besides, we design a complete pipeline to load and record the scene, control and replay the robot actions, and render images. We hope this work could encourage academic research in related fields.
<img src="img/ui.png" width="300">
# Get started with Omniverse Code/Create [version >= 2022]
## Download the [release](https://github.com/yizhouzhao/VRKitchen2.0-IndoorKit/releases/tag/0.2) or clone the this repository
> **Note**:
> The size of the extension including model assets is about 300 MB
```
git clone https://github.com/yizhouzhao/VRKitchen2.0-IndoorKit
```
Upzip or locate the root folder as <your-path-to-VRKitchen2.0-IndoorKit>
The file structure of this extension should look like:
```
<your-path-to-VRKitchen2.0-IndoorKit>
└───data [Folder to save the labeling data]
└───exts [Omniverse extenstion]
└───vrkitchen.indoor.kit
└───asset [Asset (object, house, e.t.c.) needed for robot tasks]
└───config [Extension config]
└───data [Extension data]
└───icons [Extension icons]
└───vrkitchen/indoor/kit [source code]
└───img
└───tool
│ README.md
......
```
## Add extension to Omniverse
1. **[Open extension manager]** After opening Omniverse Code, go to `Menu` -> `Window` -> `Extension`
2. **[Add this extension to Omniverse]** Click the <img src="https://github.githubassets.com/images/icons/emoji/unicode/2699.png?v8" width="18"> button, add absolute extension path to `Extension Search Paths`.
Finally, you can search the `vrkitchen.indoor.kit` and enable this extension.
> **Note**:
> The extension path to add is: `<your-path-to-VRKitchen2.0-IndoorKit>/exts`

# Play with Indoorkit
The functionality of our Indoorkit has three parts:
- TASK LAYOUT: to set up object, robot, and room for one task.
- SCENE UTILITY: to load scene and set up scene features including light, sky, matrial, and e.t.c.
- PLAY: to control the robot to perform and the task.
## 1. Task layout
Start with a new stage,

The `Task layout` module allows users to automatically add the task object, robot, and room.
a) Click the `task type combo box` to select task type from *Pick up object*, *Reorient object*, *Pour water*, and *Open drawer*.
b) Fill the `object id integer field` (ranging from 0 to 19), then click the `Add object` button to automatically add an object and a franka robot to the scene.
> **Note**:
> Now the robot prim: `/World/game/franka` is selected, you can change the position and rotation of the robot.
c) Fill the `house id integer field` (ranging from 0 to 19), then click the `Add house` button to automatically add a room structure to the task.
> **Note**:
> Now the robot prim: `/World/game/` is automatically selected, you can change the game position and rotation.
d) Click the `Record scene` button to save the scene information (about task type, object, robot, and room) into a json file.
After recording scene, you can close close the stage without saving.
## 2. Scene utility
-- Load the recorded scene and change scene features.

a) Click `New scene` to open a new stage (with /World and /World/defaultLight only). This this the same as the command: `Menu`->`File`->`New...`
b) Click `Load scene` to load the scene from saved information from `TASK LAYOUT`.
Then you can modify the scene by setting
- `Visible ground`: show ground plane
- `Light intensity`: change the defaultLight intensity
- `Sky type`: change the sky background
- `Random house material`: change floor and wall material
>**Note**:
>To load the house material requires users to open the `Nucleus` server. The materials are from `Nucleus`.
- `Enable isosurface`: enable isosurface option for water tasks.
## 2. Play
-- play the franka robot.

a) Click `Record` to start playing with the franka robot and recording the robot actions.
To control the robot:
Position the end effector (EE) relative the robot itself, use the `Robot control` UI or the keyboard:
- [W] Move EE forward;
- [S] Move EE backward;
- [A] Move EE to the left;
- [D] Move EE to the right
- [E] Move EE upward;
- [D] Move EE downward.
Rotation the end effector (EE), use the `Robot control` UI or the keyboard:
- [ARROW UP] Rotate EE upward;
- [ARROW DOWN] Rotate EE downward;
- [ARROW LEFT] Rotate EE to the left;
- [ARROW RIGHT] Rotate EE to the right.
To open and close the hand gripper, use the `Robot control` UI or the keyboard:
- [LEFT CONTROL] Open/Close the gripper.
b) Click `Stop` button to stop playing with the franka robot.
c) Click `Replay` button to replay robot actions.
>**Note**:
> The `Replay` and `Record` are according to the information of `task type`, `object id`, and `house id`.
You may render the desired type of the image at any time playing, replaying or pausing. Click `Capture image` to get a screenshot.
Finally, you can open the data folders:

# Cite this work
```
@article{zhao2022vrkitchen2,
title={VRKitchen2. 0-IndoorKit: A Tutorial for Augmented Indoor Scene Building in Omniverse},
author={Zhao, Yizhou and Gong, Steven and Gao, Xiaofeng and Ai, Wensi and Zhu, Song-Chun},
journal={arXiv preprint arXiv:2206.11887},
year={2022}
}
```
# Need more rooms?
Go to this repository: https://github.com/yizhouzhao/VRKitchen2.0-Tutorial
# License
- The rooms in this repository are from [Trescope](https://github.com/alibaba/Trescope), under the [MIT License](https://github.com/alibaba/Trescope/blob/main/LICENSE)
- The drawers and bottles in this repository are from [SAPIEN](https://sapien.ucsd.edu/), under this [Term of Use](https://sapien.ucsd.edu/about#term)
- The cups in this repository are from AI2THOR, under the [Apache License](https://github.com/allenai/ai2thor/blob/main/LICENSE).
- This repository is for OMNIVERSE CODE CONTEST, under the [OMNIVERSE PUBLISHING AGREEMENT
](https://developer.download.nvidia.com/Omniverse/secure/Omniverse_Publishing_Agreement_12May2022.pdf?jrPi6OXFm7gWYIsdrQGrSTgF4P3LNZ8cXw3jyHdg--8TYsFEK7bOTc5Az6My5OyURuC8xMU9_Ii1u8H7aPReCvxYFGCrc9VVKVdbfFShmc5sktkTrqywjogIpKeoYLtY-fdBX-WjCl_Vjziylc0Dddy0PXlVdlotRtzLmQ&t=eyJscyI6ImdzZW8iLCJsc2QiOiJodHRwczpcL1wvd3d3Lmdvb2dsZS5jb21cLyJ9).
# Acknowledgement
Thanks to the [NVIDIA Academic Hardware Grant Program](https://mynvidia.force.com/HardwareGrant/s/Application). Without its general support, this extension could not have possibly been developed so fast and so well.
|
yizhouzhao/VRKitchen2.0-IndoorKit/LICENSE.md | MIT License
Copyright (c) 2022 yizhouzhao
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
|
yizhouzhao/VRKitchen2.0-IndoorKit/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!")
|
yizhouzhao/VRKitchen2.0-IndoorKit/tools/packman/python.sh | #!/bin/bash
# Copyright 2019-2020 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.
set -e
PACKMAN_CMD="$(dirname "${BASH_SOURCE}")/packman"
if [ ! -f "$PACKMAN_CMD" ]; then
PACKMAN_CMD="${PACKMAN_CMD}.sh"
fi
source "$PACKMAN_CMD" init
export PYTHONPATH="${PM_MODULE_DIR}:${PYTHONPATH}"
export PYTHONNOUSERSITE=1
# workaround for our python not shipping with certs
if [[ -z ${SSL_CERT_DIR:-} ]]; then
export SSL_CERT_DIR=/etc/ssl/certs/
fi
"${PM_PYTHON}" -u "$@"
|
yizhouzhao/VRKitchen2.0-IndoorKit/tools/packman/python.bat | :: Copyright 2019-2020 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.
@echo off
setlocal
call "%~dp0\packman" init
set "PYTHONPATH=%PM_MODULE_DIR%;%PYTHONPATH%"
set PYTHONNOUSERSITE=1
"%PM_PYTHON%" -u %*
|
yizhouzhao/VRKitchen2.0-IndoorKit/tools/packman/packman.cmd | :: Reset errorlevel status (don't inherit from caller) [xxxxxxxxxxx]
@call :ECHO_AND_RESET_ERROR
:: You can remove the call below if you do your own manual configuration of the dev machines
call "%~dp0\bootstrap\configure.bat"
if %errorlevel% neq 0 ( exit /b %errorlevel% )
:: Everything below is mandatory
if not defined PM_PYTHON goto :PYTHON_ENV_ERROR
if not defined PM_MODULE goto :MODULE_ENV_ERROR
:: Generate temporary path for variable file
for /f "delims=" %%a in ('powershell -ExecutionPolicy ByPass -NoLogo -NoProfile ^
-File "%~dp0bootstrap\generate_temp_file_name.ps1"') do set PM_VAR_PATH=%%a
if %1.==. (
set PM_VAR_PATH_ARG=
) else (
set PM_VAR_PATH_ARG=--var-path="%PM_VAR_PATH%"
)
"%PM_PYTHON%" -S -s -u -E "%PM_MODULE%" %* %PM_VAR_PATH_ARG%
if %errorlevel% neq 0 ( exit /b %errorlevel% )
:: Marshall environment variables into the current environment if they have been generated and remove temporary file
if exist "%PM_VAR_PATH%" (
for /F "usebackq tokens=*" %%A in ("%PM_VAR_PATH%") do set "%%A"
)
if %errorlevel% neq 0 ( goto :VAR_ERROR )
if exist "%PM_VAR_PATH%" (
del /F "%PM_VAR_PATH%"
)
if %errorlevel% neq 0 ( goto :VAR_ERROR )
set PM_VAR_PATH=
goto :eof
:: Subroutines below
:PYTHON_ENV_ERROR
@echo User environment variable PM_PYTHON is not set! Please configure machine for packman or call configure.bat.
exit /b 1
:MODULE_ENV_ERROR
@echo User environment variable PM_MODULE is not set! Please configure machine for packman or call configure.bat.
exit /b 1
:VAR_ERROR
@echo Error while processing and setting environment variables!
exit /b 1
:ECHO_AND_RESET_ERROR
@echo off
if /I "%PM_VERBOSITY%"=="debug" (
@echo on
)
exit /b 0
|
yizhouzhao/VRKitchen2.0-IndoorKit/tools/packman/config.packman.xml | <config remotes="cloudfront">
<remote2 name="cloudfront">
<transport actions="download" protocol="https" packageLocation="d4i3qtqj3r0z5.cloudfront.net/${name}@${version}" />
</remote2>
</config>
|
yizhouzhao/VRKitchen2.0-IndoorKit/tools/packman/bootstrap/generate_temp_file_name.ps1 | <#
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.
#>
$out = [System.IO.Path]::GetTempFileName()
Write-Host $out
# SIG # Begin signature block
# MIIaVwYJKoZIhvcNAQcCoIIaSDCCGkQCAQExDzANBglghkgBZQMEAgEFADB5Bgor
# BgEEAYI3AgEEoGswaTA0BgorBgEEAYI3AgEeMCYCAwEAAAQQH8w7YFlLCE63JNLG
# KX7zUQIBAAIBAAIBAAIBAAIBADAxMA0GCWCGSAFlAwQCAQUABCAK+Ewup1N0/mdf
# 1l4R58rxyumHgZvTmEhrYTb2Zf0zd6CCCiIwggTTMIIDu6ADAgECAhBi50XpIWUh
# PJcfXEkK6hKlMA0GCSqGSIb3DQEBCwUAMIGEMQswCQYDVQQGEwJVUzEdMBsGA1UE
# ChMUU3ltYW50ZWMgQ29ycG9yYXRpb24xHzAdBgNVBAsTFlN5bWFudGVjIFRydXN0
# IE5ldHdvcmsxNTAzBgNVBAMTLFN5bWFudGVjIENsYXNzIDMgU0hBMjU2IENvZGUg
# U2lnbmluZyBDQSAtIEcyMB4XDTE4MDcwOTAwMDAwMFoXDTIxMDcwOTIzNTk1OVow
# gYMxCzAJBgNVBAYTAlVTMRMwEQYDVQQIDApDYWxpZm9ybmlhMRQwEgYDVQQHDAtT
# YW50YSBDbGFyYTEbMBkGA1UECgwSTlZJRElBIENvcnBvcmF0aW9uMQ8wDQYDVQQL
# DAZJVC1NSVMxGzAZBgNVBAMMEk5WSURJQSBDb3Jwb3JhdGlvbjCCASIwDQYJKoZI
# hvcNAQEBBQADggEPADCCAQoCggEBALEZN63dA47T4i90jZ84CJ/aWUwVtLff8AyP
# YspFfIZGdZYiMgdb8A5tBh7653y0G/LZL6CVUkgejcpvBU/Dl/52a+gSWy2qJ2bH
# jMFMKCyQDhdpCAKMOUKSC9rfzm4cFeA9ct91LQCAait4LhLlZt/HF7aG+r0FgCZa
# HJjJvE7KNY9G4AZXxjSt8CXS8/8NQMANqjLX1r+F+Hl8PzQ1fVx0mMsbdtaIV4Pj
# 5flAeTUnz6+dCTx3vTUo8MYtkS2UBaQv7t7H2B7iwJDakEQKk1XHswJdeqG0osDU
# z6+NVks7uWE1N8UIhvzbw0FEX/U2kpfyWaB/J3gMl8rVR8idPj8CAwEAAaOCAT4w
# ggE6MAkGA1UdEwQCMAAwDgYDVR0PAQH/BAQDAgeAMBMGA1UdJQQMMAoGCCsGAQUF
# BwMDMGEGA1UdIARaMFgwVgYGZ4EMAQQBMEwwIwYIKwYBBQUHAgEWF2h0dHBzOi8v
# ZC5zeW1jYi5jb20vY3BzMCUGCCsGAQUFBwICMBkMF2h0dHBzOi8vZC5zeW1jYi5j
# b20vcnBhMB8GA1UdIwQYMBaAFNTABiJJ6zlL3ZPiXKG4R3YJcgNYMCsGA1UdHwQk
# MCIwIKAeoByGGmh0dHA6Ly9yYi5zeW1jYi5jb20vcmIuY3JsMFcGCCsGAQUFBwEB
# BEswSTAfBggrBgEFBQcwAYYTaHR0cDovL3JiLnN5bWNkLmNvbTAmBggrBgEFBQcw
# AoYaaHR0cDovL3JiLnN5bWNiLmNvbS9yYi5jcnQwDQYJKoZIhvcNAQELBQADggEB
# AIJKh5vKJdhHJtMzATmc1BmXIQ3RaJONOZ5jMHn7HOkYU1JP0OIzb4pXXkH8Xwfr
# K6bnd72IhcteyksvKsGpSvK0PBBwzodERTAu1Os2N+EaakxQwV/xtqDm1E3IhjHk
# fRshyKKzmFk2Ci323J4lHtpWUj5Hz61b8gd72jH7xnihGi+LORJ2uRNZ3YuqMNC3
# SBC8tAyoJqEoTJirULUCXW6wX4XUm5P2sx+htPw7szGblVKbQ+PFinNGnsSEZeKz
# D8jUb++1cvgTKH59Y6lm43nsJjkZU77tNqyq4ABwgQRk6lt8cS2PPwjZvTmvdnla
# ZhR0K4of+pQaUQHXVIBdji8wggVHMIIEL6ADAgECAhB8GzU1SufbdOdBXxFpymuo
# MA0GCSqGSIb3DQEBCwUAMIG9MQswCQYDVQQGEwJVUzEXMBUGA1UEChMOVmVyaVNp
# Z24sIEluYy4xHzAdBgNVBAsTFlZlcmlTaWduIFRydXN0IE5ldHdvcmsxOjA4BgNV
# BAsTMShjKSAyMDA4IFZlcmlTaWduLCBJbmMuIC0gRm9yIGF1dGhvcml6ZWQgdXNl
# IG9ubHkxODA2BgNVBAMTL1ZlcmlTaWduIFVuaXZlcnNhbCBSb290IENlcnRpZmlj
# YXRpb24gQXV0aG9yaXR5MB4XDTE0MDcyMjAwMDAwMFoXDTI0MDcyMTIzNTk1OVow
# gYQxCzAJBgNVBAYTAlVTMR0wGwYDVQQKExRTeW1hbnRlYyBDb3Jwb3JhdGlvbjEf
# MB0GA1UECxMWU3ltYW50ZWMgVHJ1c3QgTmV0d29yazE1MDMGA1UEAxMsU3ltYW50
# ZWMgQ2xhc3MgMyBTSEEyNTYgQ29kZSBTaWduaW5nIENBIC0gRzIwggEiMA0GCSqG
# SIb3DQEBAQUAA4IBDwAwggEKAoIBAQDXlUPU3N9nrjn7UqS2JjEEcOm3jlsqujdp
# NZWPu8Aw54bYc7vf69F2P4pWjustS/BXGE6xjaUz0wt1I9VqeSfdo9P3Dodltd6t
# HPH1NbQiUa8iocFdS5B/wFlOq515qQLXHkmxO02H/sJ4q7/vUq6crwjZOeWaUT5p
# XzAQTnFjbFjh8CAzGw90vlvLEuHbjMSAlHK79kWansElC/ujHJ7YpglwcezAR0yP
# fcPeGc4+7gRyjhfT//CyBTIZTNOwHJ/+pXggQnBBsCaMbwDIOgARQXpBsKeKkQSg
# mXj0d7TzYCrmbFAEtxRg/w1R9KiLhP4h2lxeffUpeU+wRHRvbXL/AgMBAAGjggF4
# MIIBdDAuBggrBgEFBQcBAQQiMCAwHgYIKwYBBQUHMAGGEmh0dHA6Ly9zLnN5bWNk
# LmNvbTASBgNVHRMBAf8ECDAGAQH/AgEAMGYGA1UdIARfMF0wWwYLYIZIAYb4RQEH
# FwMwTDAjBggrBgEFBQcCARYXaHR0cHM6Ly9kLnN5bWNiLmNvbS9jcHMwJQYIKwYB
# BQUHAgIwGRoXaHR0cHM6Ly9kLnN5bWNiLmNvbS9ycGEwNgYDVR0fBC8wLTAroCmg
# J4YlaHR0cDovL3Muc3ltY2IuY29tL3VuaXZlcnNhbC1yb290LmNybDATBgNVHSUE
# DDAKBggrBgEFBQcDAzAOBgNVHQ8BAf8EBAMCAQYwKQYDVR0RBCIwIKQeMBwxGjAY
# BgNVBAMTEVN5bWFudGVjUEtJLTEtNzI0MB0GA1UdDgQWBBTUwAYiSes5S92T4lyh
# uEd2CXIDWDAfBgNVHSMEGDAWgBS2d/ppSEefUxLVwuoHMnYH0ZcHGTANBgkqhkiG
# 9w0BAQsFAAOCAQEAf+vKp+qLdkLrPo4gVDDjt7nc+kg+FscPRZUQzSeGo2bzAu1x
# +KrCVZeRcIP5Un5SaTzJ8eCURoAYu6HUpFam8x0AkdWG80iH4MvENGggXrTL+QXt
# nK9wUye56D5+UaBpcYvcUe2AOiUyn0SvbkMo0yF1u5fYi4uM/qkERgSF9xWcSxGN
# xCwX/tVuf5riVpLxlrOtLfn039qJmc6yOETA90d7yiW5+ipoM5tQct6on9TNLAs0
# vYsweEDgjY4nG5BvGr4IFYFd6y/iUedRHsl4KeceZb847wFKAQkkDhbEFHnBQTc0
# 0D2RUpSd4WjvCPDiaZxnbpALGpNx1CYCw8BaIzGCD4swgg+HAgEBMIGZMIGEMQsw
# CQYDVQQGEwJVUzEdMBsGA1UEChMUU3ltYW50ZWMgQ29ycG9yYXRpb24xHzAdBgNV
# BAsTFlN5bWFudGVjIFRydXN0IE5ldHdvcmsxNTAzBgNVBAMTLFN5bWFudGVjIENs
# YXNzIDMgU0hBMjU2IENvZGUgU2lnbmluZyBDQSAtIEcyAhBi50XpIWUhPJcfXEkK
# 6hKlMA0GCWCGSAFlAwQCAQUAoHwwEAYKKwYBBAGCNwIBDDECMAAwGQYJKoZIhvcN
# AQkDMQwGCisGAQQBgjcCAQQwHAYKKwYBBAGCNwIBCzEOMAwGCisGAQQBgjcCARUw
# LwYJKoZIhvcNAQkEMSIEIPW+EpFrZSdzrjFFo0UT+PzFeYn/GcWNyWFaU/JMrMfR
# MA0GCSqGSIb3DQEBAQUABIIBAA8fmU/RJcF9t60DZZAjf8FB3EZddOaHgI9z40nV
# CnfTGi0OEYU48Pe9jkQQV2fABpACfW74xmNv3QNgP2qP++mkpKBVv28EIAuINsFt
# YAITEljLN/VOVul8lvjxar5GSFFgpE5F6j4xcvI69LuCWbN8cteTVsBGg+eGmjfx
# QZxP252z3FqPN+mihtFegF2wx6Mg6/8jZjkO0xjBOwSdpTL4uyQfHvaPBKXuWxRx
# ioXw4ezGAwkuBoxWK8UG7Qu+7CSfQ3wMOjvyH2+qn30lWEsvRMdbGAp7kvfr3EGZ
# a3WN7zXZ+6KyZeLeEH7yCDzukAjptaY/+iLVjJsuzC6tCSqhgg1EMIINQAYKKwYB
# BAGCNwMDATGCDTAwgg0sBgkqhkiG9w0BBwKggg0dMIINGQIBAzEPMA0GCWCGSAFl
# AwQCAQUAMHcGCyqGSIb3DQEJEAEEoGgEZjBkAgEBBglghkgBhv1sBwEwMTANBglg
# hkgBZQMEAgEFAAQg14BnPazQkW9whhZu1d0bC3lqqScvxb3SSb1QT8e3Xg0CEFhw
# aMBZ2hExXhr79A9+bXEYDzIwMjEwNDA4MDkxMTA5WqCCCjcwggT+MIID5qADAgEC
# AhANQkrgvjqI/2BAIc4UAPDdMA0GCSqGSIb3DQEBCwUAMHIxCzAJBgNVBAYTAlVT
# MRUwEwYDVQQKEwxEaWdpQ2VydCBJbmMxGTAXBgNVBAsTEHd3dy5kaWdpY2VydC5j
# b20xMTAvBgNVBAMTKERpZ2lDZXJ0IFNIQTIgQXNzdXJlZCBJRCBUaW1lc3RhbXBp
# bmcgQ0EwHhcNMjEwMTAxMDAwMDAwWhcNMzEwMTA2MDAwMDAwWjBIMQswCQYDVQQG
# EwJVUzEXMBUGA1UEChMORGlnaUNlcnQsIEluYy4xIDAeBgNVBAMTF0RpZ2lDZXJ0
# IFRpbWVzdGFtcCAyMDIxMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA
# wuZhhGfFivUNCKRFymNrUdc6EUK9CnV1TZS0DFC1JhD+HchvkWsMlucaXEjvROW/
# m2HNFZFiWrj/ZwucY/02aoH6KfjdK3CF3gIY83htvH35x20JPb5qdofpir34hF0e
# dsnkxnZ2OlPR0dNaNo/Go+EvGzq3YdZz7E5tM4p8XUUtS7FQ5kE6N1aG3JMjjfdQ
# Jehk5t3Tjy9XtYcg6w6OLNUj2vRNeEbjA4MxKUpcDDGKSoyIxfcwWvkUrxVfbENJ
# Cf0mI1P2jWPoGqtbsR0wwptpgrTb/FZUvB+hh6u+elsKIC9LCcmVp42y+tZji06l
# chzun3oBc/gZ1v4NSYS9AQIDAQABo4IBuDCCAbQwDgYDVR0PAQH/BAQDAgeAMAwG
# A1UdEwEB/wQCMAAwFgYDVR0lAQH/BAwwCgYIKwYBBQUHAwgwQQYDVR0gBDowODA2
# BglghkgBhv1sBwEwKTAnBggrBgEFBQcCARYbaHR0cDovL3d3dy5kaWdpY2VydC5j
# b20vQ1BTMB8GA1UdIwQYMBaAFPS24SAd/imu0uRhpbKiJbLIFzVuMB0GA1UdDgQW
# BBQ2RIaOpLqwZr68KC0dRDbd42p6vDBxBgNVHR8EajBoMDKgMKAuhixodHRwOi8v
# Y3JsMy5kaWdpY2VydC5jb20vc2hhMi1hc3N1cmVkLXRzLmNybDAyoDCgLoYsaHR0
# cDovL2NybDQuZGlnaWNlcnQuY29tL3NoYTItYXNzdXJlZC10cy5jcmwwgYUGCCsG
# AQUFBwEBBHkwdzAkBggrBgEFBQcwAYYYaHR0cDovL29jc3AuZGlnaWNlcnQuY29t
# ME8GCCsGAQUFBzAChkNodHRwOi8vY2FjZXJ0cy5kaWdpY2VydC5jb20vRGlnaUNl
# cnRTSEEyQXNzdXJlZElEVGltZXN0YW1waW5nQ0EuY3J0MA0GCSqGSIb3DQEBCwUA
# A4IBAQBIHNy16ZojvOca5yAOjmdG/UJyUXQKI0ejq5LSJcRwWb4UoOUngaVNFBUZ
# B3nw0QTDhtk7vf5EAmZN7WmkD/a4cM9i6PVRSnh5Nnont/PnUp+Tp+1DnnvntN1B
# Ion7h6JGA0789P63ZHdjXyNSaYOC+hpT7ZDMjaEXcw3082U5cEvznNZ6e9oMvD0y
# 0BvL9WH8dQgAdryBDvjA4VzPxBFy5xtkSdgimnUVQvUtMjiB2vRgorq0Uvtc4GEk
# JU+y38kpqHNDUdq9Y9YfW5v3LhtPEx33Sg1xfpe39D+E68Hjo0mh+s6nv1bPull2
# YYlffqe0jmd4+TaY4cso2luHpoovMIIFMTCCBBmgAwIBAgIQCqEl1tYyG35B5AXa
# NpfCFTANBgkqhkiG9w0BAQsFADBlMQswCQYDVQQGEwJVUzEVMBMGA1UEChMMRGln
# aUNlcnQgSW5jMRkwFwYDVQQLExB3d3cuZGlnaWNlcnQuY29tMSQwIgYDVQQDExtE
# aWdpQ2VydCBBc3N1cmVkIElEIFJvb3QgQ0EwHhcNMTYwMTA3MTIwMDAwWhcNMzEw
# MTA3MTIwMDAwWjByMQswCQYDVQQGEwJVUzEVMBMGA1UEChMMRGlnaUNlcnQgSW5j
# MRkwFwYDVQQLExB3d3cuZGlnaWNlcnQuY29tMTEwLwYDVQQDEyhEaWdpQ2VydCBT
# SEEyIEFzc3VyZWQgSUQgVGltZXN0YW1waW5nIENBMIIBIjANBgkqhkiG9w0BAQEF
# AAOCAQ8AMIIBCgKCAQEAvdAy7kvNj3/dqbqCmcU5VChXtiNKxA4HRTNREH3Q+X1N
# aH7ntqD0jbOI5Je/YyGQmL8TvFfTw+F+CNZqFAA49y4eO+7MpvYyWf5fZT/gm+vj
# RkcGGlV+Cyd+wKL1oODeIj8O/36V+/OjuiI+GKwR5PCZA207hXwJ0+5dyJoLVOOo
# CXFr4M8iEA91z3FyTgqt30A6XLdR4aF5FMZNJCMwXbzsPGBqrC8HzP3w6kfZiFBe
# /WZuVmEnKYmEUeaC50ZQ/ZQqLKfkdT66mA+Ef58xFNat1fJky3seBdCEGXIX8RcG
# 7z3N1k3vBkL9olMqT4UdxB08r8/arBD13ays6Vb/kwIDAQABo4IBzjCCAcowHQYD
# VR0OBBYEFPS24SAd/imu0uRhpbKiJbLIFzVuMB8GA1UdIwQYMBaAFEXroq/0ksuC
# MS1Ri6enIZ3zbcgPMBIGA1UdEwEB/wQIMAYBAf8CAQAwDgYDVR0PAQH/BAQDAgGG
# MBMGA1UdJQQMMAoGCCsGAQUFBwMIMHkGCCsGAQUFBwEBBG0wazAkBggrBgEFBQcw
# AYYYaHR0cDovL29jc3AuZGlnaWNlcnQuY29tMEMGCCsGAQUFBzAChjdodHRwOi8v
# Y2FjZXJ0cy5kaWdpY2VydC5jb20vRGlnaUNlcnRBc3N1cmVkSURSb290Q0EuY3J0
# MIGBBgNVHR8EejB4MDqgOKA2hjRodHRwOi8vY3JsNC5kaWdpY2VydC5jb20vRGln
# aUNlcnRBc3N1cmVkSURSb290Q0EuY3JsMDqgOKA2hjRodHRwOi8vY3JsMy5kaWdp
# Y2VydC5jb20vRGlnaUNlcnRBc3N1cmVkSURSb290Q0EuY3JsMFAGA1UdIARJMEcw
# OAYKYIZIAYb9bAACBDAqMCgGCCsGAQUFBwIBFhxodHRwczovL3d3dy5kaWdpY2Vy
# dC5jb20vQ1BTMAsGCWCGSAGG/WwHATANBgkqhkiG9w0BAQsFAAOCAQEAcZUS6VGH
# VmnN793afKpjerN4zwY3QITvS4S/ys8DAv3Fp8MOIEIsr3fzKx8MIVoqtwU0HWqu
# mfgnoma/Capg33akOpMP+LLR2HwZYuhegiUexLoceywh4tZbLBQ1QwRostt1AuBy
# x5jWPGTlH0gQGF+JOGFNYkYkh2OMkVIsrymJ5Xgf1gsUpYDXEkdws3XVk4WTfraS
# Z/tTYYmo9WuWwPRYaQ18yAGxuSh1t5ljhSKMYcp5lH5Z/IwP42+1ASa2bKXuh1Eh
# 5Fhgm7oMLSttosR+u8QlK0cCCHxJrhO24XxCQijGGFbPQTS2Zl22dHv1VjMiLyI2
# skuiSpXY9aaOUjGCAk0wggJJAgEBMIGGMHIxCzAJBgNVBAYTAlVTMRUwEwYDVQQK
# EwxEaWdpQ2VydCBJbmMxGTAXBgNVBAsTEHd3dy5kaWdpY2VydC5jb20xMTAvBgNV
# BAMTKERpZ2lDZXJ0IFNIQTIgQXNzdXJlZCBJRCBUaW1lc3RhbXBpbmcgQ0ECEA1C
# SuC+Ooj/YEAhzhQA8N0wDQYJYIZIAWUDBAIBBQCggZgwGgYJKoZIhvcNAQkDMQ0G
# CyqGSIb3DQEJEAEEMBwGCSqGSIb3DQEJBTEPFw0yMTA0MDgwOTExMDlaMCsGCyqG
# SIb3DQEJEAIMMRwwGjAYMBYEFOHXgqjhkb7va8oWkbWqtJSmJJvzMC8GCSqGSIb3
# DQEJBDEiBCCHEAmNNj2zWjWYRfEi4FgzZvrI16kv/U2b9b3oHw6UVDANBgkqhkiG
# 9w0BAQEFAASCAQCdefEKh6Qmwx7xGCkrYi/A+/Cla6LdnYJp38eMs3fqTTvjhyDw
# HffXrwdqWy5/fgW3o3qJXqa5o7hLxYIoWSULOCpJRGdt+w7XKPAbZqHrN9elAhWJ
# vpBTCEaj7dVxr1Ka4NsoPSYe0eidDBmmvGvp02J4Z1j8+ImQPKN6Hv/L8Ixaxe7V
# mH4VtXIiBK8xXdi4wzO+A+qLtHEJXz3Gw8Bp3BNtlDGIUkIhVTM3Q1xcSEqhOLqo
# PGdwCw9acxdXNWWPjOJkNH656Bvmkml+0p6MTGIeG4JCeRh1Wpqm1ZGSoEcXNaof
# wOgj48YzI+dNqBD9i7RSWCqJr2ygYKRTxnuU
# SIG # End signature block
|
yizhouzhao/VRKitchen2.0-IndoorKit/tools/packman/bootstrap/configure.bat | :: 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.
set PM_PACKMAN_VERSION=6.33.2
:: Specify where packman command is rooted
set PM_INSTALL_PATH=%~dp0..
:: The external root may already be configured and we should do minimal work in that case
if defined PM_PACKAGES_ROOT goto ENSURE_DIR
:: If the folder isn't set we assume that the best place for it is on the drive that we are currently
:: running from
set PM_DRIVE=%CD:~0,2%
set PM_PACKAGES_ROOT=%PM_DRIVE%\packman-repo
:: We use *setx* here so that the variable is persisted in the user environment
echo Setting user environment variable PM_PACKAGES_ROOT to %PM_PACKAGES_ROOT%
setx PM_PACKAGES_ROOT %PM_PACKAGES_ROOT%
if %errorlevel% neq 0 ( goto ERROR )
:: The above doesn't work properly from a build step in VisualStudio because a separate process is
:: spawned for it so it will be lost for subsequent compilation steps - VisualStudio must
:: be launched from a new process. We catch this odd-ball case here:
if defined PM_DISABLE_VS_WARNING goto ENSURE_DIR
if not defined VSLANG goto ENSURE_DIR
echo The above is a once-per-computer operation. Unfortunately VisualStudio cannot pick up environment change
echo unless *VisualStudio is RELAUNCHED*.
echo If you are launching VisualStudio from command line or command line utility make sure
echo you have a fresh launch environment (relaunch the command line or utility).
echo If you are using 'linkPath' and referring to packages via local folder links you can safely ignore this warning.
echo You can disable this warning by setting the environment variable PM_DISABLE_VS_WARNING.
echo.
:: Check for the directory that we need. Note that mkdir will create any directories
:: that may be needed in the path
:ENSURE_DIR
if not exist "%PM_PACKAGES_ROOT%" (
echo Creating directory %PM_PACKAGES_ROOT%
mkdir "%PM_PACKAGES_ROOT%"
)
if %errorlevel% neq 0 ( goto ERROR_MKDIR_PACKAGES_ROOT )
:: The Python interpreter may already be externally configured
if defined PM_PYTHON_EXT (
set PM_PYTHON=%PM_PYTHON_EXT%
goto PACKMAN
)
set PM_PYTHON_VERSION=3.7.9-windows-x86_64
set PM_PYTHON_BASE_DIR=%PM_PACKAGES_ROOT%\python
set PM_PYTHON_DIR=%PM_PYTHON_BASE_DIR%\%PM_PYTHON_VERSION%
set PM_PYTHON=%PM_PYTHON_DIR%\python.exe
if exist "%PM_PYTHON%" goto PACKMAN
if not exist "%PM_PYTHON_BASE_DIR%" call :CREATE_PYTHON_BASE_DIR
set PM_PYTHON_PACKAGE=python@%PM_PYTHON_VERSION%.cab
for /f "delims=" %%a in ('powershell -ExecutionPolicy ByPass -NoLogo -NoProfile -File "%~dp0\generate_temp_file_name.ps1"') do set TEMP_FILE_NAME=%%a
set TARGET=%TEMP_FILE_NAME%.zip
call "%~dp0fetch_file_from_packman_bootstrap.cmd" %PM_PYTHON_PACKAGE% "%TARGET%"
if %errorlevel% neq 0 (
echo !!! Error fetching python from CDN !!!
goto ERROR
)
for /f "delims=" %%a in ('powershell -ExecutionPolicy ByPass -NoLogo -NoProfile -File "%~dp0\generate_temp_folder.ps1" -parentPath "%PM_PYTHON_BASE_DIR%"') do set TEMP_FOLDER_NAME=%%a
echo Unpacking Python interpreter ...
"%SystemRoot%\system32\expand.exe" -F:* "%TARGET%" "%TEMP_FOLDER_NAME%" 1> nul
del "%TARGET%"
:: Failure during extraction to temp folder name, need to clean up and abort
if %errorlevel% neq 0 (
echo !!! Error unpacking python !!!
call :CLEAN_UP_TEMP_FOLDER
goto ERROR
)
:: If python has now been installed by a concurrent process we need to clean up and then continue
if exist "%PM_PYTHON%" (
call :CLEAN_UP_TEMP_FOLDER
goto PACKMAN
) else (
if exist "%PM_PYTHON_DIR%" ( rd /s /q "%PM_PYTHON_DIR%" > nul )
)
:: Perform atomic rename
rename "%TEMP_FOLDER_NAME%" "%PM_PYTHON_VERSION%" 1> nul
:: Failure during move, need to clean up and abort
if %errorlevel% neq 0 (
echo !!! Error renaming python !!!
call :CLEAN_UP_TEMP_FOLDER
goto ERROR
)
:PACKMAN
:: The packman module may already be externally configured
if defined PM_MODULE_DIR_EXT (
set PM_MODULE_DIR=%PM_MODULE_DIR_EXT%
) else (
set PM_MODULE_DIR=%PM_PACKAGES_ROOT%\packman-common\%PM_PACKMAN_VERSION%
)
set PM_MODULE=%PM_MODULE_DIR%\packman.py
if exist "%PM_MODULE%" goto ENSURE_7ZA
set PM_MODULE_PACKAGE=packman-common@%PM_PACKMAN_VERSION%.zip
for /f "delims=" %%a in ('powershell -ExecutionPolicy ByPass -NoLogo -NoProfile -File "%~dp0\generate_temp_file_name.ps1"') do set TEMP_FILE_NAME=%%a
set TARGET=%TEMP_FILE_NAME%
call "%~dp0fetch_file_from_packman_bootstrap.cmd" %PM_MODULE_PACKAGE% "%TARGET%"
if %errorlevel% neq 0 (
echo !!! Error fetching packman from CDN !!!
goto ERROR
)
echo Unpacking ...
"%PM_PYTHON%" -S -s -u -E "%~dp0\install_package.py" "%TARGET%" "%PM_MODULE_DIR%"
if %errorlevel% neq 0 (
echo !!! Error unpacking packman !!!
goto ERROR
)
del "%TARGET%"
:ENSURE_7ZA
set PM_7Za_VERSION=16.02.4
set PM_7Za_PATH=%PM_PACKAGES_ROOT%\7za\%PM_7ZA_VERSION%
if exist "%PM_7Za_PATH%" goto END
set PM_7Za_PATH=%PM_PACKAGES_ROOT%\chk\7za\%PM_7ZA_VERSION%
if exist "%PM_7Za_PATH%" goto END
"%PM_PYTHON%" -S -s -u -E "%PM_MODULE%" pull "%PM_MODULE_DIR%\deps.packman.xml"
if %errorlevel% neq 0 (
echo !!! Error fetching packman dependencies !!!
goto ERROR
)
goto END
:ERROR_MKDIR_PACKAGES_ROOT
echo Failed to automatically create packman packages repo at %PM_PACKAGES_ROOT%.
echo Please set a location explicitly that packman has permission to write to, by issuing:
echo.
echo setx PM_PACKAGES_ROOT {path-you-choose-for-storing-packman-packages-locally}
echo.
echo Then launch a new command console for the changes to take effect and run packman command again.
exit /B %errorlevel%
:ERROR
echo !!! Failure while configuring local machine :( !!!
exit /B %errorlevel%
:CLEAN_UP_TEMP_FOLDER
rd /S /Q "%TEMP_FOLDER_NAME%"
exit /B
:CREATE_PYTHON_BASE_DIR
:: We ignore errors and clean error state - if two processes create the directory one will fail which is fine
md "%PM_PYTHON_BASE_DIR%" > nul 2>&1
exit /B 0
:END
|
yizhouzhao/VRKitchen2.0-IndoorKit/tools/packman/bootstrap/fetch_file_from_packman_bootstrap.cmd | :: 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.
:: You need to specify <package-name> <target-path> as input to this command
@setlocal
@set PACKAGE_NAME=%1
@set TARGET_PATH=%2
@echo Fetching %PACKAGE_NAME% ...
@powershell -ExecutionPolicy ByPass -NoLogo -NoProfile -File "%~dp0download_file_from_url.ps1" ^
-source "http://bootstrap.packman.nvidia.com/%PACKAGE_NAME%" -output %TARGET_PATH%
:: A bug in powershell prevents the errorlevel code from being set when using the -File execution option
:: We must therefore do our own failure analysis, basically make sure the file exists and is larger than 0 bytes:
@if not exist %TARGET_PATH% goto ERROR_DOWNLOAD_FAILED
@if %~z2==0 goto ERROR_DOWNLOAD_FAILED
@endlocal
@exit /b 0
:ERROR_DOWNLOAD_FAILED
@echo Failed to download file from S3
@echo Most likely because endpoint cannot be reached or file %PACKAGE_NAME% doesn't exist
@endlocal
@exit /b 1 |
yizhouzhao/VRKitchen2.0-IndoorKit/tools/packman/bootstrap/download_file_from_url.ps1 | <#
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.
#>
param(
[Parameter(Mandatory=$true)][string]$source=$null,
[string]$output="out.exe"
)
$filename = $output
$triesLeft = 3
do
{
$triesLeft -= 1
try
{
Write-Host "Downloading from bootstrap.packman.nvidia.com ..."
$wc = New-Object net.webclient
$wc.Downloadfile($source, $fileName)
$triesLeft = 0
}
catch
{
Write-Host "Error downloading $source!"
Write-Host $_.Exception|format-list -force
}
} while ($triesLeft -gt 0)
|
yizhouzhao/VRKitchen2.0-IndoorKit/tools/packman/bootstrap/generate_temp_folder.ps1 | <#
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.
#>
param(
[Parameter(Mandatory=$true)][string]$parentPath=$null
)
[string] $name = [System.Guid]::NewGuid()
$out = Join-Path $parentPath $name
New-Item -ItemType Directory -Path ($out) | Out-Null
Write-Host $out
# SIG # Begin signature block
# MIIaVwYJKoZIhvcNAQcCoIIaSDCCGkQCAQExDzANBglghkgBZQMEAgEFADB5Bgor
# BgEEAYI3AgEEoGswaTA0BgorBgEEAYI3AgEeMCYCAwEAAAQQH8w7YFlLCE63JNLG
# KX7zUQIBAAIBAAIBAAIBAAIBADAxMA0GCWCGSAFlAwQCAQUABCB29nsqMEu+VmSF
# 7ckeVTPrEZ6hsXjOgPFlJm9ilgHUB6CCCiIwggTTMIIDu6ADAgECAhBi50XpIWUh
# PJcfXEkK6hKlMA0GCSqGSIb3DQEBCwUAMIGEMQswCQYDVQQGEwJVUzEdMBsGA1UE
# ChMUU3ltYW50ZWMgQ29ycG9yYXRpb24xHzAdBgNVBAsTFlN5bWFudGVjIFRydXN0
# IE5ldHdvcmsxNTAzBgNVBAMTLFN5bWFudGVjIENsYXNzIDMgU0hBMjU2IENvZGUg
# U2lnbmluZyBDQSAtIEcyMB4XDTE4MDcwOTAwMDAwMFoXDTIxMDcwOTIzNTk1OVow
# gYMxCzAJBgNVBAYTAlVTMRMwEQYDVQQIDApDYWxpZm9ybmlhMRQwEgYDVQQHDAtT
# YW50YSBDbGFyYTEbMBkGA1UECgwSTlZJRElBIENvcnBvcmF0aW9uMQ8wDQYDVQQL
# DAZJVC1NSVMxGzAZBgNVBAMMEk5WSURJQSBDb3Jwb3JhdGlvbjCCASIwDQYJKoZI
# hvcNAQEBBQADggEPADCCAQoCggEBALEZN63dA47T4i90jZ84CJ/aWUwVtLff8AyP
# YspFfIZGdZYiMgdb8A5tBh7653y0G/LZL6CVUkgejcpvBU/Dl/52a+gSWy2qJ2bH
# jMFMKCyQDhdpCAKMOUKSC9rfzm4cFeA9ct91LQCAait4LhLlZt/HF7aG+r0FgCZa
# HJjJvE7KNY9G4AZXxjSt8CXS8/8NQMANqjLX1r+F+Hl8PzQ1fVx0mMsbdtaIV4Pj
# 5flAeTUnz6+dCTx3vTUo8MYtkS2UBaQv7t7H2B7iwJDakEQKk1XHswJdeqG0osDU
# z6+NVks7uWE1N8UIhvzbw0FEX/U2kpfyWaB/J3gMl8rVR8idPj8CAwEAAaOCAT4w
# ggE6MAkGA1UdEwQCMAAwDgYDVR0PAQH/BAQDAgeAMBMGA1UdJQQMMAoGCCsGAQUF
# BwMDMGEGA1UdIARaMFgwVgYGZ4EMAQQBMEwwIwYIKwYBBQUHAgEWF2h0dHBzOi8v
# ZC5zeW1jYi5jb20vY3BzMCUGCCsGAQUFBwICMBkMF2h0dHBzOi8vZC5zeW1jYi5j
# b20vcnBhMB8GA1UdIwQYMBaAFNTABiJJ6zlL3ZPiXKG4R3YJcgNYMCsGA1UdHwQk
# MCIwIKAeoByGGmh0dHA6Ly9yYi5zeW1jYi5jb20vcmIuY3JsMFcGCCsGAQUFBwEB
# BEswSTAfBggrBgEFBQcwAYYTaHR0cDovL3JiLnN5bWNkLmNvbTAmBggrBgEFBQcw
# AoYaaHR0cDovL3JiLnN5bWNiLmNvbS9yYi5jcnQwDQYJKoZIhvcNAQELBQADggEB
# AIJKh5vKJdhHJtMzATmc1BmXIQ3RaJONOZ5jMHn7HOkYU1JP0OIzb4pXXkH8Xwfr
# K6bnd72IhcteyksvKsGpSvK0PBBwzodERTAu1Os2N+EaakxQwV/xtqDm1E3IhjHk
# fRshyKKzmFk2Ci323J4lHtpWUj5Hz61b8gd72jH7xnihGi+LORJ2uRNZ3YuqMNC3
# SBC8tAyoJqEoTJirULUCXW6wX4XUm5P2sx+htPw7szGblVKbQ+PFinNGnsSEZeKz
# D8jUb++1cvgTKH59Y6lm43nsJjkZU77tNqyq4ABwgQRk6lt8cS2PPwjZvTmvdnla
# ZhR0K4of+pQaUQHXVIBdji8wggVHMIIEL6ADAgECAhB8GzU1SufbdOdBXxFpymuo
# MA0GCSqGSIb3DQEBCwUAMIG9MQswCQYDVQQGEwJVUzEXMBUGA1UEChMOVmVyaVNp
# Z24sIEluYy4xHzAdBgNVBAsTFlZlcmlTaWduIFRydXN0IE5ldHdvcmsxOjA4BgNV
# BAsTMShjKSAyMDA4IFZlcmlTaWduLCBJbmMuIC0gRm9yIGF1dGhvcml6ZWQgdXNl
# IG9ubHkxODA2BgNVBAMTL1ZlcmlTaWduIFVuaXZlcnNhbCBSb290IENlcnRpZmlj
# YXRpb24gQXV0aG9yaXR5MB4XDTE0MDcyMjAwMDAwMFoXDTI0MDcyMTIzNTk1OVow
# gYQxCzAJBgNVBAYTAlVTMR0wGwYDVQQKExRTeW1hbnRlYyBDb3Jwb3JhdGlvbjEf
# MB0GA1UECxMWU3ltYW50ZWMgVHJ1c3QgTmV0d29yazE1MDMGA1UEAxMsU3ltYW50
# ZWMgQ2xhc3MgMyBTSEEyNTYgQ29kZSBTaWduaW5nIENBIC0gRzIwggEiMA0GCSqG
# SIb3DQEBAQUAA4IBDwAwggEKAoIBAQDXlUPU3N9nrjn7UqS2JjEEcOm3jlsqujdp
# NZWPu8Aw54bYc7vf69F2P4pWjustS/BXGE6xjaUz0wt1I9VqeSfdo9P3Dodltd6t
# HPH1NbQiUa8iocFdS5B/wFlOq515qQLXHkmxO02H/sJ4q7/vUq6crwjZOeWaUT5p
# XzAQTnFjbFjh8CAzGw90vlvLEuHbjMSAlHK79kWansElC/ujHJ7YpglwcezAR0yP
# fcPeGc4+7gRyjhfT//CyBTIZTNOwHJ/+pXggQnBBsCaMbwDIOgARQXpBsKeKkQSg
# mXj0d7TzYCrmbFAEtxRg/w1R9KiLhP4h2lxeffUpeU+wRHRvbXL/AgMBAAGjggF4
# MIIBdDAuBggrBgEFBQcBAQQiMCAwHgYIKwYBBQUHMAGGEmh0dHA6Ly9zLnN5bWNk
# LmNvbTASBgNVHRMBAf8ECDAGAQH/AgEAMGYGA1UdIARfMF0wWwYLYIZIAYb4RQEH
# FwMwTDAjBggrBgEFBQcCARYXaHR0cHM6Ly9kLnN5bWNiLmNvbS9jcHMwJQYIKwYB
# BQUHAgIwGRoXaHR0cHM6Ly9kLnN5bWNiLmNvbS9ycGEwNgYDVR0fBC8wLTAroCmg
# J4YlaHR0cDovL3Muc3ltY2IuY29tL3VuaXZlcnNhbC1yb290LmNybDATBgNVHSUE
# DDAKBggrBgEFBQcDAzAOBgNVHQ8BAf8EBAMCAQYwKQYDVR0RBCIwIKQeMBwxGjAY
# BgNVBAMTEVN5bWFudGVjUEtJLTEtNzI0MB0GA1UdDgQWBBTUwAYiSes5S92T4lyh
# uEd2CXIDWDAfBgNVHSMEGDAWgBS2d/ppSEefUxLVwuoHMnYH0ZcHGTANBgkqhkiG
# 9w0BAQsFAAOCAQEAf+vKp+qLdkLrPo4gVDDjt7nc+kg+FscPRZUQzSeGo2bzAu1x
# +KrCVZeRcIP5Un5SaTzJ8eCURoAYu6HUpFam8x0AkdWG80iH4MvENGggXrTL+QXt
# nK9wUye56D5+UaBpcYvcUe2AOiUyn0SvbkMo0yF1u5fYi4uM/qkERgSF9xWcSxGN
# xCwX/tVuf5riVpLxlrOtLfn039qJmc6yOETA90d7yiW5+ipoM5tQct6on9TNLAs0
# vYsweEDgjY4nG5BvGr4IFYFd6y/iUedRHsl4KeceZb847wFKAQkkDhbEFHnBQTc0
# 0D2RUpSd4WjvCPDiaZxnbpALGpNx1CYCw8BaIzGCD4swgg+HAgEBMIGZMIGEMQsw
# CQYDVQQGEwJVUzEdMBsGA1UEChMUU3ltYW50ZWMgQ29ycG9yYXRpb24xHzAdBgNV
# BAsTFlN5bWFudGVjIFRydXN0IE5ldHdvcmsxNTAzBgNVBAMTLFN5bWFudGVjIENs
# YXNzIDMgU0hBMjU2IENvZGUgU2lnbmluZyBDQSAtIEcyAhBi50XpIWUhPJcfXEkK
# 6hKlMA0GCWCGSAFlAwQCAQUAoHwwEAYKKwYBBAGCNwIBDDECMAAwGQYJKoZIhvcN
# AQkDMQwGCisGAQQBgjcCAQQwHAYKKwYBBAGCNwIBCzEOMAwGCisGAQQBgjcCARUw
# LwYJKoZIhvcNAQkEMSIEIG5YDmcpqLxn4SB0H6OnuVkZRPh6OJ77eGW/6Su/uuJg
# MA0GCSqGSIb3DQEBAQUABIIBAA3N2vqfA6WDgqz/7EoAKVIE5Hn7xpYDGhPvFAMV
# BslVpeqE3apTcYFCEcwLtzIEc/zmpULxsX8B0SUT2VXbJN3zzQ80b+gbgpq62Zk+
# dQLOtLSiPhGW7MXLahgES6Oc2dUFaQ+wDfcelkrQaOVZkM4wwAzSapxuf/13oSIk
# ZX2ewQEwTZrVYXELO02KQIKUR30s/oslGVg77ALnfK9qSS96Iwjd4MyT7PzCkHUi
# ilwyGJi5a4ofiULiPSwUQNynSBqxa+JQALkHP682b5xhjoDfyG8laR234FTPtYgs
# P/FaeviwENU5Pl+812NbbtRD+gKlWBZz+7FKykOT/CG8sZahgg1EMIINQAYKKwYB
# BAGCNwMDATGCDTAwgg0sBgkqhkiG9w0BBwKggg0dMIINGQIBAzEPMA0GCWCGSAFl
# AwQCAQUAMHcGCyqGSIb3DQEJEAEEoGgEZjBkAgEBBglghkgBhv1sBwEwMTANBglg
# hkgBZQMEAgEFAAQgJhABfkDIPbI+nWYnA30FLTyaPK+W3QieT21B/vK+CMICEDF0
# worcGsdd7OxpXLP60xgYDzIwMjEwNDA4MDkxMTA5WqCCCjcwggT+MIID5qADAgEC
# AhANQkrgvjqI/2BAIc4UAPDdMA0GCSqGSIb3DQEBCwUAMHIxCzAJBgNVBAYTAlVT
# MRUwEwYDVQQKEwxEaWdpQ2VydCBJbmMxGTAXBgNVBAsTEHd3dy5kaWdpY2VydC5j
# b20xMTAvBgNVBAMTKERpZ2lDZXJ0IFNIQTIgQXNzdXJlZCBJRCBUaW1lc3RhbXBp
# bmcgQ0EwHhcNMjEwMTAxMDAwMDAwWhcNMzEwMTA2MDAwMDAwWjBIMQswCQYDVQQG
# EwJVUzEXMBUGA1UEChMORGlnaUNlcnQsIEluYy4xIDAeBgNVBAMTF0RpZ2lDZXJ0
# IFRpbWVzdGFtcCAyMDIxMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA
# wuZhhGfFivUNCKRFymNrUdc6EUK9CnV1TZS0DFC1JhD+HchvkWsMlucaXEjvROW/
# m2HNFZFiWrj/ZwucY/02aoH6KfjdK3CF3gIY83htvH35x20JPb5qdofpir34hF0e
# dsnkxnZ2OlPR0dNaNo/Go+EvGzq3YdZz7E5tM4p8XUUtS7FQ5kE6N1aG3JMjjfdQ
# Jehk5t3Tjy9XtYcg6w6OLNUj2vRNeEbjA4MxKUpcDDGKSoyIxfcwWvkUrxVfbENJ
# Cf0mI1P2jWPoGqtbsR0wwptpgrTb/FZUvB+hh6u+elsKIC9LCcmVp42y+tZji06l
# chzun3oBc/gZ1v4NSYS9AQIDAQABo4IBuDCCAbQwDgYDVR0PAQH/BAQDAgeAMAwG
# A1UdEwEB/wQCMAAwFgYDVR0lAQH/BAwwCgYIKwYBBQUHAwgwQQYDVR0gBDowODA2
# BglghkgBhv1sBwEwKTAnBggrBgEFBQcCARYbaHR0cDovL3d3dy5kaWdpY2VydC5j
# b20vQ1BTMB8GA1UdIwQYMBaAFPS24SAd/imu0uRhpbKiJbLIFzVuMB0GA1UdDgQW
# BBQ2RIaOpLqwZr68KC0dRDbd42p6vDBxBgNVHR8EajBoMDKgMKAuhixodHRwOi8v
# Y3JsMy5kaWdpY2VydC5jb20vc2hhMi1hc3N1cmVkLXRzLmNybDAyoDCgLoYsaHR0
# cDovL2NybDQuZGlnaWNlcnQuY29tL3NoYTItYXNzdXJlZC10cy5jcmwwgYUGCCsG
# AQUFBwEBBHkwdzAkBggrBgEFBQcwAYYYaHR0cDovL29jc3AuZGlnaWNlcnQuY29t
# ME8GCCsGAQUFBzAChkNodHRwOi8vY2FjZXJ0cy5kaWdpY2VydC5jb20vRGlnaUNl
# cnRTSEEyQXNzdXJlZElEVGltZXN0YW1waW5nQ0EuY3J0MA0GCSqGSIb3DQEBCwUA
# A4IBAQBIHNy16ZojvOca5yAOjmdG/UJyUXQKI0ejq5LSJcRwWb4UoOUngaVNFBUZ
# B3nw0QTDhtk7vf5EAmZN7WmkD/a4cM9i6PVRSnh5Nnont/PnUp+Tp+1DnnvntN1B
# Ion7h6JGA0789P63ZHdjXyNSaYOC+hpT7ZDMjaEXcw3082U5cEvznNZ6e9oMvD0y
# 0BvL9WH8dQgAdryBDvjA4VzPxBFy5xtkSdgimnUVQvUtMjiB2vRgorq0Uvtc4GEk
# JU+y38kpqHNDUdq9Y9YfW5v3LhtPEx33Sg1xfpe39D+E68Hjo0mh+s6nv1bPull2
# YYlffqe0jmd4+TaY4cso2luHpoovMIIFMTCCBBmgAwIBAgIQCqEl1tYyG35B5AXa
# NpfCFTANBgkqhkiG9w0BAQsFADBlMQswCQYDVQQGEwJVUzEVMBMGA1UEChMMRGln
# aUNlcnQgSW5jMRkwFwYDVQQLExB3d3cuZGlnaWNlcnQuY29tMSQwIgYDVQQDExtE
# aWdpQ2VydCBBc3N1cmVkIElEIFJvb3QgQ0EwHhcNMTYwMTA3MTIwMDAwWhcNMzEw
# MTA3MTIwMDAwWjByMQswCQYDVQQGEwJVUzEVMBMGA1UEChMMRGlnaUNlcnQgSW5j
# MRkwFwYDVQQLExB3d3cuZGlnaWNlcnQuY29tMTEwLwYDVQQDEyhEaWdpQ2VydCBT
# SEEyIEFzc3VyZWQgSUQgVGltZXN0YW1waW5nIENBMIIBIjANBgkqhkiG9w0BAQEF
# AAOCAQ8AMIIBCgKCAQEAvdAy7kvNj3/dqbqCmcU5VChXtiNKxA4HRTNREH3Q+X1N
# aH7ntqD0jbOI5Je/YyGQmL8TvFfTw+F+CNZqFAA49y4eO+7MpvYyWf5fZT/gm+vj
# RkcGGlV+Cyd+wKL1oODeIj8O/36V+/OjuiI+GKwR5PCZA207hXwJ0+5dyJoLVOOo
# CXFr4M8iEA91z3FyTgqt30A6XLdR4aF5FMZNJCMwXbzsPGBqrC8HzP3w6kfZiFBe
# /WZuVmEnKYmEUeaC50ZQ/ZQqLKfkdT66mA+Ef58xFNat1fJky3seBdCEGXIX8RcG
# 7z3N1k3vBkL9olMqT4UdxB08r8/arBD13ays6Vb/kwIDAQABo4IBzjCCAcowHQYD
# VR0OBBYEFPS24SAd/imu0uRhpbKiJbLIFzVuMB8GA1UdIwQYMBaAFEXroq/0ksuC
# MS1Ri6enIZ3zbcgPMBIGA1UdEwEB/wQIMAYBAf8CAQAwDgYDVR0PAQH/BAQDAgGG
# MBMGA1UdJQQMMAoGCCsGAQUFBwMIMHkGCCsGAQUFBwEBBG0wazAkBggrBgEFBQcw
# AYYYaHR0cDovL29jc3AuZGlnaWNlcnQuY29tMEMGCCsGAQUFBzAChjdodHRwOi8v
# Y2FjZXJ0cy5kaWdpY2VydC5jb20vRGlnaUNlcnRBc3N1cmVkSURSb290Q0EuY3J0
# MIGBBgNVHR8EejB4MDqgOKA2hjRodHRwOi8vY3JsNC5kaWdpY2VydC5jb20vRGln
# aUNlcnRBc3N1cmVkSURSb290Q0EuY3JsMDqgOKA2hjRodHRwOi8vY3JsMy5kaWdp
# Y2VydC5jb20vRGlnaUNlcnRBc3N1cmVkSURSb290Q0EuY3JsMFAGA1UdIARJMEcw
# OAYKYIZIAYb9bAACBDAqMCgGCCsGAQUFBwIBFhxodHRwczovL3d3dy5kaWdpY2Vy
# dC5jb20vQ1BTMAsGCWCGSAGG/WwHATANBgkqhkiG9w0BAQsFAAOCAQEAcZUS6VGH
# VmnN793afKpjerN4zwY3QITvS4S/ys8DAv3Fp8MOIEIsr3fzKx8MIVoqtwU0HWqu
# mfgnoma/Capg33akOpMP+LLR2HwZYuhegiUexLoceywh4tZbLBQ1QwRostt1AuBy
# x5jWPGTlH0gQGF+JOGFNYkYkh2OMkVIsrymJ5Xgf1gsUpYDXEkdws3XVk4WTfraS
# Z/tTYYmo9WuWwPRYaQ18yAGxuSh1t5ljhSKMYcp5lH5Z/IwP42+1ASa2bKXuh1Eh
# 5Fhgm7oMLSttosR+u8QlK0cCCHxJrhO24XxCQijGGFbPQTS2Zl22dHv1VjMiLyI2
# skuiSpXY9aaOUjGCAk0wggJJAgEBMIGGMHIxCzAJBgNVBAYTAlVTMRUwEwYDVQQK
# EwxEaWdpQ2VydCBJbmMxGTAXBgNVBAsTEHd3dy5kaWdpY2VydC5jb20xMTAvBgNV
# BAMTKERpZ2lDZXJ0IFNIQTIgQXNzdXJlZCBJRCBUaW1lc3RhbXBpbmcgQ0ECEA1C
# SuC+Ooj/YEAhzhQA8N0wDQYJYIZIAWUDBAIBBQCggZgwGgYJKoZIhvcNAQkDMQ0G
# CyqGSIb3DQEJEAEEMBwGCSqGSIb3DQEJBTEPFw0yMTA0MDgwOTExMDlaMCsGCyqG
# SIb3DQEJEAIMMRwwGjAYMBYEFOHXgqjhkb7va8oWkbWqtJSmJJvzMC8GCSqGSIb3
# DQEJBDEiBCDvFxQ6lYLr8vB+9czUl19rjCw1pWhhUXw/SqOmvIa/VDANBgkqhkiG
# 9w0BAQEFAASCAQB9ox2UrcUXQsBI4Uycnhl4AMpvhVXJME62tygFMppW1l7QftDy
# LvfPKRYm2YUioak/APxAS6geRKpeMkLvXuQS/Jlv0kY3BjxkeG0eVjvyjF4SvXbZ
# 3JCk9m7wLNE+xqOo0ICjYlIJJgRLudjWkC5Skpb1NpPS8DOaIYwRV+AWaSOUPd9P
# O5yVcnbl7OpK3EAEtwDrybCVBMPn2MGhAXybIHnth3+MFp1b6Blhz3WlReQyarjq
# 1f+zaFB79rg6JswXoOTJhwICBP3hO2Ua3dMAswbfl+QNXF+igKLJPYnaeSVhBbm6
# VCu2io27t4ixqvoD0RuPObNX/P3oVA38afiM
# SIG # End signature block
|
yizhouzhao/VRKitchen2.0-IndoorKit/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])
|
yizhouzhao/VRKitchen2.0-IndoorKit/exts/vrkitchen.indoor.kit/vrkitchen/indoor/kit/extension.py | ############# omniverse import ##################
import omni.ext
import omni.ui as ui
import carb
import pxr
############# python import ##################
import asyncio
import os
import time
import random
import math
import json
import numpy as np
############# VRKitchen import ##################
from .param import *
# from .layout.house import House
from .layout.randomizer import Randomizer
from .layout.utils import add_semantics
from .layout.house_new import House as HouseNew
from .autotask.auto import AutoTasker
# from .autotask.auto_label import AutoLabeler
from .render.helper import CustomSyntheticDataHelper
###################### ui import ################
from .ui.indoorkit_ui_widget import TaskTypeComboboxWidget, CustomRecordGroup, CustomControlGroup, CustomBoolWidget, CustomSliderWidget, \
CustomSkySelectionGroup, CustomIdNotice, CustomPathButtonWidget, CustomRenderTypeSelectionGroup
from omni.kit.window.popup_dialog import MessageDialog
# Any class derived from `omni.ext.IExt` in top level module (defined in `python.modules` of `extension.toml`) will be
# instantiated when extension gets enabled and `on_startup(ext_id)` will be called. Later when extension gets disabled
# on_shutdown() is called.
class MyExtension(omni.ext.IExt):
# ext_id is current extension id. It can be used with extension manager to query additional information, like where
# this extension is located on filesystem.
def on_startup(self, ext_id):
print("[vrkitchen.indoor.kit] VRKitchen2.0-Indoor-Kit startup")
# set rendering settings:
carb.settings.get_settings().set_bool("/rtx/ecoMode/enabled", True)
FPS = 60.0
carb.settings.get_settings().set_bool("/app/runLoops/main/rateLimitEnabled", True)
carb.settings.get_settings().set_int("/app/runLoops/main/rateLimitFrequency", int( FPS))
# carb.settings.get_settings().set_int("/persistent/simulation/minFrameRate", int(FPS))
# stage and timeline
self.stage = omni.usd.get_context().get_stage()
pxr.UsdGeom.SetStageUpAxis(self.stage, pxr.UsdGeom.Tokens.y)
self.timeline = omni.timeline.get_timeline_interface()
# robot
self.franka = None
# self.auto_labeler = AutoLabeler(None)
self.task_type = None
# set up render
self.use_isosurface = False # use isosurface
self.render_folder = RENDER_ROOT
self.render_helper = CustomSyntheticDataHelper()
# build windows
self.build_setup_layout_window()
################################################################################################
######################################## Build omni ui window ##################################
################################################################################################
def build_setup_layout_window(self):
"""
Build a window to control/debug layout
"""
from .ui.style import julia_modeler_style
self._window = ui.Window("VRKitchen2.0-Indoor-Kit", width=390)
with self._window.frame:
self._window.frame.style = julia_modeler_style
with ui.ScrollingFrame():
with ui.VStack(height=0):
# ui.Button("Debug", clicked_fn = self.debug)
self.task_desc_ui = ui.StringField(height=20, style={ "margin_height": 2})
self.task_desc_ui.model.set_value(" Welcome to VRKitchen2.0 Indoor Kit!")
ui.Spacer(height=10)
ui.Line(style_type_name_override="HeaderLine")
self.task_layout_collapse_ui = ui.CollapsableFrame("TASK LAYOUT", build_header_fn=self._build_custom_frame_header)
# self.task_layout_collapse_ui.set_collapsed_changed_fn(lambda x:self.on_task_layout_ui_collapse(x))
with self.task_layout_collapse_ui:
with ui.VStack(height=0, spacing=0):
ui.Line(style_type_name_override="HeaderLine")
ui.Spacer(height = 12)
with ui.HStack(height=30):
# set up tasks
self.task_types = TASK_TYPES
# ui.Label(" Task type: ", width = 30, style={ "margin": 2 , "color": "cornflowerblue", "font_size":18})
# default_task_index = self.task_types.index("pickup_object")
# self.task_type_ui = ui.ComboBox(default_task_index, width = 200, *self.task_types, style={ "margin": 8, "color": "cornflowerblue", "font_size":18})
self.task_type_ui = TaskTypeComboboxWidget(label="Task type:\t", options=self.task_types, on_restore_fn=self.fill_task_info)
# ui.Button(" + ", clicked_fn=self.auto_next_task, width = 20, style={ "margin_height": 8})
# ui.Button("+ object id", clicked_fn=self.auto_next_obj_only, style={ "margin": 8})
self.annotators = ANNOTATORS
ui.Label(" Annotator: ", width = 30, style={ "font_size": 12 , "color": "PowderBlue"}, visible = False)
annotator_index = ANNOTATORS.index("MyLuckyUser")
self.annotator_ui = ui.ComboBox(annotator_index, width = 100, *self.annotators, style={ "margin_height": 8, "font_size": 12, "color": "PowderBlue" }, visible=False)
# self.auto_suggest.annotator_ui = self.annotator_ui
with ui.HStack(height=30):
with ui.HStack():
ui.Label("\tObject id: ", width=30, style={"color": "DarkSalmon"})
self.task_id_ui = omni.ui.IntField(width = 30, name = "choose_id", style={ "color": "DarkSalmon"})
ui.Button("+", width = 30, style={"margin_height": 8, "color": "DarkSalmon", "border_color": 1, "border_width": 1},
clicked_fn=lambda: self.task_id_ui.model.set_value(min(self.task_id_ui.model.get_value_as_int() + 1, 19)))
ui.Button("-", width = 30, style={ "margin_height": 8, "color": "DarkSalmon", "border_color": 1, "border_width": 1},
clicked_fn=lambda: self.task_id_ui.model.set_value(max(self.task_id_ui.model.get_value_as_int() - 1, 0 )))
ui.Button("Add object", name = "add_button", clicked_fn=self.auto_add_obj, style={ "color": "DarkSalmon"})
ui.Label(" Object ", width=20, visible = False)
self.object_id_ui = omni.ui.IntField(height=20, width = 25, style={ "margin_height": 8 , "margin_width": 4}, visible = False)
self.object_id_ui.model.set_value(0)
ui.Button("+", width = 20, style={"margin_height": 8, "font_size": 12},
clicked_fn=lambda: self.object_id_ui.model.set_value(self.object_id_ui.model.get_value_as_int() + 1), visible = False)
ui.Button("-", width = 20, style={ "margin_height": 8, "font_size": 12},
clicked_fn=lambda: self.object_id_ui.model.set_value(self.object_id_ui.model.get_value_as_int() - 1), visible = False)
ui.Label(" Anchor:", width=20, visible = False)
self.anchor_id_ui = omni.ui.IntField(height=20, width = 25, style={ "margin_height": 8 , "margin_width": 4}, visible = False)
self.anchor_id_ui.model.set_value(0)
ui.Button("+", width = 20, style={"margin_height": 8, "font_size": 12},
clicked_fn=lambda: self.anchor_id_ui.model.set_value(self.anchor_id_ui.model.get_value_as_int() + 1), visible = False)
ui.Button("-", width = 20, style={ "margin_height": 8, "font_size": 12},
clicked_fn=lambda: self.anchor_id_ui.model.set_value(self.anchor_id_ui.model.get_value_as_int() - 1), visible = False)
ui.Label(" Robot:", width=20, visible = False)
self.robot_id_ui = omni.ui.IntField(height=20, width = 25, style={ "margin_height": 8 , "margin_width": 4}, visible = False)
ui.Button("+", width = 20, style={"margin_height": 8, "font_size": 12},
clicked_fn=lambda: self.robot_id_ui.model.set_value(self.robot_id_ui.model.get_value_as_int() + 1), visible = False)
ui.Button("-", width = 20, style={ "margin_height": 8, "font_size": 12},
clicked_fn=lambda: self.robot_id_ui.model.set_value(self.robot_id_ui.model.get_value_as_int() - 1), visible = False)
ui.Label("Mission ", width=20, visible = False)
self.mission_id_ui = omni.ui.IntField(height=20, width = 40, style={ "margin": 8 }, visible = False)
with ui.HStack():
ui.Label("\tHouse id: ", width = 30, style = { "color": "Plum", "font_size": 14})
self.house_id_ui = omni.ui.IntField(width = 30, name = "choose_id", style={"color": "Plum"})
self.house_id_ui.model.set_value(0)
ui.Button("+", width = 30, style={"margin_height": 8, "font_size": 14, "color": "Plum", "border_color": 1, "border_width": 1},
clicked_fn=lambda: self.house_id_ui.model.set_value(min(self.house_id_ui.model.get_value_as_int() + 1, 2)))
ui.Button("-", width = 30, style={ "margin_height": 8, "font_size": 14, "color": "Plum", "border_color": 1, "border_width": 1},
clicked_fn=lambda: self.house_id_ui.model.set_value(max(self.house_id_ui.model.get_value_as_int() - 1, 0)))
ui.Button("Add house", name = "add_button", clicked_fn=self.auto_add_house, style={ "color": "Plum"})
with ui.HStack(height=20, visible = False):
ui.Button("Add robot", clicked_fn=self.auto_add_robot, style={ "margin": 4})
ui.Button("Add mission", clicked_fn=self.auto_add_mission, style={ "margin": 4})
# ui.Label(" |", width=10)
with ui.HStack(height=20, visible = False):
ui.Button("Record object", name = "record_button", clicked_fn=self.record_obj_new, style={ "margin": 4})
ui.Button("Record robot", name = "record_button", clicked_fn=self.record_robot_new, style={ "margin": 4})
ui.Label(" |", width=10)
ui.Button("Record house", name = "record_button", clicked_fn=self.record_house_new, style={ "margin": 4})
with ui.HStack(height=20):
ui.Button("Record scene", height = 40, name = "record_button", clicked_fn=self.record_scene, style={ "margin": 4})
with ui.HStack(height=20, visible = False):
ui.Button("Load object", clicked_fn=self.load_obj_new, style={ "margin": 4})
ui.Button("Load robot", clicked_fn=self.load_robot_new, style={ "margin": 4})
# ui.Button("Load mission", clicked_fn=self.load_mission, style={ "margin": 4})
ui.Label(" |", width=10)
ui.Button("Load house", clicked_fn=self.load_house_new, style={ "margin": 4})
ui.Spacer(height = 10)
ui.Line(style_type_name_override="HeaderLine")
with ui.CollapsableFrame("SCENE UTILITY"):
with ui.VStack(height=0, spacing=4):
ui.Line(style_type_name_override="HeaderLine")
# open a new stage
ui.Button("New scene", height = 40, name = "load_button", clicked_fn=lambda : omni.kit.window.file.new(), style={ "margin": 4}, tooltip = "open a new empty stage")
# load recorded scene
ui.Button("Load scene", height = 40, name = "load_button", clicked_fn=self.load_scene, style={ "margin": 4})
# ground plan
CustomBoolWidget(label="Visible ground:", default_value=False, on_checked_fn = self.auto_add_ground)
# light intensity
CustomSliderWidget(min=0, max=3000, label="Light intensity:", default_val=1000, on_slide_fn = self.change_light_intensity)
# sky selection
CustomSkySelectionGroup(on_select_fn=self.randomize_sky)
# house material
CustomBoolWidget(label="Random house material:", default_value=False, on_checked_fn = self.randomize_material)
# water isosurface
CustomBoolWidget(label="Enable isosurface:", default_value=False, on_checked_fn = self.enable_isosurface)
# PLAY group
ui.Spacer(height = 10)
ui.Line(style_type_name_override="HeaderLine")
with ui.CollapsableFrame("PLAY"):
with ui.VStack(height=0, spacing=0):
ui.Line(style_type_name_override="HeaderLine")
ui.Spacer(height = 12)
# play and record
record_group = CustomRecordGroup(
on_click_record_fn=self.start_record,
on_click_stop_fn=self.stop_record,
on_click_replay_fn=self.replay_record,
)
# robot control
control_group = CustomControlGroup()
record_group.control_group = control_group
with ui.CollapsableFrame("Render"):
with ui.VStack(height=0, spacing=0):
CustomRenderTypeSelectionGroup(on_select_fn=self.set_render_type)
ui.Button("Capture image", height = 40, name = "tool_button", clicked_fn=self.render_an_image, style={ "margin": 4}, tooltip = "Capture current screenshot")
# PATH group
ui.Spacer(height = 10)
ui.Line(style_type_name_override="HeaderLine")
with ui.CollapsableFrame("PATH", collapsed = True):
with ui.VStack(height=0, spacing=0):
ui.Line(style_type_name_override="HeaderLine")
ui.Spacer(height = 12)
CustomPathButtonWidget(label="Task folder:", path=DATA_PATH_NEW)
CustomPathButtonWidget(label="Record folder:", path=SAVE_ROOT)
CustomPathButtonWidget(label="Render folder:", path=self.render_folder)
################################################################################################
######################################## Auto task labeling ####################################
################################################################################################
def fill_task_info(self, reset = False):
"""
Automatically (randomly fill task type, housing id, and object id)
:: params:
reset: if true, set all to zeros
"""
task_type_id = np.random.randint(len(self.task_types)) if not reset else 0
object_id = np.random.randint(20) if not reset else 0 # task id
house_id = np.random.randint(3) if not reset else 0 # house id
self.task_type_ui.model.get_item_value_model().set_value(task_type_id)
self.task_id_ui.model.set_value(object_id)
self.house_id_ui.model.set_value(house_id)
def init_auto_tasker(self):
"""
Initialize auto task labeling tool
"""
# update stage
self.stage = omni.usd.get_context().get_stage()
pxr.UsdGeom.SetStageUpAxis(self.stage, pxr.UsdGeom.Tokens.y)
task_index = self.task_type_ui.model.get_item_value_model().get_value_as_int()
task_type = self.task_types[task_index]
task_id = self.task_id_ui.model.get_value_as_int()
robot_id = self.robot_id_ui.model.get_value_as_int()
anchor_id = self.anchor_id_ui.model.get_value_as_int()
mission_id = self.mission_id_ui.model.get_value_as_int()
house_id = self.house_id_ui.model.get_value_as_int()
# meta_id = self.meta_id_ui.model.get_value_as_int()
# FIXME: add annotator
# annotator_index = self.annotator_ui.model.get_item_value_model().get_value_as_int()
annotator = "MyLuckyUser" # self.annotators[annotator_index]
self.auto_tasker = AutoTasker(task_type, task_id, robot_id, mission_id, house_id, anchor_id, annotator=annotator)
AutoTasker.TASK_DESCRIPTION = self.task_desc_ui.model.get_value_as_string()
def auto_next_obj_only(self):
"""
retrieve the next object index for current task
"""
# new scene
AutoTasker.new_scene()
global OBJ_INDEX
OBJ_INDEX = self.object_id_ui.model.get_value_as_int()
OBJ_INDEX += 1
self.object_id_ui.model.set_value(OBJ_INDEX)
self.init_auto_tasker()
self.auto_tasker.reconfig(OBJ_INDEX)
self.task_desc_ui.model.set_value(AutoTasker.TASK_DESCRIPTION)
def auto_next_task(self):
"""
next task
"""
task_id = self.task_id_ui.model.get_value_as_int()
self.task_id_ui.model.set_value(task_id + 1)
AutoTasker.new_scene()
self.init_auto_tasker()
self.auto_tasker.reconfig(0)
self.task_desc_ui.model.set_value(AutoTasker.TASK_DESCRIPTION)
def auto_next_task(self):
"""
next task
"""
task_id = self.task_id_ui.model.get_value_as_int()
self.task_id_ui.model.set_value(task_id + 1)
AutoTasker.new_scene()
self.init_auto_tasker()
self.auto_tasker.reconfig(0)
self.task_desc_ui.model.set_value(AutoTasker.TASK_DESCRIPTION)
def auto_add_obj(self):
self.init_auto_tasker()
if self.stage.GetPrimAtPath("/World/game"):
dialog = MessageDialog(
title="Add Object",
message=f"Already have `/World/game` in the scene. Please start a new stage.",
disable_cancel_button=True,
ok_handler=lambda dialog: dialog.hide()
)
dialog.show()
return
self.auto_tasker.add_obj()
# self.auto_tasker.build_HUD()
if self.stage.GetPrimAtPath("/World/game"):
self.task_desc_ui.model.set_value("Task object added!")
self.auto_add_robot()
def auto_add_robot(self):
self.init_auto_tasker()
self.auto_tasker.add_robot()
franka_prim = self.stage.GetPrimAtPath("/World/game/franka")
if franka_prim:
self.task_desc_ui.model.set_value("Feel free to move the robot, \nthen you can `Add house`")
selection = omni.usd.get_context().get_selection()
selection.clear_selected_prim_paths()
selection.set_prim_path_selected(franka_prim.GetPath().pathString, True, True, True, True)
viewport = omni.kit.viewport_legacy.get_viewport_interface()
viewport = viewport.get_viewport_window() if viewport else None
if viewport:
viewport.focus_on_selected()
else:
from omni.kit.viewport.utility import frame_viewport_selection
frame_viewport_selection(force_legacy_api=True)
def auto_add_house(self):
self.init_auto_tasker()
if self.stage.GetPrimAtPath("/World/layout"):
dialog = MessageDialog(
title="Add house",
message=f"Already have `/World/layout` in the scene. Please start a new stage.",
disable_cancel_button=True,
ok_handler=lambda dialog: dialog.hide()
)
dialog.show()
return
self.auto_tasker.add_house()
layout_prim = self.stage.GetPrimAtPath("/World/layout")
if layout_prim:
self.task_desc_ui.model.set_value("House added! Feel feel to move the /World/game and record scene.")
selection = omni.usd.get_context().get_selection()
selection.clear_selected_prim_paths()
selection.set_prim_path_selected("/World/game", True, True, True, True)
floor_prim = self.stage.GetPrimAtPath("/World/layout/floor")
def auto_add_mission(self):
self.init_auto_tasker()
self.auto_tasker.add_task()
################################################################################################
######################################## Modify Scene ##########################################
################################################################################################
def auto_add_ground(self, visible = False):
"""
Add ground to the scene
"""
self.stage = omni.usd.get_context().get_stage()
if not self.stage.GetPrimAtPath("/World/game"):
carb.log_error("Please add /World/game first!")
self.task_desc_ui.model.set_value(f"Please `Add Object`")
return
from .layout.modify import add_ground_plane
add_ground_plane(visiable=visible)
self.task_desc_ui.model.set_value(f"Add ground to scene (visible : {visible})")
selection = omni.usd.get_context().get_selection()
selection.clear_selected_prim_paths()
selection.set_prim_path_selected("/World/groundPlane", True, True, True, True)
def randomize_material(self, rand = True):
"""
Randomize house materials
"""
self.stage = omni.usd.get_context().get_stage()
if not self.stage.GetPrimAtPath("/World/layout"):
carb.log_error("Please add /World/layout (load scene) first!")
self.task_desc_ui.model.set_value(f"Please `Load Scene`")
return
self.randomizer = Randomizer()
self.randomizer.randomize_house(rand = rand)
self.task_desc_ui.model.set_value("Added floor/wall material")
def randomize_sky(self, sky_type = None):
"""
Randomize house materials
"""
self.randomizer = Randomizer()
self.randomizer.randomize_sky(sky_type = sky_type)
self.task_desc_ui.model.set_value("Sky added.")
def randomize_light(self):
"""
Randomize house materials
"""
self.randomizer = Randomizer()
self.randomizer.randomize_light()
self.task_desc_ui.model.set_value("Random light")
def change_light_intensity(self, intensity):
"""
Change default light intensity
"""
self.stage = omni.usd.get_context().get_stage()
light_prim = self.stage.GetPrimAtPath("/World/defaultLight")
if not light_prim:
# Create basic DistantLight
omni.kit.commands.execute(
"CreatePrim",
prim_path="/World/defaultLight",
prim_type="DistantLight",
select_new_prim=False,
attributes={pxr.UsdLux.Tokens.angle: 1.0, pxr.UsdLux.Tokens.intensity: 1000},
create_default_xform=True,
)
light_prim = self.stage.GetPrimAtPath("/World/defaultLight")
light_prim.GetAttribute("intensity").Set(float(intensity))
def enable_isosurface(self, enable = False):
"""
enable isosurface for water scene
"""
self.use_isosurface = enable
dialog = MessageDialog(
title="Isosurface",
message=f"Enabled iso surface: {self.use_isosurface} \n Please a [New Scene] and [Load Scene] for water task again.",
disable_cancel_button=True,
ok_handler=lambda dialog: dialog.hide()
)
dialog.show()
################################################################################################
######################################## Load / Record #########################################
################################################################################################
def init_new_house(self):
"""
Initiate HouseNew for recording/loading task info
"""
task_index = self.task_type_ui.model.get_item_value_model().get_value_as_int()
task_type = self.task_types[task_index]
task_id = self.task_id_ui.model.get_value_as_int()
robot_id = self.robot_id_ui.model.get_value_as_int()
anchor_id = self.anchor_id_ui.model.get_value_as_int()
mission_id = self.mission_id_ui.model.get_value_as_int()
house_id = self.house_id_ui.model.get_value_as_int()
annotator_index = self.annotator_ui.model.get_item_value_model().get_value_as_int()
annotator = self.annotators[annotator_index]
self.house = HouseNew(task_type, task_id, robot_id, mission_id, house_id, anchor_id, annotator)
# self.house.build_HUD()
# print("robot", self.house.robot_id)
def record_scene(self):
"""
Record obj + robot + house
"""
self.init_new_house()
self.house.record_obj_info()
self.house.record_robot_info()
self.house.record_house_info()
self.task_desc_ui.model.set_value("Scene recorded! Please start a new empty scene [Load scene] \n Note: you don't have to save the current stage.")
dialog = MessageDialog(
title="Scene Recorded",
message=f"Scene recorded! \nPlease start a [New scene] and then [Load scene] \nNote: you don't have to save the current stage.",
disable_cancel_button=True,
ok_handler=lambda dialog: dialog.hide()
)
dialog.show()
def record_obj_new(self):
"""
New pipeline to record game objects
"""
self.init_new_house()
self.house.record_obj_info()
self.task_desc_ui.model.set_value("object location recorded!")
def record_robot_new(self):
"""
New pipeline to record game robots
"""
self.init_new_house()
self.house.record_robot_info()
# if BaseChecker.SUCCESS_UI:
# BaseChecker.SUCCESS_UI.model.set_value("robot id (robot variation) recorded")
self.task_desc_ui.model.set_value("robot location recorded!")
def record_house_new(self):
self.init_new_house()
self.house.record_house_info()
# if BaseChecker.SUCCESS_UI:
# BaseChecker.SUCCESS_UI.model.set_value("house-anchor recorded")
self.task_desc_ui.model.set_value("game location in house recorded!")
def load_scene(self):
"""
Load obj + robot + house
"""
self.stage = omni.usd.get_context().get_stage()
pxr.UsdGeom.SetStageUpAxis(self.stage, pxr.UsdGeom.Tokens.y)
if self.stage.GetPrimAtPath("/World/game"):
dialog = MessageDialog(
title="Load scene",
message=f"Already have `/World/game` in the scene. Please start a new stage.",
disable_cancel_button=True,
ok_handler=lambda dialog: dialog.hide()
)
dialog.show()
return
dialog = MessageDialog(
title="Loading scene ......",
message=f"Please wait ......",
disable_cancel_button=True,
ok_handler=lambda dialog: dialog.hide()
)
dialog.show()
self.load_obj_new()
self.load_robot_new()
self.load_house_new()
# focus on game
selection = omni.usd.get_context().get_selection()
selection.clear_selected_prim_paths()
selection.set_prim_path_selected("/World/game", True, True, True, True)
viewport = omni.kit.viewport_legacy.get_viewport_interface()
viewport = viewport.get_viewport_window() if viewport else None
if viewport:
viewport.focus_on_selected()
else:
from omni.kit.viewport.utility import frame_viewport_selection
frame_viewport_selection(force_legacy_api=True)
selection.clear_selected_prim_paths()
dialog.hide()
dialog2 = MessageDialog(
title="Loading scene ......",
message=f"Loading scene complete!",
disable_cancel_button=True,
ok_handler=lambda dialog2: dialog2.hide()
)
dialog2.show()
def load_obj_new(self):
"""
New pipeline to load game objs
"""
stage = omni.usd.get_context().get_stage()
default_prim_path = stage.GetDefaultPrim().GetPath()
if default_prim_path.pathString == '':
# default_prim_path = pxr.Sdf.Path('/World')
root = pxr.UsdGeom.Xform.Define(stage, "/World").GetPrim()
stage.SetDefaultPrim(root)
default_prim_path = stage.GetDefaultPrim().GetPath()
self.init_new_house()
self.house.load_obj_info(relative=True)
task_index = self.task_type_ui.model.get_item_value_model().get_value_as_int()
task_type = self.task_types[task_index]
# fix linear joint scale
if task_type in ["open_drawer","open_cabinet", "open_door", \
"close_drawer", "close_cabinet", "close_door", "tap_water"]:
if task_type in ["open_door", "close_door"]:
self.fix_linear_joint(fix_driver=True, damping_cofficient=1000)
elif task_type in ["tap_water"]:
self.fix_linear_joint(fix_driver=True, damping_cofficient=100)
else:
self.fix_linear_joint(fix_driver=True, damping_cofficient=10)
if task_type in ["pour_water", "transfer_water", "tap_water"]:
self.add_liquid_to_cup(task_type, self.use_isosurface)
def load_robot_new(self):
"""
New pipeline to load robots objs
"""
self.is_initial_setup = False
self.init_new_house()
self.setup_robot(new_method=True)
franka_prim = omni.usd.get_context().get_stage().GetPrimAtPath("/World/game/franka")
if franka_prim:
add_semantics(franka_prim, "franka")
def load_house_new(self):
self.stage = omni.usd.get_context().get_stage()
self.init_new_house()
self.load_house_successful = self.house.load_house_info()
# if load house successfully, randomize sky, floor, and wall
if self.load_house_successful:
floor_prim = self.stage.GetPrimAtPath("/World/layout/floor")
if floor_prim:
add_semantics(floor_prim, "floor")
furniture_prim = self.stage.GetPrimAtPath("/World/layout/furniture")
if furniture_prim:
add_semantics(furniture_prim, "furniture")
wall_prim = self.stage.GetPrimAtPath("/World/layout/roomStruct")
if wall_prim:
add_semantics(wall_prim, "wall")
# from .layout.randomizer import Randomizer
# if not hasattr(self, "house_randomizer"):
# self.house_randomizer = Randomizer(None)
# self.house_randomizer.randomize_house(randomize_floor=True, randomize_wall=True)
# if IS_IN_CREAT:
# self.house_randomizer.randomize_sky()
self.randomize_material(rand=True)
# self.randomize_sky(sky_type="")
################################################################################################
######################################## Second window #########################################
################################################################################################
# pass
###################################################################################
################################ Robot ######################################
###################################################################################
def setup_robot(self, new_method = False):
"""
Set up robot in the currect example
"""
# get the game xform as the parent for the robot
self.stage = omni.usd.get_context().get_stage()
#game_xform = self.stage.GetPrimAtPath("/World/game")
robot_parent_path = "/World/game"
has_game_xform = True
if not self.stage.GetPrimAtPath(robot_parent_path):
has_game_xform = False
xform_game = pxr.UsdGeom.Xform.Define(self.stage, robot_parent_path)
xform_game.AddTranslateOp().Set(pxr.Gf.Vec3f(0.0, 0.0, 0.0))
xform_game.AddOrientOp().Set(pxr.Gf.Quatf(1.0, 0.0, 0.0, 0.0))
xform_game.AddScaleOp().Set(pxr.Gf.Vec3f(1.0, 1.0, 1.0))
# retreive timeline
# _timeline = omni.timeline.get_timeline_interface()
# _timeline.play() # default not playing
if not new_method:
# old method
# load json info from example
task_index = self.task_type_ui.model.get_item_value_model().get_value_as_int()
task_type = self.task_types[task_index]
task_id = self.task_id_ui.model.get_value_as_int()
house_id = self.house_id_ui.model.get_value_as_int()
object_id = self.object_id_ui.model.get_value_as_int()
task_json = os.path.join(DATA_PATH_ROOT, "tasks", task_type, str(house_id), str(object_id), str(task_id) + ".json")
print("task json: ", task_json)
has_robot_info = False
if os.path.exists(task_json):
# raise Exception( "The json file at path {} provided wasn't found".format(room_layout_json) )
layout = json.load(open(task_json))
if "robot" in layout:
position = layout["robot"]["position"]
rotation = layout["robot"]["rotation"]
has_robot_info = True
# if there is no robot information / or no game_xform
if not has_robot_info or not has_game_xform:
carb.log_warn("Don't know the location/rotation for the robot")
position = [0,0,0]
rotation = [-0.5,0.5,0.5,0.5]
# new robot loading method
else:
#from .layout.house_new import HouseNew
self.init_new_house()
position, rotation = self.house.load_robot_info()
# print("position, rotation ", np.array(position), np.array(rotation))
if False: # (not self.is_initial_setup) and IS_IN_ISAAC_SIM:
# target_path = "/World/game/mobility_Bottle_3618"
target_path = None
for target_prim in self.stage.GetPrimAtPath("/World/game").GetChildren():
if "mobility" in target_prim.GetPath().pathString:
target_path = target_prim.GetPath().pathString
if target_path is None:
raise Exception("Must have a game object with mobility in the scene")
# self.franka = FrankabotKeyboard()
self.franka = FrankabotGamePad(target_path, position=np.array(position), rotation=np.array(rotation), parent_path=robot_parent_path)
else:
franka_path = os.path.join(ROBOT_PATH, "franka/franka.usd")
# load robot
robot_prim = self.stage.GetPrimAtPath(robot_parent_path + "/franka")
if not robot_prim.IsValid():
robot_prim = self.stage.DefinePrim(robot_parent_path + "/franka")
success_bool = robot_prim.GetReferences().AddReference(franka_path)
if not success_bool:
raise Exception("The usd file at path {} provided wasn't found".format(franka_path))
# set robot xform
# robot_xform = pxr.UsdGeom.Xformable.Get(self.stage, robot_prim.GetPath())
# print("position $ rotation: ", position[0], position[1], position[2], rotation)
robot_xform_mat = pxr.Gf.Matrix4d().SetScale([1,1,1]) * \
pxr.Gf.Matrix4d().SetRotate(pxr.Gf.Quatf(float(rotation[0]), float(rotation[1]), float(rotation[2]), float(rotation[3]))) * \
pxr.Gf.Matrix4d().SetTranslate([float(position[0]), float(position[1]), float(position[2])])
omni.kit.commands.execute(
"TransformPrimCommand",
path=robot_prim.GetPath().pathString,
new_transform_matrix=robot_xform_mat,
)
# robot_xform.AddTranslateOp().Set(pxr.Gf.Vec3f(float(position[0]), float(position[1]), float(position[2])))
# robot_xform.AddOrientOp().Set(pxr.Gf.Quatf(float(rotation[0]), float(rotation[1]), float(rotation[2]), float(rotation[3])))
# robot_xform.AddScaleOp().Set(pxr.Gf.Vec3f(1.0, 1.0, 1.0))
# selection = omni.usd.get_context().get_selection()
# selection.clear_selected_prim_paths()
# selection.set_prim_path_selected(robot_parent_path + "/franka", True, True, True, True)
# setup physics
from pxr import PhysxSchema, UsdPhysics
physicsScenePath = "/World/physicsScene"
scene = UsdPhysics.Scene.Get(self.stage, physicsScenePath)
if not scene:
scene = UsdPhysics.Scene.Define(self.stage, physicsScenePath)
self._gravityDirection = pxr.Gf.Vec3f(0.0, -1.0, 0.0)
self._gravityMagnitude = 981
scene.CreateGravityDirectionAttr().Set(self._gravityDirection)
scene.CreateGravityMagnitudeAttr().Set(self._gravityMagnitude)
physxSceneAPI = PhysxSchema.PhysxSceneAPI.Apply(scene.GetPrim())
physxSceneAPI.CreateEnableCCDAttr().Set(True)
physxSceneAPI.GetTimeStepsPerSecondAttr().Set(60)
physxSceneAPI.CreateEnableGPUDynamicsAttr().Set(True)
physxSceneAPI.CreateEnableEnhancedDeterminismAttr().Set(True)
physxSceneAPI.CreateEnableStabilizationAttr().Set(True)
def fix_linear_joint(self, fix_driver = True, damping_cofficient = 1):
"""
Fix the linear joint limit when scaling an object
"""
self.stage = omni.usd.get_context().get_stage()
prim_list = self.stage.TraverseAll()
for prim in prim_list:
if "joint_" in str(prim.GetPath()):
if fix_driver:
# find linear drive
joint_driver = pxr.UsdPhysics.DriveAPI.Get(prim, "linear")
if joint_driver:
joint_driver.CreateDampingAttr(damping_cofficient)
# find linear drive
joint_driver = pxr.UsdPhysics.DriveAPI.Get(prim, "angular")
if joint_driver:
joint_driver.CreateDampingAttr(damping_cofficient)
# find linear joint upperlimit
joint = pxr.UsdPhysics.PrismaticJoint.Get(self.stage, prim.GetPath())
if joint:
upper_limit = joint.GetUpperLimitAttr().Get() #GetAttribute("xformOp:translate").Get()
print(prim.GetPath(), "upper_limit", upper_limit)
mobility_prim = prim.GetParent().GetParent()
mobility_xform = pxr.UsdGeom.Xformable.Get(self.stage, mobility_prim.GetPath())
scale_factor = mobility_xform.GetOrderedXformOps()[2].Get()[0]
print("scale_factor", scale_factor)
joint.CreateUpperLimitAttr(upper_limit * scale_factor / 100)
###################################################################################
################################ Liquid ######################################
###################################################################################
def init_fluid_helper(self, use_isosurface = False):
from .layout.fluid.cup_setup import CupFluidHelper
# cup_id = 0 # self.cup_id_ui.model.get_value_as_int()
# r = self.r_ui.model.get_value_as_float()
# g = self.g_ui.model.get_value_as_float()
# b = self.b_ui.model.get_value_as_float()
self.cup_fluid_helper = CupFluidHelper(use_isosurface)
# def set_up_fluid_helper(self):
# # Fluid System setup
# self.init_fluid_helper()
# self.cup_fluid_helper.create()
def add_liquid_to_cup(self, task_type, use_isosurface = False):
self.init_fluid_helper(use_isosurface)
self.stage = omni.usd.get_context().get_stage()
game_prim = self.stage.GetPrimAtPath("/World/game")
enable_physics = True
if task_type == 'tap_water':
enable_physics = False
for prim in game_prim.GetChildren():
if "mobility_" in prim.GetPath().pathString and task_type in ["pour_water", "transfer_water"]:
self.cup_fluid_helper.modify_cup_scene(prim, add_liquid = True, set_physics = enable_physics)
elif "container_" in prim.GetPath().pathString:
self.cup_fluid_helper.modify_cup_scene(prim, add_liquid = False, set_physics = enable_physics)
###################################################################################
################################ Play and Record #############################
###################################################################################
def init_franka_tensor(self):
"""
Init franka tensor controller
"""
from .param import APP_VERION
assert APP_VERION >= "2022.0.0", "need Omniverse Isaac-Sim/Create in 2022"
task_index = self.task_type_ui.model.get_item_value_model().get_value_as_int()
task_type = self.task_types[task_index]
task_id = self.task_id_ui.model.get_value_as_int()
# robot_id = self.robot_id_ui.model.get_value_as_int()
# mission_id = self.mission_id_ui.model.get_value_as_int()
house_id = self.house_id_ui.model.get_value_as_int()
# anchor_id = self.anchor_id_ui.model.get_value_as_int()
annotator_index = self.annotator_ui.model.get_item_value_model().get_value_as_int()
annotator = ANNOTATORS[annotator_index]
root_dir = '-'.join([str(os.path.join(SAVE_ROOT, annotator, task_type)),str(task_id), str(house_id)])#, \
#str(robot_id), str(mission_id), str(house_id), str(anchor_id)])
traj_dir = os.path.join(root_dir, TRAJ_FOLDER)
# print("traj_dir", traj_dir)
from .robot_setup.franka_tensor import FrankaTensor
self.ft = FrankaTensor(save_path=traj_dir)
def stop_record(self):
"""
Stop recording button
"""
if not hasattr(self, "ft"):
self.timeline.stop()
carb.log_error( "please load layout and start recording first")
return
self.ft.is_record = False
self.ft.is_replay = False
self.timeline.stop()
self.task_desc_ui.model.set_value("Stop.")
def replay_record(self):
"""
Replay recording button
"""
self.init_franka_tensor()
self.ft.is_replay = True
self.ft.is_record = False
self.ft.load_record()
self.timeline.play()
self.task_desc_ui.model.set_value("Start replaying...")
def start_record(self):
"""
Play and record
"""
self.init_franka_tensor()
self.ft.is_replay = False
self.ft.is_record = True
import shutil
if os.path.exists(self.ft.save_path):
shutil.rmtree(self.ft.save_path)
os.makedirs(self.ft.save_path, exist_ok=True)
self.timeline.play()
self.task_desc_ui.model.set_value("Start recording...")
def set_render_type(self, render_type):
"""
Set up rendering type for current camera
"""
self.render_helper.reset()
self.render_helper.render_type = render_type
print("Setting render_type", self.render_helper.render_type)
def render_an_image(self):
"""
Render an image to render folder according render type
"""
task_index = self.task_type_ui.model.get_item_value_model().get_value_as_int()
task_type = self.task_types[task_index]
task_id = self.task_id_ui.model.get_value_as_int()
house_id = self.house_id_ui.model.get_value_as_int()
self.render_helper.render_image(self.render_folder, prefix = f"{task_type}_{task_id}_{house_id}")
self.task_desc_ui.model.set_value("image captured!")
######################## ui ###############################
def _build_custom_frame_header(self, collapsed, text):
"""
When task layout ui collapse, show id notified for task, object, and house id
"""
if collapsed:
alignment = ui.Alignment.RIGHT_CENTER
width = 8
height = 8
else:
alignment = ui.Alignment.CENTER_BOTTOM
width = 8
height = 8
with ui.HStack():
ui.Spacer(width=8)
with ui.VStack(width=0):
ui.Spacer()
ui.Triangle(
style = {"Triangle": {"background_color": 0xDDDDDDDD}}, width=width, height=height, alignment=alignment
)
ui.Spacer()
ui.Spacer(width=8)
ui.Label(text, width = 100)
if collapsed:
self.id_note_ui = CustomIdNotice()
# print("on_task_layout_ui_collapse", task_block_collapsed)
self.id_note_ui.ui.visible = collapsed
task_index = self.task_type_ui.model.get_item_value_model().get_value_as_int()
task_type = self.task_types[task_index]
task_id = self.task_id_ui.model.get_value_as_int()
robot_id = self.robot_id_ui.model.get_value_as_int()
anchor_id = self.anchor_id_ui.model.get_value_as_int()
mission_id = self.mission_id_ui.model.get_value_as_int()
house_id = self.house_id_ui.model.get_value_as_int()
self.id_note_ui.task_ui.text = task_type
self.id_note_ui.object_ui.text = f"Object: {task_id}"
self.id_note_ui.house_ui.text = f"House: {house_id}"
############################# shot down #########################
def on_shutdown(self):
print("[vrkitchen.indoor.kit] VRKitchen2.0-Indoor-Kit shutdown")
############################# debug #############################
def debug(self):
"""
Debug
"""
print("debug") |
yizhouzhao/VRKitchen2.0-IndoorKit/exts/vrkitchen.indoor.kit/vrkitchen/indoor/kit/__init__.py | from .extension import *
|
yizhouzhao/VRKitchen2.0-IndoorKit/exts/vrkitchen.indoor.kit/vrkitchen/indoor/kit/param.py | import omni
import carb
import os
from pathlib import Path
EXTENSION_FOLDER_PATH = Path(
omni.kit.app.get_app().get_extension_manager().get_extension_path_by_module(__name__)
)
ROOT = str(EXTENSION_FOLDER_PATH.parent.parent.resolve())
# ROOT = str(Path(__file__).parent.joinpath("../../../../../").resolve())
print("EXTENSION_FOLDER_PATH", EXTENSION_FOLDER_PATH, "ROOT", ROOT)
IS_IN_ISAAC_SIM = str(carb.settings.get_settings().get("/app/window/title")).startswith("Isaac Sim")
IS_IN_CREAT = str(carb.settings.get_settings().get("/app/window/title")).startswith("Create")
IS_IN_CODE = str(carb.settings.get_settings().get("/app/window/title")).startswith("Code")
APP_VERION = str(carb.settings.get_settings().get("/app/version"))
assert APP_VERION >= "2022.1.0", "Please start Isaac-Sim/Create/Code with version no small than 2022.1.0"
print("APP name: ", str(carb.settings.get_settings().get("/app/window/title")), APP_VERION)
# root = '/home/yizhou/Research/'
# root = '/home/vince/Documents/Research/'
# ROOT = '/home/nikepupu/Desktop' if IS_IN_ISAAC_SIM else 'E:/researches'
# Asset paths
ASSET_PATH = ROOT + "/exts/vrkitchen.indoor.kit/asset/"
SAPIEN_ASSET_PATH = ASSET_PATH + "/Sapien/"
HOUSE_INFO_PATH = ASSET_PATH + "/3DFront/"
CUSTOM_ASSET_PATH = ASSET_PATH + "/Custom/"
# STORAGE_ASSET_PATH = ROOT + "/asset/sapien_parsed/StorageFurniture/"
# Data path
DATA_PATH_ROOT = ROOT + "/data/"
DATA_PATH_NEW = DATA_PATH_ROOT + "/data_auto/"
SAVE_ROOT = DATA_PATH_ROOT + '/data_record/'
RENDER_ROOT = DATA_PATH_ROOT + '/data_render/'
#
ROBOT_PATH = ASSET_PATH + "Robot/"
ORIGINAL_IMAGES_FORLDER = "raw_images"
TRAJ_FOLDER = "trajectory"
DEPTH_IMAGES_FOLDER = "depth_images"
SEMANTIC_IMAGES_FOLDER = "semantic_images"
USE_ISO_SURFACE = False
#Annotator
ANNOTATORS = [
"MyLuckyUser",
]
# Task
TASK_TYPES = ["pickup_object","reorient_object", "pour_water",
"open_drawer"] # ,"open_cabinet", "put_object_into_box", "open_door", "transfer_water",
#"close_drawer", "close_cabinet", "close_door", "take_object_out_box"]
#Objects
OBJECT_TYPES = ["Bottle", "Box", "Door", "Faucet", "LightSwitch", "Microwave", "StorageFurniture"]
# Task objects
GAME_OBJ_NAMES = ["mobility", "switch", "SM_", "watercup", "fluid"]
CONTAINER_NAMES = ["box", "cup"]
OTHER_OBJ_NAMES = ["basin"]
# Physics
RIGIDBODY_OBJ_TYPES = ["Bottle", "SM_"] |
yizhouzhao/VRKitchen2.0-IndoorKit/exts/vrkitchen.indoor.kit/vrkitchen/indoor/kit/render/helper.py | import math
import time
import typing
import asyncio
import carb
import omni
import numpy as np
from PIL import Image
import os
import omni.syntheticdata as syn
from omni.kit.window.popup_dialog import MessageDialog
class CustomSyntheticDataHelper:
def __init__(self):
# initialize syntheticdata extension
self.app = omni.kit.app.get_app_interface()
ext_manager = self.app.get_extension_manager()
if not ext_manager.is_extension_enabled("omni.syntheticdata"):
ext_manager.set_extension_enabled("omni.syntheticdata", True)
self.reset()
def reset(self):
# viewport
self.render_type = "Rgb"
# viewport = omni.kit.viewport_legacy.get_viewport_interface()
# viewport_handle = viewport.get_instance("Viewport")
from omni.kit.viewport.utility import get_active_viewport
self.viewport = get_active_viewport()
self.viewport_window = omni.kit.viewport.utility.get_viewport_from_window_name() # viewport.get_viewport_window(None)
self.timeline = omni.timeline.get_timeline_interface()
def render_image(self, export_folder = None, prefix = ""):
print("rendering image...")
self.stage = omni.usd.get_context().get_stage()
# get camera
# self.viewport_window.set_texture_resolution(*resolution)
camera_name = self.viewport_window.get_active_camera().pathString.replace("/","")
# set up export folder
if export_folder:
if not os.path.exists(export_folder):
os.makedirs(export_folder, exist_ok=True)
time_str = str(int(self.timeline.get_current_time() * self.stage.GetTimeCodesPerSecond()))
img_save_path = f"{export_folder}/{prefix}_{camera_name}_{self.render_type}_{time_str}.png"
# get render type
# synthetic_type = syn._syntheticdata.SensorType.Rgb
# if self.render_type == "Depth":
# synthetic_type = syn._syntheticdata.SensorType.DepthLinear
# elif self.render_type == "Semantic":
# synthetic_type = syn._syntheticdata.SensorType.SemanticSegmentation
# render and export
async def render_img():
# Render one frame
await omni.kit.app.get_app().next_update_async()
syn.sensors.enable_sensors(
self.viewport,
[
syn._syntheticdata.SensorType.Rgb,
syn._syntheticdata.SensorType.DepthLinear,
syn._syntheticdata.SensorType.SemanticSegmentation,
syn._syntheticdata.SensorType.InstanceSegmentation
],
)
# # await syn.sensors.initialize_async(self.viewport_window, [])
# await syn.sensors.next_sensor_data_async(self.viewport, True)
# if self.render_type == "Depth":
# from omni.syntheticdata.scripts.visualize import get_depth
# data = get_depth(self.viewport_window, mode = "linear")
# # print("img", data.shape)
# img = Image.fromarray(data.astype(np.uint8))
if self.render_type == "Depth":
await syn.sensors.next_sensor_data_async(self.viewport)
data = syn.sensors.get_depth_linear(self.viewport)
print("depthimg", data.shape)
img = Image.fromarray(data.astype(np.uint8))
elif self.render_type == "Semantic":
await syn.sensors.next_sensor_data_async(self.viewport)
data = syn.sensors.get_instance_segmentation(self.viewport, parsed = True)
img = Image.fromarray(data.astype(np.uint8))
else:
await syn.sensors.next_sensor_data_async(self.viewport)
data = syn.sensors.get_rgb(self.viewport)
print("img", data.shape, data.dtype)
img = Image.fromarray(data)
if export_folder:
img.save(img_save_path)
print("image saved at path: ", img_save_path)
dialog = MessageDialog(
title="Image capture",
message=f"Screenshot captured!",
disable_cancel_button=True,
ok_handler=lambda dialog: dialog.hide()
)
dialog.show()
asyncio.ensure_future(render_img())
|
yizhouzhao/VRKitchen2.0-IndoorKit/exts/vrkitchen.indoor.kit/vrkitchen/indoor/kit/ui/style.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__ = ["julia_modeler_style"]
from omni.ui import color as cl
from omni.ui import constant as fl
from omni.ui import url
import omni.kit.app
import omni.ui as ui
import pathlib
EXTENSION_FOLDER_PATH = pathlib.Path(
omni.kit.app.get_app().get_extension_manager().get_extension_path_by_module(__name__)
)
ATTR_LABEL_WIDTH = 150
BLOCK_HEIGHT = 22
TAIL_WIDTH = 35
WIN_WIDTH = 400
WIN_HEIGHT = 930
# Pre-defined constants. It's possible to change them at runtime.
cl.window_bg_color = cl(0.2, 0.2, 0.2, 1.0)
cl.window_title_text = cl(.9, .9, .9, .9)
cl.collapsible_header_text = cl(.8, .8, .8, .8)
cl.collapsible_header_text_hover = cl(.95, .95, .95, 1.0)
cl.main_attr_label_text = cl(.65, .65, .65, 1.0)
cl.main_attr_label_text_hover = cl(.9, .9, .9, 1.0)
cl.multifield_label_text = cl(.65, .65, .65, 1.0)
cl.combobox_label_text = cl(.65, .65, .65, 1.0)
cl.field_bg = cl(0.18, 0.18, 0.18, 1.0)
cl.field_border = cl(1.0, 1.0, 1.0, 0.2)
cl.btn_border = cl(1.0, 1.0, 1.0, 0.4)
cl.slider_fill = cl(1.0, 1.0, 1.0, 0.3)
cl.revert_arrow_enabled = cl(.25, .5, .75, 1.0)
cl.revert_arrow_disabled = cl(.75, .75, .75, 1.0)
cl.transparent = cl(0, 0, 0, 0)
fl.main_label_attr_hspacing = 10
fl.attr_label_v_spacing = 3
fl.collapsable_group_spacing = 2
fl.outer_frame_padding = 15
fl.tail_icon_width = 15
fl.border_radius = 3
fl.border_width = 1
fl.window_title_font_size = 18
fl.field_text_font_size = 14
fl.main_label_font_size = 14
fl.multi_attr_label_font_size = 14
fl.radio_group_font_size = 14
fl.collapsable_header_font_size = 13
fl.range_text_size = 10
url.closed_arrow_icon = f"{EXTENSION_FOLDER_PATH}/icons/closed.svg"
url.open_arrow_icon = f"{EXTENSION_FOLDER_PATH}/icons/opened.svg"
url.revert_arrow_icon = f"{EXTENSION_FOLDER_PATH}/icons/revert_arrow.svg"
url.checkbox_on_icon = f"{EXTENSION_FOLDER_PATH}/icons/checkbox_on.svg"
url.checkbox_off_icon = f"{EXTENSION_FOLDER_PATH}/icons/checkbox_off.svg"
url.radio_btn_on_icon = f"{EXTENSION_FOLDER_PATH}/icons/radio_btn_on.svg"
url.radio_btn_off_icon = f"{EXTENSION_FOLDER_PATH}/icons/radio_btn_off.svg"
url.diag_bg_lines_texture = f"{EXTENSION_FOLDER_PATH}/icons/diagonal_texture_screenshot.png"
####################### Indoor Kit ###########################################
# url.start_btn_on_icon = f"{EXTENSION_FOLDER_PATH}/icons/random.svg"
url.start_btn_on_icon = f"{EXTENSION_FOLDER_PATH}/icons/toolbar_play.svg"
url.replay_btn_on_icon = f"{EXTENSION_FOLDER_PATH}/icons/toolbar_replay.svg"
url.stop_btn_on_icon = f"{EXTENSION_FOLDER_PATH}/icons/toolbar_stop.svg"
url.pause_btn_on_icon = f"{EXTENSION_FOLDER_PATH}/icons/timeline_pause.svg"
url.pencil_btn_on_icon = f"{EXTENSION_FOLDER_PATH}/icons/pencil.svg"
url.open_folder_btn_on_icon = f"{EXTENSION_FOLDER_PATH}/icons/open_folder.svg"
# The main style dict
julia_modeler_style = {
"Button::tool_button": {
"background_color": cl.field_bg,
"margin_height": 8,
"margin_width": 6,
"border_color": cl.btn_border,
"border_width": fl.border_width,
"font_size": fl.field_text_font_size,
},
"CollapsableFrame::group": {
"margin_height": fl.collapsable_group_spacing,
"background_color": cl.transparent,
},
# TODO: For some reason this ColorWidget style doesn't respond much, if at all (ie, border_radius, corner_flag)
"ColorWidget": {
"border_radius": fl.border_radius,
"border_color": cl(0.0, 0.0, 0.0, 0.0),
},
"Field": {
"background_color": cl.field_bg,
"border_radius": fl.border_radius,
"border_color": cl.field_border,
"border_width": fl.border_width,
},
"Field::attr_field": {
"corner_flag": ui.CornerFlag.RIGHT,
"font_size": 2, # fl.field_text_font_size, # Hack to allow for a smaller field border until field padding works
},
"Field::attribute_color": {
"font_size": fl.field_text_font_size,
},
"Field::multi_attr_field": {
"padding": 4, # TODO: Hacky until we get padding fix
"font_size": fl.field_text_font_size,
},
"Field::path_field": {
"corner_flag": ui.CornerFlag.RIGHT,
"font_size": fl.field_text_font_size,
},
"HeaderLine": {"color": cl(.5, .5, .5, .5)},
"Image::collapsable_opened": {
"color": cl.collapsible_header_text,
"image_url": url.open_arrow_icon,
},
"Image::collapsable_opened:hovered": {
"color": cl.collapsible_header_text_hover,
"image_url": url.open_arrow_icon,
},
"Image::collapsable_closed": {
"color": cl.collapsible_header_text,
"image_url": url.closed_arrow_icon,
},
"Image::collapsable_closed:hovered": {
"color": cl.collapsible_header_text_hover,
"image_url": url.closed_arrow_icon,
},
"Image::radio_on": {"image_url": url.radio_btn_on_icon},
"Image::radio_off": {"image_url": url.radio_btn_off_icon},
"Image::revert_arrow": {
"image_url": url.revert_arrow_icon,
"color": cl.revert_arrow_enabled,
},
"Image::revert_arrow:disabled": {
"image_url": url.revert_arrow_icon,
"color": cl.revert_arrow_disabled
},
"Image::revert_arrow_task_type": {
"image_url": url.revert_arrow_icon,
"color": cl.revert_arrow_enabled,
},
"Image::revert_arrow_task_type:disabled": {
"image_url": url.pencil_btn_on_icon,
"color": cl.revert_arrow_disabled
},
"Image::open_folder": {
"image_url": url.open_folder_btn_on_icon,
"color": cl.revert_arrow_disabled
},
"Image::checked": {"image_url": url.checkbox_on_icon},
"Image::unchecked": {"image_url": url.checkbox_off_icon},
"Image::slider_bg_texture": {
"image_url": url.diag_bg_lines_texture,
"border_radius": fl.border_radius,
"corner_flag": ui.CornerFlag.LEFT,
},
"Label::attribute_name": {
"alignment": ui.Alignment.RIGHT_TOP,
"margin_height": fl.attr_label_v_spacing,
"margin_width": fl.main_label_attr_hspacing,
# "color": "lightsteelblue",
"font_size": fl.main_label_font_size,
},
"Label::attribute_name:hovered": {"color": cl.main_attr_label_text_hover},
"Label::collapsable_name": {"font_size": fl.collapsable_header_font_size},
"Label::multi_attr_label": {
"color": cl.multifield_label_text,
"font_size": fl.multi_attr_label_font_size,
},
"Label::radio_group_name": {
"font_size": fl.radio_group_font_size,
"alignment": ui.Alignment.CENTER,
"color": cl.main_attr_label_text,
},
"Label::range_text": {
"font_size": fl.range_text_size,
},
"Label::window_title": {
"font_size": fl.window_title_font_size,
"color": cl.window_title_text,
},
"ScrollingFrame::window_bg": {
"background_color": cl.window_bg_color,
"padding": fl.outer_frame_padding,
"border_radius": 20 # Not obvious in a window, but more visible with only a frame
},
"Slider::attr_slider": {
"draw_mode": ui.SliderDrawMode.FILLED,
"padding": 0,
"color": cl.transparent,
# Meant to be transparent, but completely transparent shows opaque black instead.
"background_color": cl(0.28, 0.28, 0.28, 0.01),
"secondary_color": cl.slider_fill,
"border_radius": fl.border_radius,
"corner_flag": ui.CornerFlag.LEFT, # TODO: Not actually working yet OM-53727
},
# Combobox workarounds
"Rectangle::combobox": { # TODO: remove when ComboBox can have a border
"background_color": cl.field_bg,
"border_radius": fl.border_radius,
"border_color": cl.btn_border,
"border_width": fl.border_width,
},
"ComboBox::dropdown_menu": {
"color": "lightsteelblue", # label color
"padding_height": 1.25,
"margin": 2,
"background_color": cl.field_bg,
"border_radius": fl.border_radius,
"font_size": fl.field_text_font_size,
"secondary_color": cl.transparent, # button background color
},
"Rectangle::combobox_icon_cover": {"background_color": cl.field_bg},
################## VRKitchen Indoor Kit ###############
"Field::choose_id": {
"margin": 8,
},
"Button::record_button": {
"background_color": cl.field_bg,
"border_color": cl.btn_border,
"border_width": fl.border_width,
"border_radius": 6,
"margin": 4,
"corner_flag": ui.CornerFlag.ALL,
},
"Button::load_button": {
"background_color": cl.field_bg,
"border_color": cl.btn_border,
"border_width": fl.border_width,
"border_radius": 10,
"margin": 4,
"corner_flag": ui.CornerFlag.ALL,
},
"Button::add_button": {
"background_color": cl.field_bg,
"border_color": cl.btn_border,
"border_width": fl.border_width,
"border_radius": 2,
"margin": 8,
"corner_flag": ui.CornerFlag.ALL,
},
"Button::control_button": {
"background_color": cl.field_bg,
"border_color": cl.btn_border,
"border_width": fl.border_width,
"border_radius": 4,
"margin": 2,
"corner_flag": ui.CornerFlag.ALL,
},
"Button::control_button_disabled": {
"background_color": cl(0.1, 0.7, 0.3, 0.4),
"border_color": cl.btn_border,
"border_width": fl.border_width,
"border_radius": 4,
"margin": 2,
"corner_flag": ui.CornerFlag.ALL,
},
"Button::control_button_pressed1": {
"background_color": cl( 0.7, 0.1, 0.3, 0.3),
"border_color": cl.btn_border,
"border_width": fl.border_width,
"border_radius": 4,
"margin": 2,
"corner_flag": ui.CornerFlag.ALL,
},
"Button::control_button_pressed2": {
"background_color": cl(0.1, 0.3, 0.7, 0.3),
"border_color": cl.btn_border,
"border_width": fl.border_width,
"border_radius": 4,
"margin": 2,
"corner_flag": ui.CornerFlag.ALL,
},
"Button::control_button_pressed3": {
"background_color": cl(0.7, 0.3, 0.7, 0.3),
"border_color": cl.btn_border,
"border_width": fl.border_width,
"border_radius": 4,
"margin": 2,
"corner_flag": ui.CornerFlag.ALL,
},
"Image::start_on": {
"image_url": url.start_btn_on_icon,
},
"Image::replay_on": {
"image_url": url.replay_btn_on_icon,
},
"Image::stop_on": {
"image_url": url.stop_btn_on_icon,
},
"Image::pause_on": {
"image_url": url.pause_btn_on_icon,
},
# "Image::radio_off": {"image_url": url.radio_btn_off_icon},
}
|
yizhouzhao/VRKitchen2.0-IndoorKit/exts/vrkitchen.indoor.kit/vrkitchen/indoor/kit/ui/indoorkit_ui_widget.py | from typing import List, Optional
import omni
import omni.ui as ui
from .style import ATTR_LABEL_WIDTH, cl, fl
from .custom_base_widget import CustomBaseWidget
from ..robot_setup.controller import Controller
SPACING = 5
class TaskTypeComboboxWidget():
"""A customized combobox widget"""
def __init__(self,
model: ui.AbstractItemModel = None,
options: List[str] = None,
default_value=0,
on_restore_fn: callable = None,
**kwargs):
"""
Set up the take type combo box widget
::params:
:on_restore_fn: call when write/restore the widget
"""
self.__default_val = default_value
self.__options = options or ["1", "2", "3"]
self.__combobox_widget = None
self.on_restore_fn = on_restore_fn
# Call at the end, rather than start, so build_fn runs after all the init stuff
# CustomBaseWidget.__init__(self, model=model, **kwargs)
self.existing_model: Optional[ui.AbstractItemModel] = kwargs.pop("model", None)
self.revert_img = None
self.__attr_label: Optional[str] = kwargs.pop("label", "")
self.__frame = ui.Frame()
with self.__frame:
self._build_fn()
def destroy(self):
self.existing_model = None
self.revert_img = None
self.__attr_label = None
self.__frame = None
self.__options = None
self.__combobox_widget = None
@property
def model(self) -> Optional[ui.AbstractItemModel]:
"""The widget's model"""
if self.__combobox_widget:
return self.__combobox_widget.model
@model.setter
def model(self, value: ui.AbstractItemModel):
"""The widget's model"""
self.__combobox_widget.model = value
def _on_value_changed(self, *args):
"""Set revert_img to correct state."""
model = self.__combobox_widget.model
index = model.get_item_value_model().get_value_as_int()
self.revert_img.enabled = self.__default_val != index
def _restore_default(self):
"""Restore the default value."""
if self.revert_img.enabled:
# self.__combobox_widget.model.get_item_value_model().set_value(
# self.__default_val)
self.revert_img.enabled = False
if self.on_restore_fn:
self.on_restore_fn(True)
else:
self.revert_img.enabled = True
if self.on_restore_fn:
self.on_restore_fn(False)
def _build_body(self):
"""Main meat of the widget. Draw the Rectangle, Combobox, and
set up callbacks to keep them updated.
"""
with ui.HStack():
with ui.ZStack():
# TODO: Simplify when borders on ComboBoxes work in Kit!
# and remove style rule for "combobox" Rect
# Use the outline from the Rectangle for the Combobox
ui.Rectangle(name="combobox",
height=22)
option_list = list(self.__options)
self.__combobox_widget = ui.ComboBox(
0, *option_list,
name="dropdown_menu",
# Abnormal height because this "transparent" combobox
# has to fit inside the Rectangle behind it
height=10
)
# Swap for different dropdown arrow image over current one
with ui.HStack():
ui.Spacer() # Keep it on the right side
with ui.VStack(width=0): # Need width=0 to keep right-aligned
ui.Spacer(height=5)
with ui.ZStack():
ui.Rectangle(width=15, height=15, name="combobox_icon_cover")
ui.Image(name="collapsable_closed", width=12, height=12)
ui.Spacer(width=2) # Right margin
ui.Spacer(width=ui.Percent(5))
self.__combobox_widget.model.add_item_changed_fn(self._on_value_changed)
def _build_head(self):
"""Build the left-most piece of the widget line (label in this case)"""
ui.Label(
self.__attr_label,
width=80,
style = {"color": "lightsteelblue", "margin_height": 2, "alignment": ui.Alignment.RIGHT_TOP}
)
def _build_tail(self):
"""Build the right-most piece of the widget line. In this case,
we have a Revert Arrow button at the end of each widget line.
"""
with ui.HStack(width=0):
# ui.Spacer(width=5)
with ui.VStack(height=0):
ui.Spacer(height=3)
self.revert_img = ui.Image(
name="revert_arrow_task_type",
fill_policy=ui.FillPolicy.PRESERVE_ASPECT_FIT,
width=12,
height=13,
enabled=False,
tooltip="randomly fill (or reset) task type, object id, and house id."
)
ui.Spacer(width=5)
# call back for revert_img click, to restore the default value
self.revert_img.set_mouse_pressed_fn(
lambda x, y, b, m: self._restore_default())
def _build_fn(self):
"""Puts the 3 pieces together."""
with ui.HStack():
self._build_head()
self._build_body()
self._build_tail()
class CustomRecordGroup:
STYLE = {
"Rectangle::image_button": {
"background_color": 0x0,
"border_width": 1.5,
"border_radius": 2.0,
"margin": 4,
"border_color": cl.btn_border,
"corner_flag": ui.CornerFlag.RIGHT,
},
"Rectangle::image_button:hovered": {
"background_color": 0xAAB8B8B8,
"border_width": 0,
"border_radius": 2.0,
},
"Rectangle::image_button:selected": {
"background_color": 0x0,
"border_width": 1,
"border_color": 0xFFC5911A,
"border_radius": 2.0,
},
}
def __init__(self, width = 60, height = 60,
on_click_record_fn: callable = None,
on_click_stop_fn: callable = None,
on_click_replay_fn: callable = None,
):
self.timeline = omni.timeline.get_timeline_interface()
self.on_click_record_fn = on_click_record_fn
self.on_click_stop_fn = on_click_stop_fn
self.on_click_replay_fn = on_click_replay_fn
# another ui for control
self.control_group : CustomControlGroup = None
self._selected = False
with ui.HStack():
with ui.HStack():
with ui.ZStack(width=0, height=0, spacing=0): #
with ui.Placer(offset_x=width, offset_y=0):
self.play_label = ui.Label("Record", width = 60)
with ui.Placer(offset_x=0, offset_y=0):
self.rect_play = ui.Rectangle(name="image_button", width=2 * width, height=height, style=CustomRecordGroup.STYLE)
with ui.Placer(offset_x=5, offset_y=5):
self.image_play = ui.Image(
name="start_on", width=width - 10, height=height - 10, fill_policy=ui.FillPolicy.STRETCH
)
self.rect_play.set_mouse_pressed_fn(lambda x, y, btn, a: self._on_mouse_pressed_play(btn))
with ui.ZStack(width=0, height=0, spacing=0): #
with ui.Placer(offset_x=width, offset_y=0):
self.stop_label = ui.Label("Stop", width = 60)
with ui.Placer(offset_x=0, offset_y=0):
self.rect_stop = ui.Rectangle(name="image_button", width=2 * width, height=height, style=CustomRecordGroup.STYLE)
with ui.Placer(offset_x=5, offset_y=5):
self.image_stop = ui.Image(
name="stop_on", width=width - 10, height=height - 10, fill_policy=ui.FillPolicy.STRETCH
)
self.rect_stop.set_mouse_pressed_fn(lambda x, y, btn, a: self._on_mouse_pressed_stop(btn)) #
with ui.HStack():
with ui.ZStack(width=0, height=0, spacing=0):
with ui.Placer(offset_x=width, offset_y=0):
self.replay_label = ui.Label("Replay", width = 60)
with ui.Placer(offset_x=0, offset_y=0):
self.rect_replay = ui.Rectangle(name="image_button", width= 2 * width, height=height, style=CustomRecordGroup.STYLE)
with ui.Placer(offset_x=10, offset_y=10):
self.image_replay = ui.Image(
name="replay_on", width=width - 20, height=height - 20, fill_policy=ui.FillPolicy.STRETCH
)
self.rect_replay.set_mouse_pressed_fn(lambda x, y, btn, a: self._on_mouse_pressed_replay(btn))
def __del__(self):
# set ui.Image objects to None explicitly to avoid this error:
# Client omni.ui Failed to acquire interface [omni::kit::renderer::IGpuFoundation v0.2] while unloading all plugins
self.image_play = None
def _on_mouse_pressed_play(self, key):
# 0 is for mouse left button
if key == 0:
if self.timeline.is_stopped(): # if stopped, start recording
self.play_label.text = "Pause"
self.image_play.name = "pause_on"
self.on_click_record_fn()
if self.control_group:
self.control_group.enable()
elif self.timeline.is_playing(): # if is playing, pause
self.play_label.text = "Continue"
self.image_play.name = "start_on"
self.timeline.pause()
else: # if is paused, just play
self.play_label.text = "Pause"
self.image_play.name = "pause_on"
self.timeline.play()
def _on_mouse_pressed_replay(self, key):
# 0 is for mouse left button
if key == 0:
if self.timeline.is_stopped(): # if stopped, start recording
self.replay_label.text = "Pause"
self.image_replay.name = "pause_on"
self.on_click_replay_fn()
elif self.timeline.is_playing(): # if is playing, pause
self.replay_label.text = "Continue"
self.image_replay.name = "replay_on"
self.timeline.pause()
else: # if is paused, just play
self.replay_label.text = "Pause"
self.image_replay.name = "pause_on"
self.timeline.play()
def _on_mouse_pressed_stop(self, key):
# print("press stop button", self.timeline.is_playing(), self.timeline.is_stopped())
# 0 is for mouse left button
if key == 0:
self.play_label.text = "Record"
self.image_play.name = "start_on"
self.replay_label.text = "Replay"
self.image_replay.name = "replay_on"
self.on_click_stop_fn()
if self.control_group:
self.control_group.disable()
@property
def selected(self):
return self._selected
@selected.setter
def selected(self, value):
self._selected = value
class CustomControlGroup():
def __init__(self) -> None:
self.collapse_frame = ui.CollapsableFrame("Robot control")
self.collapse_frame.collapsed = False
self.collapse_frame.enabled = True
# ui
with self.collapse_frame:
with ui.VStack(height=0, spacing=0):
with ui.HStack():
ui.Label("position control: ")
self.button_w = ui.Button("W", name = "control_button", tooltip = "move end factor forward")
self.button_s = ui.Button("S", name = "control_button", tooltip = "move end factor backward")
self.button_a = ui.Button("A", name = "control_button", tooltip = "move end factor to left")
self.button_d = ui.Button("D", name = "control_button", tooltip = "move end factor to right")
self.button_q = ui.Button("Q", name = "control_button", tooltip = "move end factor to down")
self.button_e = ui.Button("E", name = "control_button", tooltip = "move end factor to up")
with ui.HStack():
ui.Label("rotation control: ")
self.button_up = ui.Button("UP", name = "control_button", tooltip = "Rotate hand upward")
self.button_down = ui.Button("DOWN", name = "control_button", tooltip = "Rotate hand downard")
self.button_left = ui.Button("LEFT", name = "control_button", tooltip = "Rotate hand to left")
self.button_right = ui.Button("RIGHT", name = "control_button", tooltip = "Rotate hand to right")
with ui.HStack():
ui.Label("gripper control: ")
self.button_control = ui.Button("LEFT CTRL", name = "control_button", tooltip = "Close/Open gripper")
self.button_list = [self.button_w, self.button_s, self.button_a, self.button_d, self.button_q, self.button_e,
self.button_up, self.button_down, self.button_left, self.button_right,
]
self.button_w.set_clicked_fn(lambda : self._on_button("w"))
self.button_s.set_clicked_fn(lambda : self._on_button("s"))
self.button_a.set_clicked_fn(lambda : self._on_button("a"))
self.button_d.set_clicked_fn(lambda : self._on_button("d"))
self.button_q.set_clicked_fn(lambda : self._on_button("q"))
self.button_e.set_clicked_fn(lambda : self._on_button("e"))
self.button_up.set_clicked_fn(lambda : self._on_button("up", 2))
self.button_down.set_clicked_fn(lambda : self._on_button("down", 2))
self.button_left.set_clicked_fn(lambda : self._on_button("left", 2))
self.button_right.set_clicked_fn(lambda : self._on_button("right", 2))
self.button_control.set_clicked_fn(lambda: self._on_button_control())
self.disable()
def enable(self):
"""
Enable itself by showing the robot controling buttons
"""
self.collapse_frame.collapsed = False
self.collapse_frame.enabled = True
self.enable_buttons()
def disable(self):
"""
Disable itself by closing the robot controling buttons
"""
self.collapse_frame.collapsed = True
# self.collapse_frame.enabled = False
def disable_buttons(self):
for button in self.button_list:
button.name = "control_button_disabled"
# button.enabled = False
Controller.reset_movement()
def enable_buttons(self):
for button in self.button_list:
button.enabled = True
button.name = "control_button"
Controller.reset_movement()
def _on_button(self, attr_name:str, style = 1):
attr = getattr(Controller, attr_name)
# print("attr", attr_name, attr)
button = getattr(self, f"button_{attr_name}")
if attr:
setattr(Controller, attr_name, False)
button.name = "control_button"
self.enable_buttons()
else:
self.disable_buttons()
setattr(Controller, attr_name, True)
button.enabled = True
button.name = f"control_button_pressed{style}"
def _on_button_control(self):
if Controller.left_control:
Controller.left_control = False
self.button_control.text = "LEFT CTRL"
self.button_control.name = "control_button"
else:
Controller.left_control = True
self.button_control.text = "Gripper closed"
self.button_control.name = "control_button_pressed3"
class CustomBoolWidget(CustomBaseWidget):
"""A custom checkbox or switch widget"""
def __init__(self,
model: ui.AbstractItemModel = None,
default_value: bool = True,
on_checked_fn: callable = None,
**kwargs):
self.__default_val = default_value
self.__bool_image = None
self.on_checked_fn = on_checked_fn
# Call at the end, rather than start, so build_fn runs after all the init stuff
CustomBaseWidget.__init__(self, model=model, **kwargs)
def destroy(self):
CustomBaseWidget.destroy()
self.__bool_image = None
def _restore_default(self):
"""Restore the default value."""
if self.revert_img.enabled:
self.__bool_image.checked = self.__default_val
self.__bool_image.name = (
"checked" if self.__bool_image.checked else "unchecked"
)
self.revert_img.enabled = False
def _on_value_changed(self):
"""Swap checkbox images and set revert_img to correct state."""
self.__bool_image.checked = not self.__bool_image.checked
self.__bool_image.name = (
"checked" if self.__bool_image.checked else "unchecked"
)
self.revert_img.enabled = self.__default_val != self.__bool_image.checked
if self.on_checked_fn:
self.on_checked_fn(self.__bool_image.checked)
def _build_body(self):
"""Main meat of the widget. Draw the appropriate checkbox image, and
set up callback.
"""
with ui.HStack():
with ui.VStack():
# Just shift the image down slightly (2 px) so it's aligned the way
# all the other rows are.
ui.Spacer(height=2)
self.__bool_image = ui.Image(
name="checked" if self.__default_val else "unchecked",
fill_policy=ui.FillPolicy.PRESERVE_ASPECT_FIT,
height=16, width=16, checked=self.__default_val
)
# Let this spacer take up the rest of the Body space.
ui.Spacer()
self.__bool_image.set_mouse_pressed_fn(
lambda x, y, b, m: self._on_value_changed())
NUM_FIELD_WIDTH = 50
SLIDER_WIDTH = ui.Percent(100)
FIELD_HEIGHT = 22 # TODO: Once Field padding is fixed, this should be 18
SPACING = 4
TEXTURE_NAME = "slider_bg_texture"
class CustomSliderWidget(CustomBaseWidget):
"""A compound widget for scalar slider input, which contains a
Slider and a Field with text input next to it.
"""
def __init__(self,
model: ui.AbstractItemModel = None,
num_type: str = "int",
min=0.0,
max=1.0,
default_val=0.0,
display_range: bool = False,
on_slide_fn: callable = None,
**kwargs):
self.__slider: Optional[ui.AbstractSlider] = None
self.__numberfield: Optional[ui.AbstractField] = None
self.__min = min
self.__max = max
self.__default_val = default_val
self.__num_type = num_type
self.__display_range = display_range
self.on_slide_fn = on_slide_fn
# Call at the end, rather than start, so build_fn runs after all the init stuff
CustomBaseWidget.__init__(self, model=model, **kwargs)
def destroy(self):
CustomBaseWidget.destroy()
self.__slider = None
self.__numberfield = None
@property
def model(self) -> Optional[ui.AbstractItemModel]:
"""The widget's model"""
if self.__slider:
return self.__slider.model
@model.setter
def model(self, value: ui.AbstractItemModel):
"""The widget's model"""
self.__slider.model = value
self.__numberfield.model = value
def _on_value_changed(self, *args):
"""Set revert_img to correct state."""
if self.__num_type == "float":
index = self.model.as_float
else:
index = self.model.as_int
self.revert_img.enabled = self.__default_val != index
if self.on_slide_fn:
self.on_slide_fn(index)
def _restore_default(self):
"""Restore the default value."""
if self.revert_img.enabled:
self.model.set_value(self.__default_val)
self.revert_img.enabled = False
def _build_display_range(self):
"""Builds just the tiny text range under the slider."""
with ui.HStack():
ui.Label(str(self.__min), alignment=ui.Alignment.LEFT, name="range_text")
if self.__min < 0 and self.__max > 0:
# Add middle value (always 0), but it may or may not be centered,
# depending on the min/max values.
total_range = self.__max - self.__min
# subtract 25% to account for end number widths
left = 100 * abs(0 - self.__min) / total_range - 25
right = 100 * abs(self.__max - 0) / total_range - 25
ui.Spacer(width=ui.Percent(left))
ui.Label("0", alignment=ui.Alignment.CENTER, name="range_text")
ui.Spacer(width=ui.Percent(right))
else:
ui.Spacer()
ui.Label(str(self.__max), alignment=ui.Alignment.RIGHT, name="range_text")
ui.Spacer(height=.75)
def _build_body(self):
"""Main meat of the widget. Draw the Slider, display range text, Field,
and set up callbacks to keep them updated.
"""
with ui.HStack(spacing=0):
# the user provided a list of default values
with ui.VStack(spacing=3, width=ui.Fraction(3)):
with ui.ZStack():
# Put texture image here, with rounded corners, then make slider
# bg be fully transparent, and fg be gray and partially transparent
with ui.Frame(width=SLIDER_WIDTH, height=FIELD_HEIGHT,
horizontal_clipping=True):
# Spacing is negative because "tileable" texture wasn't
# perfectly tileable, so that adds some overlap to line up better.
with ui.HStack(spacing=-12):
for i in range(50): # tiling the texture
ui.Image(name=TEXTURE_NAME,
fill_policy=ui.FillPolicy.PRESERVE_ASPECT_CROP,
width=50,)
slider_cls = (
ui.FloatSlider if self.__num_type == "float" else ui.IntSlider
)
self.__slider = slider_cls(
height=FIELD_HEIGHT,
min=self.__min, max=self.__max, name="attr_slider"
)
if self.__display_range:
self._build_display_range()
with ui.VStack(width=ui.Fraction(1)):
model = self.__slider.model
model.set_value(self.__default_val)
field_cls = (
ui.FloatField if self.__num_type == "float" else ui.IntField
)
# Note: This is a hack to allow for text to fill the Field space more, as there was a bug
# with Field padding. It is fixed, and will be available in the next release of Kit.
with ui.ZStack():
# height=FIELD_HEIGHT-1 to account for the border, so the field isn't
# slightly taller than the slider
ui.Rectangle(
style_type_name_override="Field",
name="attr_field",
height=FIELD_HEIGHT - 1
)
with ui.HStack(height=0):
ui.Spacer(width=2)
self.__numberfield = field_cls(
model,
height=0,
style={
"background_color": cl.transparent,
"border_color": cl.transparent,
"padding": 4,
"font_size": fl.field_text_font_size,
},
)
if self.__display_range:
ui.Spacer()
model.add_value_changed_fn(self._on_value_changed)
class CustomSkySelectionGroup(CustomBaseWidget):
def __init__(self,
on_select_fn: callable = None
) -> None:
self.on_select_fn = on_select_fn
self.sky_type = ""
CustomBaseWidget.__init__(self, label = "Sky type:")
def _build_body(self):
with ui.HStack():
self.button_clear = ui.Button("Sunny", name = "control_button")
self.button_cloudy = ui.Button("Cloudy", name = "control_button")
self.button_overcast = ui.Button("Overcast", name = "control_button")
self.button_night = ui.Button("Night", name = "control_button")
self.button_clear.set_clicked_fn(lambda : self._on_button("clear"))
self.button_cloudy.set_clicked_fn(lambda : self._on_button("cloudy"))
self.button_overcast.set_clicked_fn(lambda : self._on_button("overcast"))
self.button_night.set_clicked_fn(lambda : self._on_button("night"))
self.button_list = [self.button_clear, self.button_cloudy, self.button_overcast, self.button_night]
def enable_buttons(self):
for button in self.button_list:
button.enabled = True
button.name = "control_button"
def _on_button(self, sky_type:str):
if self.on_select_fn:
self.on_select_fn(sky_type.capitalize())
self.enable_buttons()
button = getattr(self, f"button_{sky_type}")
button.name = f"control_button_pressed{2}"
self.revert_img.enabled = True
def _restore_default(self):
"""Restore the default value."""
if self.revert_img.enabled:
self.revert_img.enabled = False
self.enable_buttons()
self.on_select_fn("")
class CustomIdNotice():
def __init__(self) -> None:
self.ui = ui.HStack()
with self.ui:
ui.Spacer(width=4)
self.task_ui = ui.Button("pickup_object", name = "control_button", style = {"color": "lightsteelblue", "border_color": "lightsteelblue"}, enabled = False)
ui.Spacer(width=4)
self.object_ui = ui.Button("object: 0", name = "control_button", style = {"color": "DarkSalmon", "border_color": "DarkSalmon"}, enabled = False)
ui.Spacer(width=4)
self.house_ui = ui.Button("house: 1", name = "control_button", style = {"color": "Plum", "border_color": "Plum"}, enabled = False)
self.ui.visible = False
class CustomRenderTypeSelectionGroup(CustomBaseWidget):
def __init__(self,
on_select_fn: callable = None
) -> None:
self.on_select_fn = on_select_fn
self.sky_type = ""
CustomBaseWidget.__init__(self, label = "Render type:")
def _build_body(self):
with ui.HStack():
self.button_rgb = ui.Button("RGB", name = "control_button_pressed3")
self.button_depth= ui.Button("Depth", name = "control_button")
self.button_semantic = ui.Button("Semantic", name = "control_button")
self.button_rgb.set_clicked_fn(lambda : self._on_button("rgb"))
self.button_depth.set_clicked_fn(lambda : self._on_button("depth"))
self.button_semantic.set_clicked_fn(lambda : self._on_button("semantic"))
self.button_list = [self.button_rgb, self.button_depth, self.button_semantic]
def enable_buttons(self):
for button in self.button_list:
button.enabled = True
button.name = "control_button"
def _on_button(self, render_type:str):
if self.on_select_fn:
self.on_select_fn(render_type.capitalize())
self.enable_buttons()
button = getattr(self, f"button_{render_type}")
button.name = f"control_button_pressed{3}"
self.revert_img.enabled = True
def _restore_default(self):
"""Restore the default value."""
if self.revert_img.enabled:
self.revert_img.enabled = False
self.enable_buttons()
self._on_button("rgb")
import subprocess, os, platform
class CustomPathButtonWidget:
"""A compound widget for holding a path in a StringField, and a button
that can perform an action.
TODO: Get text ellision working in the path field, to start with "..."
"""
def __init__(self,
label: str,
path: str,
btn_callback: callable = None):
self.__attr_label = label
self.__pathfield: ui.StringField = None
self.__path = path
self.__btn = None
self.__callback = btn_callback
self.__frame = ui.Frame()
with self.__frame:
self._build_fn()
def destroy(self):
self.__pathfield = None
self.__btn = None
self.__callback = None
self.__frame = None
@property
def model(self) -> Optional[ui.AbstractItem]:
"""The widget's model"""
if self.__pathfield:
return self.__pathfield.model
@model.setter
def model(self, value: ui.AbstractItem):
"""The widget's model"""
self.__pathfield.model = value
def get_path(self):
return self.model.as_string
def _build_fn(self):
"""Draw all of the widget parts and set up callbacks."""
with ui.HStack():
ui.Label(
self.__attr_label,
name="attribute_name",
width=120,
)
self.__pathfield = ui.StringField(
name="path_field",
enabled = False,
)
ui.Spacer(width = 8)
# # TODO: Add clippingType=ELLIPSIS_LEFT for long paths
self.__pathfield.model.set_value(self.__path)
self.folder_img = ui.Image(
name="open_folder",
fill_policy=ui.FillPolicy.PRESERVE_ASPECT_FIT,
width=12,
height=18,
)
self.folder_img.set_mouse_pressed_fn(lambda x, y, b, m: self.open_path(self.__path))
def open_path(self, path):
if platform.system() == "Darwin": # macOS
subprocess.call(("open", path))
elif platform.system() == "Windows": # Windows
os.startfile(path)
else: # linux variants
subprocess.call(("xdg-open", path))
|
yizhouzhao/VRKitchen2.0-IndoorKit/exts/vrkitchen.indoor.kit/vrkitchen/indoor/kit/ui/custom_base_widget.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__ = ["CustomBaseWidget"]
from typing import Optional
import omni.ui as ui
from .style import ATTR_LABEL_WIDTH
class CustomBaseWidget:
"""The base widget for custom widgets that follow the pattern of Head (Label),
Body Widgets, Tail Widget"""
def __init__(self, *args, model=None, **kwargs):
self.existing_model: Optional[ui.AbstractItemModel] = kwargs.pop("model", None)
self.revert_img = None
self.__attr_label: Optional[str] = kwargs.pop("label", "")
self.__frame = ui.Frame()
with self.__frame:
self._build_fn()
def destroy(self):
self.existing_model = None
self.revert_img = None
self.__attr_label = None
self.__frame = None
def __getattr__(self, attr):
"""Pretend it's self.__frame, so we have access to width/height and
callbacks.
"""
return getattr(self.__frame, attr)
def _build_head(self):
"""Build the left-most piece of the widget line (label in this case)"""
ui.Label(
self.__attr_label,
name="attribute_name",
width=120,
)
def _build_body(self):
"""Build the custom part of the widget. Most custom widgets will
override this method, as it is where the meat of the custom widget is.
"""
ui.Spacer()
def _build_tail(self):
"""Build the right-most piece of the widget line. In this case,
we have a Revert Arrow button at the end of each widget line.
"""
with ui.HStack(width=0):
ui.Spacer(width=5)
with ui.VStack(height=0):
ui.Spacer(height=3)
self.revert_img = ui.Image(
name="revert_arrow",
fill_policy=ui.FillPolicy.PRESERVE_ASPECT_FIT,
width=12,
height=13,
enabled=False,
)
ui.Spacer(width=5)
# call back for revert_img click, to restore the default value
self.revert_img.set_mouse_pressed_fn(
lambda x, y, b, m: self._restore_default())
def _build_fn(self):
"""Puts the 3 pieces together."""
with ui.HStack():
self._build_head()
self._build_body()
self._build_tail()
|
yizhouzhao/VRKitchen2.0-IndoorKit/exts/vrkitchen.indoor.kit/vrkitchen/indoor/kit/autotask/auto_config.py | # automatically generation configs meta data for task generation
import json
import copy
g_meta_json_path = "./configs.json"
# initail and target value pair for continous task
g_init_target_value_pair = [
(0, 0.25), (0, 0.5), (0, 0.75), (0, 1),
(0.25, 0.5), (0.25, 0.75), (0.25, 1),
(0.5, 0.75), (0.5, 1),
(0.75, 1)
]
g_mission_template = {
"size": 0,
"orient": [0, 0, 0.7071068, 0.7071068],
"robot_offset": [-40, 0, 0],
"robot_orient": [0.7071068, -0.7071068,0, 0],
"task_type": "",
"task_id": "",
"robot_id": "",
"mission_id": "",
"goal":{
"description":"Open the door a little.",
"condition": {
"init_value": -1,
"type": "rotation",
"target": "",
"joint":"",
"target_value": 0
}
}
}
def add_continuous_meta_open_mission(task_type, meta_json_path = g_meta_json_path):
"""
add continous mission types for open task
"""
# load json
assert task_type in ["open_door", "open_drawer", "open_cabinet", "close_door", "pour_water",
"close_drawer", "close_cabinet", "transfer_water", "tap_water"]
meta_json = json.load(open(meta_json_path))
# if task_type not in meta_json:
# clean
meta_json[task_type] = []
task_missions = meta_json[task_type]
for init_value, target_value in g_init_target_value_pair:
mission = copy.deepcopy(g_mission_template)
goal = mission["goal"]
condition = goal["condition"]
if task_type == "open_door":
#mission["robot_offset"] = [-40, 0, 0]
mission["robot_offset"] = [50, 0, 0]
mission["robot_orient"] = [0,0,0.7071068,0.7071068]
goal["description"] = "Open the door"
condition["type"] = "rotation"
condition["init_value"] = init_value
condition["target_value"] = target_value
elif task_type == "close_door":
mission["robot_offset"] = [70, 0, 0]
mission["robot_orient"] = [0,0,0.7071068,0.7071068]
goal["description"] = "close the door"
condition["type"] = "rotation"
condition["init_value"] = target_value
condition["target_value"] = init_value
elif task_type == "pour_water":
# only pour half and empty
if not (init_value, target_value) in [(0.5, 1), (0, 1)]:
continue
mission["robot_offset"] = [-30, 0, 0]
goal["description"] = "Pour the liquid out of the contrainer."
condition["type"] = "liquid"
condition["init_value"] = target_value
condition["target_value"] = init_value
mission["size"] = 1.0
mission["orient"] = [1, 0, 0, 0]
elif task_type == "transfer_water":
# only pour half and empty
if not (init_value, target_value) in [(0, 0.25), (0, 0.5), (0, 0.75), (0, 1)]:
continue
mission["robot_offset"] = [-30, 0, 0]
goal["description"] = "Pour the liquid into another contrainer."
condition["type"] = "liquid"
# condition["init_value"] = target_value
condition["target_value"] = target_value
mission["size"] = 1.0
mission["orient"] = [1, 0, 0, 0]
elif task_type == "close_drawer":
condition["type"] = "linear"
mission["robot_offset"] = [-70, 0, 0]
goal["description"] = "close the drawer"
condition["init_value"] = target_value
condition["target_value"] = init_value
mission["size"] = 70
elif task_type == "open_drawer":
condition["type"] = "linear"
mission["robot_offset"] = [-50, 0, 0]
goal["description"] = "Open the drawer"
condition["init_value"] = init_value
condition["target_value"] = target_value
mission["size"] = 70
elif task_type == "open_cabinet":
condition["type"] = "rotation"
mission["robot_offset"] = [-50, 0, 0]
goal["description"] = "Open the cabinet"
condition["init_value"] = init_value
condition["target_value"] = target_value
mission["size"] = 70
elif task_type == "close_cabinet":
condition["type"] = "rotation"
mission["robot_offset"] = [-870, 0, 0]
goal["description"] = "Close the cabinet"
condition["init_value"] = target_value
condition["target_value"] = init_value
mission["size"] = 70
elif task_type == "tap_water":
# only pour half and empty
if not (init_value, target_value) in [(0, 0.25), (0, 0.5), (0, 0.75), (0, 1)]:
continue
mission["robot_offset"] = [-30, 0, 0]
goal["description"] = "Get tap water."
condition["type"] = "liquid"
condition["init_value"] = init_value
condition["target_value"] = target_value
mission["size"] = 20
mission["orient"] = [0.7071068,-0.7071068,0,0]
task_missions.append(mission)
print("task_missions", task_missions)
with open(meta_json_path, "w") as f:
json.dump(meta_json, f, indent = 4)
if __name__ == "__main__":
print("genrating continous mission")
add_continuous_meta_open_mission("open_door")
|
yizhouzhao/VRKitchen2.0-IndoorKit/exts/vrkitchen.indoor.kit/vrkitchen/indoor/kit/autotask/auto.py | # auto task generating
import os
import json
import numpy as np
import asyncio
import omni
import pxr
import carb
from omni.physx.scripts import physicsUtils
from ..param import IS_IN_ISAAC_SIM, DATA_PATH_NEW, CUSTOM_ASSET_PATH, ROBOT_PATH, SAPIEN_ASSET_PATH, IS_IN_CREAT, \
GAME_OBJ_NAMES, CONTAINER_NAMES, OTHER_OBJ_NAMES, HOUSE_INFO_PATH
from ..task_check import BaseChecker #, JointChecker, GraspChecker, OrientChecker, ContainerChecker
from .meta import AUTOTASK_META
# if IS_IN_CREAT:
# import omni.kit.viewport_widgets_manager as wm
# from ..ui.hud import LabelWidget
class AutoTasker():
TASK_DESCRIPTION = ""
TASK_ID = ""
def __init__(self,
task_type:str,
task_id:int,
robot_id:int = 0,
mission_id:int = 0,
house_id:int = 0,
anchor_id:int = 0,
meta_id : int = 0, # to retrieve which config from meta data
annotator : int = 0,
) -> None:
self.task_type = task_type
self.task_id = str(task_id)
self.robot_id = str(robot_id)
self.mission_id = str(mission_id)
self.house_id = str(house_id)
self.anchor_id = str(anchor_id)
self.meta_id = mission_id # meta_id
self.data_path = DATA_PATH_NEW
# scene
self.stage = omni.usd.get_context().get_stage()
##
self.annotator = annotator
# get objects
self.probe_obj_folder()
def probe_obj_folder(self):
"""
check task folder
"""
task_type_folder = os.path.join(self.data_path, self.annotator, "task", self.task_type)
if not os.path.exists(task_type_folder):
os.makedirs(task_type_folder)
task_folder = os.path.join(self.data_path, self.annotator, "task", self.task_type, str(self.task_id))
if not os.path.exists(task_folder):
os.makedirs(task_folder)
"""
Get furniture
"""
if self.task_type in ["open_drawer", "open_cabinet", "close_drawer", "close_cabinet"]:
self.obj_type = "StorageFurniture"
self.obj_folder = os.path.join(SAPIEN_ASSET_PATH, self.obj_type)
elif self.task_type in ["pickup_object", "reorient_object"]:
self.obj_type = "Bottle"
self.obj_folder = os.path.join(CUSTOM_ASSET_PATH, self.obj_type)
elif self.task_type in ["put_object_into_box", "take_object_out_box"]:
self.obj_type = "Box"
self.obj_folder = os.path.join(SAPIEN_ASSET_PATH, self.obj_type)
elif self.task_type in ["open_door", "close_door"]:
self.obj_type = "Door"
self.obj_folder = os.path.join(SAPIEN_ASSET_PATH, self.obj_type)
elif self.task_type in ["pour_water", "transfer_water"]:
self.obj_type = "Cup"
self.obj_folder = os.path.join(CUSTOM_ASSET_PATH, self.obj_type)
elif self.task_type in ["tap_water"]:
self.obj_type = "Faucet"
self.obj_folder = os.path.join(SAPIEN_ASSET_PATH, self.obj_type)
else:
raise Exception(f"current task type not supported: {self.task_type}")
objs = [ item for item in os.listdir(self.obj_folder) if item.isnumeric() ]
self.obj_list = sorted( objs, key=lambda x: int(x))
self.obj_id = self.obj_list[int(self.task_id)]
self.target_obj_path = "/mobility_" + self.obj_type + "_" + str(self.obj_id)
def reconfig(self, obj_index):
"""
Reconfig obj from object index
"""
self.obj_index = obj_index
self.obj_id = self.obj_list[int(obj_index)]
self.target_obj_path = "/mobility_" + self.obj_type + "_" + str(self.obj_id)
print("AUTOTASK_META[self.task_type][self.meta_id]", AUTOTASK_META[self.task_type][self.meta_id])
AutoTasker.TASK_DESCRIPTION = AUTOTASK_META[self.task_type][self.meta_id]["goal"]["description"]
print("AutoTasker.TASK_DESCRIPTION", AutoTasker.TASK_DESCRIPTION)
def add_obj(self):
"""
Add object to the scene
"""
self.stage = omni.usd.get_context().get_stage()
# set up game root
default_prim_path_str = self.stage.GetDefaultPrim().GetPath().pathString
## this is necessary because for standalone this might not be /World
if not default_prim_path_str:
default_prim_path_str = "/World"
self.xform_game_path = default_prim_path_str + "/game" # omni.usd.get_stage_next_free_path(self.stage, "/World/game", True)
# move obj to the correct place
xform_game = self.stage.GetPrimAtPath(self.xform_game_path)
if not xform_game:
xform_game = pxr.UsdGeom.Xform.Define(self.stage, self.xform_game_path)
# set game xform
game_xform = pxr.Gf.Matrix4d().SetScale([1, 1, 1]) * \
pxr.Gf.Matrix4d().SetRotate(pxr.Gf.Quatf(1.0,0.0,0.0,0.0)) * pxr.Gf.Matrix4d().SetTranslate([0,0,0])
omni.kit.commands.execute(
"TransformPrimCommand",
path=self.xform_game_path,
new_transform_matrix=game_xform,
)
# set obj prim path
mobility_prim_path = xform_game.GetPath().pathString + self.target_obj_path
print("mobility_prim_path", mobility_prim_path)
prim = self.stage.GetPrimAtPath(mobility_prim_path)
if not prim.IsValid():
prim = self.stage.DefinePrim(mobility_prim_path)
if self.task_type in ["pour_water", "transfer_water"]:
obj_usd_path = os.path.join(self.obj_folder, self.obj_id, "cup.usd")
else:
obj_usd_path = os.path.join(self.obj_folder, self.obj_id, "mobility.usd")
# import obj
success_bool = prim.GetReferences().AddReference(obj_usd_path)
if not success_bool:
raise Exception(f"Cannot import obj usd at path {obj_usd_path}")
# set up scale
if self.task_type in ["open_door", "close_door"]:
from .utils import calculate_door_size
scale = calculate_door_size(prim)
else:
scale = [AUTOTASK_META[self.task_type][self.meta_id]["size"]]*3
if prim.HasAttribute("xformOp:scale"):
prim.GetAttribute("xformOp:scale").Set(pxr.Gf.Vec3f(scale))
else:
obj_xform = pxr.Gf.Matrix4d().SetScale(scale)
omni.kit.commands.execute(
"TransformPrimCommand",
path=prim.GetPath().pathString,
new_transform_matrix=obj_xform,
)
# set up orient
#if self.task_type "reorient_object":
orient = AUTOTASK_META[self.task_type][self.meta_id]["orient"]
print("orient: ", orient)
mat = pxr.Gf.Matrix4f(pxr.UsdGeom.Xformable(prim).ComputeLocalToWorldTransform(0))
obj_xform = pxr.Gf.Matrix4f().SetScale(scale) * pxr.Gf.Matrix4f().SetRotate(pxr.Gf.Quatf(*orient))
new_xform = obj_xform
# new_xform = obj_xform * mat
print("new_xform", prim, obj_xform, mat, "rot", new_xform.ExtractRotationQuat(), "scale:", scale)
omni.kit.commands.execute(
"TransformPrimCommand",
path=prim.GetPath().pathString,
new_transform_matrix=new_xform,
)
# other imports
if self.task_type in ["put_object_into_box", "transfer_water", "tap_water"]:
self.add_auxilary_object()
# unbind material
if self.task_type in ["transfer_water", "pour_water"]:
print("unbind material")
omni.kit.commands.execute(
'BindMaterial',
prim_path=prim.GetPath().pathString + "/cupShape",
material_path=None,
strength=pxr.UsdShade.Tokens.strongerThanDescendants
)
def add_auxilary_object(self):
"""
Add object to the scene
"""
self.stage = omni.usd.get_context().get_stage()
# set up game root
default_prim_path_str = self.stage.GetDefaultPrim().GetPath().pathString
## this is necessary because for standalone this might not be /World
if not default_prim_path_str:
default_prim_path_str = "/World"
self.xform_game_path = default_prim_path_str + "/game" # omni.usd.get_stage_next_free_path(self.stage, "/World/game", True)
# move obj to the correct place
xform_game = self.stage.GetPrimAtPath(self.xform_game_path)
if not xform_game:
raise Exception(f"must have /World/game prim")
if self.task_type == "put_object_into_box":
aux_folder = os.path.join(CUSTOM_ASSET_PATH, "standalone")
aux_folder_objs = os.listdir(aux_folder)
aux_obj_name = aux_folder_objs[self.obj_index + 12]
aux_prim_path = xform_game.GetPath().pathString + "/mobility_standalone_" + aux_obj_name
obj_usd_path = os.path.join(aux_folder, aux_obj_name, "mobility.usd")
position = [-20,0,0]
else:
aux_folder = os.path.join(CUSTOM_ASSET_PATH, "Cup")
aux_folder_objs = sorted(os.listdir(aux_folder), key=lambda x:int(x))
aux_obj_name = str(int(self.task_id))
aux_prim_path = xform_game.GetPath().pathString + "/container_Cup_" + aux_obj_name
obj_usd_path = os.path.join(aux_folder, aux_obj_name, "cup.usd")
position = [0,0,-20]
# print("aux_prim_path", aux_prim_path)
prim = self.stage.GetPrimAtPath(aux_prim_path)
if not prim.IsValid():
prim = self.stage.DefinePrim(aux_prim_path)
success_bool = prim.GetReferences().AddReference(obj_usd_path)
if not success_bool:
raise Exception(f"Cannot import obj usd at path {obj_usd_path}")
# offset
if True:
purposes = [pxr.UsdGeom.Tokens.default_]
bboxcache = pxr.UsdGeom.BBoxCache(pxr.Usd.TimeCode.Default(), purposes)
game_prim = self.stage.GetPrimAtPath(self.xform_game_path)
bboxes = bboxcache.ComputeWorldBound(game_prim)
# print("bboxes", bboxes)
game_bboxes = [bboxes.ComputeAlignedRange().GetMin(),bboxes.ComputeAlignedRange().GetMax()]
else:
game_bboxes = omni.usd.get_context().compute_path_world_bounding_box(self.xform_game_path)
position[1] += game_bboxes[0][1] # the same y
position[0] += game_bboxes[0][0] # offset x
position[2] += game_bboxes[0][2] # offset x
# set up scale
obj_xform = pxr.Gf.Matrix4d().SetScale([1,1,1]).SetRotate(pxr.Gf.Quatf(1,0,0,0)).SetTranslate(position)
omni.kit.commands.execute(
"TransformPrimCommand",
path=prim.GetPath().pathString,
new_transform_matrix=obj_xform,
)
# unbind material
if self.task_type in ["transfer_water", "pour_water"]:
print("unbind material")
omni.kit.commands.execute(
'BindMaterial',
prim_path=prim.GetPath().pathString + "/cupShape",
material_path=None,
strength=pxr.UsdShade.Tokens.strongerThanDescendants
)
def add_robot(self):
"""
Add robot to the scene:
1. load robot
2. calculate position
"""
self.stage = omni.usd.get_context().get_stage()
franka_path = os.path.join(ROBOT_PATH, "franka/franka.usd")
self.xform_game_path = "/World/game"
# position, rotation
position = [i for i in AUTOTASK_META[self.task_type][self.meta_id]["robot_offset"]]
rotation = [i for i in AUTOTASK_META[self.task_type][self.meta_id]["robot_orient"]]
# offset
if True: ##IS_IN_ISAAC_SIM:
purposes = [pxr.UsdGeom.Tokens.default_]
bboxcache = pxr.UsdGeom.BBoxCache(pxr.Usd.TimeCode.Default(), purposes)
prim = self.stage.GetPrimAtPath(self.xform_game_path)
bboxes = bboxcache.ComputeWorldBound(prim)
# print("bboxes", bboxes)
game_bboxes = [bboxes.ComputeAlignedRange().GetMin(),bboxes.ComputeAlignedRange().GetMax()]
else:
game_bboxes = omni.usd.get_context().compute_path_world_bounding_box(self.xform_game_path)
print("game_bboxes", game_bboxes)
position[1] += game_bboxes[0][1]
# print("game_bboxes", game_bboxes, position)
if position[0] != 0 :
position[0] += game_bboxes[0][0]
if position[2] != 0 :
position[2] += game_bboxes[0][2]
# load robot
robot_prim = self.stage.GetPrimAtPath(self.xform_game_path + "/franka")
if not robot_prim.IsValid():
robot_prim = self.stage.DefinePrim(self.xform_game_path + "/franka")
print("add robot at path: ", franka_path)
success_bool = robot_prim.GetReferences().AddReference(franka_path)
if not success_bool:
raise Exception("The usd file at path {} provided wasn't found".format(franka_path))
# set robot xform
robot_xform = pxr.UsdGeom.Xformable.Get(self.stage, robot_prim.GetPath())
robot_xform.ClearXformOpOrder()
# print("position $ rotation: ", position[0], position[1], position[2], rotation)
robot_xform.AddTranslateOp().Set(pxr.Gf.Vec3f(float(position[0]), float(position[1]), float(position[2])))
robot_xform.AddOrientOp().Set(pxr.Gf.Quatf(float(rotation[0]), float(rotation[1]), float(rotation[2]), float(rotation[3])))
robot_xform.AddScaleOp().Set(pxr.Gf.Vec3f(1.0, 1.0, 1.0))
#selection = omni.usd.get_context().get_selection()
#selection.clear_selected_prim_paths()
#selection.set_prim_path_selected(robot_parent_path + "/franka", True, True, True, True)
def add_house(self):
"""
Add house from house_d
"""
print("auto add house??")
# scene
self.stage = omni.usd.get_context().get_stage()
self.layer = self.stage.GetRootLayer()
house_path = os.path.join(HOUSE_INFO_PATH, self.house_id, "layout.usd")
# omni.kit.commands.execute(
# "CreateSublayer",
# layer_identifier=self.layer.identifier,
# sublayer_position=0,
# new_layer_path=house_path,
# transfer_root_content=False,
# create_or_insert=False,
# layer_name="house",
# )
# move obj to the correct place
house_prim_path = "/World/layout"
house_prim = self.stage.GetPrimAtPath(house_prim_path)
if not house_prim.IsValid():
house_prim = self.stage.DefinePrim(house_prim_path)
success_bool = house_prim.GetReferences().AddReference(house_path)
if not success_bool:
raise Exception(f"The house is not load at {house_path}")
if not self.task_type in ["tap_water", "transfer_water", "pour_water"]:
from omni.physx.scripts.utils import setStaticCollider
# static collider
furniture_prim = self.stage.GetPrimAtPath(house_prim_path + "/furniture")
setStaticCollider(furniture_prim, approximationShape="none")
# TODO: check room_struct collider
room_struct_prim = self.stage.GetPrimAtPath(house_prim_path + "/roomStruct")
setStaticCollider(room_struct_prim, approximationShape="none")
# put game onto ground
game_prim_path = "/World/game"
game_prim = self.stage.GetPrimAtPath(game_prim_path)
if game_prim:
if True: #IS_IN_ISAAC_SIM:
purposes = [pxr.UsdGeom.Tokens.default_]
bboxcache = pxr.UsdGeom.BBoxCache(pxr.Usd.TimeCode.Default(), purposes)
bboxes = bboxcache.ComputeWorldBound(game_prim)
# print("bboxes", bboxes)
y = bboxes.ComputeAlignedRange().GetMin()[1]
else:
# prim_path = stage.GetDefaultPrim().GetPath().pathString
usd_context = omni.usd.get_context()
bboxes = usd_context.compute_path_world_bounding_box(game_prim_path)
y = bboxes[0][1]
game_xform = pxr.Gf.Matrix4d().SetScale([1, 1, 1]) * \
pxr.Gf.Matrix4d().SetRotate(pxr.Gf.Quatf(1.0,0.0,0.0,0.0)) * pxr.Gf.Matrix4d().SetTranslate([0,-y,0])
omni.kit.commands.execute(
"TransformPrimCommand",
path=game_prim_path,
new_transform_matrix=game_xform,
)
# add ground
ground_prim = self.stage.GetPrimAtPath("/World/groundPlane")
if not ground_prim:
physicsUtils.add_ground_plane(self.stage, "/World/groundPlane", "Y", 1000.0,
pxr.Gf.Vec3f(0.0, 0.0, 0), pxr.Gf.Vec3f(0.2))
ground_prim = self.stage.GetPrimAtPath("/World/groundPlane")
# prim_list = list(self.stage.TraverseAll())
# prim_list = [ item for item in prim_list if 'groundPlane' in item.GetPath().pathString and item.GetTypeName() == 'Mesh' ]
# for prim in prim_list:
ground_prim.GetAttribute('visibility').Set('invisible')
def add_task(self):
"""
Add task to current scene
"""
self.stage = omni.usd.get_context().get_stage()
self.task_checker = BaseChecker(self.task_type, self.task_id, self.robot_id, self.mission_id, annotator = "Yizhou", run_time = False)
# if self.task_type in ["open_drawer", "open_cabinet", "open_door", "close_door"]:
# self.task_checker = JointChecker(self.task_type, self.task_id, self.robot_id, self.mission_id)
# elif self.task_type == "pickup_object":
# self.task_checker = GraspChecker(self.task_type, self.task_id, self.robot_id, self.mission_id)
# elif self.task_type == "reorient_object":
# self.task_checker = OrientChecker(self.task_type, self.task_id, self.robot_id, self.mission_id)
# elif self.task_type in ["put_object_into_box"]:
# self.task_checker = ContainerChecker(self.task_type, self.task_id, self.robot_id, self.mission_id)
# else:
# raise Exception(f"Current task type {self.task_type} not supported")
# modify task from template
# print(AUTOTASK_META[self.task_type][self.meta_index]["task_template"])
self.task_checker.current_mission = AUTOTASK_META[self.task_type][self.meta_id]
condition = self.task_checker.current_mission["goal"]["condition"]
# get target
target_prim = None
for prim in self.stage.GetPrimAtPath("/World/game").GetChildren():
for game_name in GAME_OBJ_NAMES:
if game_name in prim.GetPath().pathString:
target_prim = prim
break
condition["target"] = target_prim.GetPath().pathString.split("/")[-1]
# other condition
if self.task_type in ["open_drawer", "open_cabinet", "open_door", "close_door", "close_drawer", "close_cabinet"]:
selection = omni.usd.get_context().get_selection()
assert len(selection.get_selected_prim_paths()) == 1, "Please select one joint!"
joint_path = selection.get_selected_prim_paths()[0]
joint_name = joint_path.split("/")[-1]
# print("joint_name:", joint_name)
self.task_checker.current_mission["goal"]
condition["joint"] = joint_name
elif self.task_type in ["put_object_into_box", "transfer_water", "take_object_out_box", "tap_water"]:
container_prim = None
for prim in self.stage.GetPrimAtPath("/World/game").GetChildren():
for game_name in CONTAINER_NAMES:
if game_name in prim.GetPath().pathString.lower():
container_prim = prim
break
if not container_prim:
raise Exception(f"Container prim must exist at under /World/game")
condition["container"] = container_prim.GetPath().pathString.split("/")[-1]
# save mission
self.task_checker.current_mission["goal"]["description"] = AutoTasker.TASK_DESCRIPTION
print("current_mission", self.task_checker.current_mission)
self.task_checker.current_mission["goal"]["condition"] = condition
self.task_checker.save_mission()
@classmethod
def new_scene(cls):
async def open_new_scene():
await omni.usd.get_context().new_stage_async()
await omni.kit.app.get_app().next_update_async()
asyncio.ensure_future(open_new_scene())
# def build_HUD(self):
# if IS_IN_CREAT or IS_IN_ISAAC_SIM:
# gui_path = self.stage.GetDefaultPrim().GetPath().pathString + "/GUI"
# gui = self.stage.GetPrimAtPath(gui_path)
# if not gui:
# gui = pxr.UsdGeom.Xform.Define(self.stage, gui_path)
# gui_location = pxr.Gf.Vec3f(0, 50, 0)
# gui.AddTranslateOp().Set(gui_location)
# self.wiget_id = wm.add_widget(gui_path, LabelWidget(f"Object id: {self.obj_id}"), wm.WidgetAlignment.TOP)
|
yizhouzhao/VRKitchen2.0-IndoorKit/exts/vrkitchen.indoor.kit/vrkitchen/indoor/kit/autotask/utils.py | # utility function
import re
import omni
import pxr
from ..param import IS_IN_CREAT
def calculate_door_size(prim, scale = 1):
"""
calculate door size to scale it to the proper size for 3DFront
"""
target_box_size = [10, 73.157, 209] # 3D-FRONT door frame size
if False: #IS_IN_CREAT:
usd_context = omni.usd.get_context()
prim_bboxes = usd_context.compute_path_world_bounding_box(prim.GetPath().pathString)
# In create
else:
purposes = [pxr.UsdGeom.Tokens.default_]
bboxcache = pxr.UsdGeom.BBoxCache(pxr.Usd.TimeCode.Default(), purposes)
bboxes = bboxcache.ComputeWorldBound(prim)
# print("bboxes", bboxes)
prim_bboxes = [bboxes.ComputeAlignedRange().GetMin(), bboxes.ComputeAlignedRange().GetMax()]
print("prim_bboxes", prim_bboxes)
s_x = target_box_size[0] / (prim_bboxes[1][0] - prim_bboxes[0][0]) * scale
s_y = target_box_size[1] / (prim_bboxes[1][1] - prim_bboxes[0][1]) * scale
s_z = target_box_size[2] / (prim_bboxes[1][2] - prim_bboxes[0][2]) * scale
# if prim_bboxes[1][1] - prim_bboxes[0][1] < prim_bboxes[1][2] - prim_bboxes[0][2]:
# s_y, s_z = s_z, s_y
print("[1, s_y, s_z]", s_x, s_y, s_z)
return [1, s_y, s_z]
|
yizhouzhao/VRKitchen2.0-IndoorKit/exts/vrkitchen.indoor.kit/vrkitchen/indoor/kit/autotask/meta.py | import json
from pathlib import Path
import os
auto_folder = str(Path(__file__).parent.resolve()).replace("\\", "/")
# print("auto_folder", auto_folder)
AUTOTASK_META = json.load(open(os.path.join(auto_folder,"configs.json"))) |
yizhouzhao/VRKitchen2.0-IndoorKit/exts/vrkitchen.indoor.kit/vrkitchen/indoor/kit/autotask/auto_suggest.py | # task labeling suggestion
from logging import root
from omni import ui
import os
import json
import carb
from ..param import DATA_PATH_NEW, TASK_TYPES, ANNOTATORS
def generate_suggestion_text_from_list(id_list):
if len(id_list) == 0:
return "no suggestion"
return ",".join([str(_) for _ in id_list])
class AutoSuggest():
def __init__(self) -> None:
pass
def read_ui(self):
self.task_type_index = self.suggest_task_type_ui.model.get_item_value_model().get_value_as_int()
self.task_type = TASK_TYPES[self.task_type_index - 1]
self.task_id = self.suggest_task_id_ui.model.get_value_as_int()
self.robot_id = self.suggest_robot_id_ui.model.get_value_as_int()
self.mission_id = self.suggest_mission_id_ui.model.get_value_as_int()
self.house_id = self.suggest_house_id_ui.model.get_value_as_int()
self.anchor_id = self.suggest_anchor_id_ui.model.get_value_as_int()
self.annotator_index = self.annotator_ui.model.get_item_value_model().get_value_as_int()
self.annotator = ANNOTATORS[self.annotator_index]
def reset_ui(self):
self.suggest_task_type_ui.model.get_item_value_model().set_value(0)
self.suggest_task_id_ui.model.set_value(-1)
self.suggest_robot_id_ui.model.set_value(-1)
self.suggest_mission_id_ui.model.set_value(-1)
self.suggest_house_id_ui.model.set_value(-1)
self.suggest_anchor_id_ui.model.set_value(-1)
self.suggest_task_id_text_ui.model.set_value("")
self.suggest_robot_id_text_ui.model.set_value("")
self.suggest_mission_id_text_ui.model.set_value("")
self.suggest_anchor_id_text_ui.model.set_value("")
self.suggest_house_id_text_ui.model.set_value("")
self.info_ui.model.set_value("")
def suggest_trial_num(self):
from ..param import SAVE_ROOT
root_dir = '-'.join([self.task_type, str(self.task_id), str(self.robot_id), str(self.mission_id), str(self.house_id), \
str(self.anchor_id) ])
folders = os.listdir(SAVE_ROOT)
folders = [folder for folder in folders if folder.startswith(root_dir)]
return len(folders)
def suggest_task(self):
self.read_ui()
task_ids = os.listdir(os.path.join(DATA_PATH_NEW, self.annotator, "task", self.task_type))
task_ids.sort(key=lambda x: int(x))
self.suggest_task_id_text_ui.model.set_value(generate_suggestion_text_from_list(task_ids))
def suggest_robot(self):
self.read_ui()
robot_file = os.path.join(DATA_PATH_NEW, self.annotator, "task", self.task_type, str(self.task_id), "robots.json")
if os.path.exists(robot_file):
robot_ids = list(json.load(open(robot_file)).keys())
else:
carb.log_warn(f"No robots found for task {self.task_type}: {self.task_id}")
robot_ids = []
# print(robot_ids)
self.suggest_robot_id_text_ui.model.set_value(generate_suggestion_text_from_list(robot_ids))
def suggest_anchor_id(self):
self.read_ui()
house_folder = os.path.join(DATA_PATH_NEW, self.annotator, "house")
house_folders = os.listdir(house_folder)
keys = []
# folder: 0, 1, 2 etc...
display = []
for folder in house_folders:
path = str(os.path.join(house_folder, folder, "anchor.json" ))
if os.path.exists(path):
with open(path) as f:
data = json.load(f)
keys.extend(list(data.keys()))
for name in keys:
tmp = name.split()
assert (len(tmp) == 4)
task_type = tmp[0]
task_id = tmp[1]
robot_id = tmp[2]
anchor_id = tmp[3]
if task_type == self.task_type and str(task_id) == str(self.task_id) and str(robot_id) == str(self.robot_id):
display.append(anchor_id)
self.suggest_anchor_id_text_ui.model.set_value(generate_suggestion_text_from_list(display))
def suggest_houseID(self):
self.read_ui()
house_folder = os.path.join(DATA_PATH_NEW, self.annotator, "house")
house_folders = os.listdir(house_folder)
keys = []
# folder: 0, 1, 2 etc...
display = []
for folder in house_folders:
path = str(os.path.join(house_folder, folder, "anchor.json" ))
if os.path.exists(path):
with open(path) as f:
data = json.load(f)
keys.extend(list(data.keys()))
for name in keys:
tmp = name.split()
assert (len(tmp) == 4)
task_type = tmp[0]
task_id = tmp[1]
robot_id = tmp[2]
anchor_id = tmp[3]
if task_type == self.task_type and str(task_id) == str(self.task_id) and str(robot_id) == str(self.robot_id):
display.append(folder)
self.suggest_house_id_text_ui.model.set_value(generate_suggestion_text_from_list(display))
def suggest_mission(self):
self.read_ui()
mission_file = os.path.join(DATA_PATH_NEW, self.annotator, "task", self.task_type, str(self.task_id), "missions.json")
mission_ids = []
if os.path.exists(mission_file):
mission_info = json.load(open(mission_file))
# identifier_prefix = self.task_type + " " + str(self.task_id) + " " + str(self.robot_id)
identifier_prefix = self.task_type + " " + str(self.task_id) #+ " " + str(self.robot_id)
for key in mission_info:
if key.startswith(identifier_prefix):
mission_ids.append(key.split()[-1])
else:
carb.log_warn(f"No mission found for task {self.task_type}: {self.task_id}")
self.suggest_mission_id_text_ui.model.set_value(generate_suggestion_text_from_list(mission_ids))
def suggest_goal(self):
self.read_ui()
task_folder = os.path.join(DATA_PATH_NEW, self.annotator, "task", self.task_type, str(self.task_id))
if not os.path.exists(task_folder):
carb.log_warn(f"Task folder not exist at {task_folder}")
self.info_ui.model.set_value("Please add mission.")
mission_file_path = os.path.join(task_folder, "missions.json")
if os.path.exists(mission_file_path):
missions = json.load(open(mission_file_path))
carb.log_info(f"Loading missions.json at path {mission_file_path}")
mission_identifier_prefix = self.task_type + " " + str(self.task_id) + " "
mission_identifier_suffix = str(self.mission_id)
for key, value in missions.items():
if key.startswith(mission_identifier_prefix) and key.endswith(mission_identifier_suffix):
current_task = missions[key]
self.info_ui.model.set_value(json.dumps(current_task["goal"], indent = 2))
else:
self.info_ui.model.set_value("Please add mission.")
|
yizhouzhao/VRKitchen2.0-IndoorKit/exts/vrkitchen.indoor.kit/vrkitchen/indoor/kit/autotask/configs.json | {
"open_drawer": [
{
"size": 70,
"orient": [
0.7071068,
-0.7071068,
0,
0
],
"robot_offset": [
-50,
0,
0
],
"robot_orient": [
0.7071068,
-0.7071068,
0,
0
],
"task_type": "",
"task_id": "",
"robot_id": "",
"mission_id": "",
"goal": {
"description": "Open the drawer",
"condition": {
"init_value": 0,
"type": "linear",
"target": "",
"joint": "",
"target_value": 0.25
}
}
},
{
"size": 70,
"orient": [
0,
0,
0.7071068,
0.7071068
],
"robot_offset": [
-50,
0,
0
],
"robot_orient": [
0.7071068,
-0.7071068,
0,
0
],
"task_type": "",
"task_id": "",
"robot_id": "",
"mission_id": "",
"goal": {
"description": "Open the drawer",
"condition": {
"init_value": 0,
"type": "linear",
"target": "",
"joint": "",
"target_value": 0.5
}
}
},
{
"size": 70,
"orient": [
0,
0,
0.7071068,
0.7071068
],
"robot_offset": [
-50,
0,
0
],
"robot_orient": [
0.7071068,
-0.7071068,
0,
0
],
"task_type": "",
"task_id": "",
"robot_id": "",
"mission_id": "",
"goal": {
"description": "Open the drawer",
"condition": {
"init_value": 0,
"type": "linear",
"target": "",
"joint": "",
"target_value": 0.75
}
}
},
{
"size": 70,
"orient": [
0,
0,
0.7071068,
0.7071068
],
"robot_offset": [
-50,
0,
0
],
"robot_orient": [
0.7071068,
-0.7071068,
0,
0
],
"task_type": "",
"task_id": "",
"robot_id": "",
"mission_id": "",
"goal": {
"description": "Open the drawer",
"condition": {
"init_value": 0,
"type": "linear",
"target": "",
"joint": "",
"target_value": 1
}
}
},
{
"size": 70,
"orient": [
0,
0,
0.7071068,
0.7071068
],
"robot_offset": [
-50,
0,
0
],
"robot_orient": [
0.7071068,
-0.7071068,
0,
0
],
"task_type": "",
"task_id": "",
"robot_id": "",
"mission_id": "",
"goal": {
"description": "Open the drawer",
"condition": {
"init_value": 0.25,
"type": "linear",
"target": "",
"joint": "",
"target_value": 0.5
}
}
},
{
"size": 70,
"orient": [
0,
0,
0.7071068,
0.7071068
],
"robot_offset": [
-50,
0,
0
],
"robot_orient": [
0.7071068,
-0.7071068,
0,
0
],
"task_type": "",
"task_id": "",
"robot_id": "",
"mission_id": "",
"goal": {
"description": "Open the drawer",
"condition": {
"init_value": 0.25,
"type": "linear",
"target": "",
"joint": "",
"target_value": 0.75
}
}
},
{
"size": 70,
"orient": [
0,
0,
0.7071068,
0.7071068
],
"robot_offset": [
-50,
0,
0
],
"robot_orient": [
0.7071068,
-0.7071068,
0,
0
],
"task_type": "",
"task_id": "",
"robot_id": "",
"mission_id": "",
"goal": {
"description": "Open the drawer",
"condition": {
"init_value": 0.25,
"type": "linear",
"target": "",
"joint": "",
"target_value": 1
}
}
},
{
"size": 70,
"orient": [
0,
0,
0.7071068,
0.7071068
],
"robot_offset": [
-50,
0,
0
],
"robot_orient": [
0.7071068,
-0.7071068,
0,
0
],
"task_type": "",
"task_id": "",
"robot_id": "",
"mission_id": "",
"goal": {
"description": "Open the drawer",
"condition": {
"init_value": 0.5,
"type": "linear",
"target": "",
"joint": "",
"target_value": 0.75
}
}
},
{
"size": 70,
"orient": [
0,
0,
0.7071068,
0.7071068
],
"robot_offset": [
-50,
0,
0
],
"robot_orient": [
0.7071068,
-0.7071068,
0,
0
],
"task_type": "",
"task_id": "",
"robot_id": "",
"mission_id": "",
"goal": {
"description": "Open the drawer",
"condition": {
"init_value": 0.5,
"type": "linear",
"target": "",
"joint": "",
"target_value": 1
}
}
},
{
"size": 70,
"orient": [
0,
0,
0.7071068,
0.7071068
],
"robot_offset": [
-50,
0,
0
],
"robot_orient": [
0.7071068,
-0.7071068,
0,
0
],
"task_type": "",
"task_id": "",
"robot_id": "",
"mission_id": "",
"goal": {
"description": "Open the drawer",
"condition": {
"init_value": 0.75,
"type": "linear",
"target": "",
"joint": "",
"target_value": 1
}
}
}
],
"open_cabinet": [
{
"size": 70,
"orient": [
0.7071068,
-0.7071068,
0,
0
],
"robot_offset": [
-50,
0,
0
],
"robot_orient": [
0.7071068,
-0.7071068,
0,
0
],
"task_type": "",
"task_id": "",
"robot_id": "",
"mission_id": "",
"goal": {
"description": "Open the cabinet",
"condition": {
"init_value": 0,
"type": "rotation",
"target": "",
"joint": "",
"target_value": 0.25
}
}
},
{
"size": 70,
"orient": [
0,
0,
0.7071068,
0.7071068
],
"robot_offset": [
-50,
0,
0
],
"robot_orient": [
0.7071068,
-0.7071068,
0,
0
],
"task_type": "",
"task_id": "",
"robot_id": "",
"mission_id": "",
"goal": {
"description": "Open the cabinet",
"condition": {
"init_value": 0,
"type": "rotation",
"target": "",
"joint": "",
"target_value": 0.5
}
}
},
{
"size": 70,
"orient": [
0,
0,
0.7071068,
0.7071068
],
"robot_offset": [
-50,
0,
0
],
"robot_orient": [
0.7071068,
-0.7071068,
0,
0
],
"task_type": "",
"task_id": "",
"robot_id": "",
"mission_id": "",
"goal": {
"description": "Open the cabinet",
"condition": {
"init_value": 0,
"type": "rotation",
"target": "",
"joint": "",
"target_value": 0.75
}
}
},
{
"size": 70,
"orient": [
0,
0,
0.7071068,
0.7071068
],
"robot_offset": [
-50,
0,
0
],
"robot_orient": [
0.7071068,
-0.7071068,
0,
0
],
"task_type": "",
"task_id": "",
"robot_id": "",
"mission_id": "",
"goal": {
"description": "Open the cabinet",
"condition": {
"init_value": 0,
"type": "rotation",
"target": "",
"joint": "",
"target_value": 1
}
}
},
{
"size": 70,
"orient": [
0,
0,
0.7071068,
0.7071068
],
"robot_offset": [
-50,
0,
0
],
"robot_orient": [
0.7071068,
-0.7071068,
0,
0
],
"task_type": "",
"task_id": "",
"robot_id": "",
"mission_id": "",
"goal": {
"description": "Open the cabinet",
"condition": {
"init_value": 0.25,
"type": "rotation",
"target": "",
"joint": "",
"target_value": 0.5
}
}
},
{
"size": 70,
"orient": [
0,
0,
0.7071068,
0.7071068
],
"robot_offset": [
-50,
0,
0
],
"robot_orient": [
0.7071068,
-0.7071068,
0,
0
],
"task_type": "",
"task_id": "",
"robot_id": "",
"mission_id": "",
"goal": {
"description": "Open the cabinet",
"condition": {
"init_value": 0.25,
"type": "rotation",
"target": "",
"joint": "",
"target_value": 0.75
}
}
},
{
"size": 70,
"orient": [
0,
0,
0.7071068,
0.7071068
],
"robot_offset": [
-50,
0,
0
],
"robot_orient": [
0.7071068,
-0.7071068,
0,
0
],
"task_type": "",
"task_id": "",
"robot_id": "",
"mission_id": "",
"goal": {
"description": "Open the cabinet",
"condition": {
"init_value": 0.25,
"type": "rotation",
"target": "",
"joint": "",
"target_value": 1
}
}
},
{
"size": 70,
"orient": [
0,
0,
0.7071068,
0.7071068
],
"robot_offset": [
-50,
0,
0
],
"robot_orient": [
0.7071068,
-0.7071068,
0,
0
],
"task_type": "",
"task_id": "",
"robot_id": "",
"mission_id": "",
"goal": {
"description": "Open the cabinet",
"condition": {
"init_value": 0.5,
"type": "rotation",
"target": "",
"joint": "",
"target_value": 0.75
}
}
},
{
"size": 70,
"orient": [
0,
0,
0.7071068,
0.7071068
],
"robot_offset": [
-50,
0,
0
],
"robot_orient": [
0.7071068,
-0.7071068,
0,
0
],
"task_type": "",
"task_id": "",
"robot_id": "",
"mission_id": "",
"goal": {
"description": "Open the cabinet",
"condition": {
"init_value": 0.5,
"type": "rotation",
"target": "",
"joint": "",
"target_value": 1
}
}
},
{
"size": 70,
"orient": [
0,
0,
0.7071068,
0.7071068
],
"robot_offset": [
-50,
0,
0
],
"robot_orient": [
0.7071068,
-0.7071068,
0,
0
],
"task_type": "",
"task_id": "",
"robot_id": "",
"mission_id": "",
"goal": {
"description": "Open the cabinet",
"condition": {
"init_value": 0.75,
"type": "rotation",
"target": "",
"joint": "",
"target_value": 1
}
}
}
],
"pickup_object": [
{
"size": 15,
"orient": [
1,
0,
0,
0
],
"robot_offset": [
-40,
0,
0
],
"robot_orient": [
0.7071068,
-0.7071068,
0,
0
],
"task_type": "",
"task_id": "",
"robot_id": "",
"mission_id": "",
"goal": {
"description": "Pick up the bottle.",
"condition": {
"type": "translate_y",
"target": "",
"joint": "",
"target_value": 20
}
}
},
{
"size": 15,
"orient": [
1,
0,
0,
0
],
"robot_offset": [
-40,
0,
0
],
"robot_orient": [
0.7071068,
-0.7071068,
0,
0
],
"task_type": "",
"task_id": "",
"robot_id": "",
"mission_id": "",
"goal": {
"description": "Pick up the bottle.",
"condition": {
"type": "translate_y",
"target": "",
"joint": "",
"target_value": 40
}
}
},
{
"size": 15,
"orient": [
1,
0,
0,
0
],
"robot_offset": [
-40,
0,
0
],
"robot_orient": [
0.7071068,
-0.7071068,
0,
0
],
"task_type": "",
"task_id": "",
"robot_id": "",
"mission_id": "",
"goal": {
"description": "Pick up the bottle.",
"condition": {
"type": "translate_y",
"target": "",
"joint": "",
"target_value": 60
}
}
},
{
"size": 15,
"orient": [
1,
0,
0,
0
],
"robot_offset": [
-40,
0,
0
],
"robot_orient": [
0.7071068,
-0.7071068,
0,
0
],
"task_type": "",
"task_id": "",
"robot_id": "",
"mission_id": "",
"goal": {
"description": "Pick up the bottle.",
"condition": {
"type": "translate_y",
"target": "",
"joint": "",
"target_value": 80
}
}
}
],
"reorient_object": [
{
"size": 15,
"orient": [
-0.8733046,
-0.4871745,
0,
0
],
"robot_offset": [
-40,
0,
0
],
"robot_orient": [
0.7071068,
-0.7071068,
0,
0
],
"task_type": "",
"task_id": "",
"robot_id": "",
"mission_id": "",
"goal": {
"description": "Place the bottle properly.",
"condition": {
"type": "orient_y",
"target": "",
"joint": "",
"target_value": 0
}
}
},
{
"size": 15,
"orient": [
-0.8733046,
-0.4871745,
0,
0
],
"robot_offset": [
-40,
0,
0
],
"robot_orient": [
0.7071068,
-0.7071068,
0,
0
],
"task_type": "",
"task_id": "",
"robot_id": "",
"mission_id": "",
"goal": {
"description": "Place the bottle properly.",
"condition": {
"type": "orient_y",
"target": "",
"joint": "",
"target_value": 45
}
}
},
{
"size": 15,
"orient": [
-0.8733046,
-0.4871745,
0,
0
],
"robot_offset": [
-40,
0,
0
],
"robot_orient": [
0.7071068,
-0.7071068,
0,
0
],
"task_type": "",
"task_id": "",
"robot_id": "",
"mission_id": "",
"goal": {
"description": "Place the bottle properly.",
"condition": {
"type": "orient_y",
"target": "",
"joint": "",
"target_value": 135
}
}
},
{
"size": 15,
"orient": [
-0.8733046,
-0.4871745,
0,
0
],
"robot_offset": [
-40,
0,
0
],
"robot_orient": [
0.7071068,
-0.7071068,
0,
0
],
"task_type": "",
"task_id": "",
"robot_id": "",
"mission_id": "",
"goal": {
"description": "Place the bottle properly.",
"condition": {
"type": "orient_y",
"target": "",
"joint": "",
"target_value": 180
}
}
}
],
"put_object_into_box": [
{
"size": 0.5,
"orient": [
0.5,
-0.5,
-0.5,
-0.5
],
"robot_offset": [
-40,
0,
0
],
"robot_orient": [
0.7071068,
-0.7071068,
0,
0
],
"task_type": "",
"task_id": "",
"robot_id": "",
"mission_id": "",
"goal": {
"description": "Place the object into the box.",
"condition": {
"type": "contain",
"target": "",
"container": "",
"joint": "",
"target_value": -1
}
}
}
],
"take_object_out_box": [
{
"size": 0.5,
"orient": [
0.5,
-0.5,
-0.5,
-0.5
],
"robot_offset": [
-20,
0,
0
],
"robot_orient": [
0.7071068,
-0.7071068,
0,
0
],
"task_type": "",
"task_id": "",
"robot_id": "",
"mission_id": "",
"goal": {
"description": "Take the object out of the box.",
"condition": {
"type": "contain",
"target": "",
"container": "",
"joint": "",
"target_value": 1
}
}
}
],
"open_door": [
{
"size": 0,
"orient": [
0,
0,
0.7071068,
0.7071068
],
"robot_offset": [
70,
0,
0
],
"robot_orient": [
0,
0,
0.7071068,
0.7071068
],
"task_type": "",
"task_id": "",
"robot_id": "",
"mission_id": "",
"goal": {
"description": "Open the door",
"condition": {
"init_value": 0,
"type": "rotation",
"target": "",
"joint": "",
"target_value": 0.25
}
}
},
{
"size": 0,
"orient": [
0,
0,
0.7071068,
0.7071068
],
"robot_offset": [
70,
0,
0
],
"robot_orient": [
0,
0,
0.7071068,
0.7071068
],
"task_type": "",
"task_id": "",
"robot_id": "",
"mission_id": "",
"goal": {
"description": "Open the door",
"condition": {
"init_value": 0,
"type": "rotation",
"target": "",
"joint": "",
"target_value": 0.5
}
}
},
{
"size": 0,
"orient": [
0,
0,
0.7071068,
0.7071068
],
"robot_offset": [
70,
0,
0
],
"robot_orient": [
0,
0,
0.7071068,
0.7071068
],
"task_type": "",
"task_id": "",
"robot_id": "",
"mission_id": "",
"goal": {
"description": "Open the door",
"condition": {
"init_value": 0,
"type": "rotation",
"target": "",
"joint": "",
"target_value": 0.75
}
}
},
{
"size": 0,
"orient": [
0,
0,
0.7071068,
0.7071068
],
"robot_offset": [
70,
0,
0
],
"robot_orient": [
0,
0,
0.7071068,
0.7071068
],
"task_type": "",
"task_id": "",
"robot_id": "",
"mission_id": "",
"goal": {
"description": "Open the door",
"condition": {
"init_value": 0,
"type": "rotation",
"target": "",
"joint": "",
"target_value": 1
}
}
},
{
"size": 0,
"orient": [
0,
0,
0.7071068,
0.7071068
],
"robot_offset": [
70,
0,
0
],
"robot_orient": [
0,
0,
0.7071068,
0.7071068
],
"task_type": "",
"task_id": "",
"robot_id": "",
"mission_id": "",
"goal": {
"description": "Open the door",
"condition": {
"init_value": 0.25,
"type": "rotation",
"target": "",
"joint": "",
"target_value": 0.5
}
}
},
{
"size": 0,
"orient": [
0,
0,
0.7071068,
0.7071068
],
"robot_offset": [
70,
0,
0
],
"robot_orient": [
0,
0,
0.7071068,
0.7071068
],
"task_type": "",
"task_id": "",
"robot_id": "",
"mission_id": "",
"goal": {
"description": "Open the door",
"condition": {
"init_value": 0.25,
"type": "rotation",
"target": "",
"joint": "",
"target_value": 0.75
}
}
},
{
"size": 0,
"orient": [
0,
0,
0.7071068,
0.7071068
],
"robot_offset": [
70,
0,
0
],
"robot_orient": [
0,
0,
0.7071068,
0.7071068
],
"task_type": "",
"task_id": "",
"robot_id": "",
"mission_id": "",
"goal": {
"description": "Open the door",
"condition": {
"init_value": 0.25,
"type": "rotation",
"target": "",
"joint": "",
"target_value": 1
}
}
},
{
"size": 0,
"orient": [
0,
0,
0.7071068,
0.7071068
],
"robot_offset": [
70,
0,
0
],
"robot_orient": [
0,
0,
0.7071068,
0.7071068
],
"task_type": "",
"task_id": "",
"robot_id": "",
"mission_id": "",
"goal": {
"description": "Open the door",
"condition": {
"init_value": 0.5,
"type": "rotation",
"target": "",
"joint": "",
"target_value": 0.75
}
}
},
{
"size": 0,
"orient": [
0,
0,
0.7071068,
0.7071068
],
"robot_offset": [
70,
0,
0
],
"robot_orient": [
0,
0,
0.7071068,
0.7071068
],
"task_type": "",
"task_id": "",
"robot_id": "",
"mission_id": "",
"goal": {
"description": "Open the door",
"condition": {
"init_value": 0.5,
"type": "rotation",
"target": "",
"joint": "",
"target_value": 1
}
}
},
{
"size": 0,
"orient": [
0,
0,
0.7071068,
0.7071068
],
"robot_offset": [
70,
0,
0
],
"robot_orient": [
0,
0,
0.7071068,
0.7071068
],
"task_type": "",
"task_id": "",
"robot_id": "",
"mission_id": "",
"goal": {
"description": "Open the door",
"condition": {
"init_value": 0.75,
"type": "rotation",
"target": "",
"joint": "",
"target_value": 1
}
}
}
],
"close_door": [
{
"size": 0,
"orient": [
0,
0,
0.7071068,
0.7071068
],
"robot_offset": [
70,
0,
0
],
"robot_orient": [
0,
0,
0.7071068,
0.7071068
],
"task_type": "",
"task_id": "",
"robot_id": "",
"mission_id": "",
"goal": {
"description": "close the door",
"condition": {
"init_value": 0.25,
"type": "rotation",
"target": "",
"joint": "",
"target_value": 0
}
}
},
{
"size": 0,
"orient": [
0,
0,
0.7071068,
0.7071068
],
"robot_offset": [
70,
0,
0
],
"robot_orient": [
0,
0,
0.7071068,
0.7071068
],
"task_type": "",
"task_id": "",
"robot_id": "",
"mission_id": "",
"goal": {
"description": "close the door",
"condition": {
"init_value": 0.5,
"type": "rotation",
"target": "",
"joint": "",
"target_value": 0
}
}
},
{
"size": 0,
"orient": [
0,
0,
0.7071068,
0.7071068
],
"robot_offset": [
70,
0,
0
],
"robot_orient": [
0,
0,
0.7071068,
0.7071068
],
"task_type": "",
"task_id": "",
"robot_id": "",
"mission_id": "",
"goal": {
"description": "close the door",
"condition": {
"init_value": 0.75,
"type": "rotation",
"target": "",
"joint": "",
"target_value": 0
}
}
},
{
"size": 0,
"orient": [
0,
0,
0.7071068,
0.7071068
],
"robot_offset": [
70,
0,
0
],
"robot_orient": [
0,
0,
0.7071068,
0.7071068
],
"task_type": "",
"task_id": "",
"robot_id": "",
"mission_id": "",
"goal": {
"description": "close the door",
"condition": {
"init_value": 1,
"type": "rotation",
"target": "",
"joint": "",
"target_value": 0
}
}
},
{
"size": 0,
"orient": [
0,
0,
0.7071068,
0.7071068
],
"robot_offset": [
70,
0,
0
],
"robot_orient": [
0,
0,
0.7071068,
0.7071068
],
"task_type": "",
"task_id": "",
"robot_id": "",
"mission_id": "",
"goal": {
"description": "close the door",
"condition": {
"init_value": 0.5,
"type": "rotation",
"target": "",
"joint": "",
"target_value": 0.25
}
}
},
{
"size": 0,
"orient": [
0,
0,
0.7071068,
0.7071068
],
"robot_offset": [
70,
0,
0
],
"robot_orient": [
0,
0,
0.7071068,
0.7071068
],
"task_type": "",
"task_id": "",
"robot_id": "",
"mission_id": "",
"goal": {
"description": "close the door",
"condition": {
"init_value": 0.75,
"type": "rotation",
"target": "",
"joint": "",
"target_value": 0.25
}
}
},
{
"size": 0,
"orient": [
0,
0,
0.7071068,
0.7071068
],
"robot_offset": [
70,
0,
0
],
"robot_orient": [
0,
0,
0.7071068,
0.7071068
],
"task_type": "",
"task_id": "",
"robot_id": "",
"mission_id": "",
"goal": {
"description": "close the door",
"condition": {
"init_value": 1,
"type": "rotation",
"target": "",
"joint": "",
"target_value": 0.25
}
}
},
{
"size": 0,
"orient": [
0,
0,
0.7071068,
0.7071068
],
"robot_offset": [
70,
0,
0
],
"robot_orient": [
0,
0,
0.7071068,
0.7071068
],
"task_type": "",
"task_id": "",
"robot_id": "",
"mission_id": "",
"goal": {
"description": "close the door",
"condition": {
"init_value": 0.75,
"type": "rotation",
"target": "",
"joint": "",
"target_value": 0.5
}
}
},
{
"size": 0,
"orient": [
0,
0,
0.7071068,
0.7071068
],
"robot_offset": [
70,
0,
0
],
"robot_orient": [
0,
0,
0.7071068,
0.7071068
],
"task_type": "",
"task_id": "",
"robot_id": "",
"mission_id": "",
"goal": {
"description": "close the door",
"condition": {
"init_value": 1,
"type": "rotation",
"target": "",
"joint": "",
"target_value": 0.5
}
}
},
{
"size": 0,
"orient": [
0,
0,
0.7071068,
0.7071068
],
"robot_offset": [
70,
0,
0
],
"robot_orient": [
0,
0,
0.7071068,
0.7071068
],
"task_type": "",
"task_id": "",
"robot_id": "",
"mission_id": "",
"goal": {
"description": "close the door",
"condition": {
"init_value": 1,
"type": "rotation",
"target": "",
"joint": "",
"target_value": 0.75
}
}
}
],
"pour_water": [
{
"size": 1.0,
"orient": [
1,
0,
0,
0
],
"robot_offset": [
-40,
0,
0
],
"robot_orient": [
0.7071068,
-0.7071068,
0,
0
],
"task_type": "",
"task_id": "",
"robot_id": "",
"mission_id": "",
"goal": {
"description": "Pour the liquid out of the contrainer.",
"condition": {
"init_value": 1,
"type": "liquid",
"target": "",
"joint": "",
"target_value": 0.75
}
}
},
{
"size": 1.0,
"orient": [
1,
0,
0,
0
],
"robot_offset": [
-40,
0,
0
],
"robot_orient": [
0.7071068,
-0.7071068,
0,
0
],
"task_type": "",
"task_id": "",
"robot_id": "",
"mission_id": "",
"goal": {
"description": "Pour the liquid out of the contrainer.",
"condition": {
"init_value": 1,
"type": "liquid",
"target": "",
"joint": "",
"target_value": 0.5
}
}
},
{
"size": 1.0,
"orient": [
1,
0,
0,
0
],
"robot_offset": [
-40,
0,
0
],
"robot_orient": [
0.7071068,
-0.7071068,
0,
0
],
"task_type": "",
"task_id": "",
"robot_id": "",
"mission_id": "",
"goal": {
"description": "Pour the liquid out of the contrainer.",
"condition": {
"init_value": 1,
"type": "liquid",
"target": "",
"joint": "",
"target_value": 0.25
}
}
},
{
"size": 1.0,
"orient": [
1,
0,
0,
0
],
"robot_offset": [
-40,
0,
0
],
"robot_orient": [
0.7071068,
-0.7071068,
0,
0
],
"task_type": "",
"task_id": "",
"robot_id": "",
"mission_id": "",
"goal": {
"description": "Pour the liquid out of the contrainer.",
"condition": {
"init_value": 1,
"type": "liquid",
"target": "",
"joint": "",
"target_value": 0.0
}
}
}
],
"close_drawer": [
{
"size": 0,
"orient": [
0,
0,
0.7071068,
0.7071068
],
"robot_offset": [
-70,
0,
0
],
"robot_orient": [
0.7071068,
-0.7071068,
0,
0
],
"task_type": "",
"task_id": "",
"robot_id": "",
"mission_id": "",
"goal": {
"description": "close the drawer",
"condition": {
"init_value": 0.25,
"type": "linear",
"target": "",
"joint": "",
"target_value": 0
}
}
},
{
"size": 0,
"orient": [
0,
0,
0.7071068,
0.7071068
],
"robot_offset": [
-70,
0,
0
],
"robot_orient": [
0.7071068,
-0.7071068,
0,
0
],
"task_type": "",
"task_id": "",
"robot_id": "",
"mission_id": "",
"goal": {
"description": "close the drawer",
"condition": {
"init_value": 0.5,
"type": "linear",
"target": "",
"joint": "",
"target_value": 0
}
}
},
{
"size": 0,
"orient": [
0,
0,
0.7071068,
0.7071068
],
"robot_offset": [
-70,
0,
0
],
"robot_orient": [
0.7071068,
-0.7071068,
0,
0
],
"task_type": "",
"task_id": "",
"robot_id": "",
"mission_id": "",
"goal": {
"description": "close the drawer",
"condition": {
"init_value": 0.75,
"type": "linear",
"target": "",
"joint": "",
"target_value": 0
}
}
},
{
"size": 0,
"orient": [
0,
0,
0.7071068,
0.7071068
],
"robot_offset": [
-70,
0,
0
],
"robot_orient": [
0.7071068,
-0.7071068,
0,
0
],
"task_type": "",
"task_id": "",
"robot_id": "",
"mission_id": "",
"goal": {
"description": "close the drawer",
"condition": {
"init_value": 1,
"type": "linear",
"target": "",
"joint": "",
"target_value": 0
}
}
},
{
"size": 0,
"orient": [
0,
0,
0.7071068,
0.7071068
],
"robot_offset": [
-70,
0,
0
],
"robot_orient": [
0.7071068,
-0.7071068,
0,
0
],
"task_type": "",
"task_id": "",
"robot_id": "",
"mission_id": "",
"goal": {
"description": "close the drawer",
"condition": {
"init_value": 0.5,
"type": "linear",
"target": "",
"joint": "",
"target_value": 0.25
}
}
},
{
"size": 0,
"orient": [
0,
0,
0.7071068,
0.7071068
],
"robot_offset": [
-70,
0,
0
],
"robot_orient": [
0.7071068,
-0.7071068,
0,
0
],
"task_type": "",
"task_id": "",
"robot_id": "",
"mission_id": "",
"goal": {
"description": "close the drawer",
"condition": {
"init_value": 0.75,
"type": "linear",
"target": "",
"joint": "",
"target_value": 0.25
}
}
},
{
"size": 0,
"orient": [
0,
0,
0.7071068,
0.7071068
],
"robot_offset": [
-70,
0,
0
],
"robot_orient": [
0.7071068,
-0.7071068,
0,
0
],
"task_type": "",
"task_id": "",
"robot_id": "",
"mission_id": "",
"goal": {
"description": "close the drawer",
"condition": {
"init_value": 1,
"type": "linear",
"target": "",
"joint": "",
"target_value": 0.25
}
}
},
{
"size": 0,
"orient": [
0,
0,
0.7071068,
0.7071068
],
"robot_offset": [
-70,
0,
0
],
"robot_orient": [
0.7071068,
-0.7071068,
0,
0
],
"task_type": "",
"task_id": "",
"robot_id": "",
"mission_id": "",
"goal": {
"description": "close the drawer",
"condition": {
"init_value": 0.75,
"type": "linear",
"target": "",
"joint": "",
"target_value": 0.5
}
}
},
{
"size": 0,
"orient": [
0,
0,
0.7071068,
0.7071068
],
"robot_offset": [
-70,
0,
0
],
"robot_orient": [
0.7071068,
-0.7071068,
0,
0
],
"task_type": "",
"task_id": "",
"robot_id": "",
"mission_id": "",
"goal": {
"description": "close the drawer",
"condition": {
"init_value": 1,
"type": "linear",
"target": "",
"joint": "",
"target_value": 0.5
}
}
},
{
"size": 0,
"orient": [
0,
0,
0.7071068,
0.7071068
],
"robot_offset": [
-70,
0,
0
],
"robot_orient": [
0.7071068,
-0.7071068,
0,
0
],
"task_type": "",
"task_id": "",
"robot_id": "",
"mission_id": "",
"goal": {
"description": "close the drawer",
"condition": {
"init_value": 1,
"type": "linear",
"target": "",
"joint": "",
"target_value": 0.75
}
}
}
],
"close_cabinet": [
{
"size": 70,
"orient": [
0,
0,
0.7071068,
0.7071068
],
"robot_offset": [
-870,
0,
0
],
"robot_orient": [
0.7071068,
-0.7071068,
0,
0
],
"task_type": "",
"task_id": "",
"robot_id": "",
"mission_id": "",
"goal": {
"description": "Close the cabinet",
"condition": {
"init_value": 0.25,
"type": "rotation",
"target": "",
"joint": "",
"target_value": 0
}
}
},
{
"size": 70,
"orient": [
0,
0,
0.7071068,
0.7071068
],
"robot_offset": [
-870,
0,
0
],
"robot_orient": [
0.7071068,
-0.7071068,
0,
0
],
"task_type": "",
"task_id": "",
"robot_id": "",
"mission_id": "",
"goal": {
"description": "Close the cabinet",
"condition": {
"init_value": 0.5,
"type": "rotation",
"target": "",
"joint": "",
"target_value": 0
}
}
},
{
"size": 70,
"orient": [
0,
0,
0.7071068,
0.7071068
],
"robot_offset": [
-870,
0,
0
],
"robot_orient": [
0.7071068,
-0.7071068,
0,
0
],
"task_type": "",
"task_id": "",
"robot_id": "",
"mission_id": "",
"goal": {
"description": "Close the cabinet",
"condition": {
"init_value": 0.75,
"type": "rotation",
"target": "",
"joint": "",
"target_value": 0
}
}
},
{
"size": 70,
"orient": [
0,
0,
0.7071068,
0.7071068
],
"robot_offset": [
-870,
0,
0
],
"robot_orient": [
0.7071068,
-0.7071068,
0,
0
],
"task_type": "",
"task_id": "",
"robot_id": "",
"mission_id": "",
"goal": {
"description": "Close the cabinet",
"condition": {
"init_value": 1,
"type": "rotation",
"target": "",
"joint": "",
"target_value": 0
}
}
},
{
"size": 70,
"orient": [
0,
0,
0.7071068,
0.7071068
],
"robot_offset": [
-870,
0,
0
],
"robot_orient": [
0.7071068,
-0.7071068,
0,
0
],
"task_type": "",
"task_id": "",
"robot_id": "",
"mission_id": "",
"goal": {
"description": "Close the cabinet",
"condition": {
"init_value": 0.5,
"type": "rotation",
"target": "",
"joint": "",
"target_value": 0.25
}
}
},
{
"size": 70,
"orient": [
0,
0,
0.7071068,
0.7071068
],
"robot_offset": [
-870,
0,
0
],
"robot_orient": [
0.7071068,
-0.7071068,
0,
0
],
"task_type": "",
"task_id": "",
"robot_id": "",
"mission_id": "",
"goal": {
"description": "Close the cabinet",
"condition": {
"init_value": 0.75,
"type": "rotation",
"target": "",
"joint": "",
"target_value": 0.25
}
}
},
{
"size": 70,
"orient": [
0,
0,
0.7071068,
0.7071068
],
"robot_offset": [
-870,
0,
0
],
"robot_orient": [
0.7071068,
-0.7071068,
0,
0
],
"task_type": "",
"task_id": "",
"robot_id": "",
"mission_id": "",
"goal": {
"description": "Close the cabinet",
"condition": {
"init_value": 1,
"type": "rotation",
"target": "",
"joint": "",
"target_value": 0.25
}
}
},
{
"size": 70,
"orient": [
0,
0,
0.7071068,
0.7071068
],
"robot_offset": [
-870,
0,
0
],
"robot_orient": [
0.7071068,
-0.7071068,
0,
0
],
"task_type": "",
"task_id": "",
"robot_id": "",
"mission_id": "",
"goal": {
"description": "Close the cabinet",
"condition": {
"init_value": 0.75,
"type": "rotation",
"target": "",
"joint": "",
"target_value": 0.5
}
}
},
{
"size": 70,
"orient": [
0,
0,
0.7071068,
0.7071068
],
"robot_offset": [
-870,
0,
0
],
"robot_orient": [
0.7071068,
-0.7071068,
0,
0
],
"task_type": "",
"task_id": "",
"robot_id": "",
"mission_id": "",
"goal": {
"description": "Close the cabinet",
"condition": {
"init_value": 1,
"type": "rotation",
"target": "",
"joint": "",
"target_value": 0.5
}
}
},
{
"size": 70,
"orient": [
0,
0,
0.7071068,
0.7071068
],
"robot_offset": [
-870,
0,
0
],
"robot_orient": [
0.7071068,
-0.7071068,
0,
0
],
"task_type": "",
"task_id": "",
"robot_id": "",
"mission_id": "",
"goal": {
"description": "Close the cabinet",
"condition": {
"init_value": 1,
"type": "rotation",
"target": "",
"joint": "",
"target_value": 0.75
}
}
}
],
"transfer_water": [
{
"size": 1.0,
"orient": [
1,
0,
0,
0
],
"robot_offset": [
-40,
0,
0
],
"robot_orient": [
0.7071068,
-0.7071068,
0,
0
],
"task_type": "",
"task_id": "",
"robot_id": "",
"mission_id": "",
"goal": {
"description": "Pour the liquid into another contrainer.",
"condition": {
"init_value": -1,
"type": "liquid",
"target": "",
"joint": "",
"target_value": 0.25
}
}
},
{
"size": 1.0,
"orient": [
1,
0,
0,
0
],
"robot_offset": [
-40,
0,
0
],
"robot_orient": [
0.7071068,
-0.7071068,
0,
0
],
"task_type": "",
"task_id": "",
"robot_id": "",
"mission_id": "",
"goal": {
"description": "Pour the liquid into another contrainer.",
"condition": {
"init_value": -1,
"type": "liquid",
"target": "",
"joint": "",
"target_value": 0.5
}
}
},
{
"size": 1.0,
"orient": [
1,
0,
0,
0
],
"robot_offset": [
-40,
0,
0
],
"robot_orient": [
0.7071068,
-0.7071068,
0,
0
],
"task_type": "",
"task_id": "",
"robot_id": "",
"mission_id": "",
"goal": {
"description": "Pour the liquid into another contrainer.",
"condition": {
"init_value": -1,
"type": "liquid",
"target": "",
"joint": "",
"target_value": 0.75
}
}
},
{
"size": 1.0,
"orient": [
1,
0,
0,
0
],
"robot_offset": [
-40,
0,
0
],
"robot_orient": [
0.7071068,
-0.7071068,
0,
0
],
"task_type": "",
"task_id": "",
"robot_id": "",
"mission_id": "",
"goal": {
"description": "Pour the liquid into another contrainer.",
"condition": {
"init_value": -1,
"type": "liquid",
"target": "",
"joint": "",
"target_value": 1
}
}
}
],
"tap_water": [
{
"size": 20,
"orient": [
0.7071068,
-0.7071068,
0,
0
],
"robot_offset": [
-40,
0,
0
],
"robot_orient": [
0.7071068,
-0.7071068,
0,
0
],
"task_type": "",
"task_id": "",
"robot_id": "",
"mission_id": "",
"goal": {
"description": "Get tap water.",
"condition": {
"init_value": 0,
"type": "liquid",
"target": "",
"joint": "",
"target_value": 0.25
}
}
},
{
"size": 20,
"orient": [
0.7071068,
-0.7071068,
0,
0
],
"robot_offset": [
-40,
0,
0
],
"robot_orient": [
0.7071068,
-0.7071068,
0,
0
],
"task_type": "",
"task_id": "",
"robot_id": "",
"mission_id": "",
"goal": {
"description": "Get tap water.",
"condition": {
"init_value": 0,
"type": "liquid",
"target": "",
"joint": "",
"target_value": 0.5
}
}
},
{
"size": 20,
"orient": [
0.7071068,
-0.7071068,
0,
0
],
"robot_offset": [
-40,
0,
0
],
"robot_orient": [
0.7071068,
-0.7071068,
0,
0
],
"task_type": "",
"task_id": "",
"robot_id": "",
"mission_id": "",
"goal": {
"description": "Get tap water.",
"condition": {
"init_value": 0,
"type": "liquid",
"target": "",
"joint": "",
"target_value": 0.75
}
}
},
{
"size": 20,
"orient": [
0.7071068,
-0.7071068,
0,
0
],
"robot_offset": [
-40,
0,
0
],
"robot_orient": [
0.7071068,
-0.7071068,
0,
0
],
"task_type": "",
"task_id": "",
"robot_id": "",
"mission_id": "",
"goal": {
"description": "Get tap water.",
"condition": {
"init_value": 0,
"type": "liquid",
"target": "",
"joint": "",
"target_value": 1
}
}
}
]
} |
yizhouzhao/VRKitchen2.0-IndoorKit/exts/vrkitchen.indoor.kit/vrkitchen/indoor/kit/autotask/auto_label.py | import omni
import numpy as np
try:
import pandas as pd
except:
omni.kit.pipapi.install("pandas")
import pandas as pd
GOODLE_SHEET_INFO = {
"close_cabinet": "187VN5J70tEH6ByemAs60FRA2uxE5UmtMr2rBZ0DCOAs",
"close_door": "1Lm-nqYdeUfjGZc2WyqJCG5JcI1z5zDhfeoxZiUX7VKE",
"close_drawer": "1OMmuQNKcvbc-CQm67CQbQSmiQGRMVXtNYYXgTsNg9NE",
"open_cabinet": "1SWXaK5v701wMklIMu4MTgh8Wes5WS9bd_YTrH9-DPdw",
"open_drawer": "1DHYxbRRs0i11rEmDKJ7XK4H0UTTct2QpPTpIPkHnImU",
"pickup_object": "1mq7qCTsJWKnr1-MWA7kzOehZM6fw-o8iHpqKAS6PM44",
"pour_water": "1mS1HUljpu2tZCfiHNvHc2FfrsvGFzwyXRm6pqj3uzZU",
"reorient_object": "1VyoSXjUxp5ef2RPGRxovIv3SA5rr-gm66sjABegqcwM",
"transfer_water": "1fKLFHfF3LsYIWlheqQwGHIf6Bpn05BnT-AQheANyO6o",
"tap_water": "1kgXT6baclDuvyCe4ijJgrR1xTDbkZggxP7d5gQpWR8w",
"open_door": "1fKp1vzDMeoR0lPspqtVZTaHdNhCyXdJ6SN2EnIjQ6CA",
}
# for key in GOODLE_SHEET_INFO:
# sheet_id = GOODLE_SHEET_INFO[key]
# test = pd.read_csv(f"https://docs.google.com/spreadsheets/d/{sheet_id}/export?format=csv")
# print(test.head())
class AutoLabeler():
def __init__(self, task_type) -> None:
# load task
self.task_type = task_type
self.cache = {}
# for task_type_cache in GOODLE_SHEET_INFO.keys():
# cache_id = GOODLE_SHEET_INFO[task_type_cache]
# try:
# self.cache[task_type_cache] = pd.read_csv(f"https://docs.google.com/spreadsheets/d/{cache_id}/export?format=csv")
# except:
# print("service not available: ", task_type_cache)
# load data
if self.task_type:
sheet_id = GOODLE_SHEET_INFO[self.task_type]
self.data = pd.read_csv(f"https://docs.google.com/spreadsheets/d/{sheet_id}/export?format=csv")
self.cache[task_type] = self.data
# load id
self.current_id = -1
def set_task_type(self, task_type):
if task_type not in self.cache:
cache_id = GOODLE_SHEET_INFO[task_type]
try:
self.cache[task_type] = pd.read_csv(f"https://docs.google.com/spreadsheets/d/{cache_id}/export?format=csv")
except:
print("service not available: ", task_type)
self.data = self.cache[task_type]
def set_id(self, id):
"""
set current id
"""
self.current_id = id
def find_row_num(self, task_id, robot_id, mission_id, house_id, trial_id):
cond = np.where( (self.data['task_id'] == int(task_id)) & (self.data['robot_id'] == int(robot_id)) &
(self.data['mission_id'] == int(mission_id)) & (self.data['house_id'] == int(house_id)) & (self.data['trial_id'] == int(trial_id))
)
try:
return int(cond[0])+2
except:
return -1
def load_row(self):
"""
Load task information from row_id
"""
assert self.current_id >= 0
if self.current_id >= len(self.data):
raise Exception(f"Note: current labeling is done {self.task_type}: {self.current_id} / {len(self.data)}")
id = self.current_id
task_id = self.data["task_id"][id]
robot_id = self.data["robot_id"][id]
mission_id = self.data["mission_id"][id]
house_id = self.data["house_id"][id]
trial_id = self.data["trial_id"][id]
return int(task_id), int(robot_id), int(mission_id), int(house_id), int(trial_id)
def next(self):
"""
find next id
"""
if self.current_id >= 0:
self.current_id += 1
else:
"""
find current labeling index
"""
for i in range(len(self.data)):
if pd.isnull(self.data['progress'][i]):
self.current_id = i
return
|
yizhouzhao/VRKitchen2.0-IndoorKit/exts/vrkitchen.indoor.kit/vrkitchen/indoor/kit/layout/house.py | import os
import json
import omni
import pxr
import carb
# phyxc
from omni.physx.scripts.utils import setCollider, setRigidBody, setStaticCollider, set_physics_scene_asyncsimrender
from ..param import SAPIEN_ASSET_PATH, HOUSE_INFO_PATH, DATA_PATH_ROOT, RIGIDBODY_OBJ_TYPES, GAME_OBJ_NAMES
from .utils import rename_prim, rotationXYZ_to_quaternion
# from omni.isaac.core.utils.stage import (
# get_current_stage,
# )
from pxr import UsdGeom, UsdLux, Gf, Vt, UsdPhysics, PhysxSchema, Usd, UsdShade, Sdf
class House():
def __init__(self,
data_path:str = DATA_PATH_ROOT,
sapien_asset_path:str = SAPIEN_ASSET_PATH,
house_info_path:str = HOUSE_INFO_PATH):
self.data_path = data_path
self.sapien_asset_path = sapien_asset_path
self.house_info_path = house_info_path
self.layout = {
"id":0,
"params":{
# "SCENE_ASSET_PATH":self.data_path,
"SAPIEN_ASSET_PATH":self.sapien_asset_path,
"HOUSE_INFO_PATH":self.house_info_path,
},
"asset":{
"room_name":"",
"sapien":[],
},
"layout_offsets":[]
}
def set_id(self, example_id):
"""
Set up example id
"""
self.example_id = example_id
self.layout["id"] = example_id
def set_task(self, task_type, task_id = None):
"""
Set up task type
"""
self.layout["task"] = task_type
def get_furniture_info(self):
"""
Get furniture information especially for collision from current scene
"""
self.stage = omni.usd.get_context().get_stage()
# furniture parent
furni_parent = self.stage.GetPrimAtPath("/World/layout/furniture")
additional_collisions = []
for prim in furni_parent.GetChildren():
if prim.HasAPI(pxr.UsdPhysics.RigidBodyAPI) or prim.HasAPI(pxr.UsdPhysics.CollisionAPI):
# prim.GetAttribute("physics:rigidBodyEnabled").Set(False)
print("collision prim name", prim.GetPath(), prim.GetAttribute("physics:rigidBodyEnabled").Get())
# robot_prim.GetAttribute("xformOp:orient").Get()
additional_collisions.append(prim.GetPath().pathString)
self.layout["asset"]["furniture_collisions"] = additional_collisions
def get_robot_info(self, robot_prim_path = "/World/game/franka"):
"""
Get robot information at robot_prim_path
"""
self.stage = omni.usd.get_context().get_stage()
robot_prim = self.stage.GetPrimAtPath(robot_prim_path)
if not robot_prim or not pxr.UsdGeom.Xform.Get(self.stage, robot_prim_path):
raise Exception(f"Must have a robot with XForm at path {robot_prim_path}")
quad = robot_prim.GetAttribute("xformOp:orient").Get()
if not quad:
rotateXYZ = robot_prim.GetAttribute("xformOp:rotateXYZ").Get()
quad = rotationXYZ_to_quaternion(rotateXYZ)
translate = robot_prim.GetAttribute("xformOp:translate").Get()
scale = robot_prim.GetAttribute("xformOp:scale").Get()
quad = eval(str(quad))
# print(quad)
robot_info = {
"position": [round(translate[0], 3), round(translate[1],3), round(translate[2], 3)],
"rotation": [round(quad[0], 3), round(quad[1], 3), round(quad[2], 3), round(quad[3], 3)],
}
return robot_info
def add_asset_info(self):
"""
Add other asset infomation
"""
# move to randomizer
pass
def get_asset_info(self, append = False):
"""
Get mobility, and furniture information from current scene
:param::
append: append room information if True else delete json
"""
self.stage = omni.usd.get_context().get_stage()
room_layout_json = os.path.join(self.data_path, "house", str(self.example_id) + ".json")
# if layout json already exists, record game/parent offset as obj randomization
if os.path.exists(room_layout_json):
carb.log_warn(f"room info already exists at {room_layout_json}")
# append other information into json
if append:
self.layout = json.load(open(room_layout_json))
self.add_asset_info()
return
else:
# delete json and start another
os.remove(room_layout_json)
# Get room name
room_path = self.stage.GetRootLayer().realPath
# print("room_path: ", room_path)
if room_path:
relative_path = omni.client.make_relative_url(self.house_info_path, room_path)
print("room_name: ", relative_path)
self.layout["asset"]["room_name"] = relative_path
else:
self.layer = self.stage.GetRootLayer()
# print("layer: ", )
for ref in self.layer.GetExternalReferences():
if "layout" in str(ref):
#PathUtils.compute_relative_path(self.house_info_path,str(ref))
relative_path = omni.client.make_relative_url(self.house_info_path, str(ref))
relative_path.replace("\\\\", "/")
self.layout["asset"]["room_name"] = relative_path
break
# Get sapien asset name
prims = [self.stage.GetDefaultPrim()]
game_prim = self.stage.GetPrimAtPath("/World/game")
if game_prim:
prims.append(game_prim)
for game_prim in prims:
for prim in game_prim.GetChildren():
# if prim is game obj, record information
is_game_obj = False
for game_name in GAME_OBJ_NAMES:
if game_name in prim.GetPath().pathString:
is_game_obj = True
break
if is_game_obj:
reference, _ = omni.usd.get_composed_references_from_prim(prim)[0]
print("mobility reference: ", reference.assetPath)
# get obj type from paths
path_splits = reference.assetPath.split("/")
if 'sapien_parsed' in path_splits:
# sapien objs
obj_type = reference.assetPath.split("/")[-3]
obj_id = int(reference.assetPath.split("/")[-2])
assetPath = None
elif 'omniverse:' in path_splits:
# obj from omniverse cloud
assetPath = reference.assetPath
obj_type = path_splits[-2]
obj_id = 0
else:
# custom objs
assetPath = "/".join(path_splits[-3:])
obj_type = path_splits[-3]
obj_id = path_splits[-2]
obj_info = {
"asset_path": assetPath,
"obj_type": obj_type,
"obj_id": obj_id,
}
# for attr in prim.GetAttributes():
# print(attr)
if prim.HasAttribute("xformOp:orient"):
quad = prim.GetAttribute("xformOp:orient").Get()
else:
rotateXYZ = prim.GetAttribute("xformOp:rotateXYZ").Get()
quad = rotationXYZ_to_quaternion(rotateXYZ)
translate = prim.GetAttribute("xformOp:translate").Get()
scale = prim.GetAttribute("xformOp:scale").Get()
quad = eval(str(quad))
# print("quad", quad)
obj_info["xformOp:translate"] = [translate[0], translate[1], translate[2]]
obj_info["xformOp:orient"] = [quad[0], quad[1], quad[2], quad[3]]
obj_info["xformOp:scale"] = [scale[0],scale[1],scale[2]]
self.layout["asset"]["sapien"].append(obj_info)
# print("get mobility info ???")
# get robot information if don't have
# if "robot" not in self.layout:
# if self.stage.GetPrimAtPath("/World/game/franka"):
# # if has robot
# self.get_robot_info()
# get additional furniture collision information if don't have
# if "furniture_collisions" not in self.layout["asset"]:
# self.get_furniture_info()
print("get mobility info", self.layout)
def save_asset_info(self):
"""
Save asset at data_path
"""
print("saveing file at " + str(self.layout["id"]) + ".json")
with open(os.path.join(self.data_path, "house", str(self.layout["id"]) + ".json"), "w") as output_file:
json.dump(self.layout, output_file, sort_keys=True, indent=4)
def _setup_physics_material(self, path):
"""
Set up physic material for prim at Path
"""
# def _setup_physics_material(self, path: Sdf.Path):
from pxr import UsdGeom, UsdLux, Gf, Vt, UsdPhysics, PhysxSchema, Usd, UsdShade, Sdf
from omni.physx.scripts import physicsUtils
stage = omni.usd.get_context().get_stage()
_material_static_friction = 1.0
_material_dynamic_friction = 1.0
_material_restitution = 0.0
_physicsMaterialPath = None
if _physicsMaterialPath is None:
_physicsMaterialPath = stage.GetDefaultPrim().GetPath().AppendChild("physicsMaterial")
UsdShade.Material.Define(stage, _physicsMaterialPath)
material = UsdPhysics.MaterialAPI.Apply(stage.GetPrimAtPath(_physicsMaterialPath))
material.CreateStaticFrictionAttr().Set(_material_static_friction)
material.CreateDynamicFrictionAttr().Set(_material_dynamic_friction)
material.CreateRestitutionAttr().Set(_material_restitution)
collisionAPI = UsdPhysics.CollisionAPI.Get(stage, path)
prim = stage.GetPrimAtPath(path)
if not collisionAPI:
collisionAPI = UsdPhysics.CollisionAPI.Apply(prim)
# apply material
# physicsUtils.add_physics_material_to_prim(stage, prim, _physicsMaterialPath)
def load_asset_info(self, house_id, object_id = None):
"""
load asset from data path
"""
room_layout_json = os.path.join(self.data_path, "house", str(house_id) + ".json")
print("hosue id", str(house_id), "data path: wtf", room_layout_json)
if not os.path.exists(room_layout_json):
raise Exception( "The json file at path {} provided wasn't found".format(room_layout_json) )
# load json
self.layout = json.load(open(room_layout_json))
# get currect stage and layer
self.stage = omni.usd.get_context().get_stage()
self.layer = self.stage.GetRootLayer()
# load house info
house_path = os.path.join(self.house_info_path, self.layout["asset"]["room_name"].replace("\\","/"))
# print('self.layout["asset"]["room_name"]',self.layout["asset"]["room_name"])
print("house_path: ", house_path)
omni.kit.commands.execute(
"CreateSublayer",
layer_identifier=self.layer.identifier,
sublayer_position=0,
new_layer_path=house_path,
transfer_root_content=False,
create_or_insert=False,
layer_name="",
)
# set up furniture root
default_prim_path_str = self.stage.GetDefaultPrim().GetPath().pathString
## this is necessary because for standalone this might not be /World
if not default_prim_path_str:
default_prim_path_str = "/World"
self.xform_game_path = default_prim_path_str + "/game" # omni.usd.get_stage_next_free_path(self.stage, "/World/game", True)
if not self.stage.GetPrimAtPath(self.xform_game_path):
xform_game = pxr.UsdGeom.Xform.Define(self.stage, self.xform_game_path)
xform_game.AddTranslateOp().Set(pxr.Gf.Vec3f(0.0, 0.0, 0.0))
xform_game.AddOrientOp().Set(pxr.Gf.Quatf(1.0, 0.0, 0.0, 0.0))
xform_game.AddScaleOp().Set(pxr.Gf.Vec3f(1.0, 1.0, 1.0))
# # Everything has to have collision
# furni_parent = self.stage.GetPrimAtPath("/World/furniture")
# for prim in furni_parent.GetChildren():
# setCollider(prim, "convexDecomposition")
# floor_prim = self.stage.GetPrimAtPath("/World/floors")
# setCollider(floor_prim, "convexDecomposition")
# add collision infomation
if "furniture_collisions" in self.layout["asset"]:
for furni_path in self.layout["asset"]["furniture_collisions"]:
prim = self.stage.GetPrimAtPath(furni_path)
setCollider(prim, "convexDecomposition")
print("try to set collider: ", furni_path)
setRigidBody(prim, "convexDecomposition", False)
physicsAPI = UsdPhysics.RigidBodyAPI.Apply(prim)
physicsAPI.CreateRigidBodyEnabledAttr(False)
# physicsAPI.CreateDisableGravityAttr(True)
print("set rigid body: ", furni_path)
# load furniture info
for obj in self.layout["asset"]["sapien"]:
# filter object only necessary for currect task
if object_id != None:
if obj['obj_id'] != object_id:
continue
# get asset path
if "asset_path" in obj and obj["asset_path"] is not None:
if "omniverse:" in obj["asset_path"]:
# cloud obj
obj_usd_path = obj["asset_path"]
else:
# custom object
obj_usd_path = os.path.join(self.sapien_asset_path, "../custom", obj["asset_path"])
else:
# sapien object
obj_usd_path = os.path.join(self.sapien_asset_path, obj["obj_type"], str(obj["obj_id"]), "mobility.usd")
print("obj_usd_path", obj_usd_path)
# load data
mobility_prim_path = xform_game.GetPath().pathString + "/mobility"
prim = self.stage.GetPrimAtPath(mobility_prim_path)
if not prim.IsValid():
prim = self.stage.DefinePrim(mobility_prim_path)
success_bool = prim.GetReferences().AddReference(obj_usd_path)
if not success_bool:
raise Exception("The usd file at path {} provided wasn't found".format(obj_usd_path))
# set xform
# obj_xform = pxr.UsdGeom.Xformable.Get(self.stage, prim.GetPath())
# translate_component = obj_xform.GetOrderedXformOps()[0]
# orient_component = obj_xform.GetOrderedXformOps()[1]
# scale_component = obj_xform.GetOrderedXformOps()[2]
translate = obj["xformOp:translate"]
# translate_component.Set(tuple(translate))
orient = eval(obj["xformOp:orient"]) if isinstance(obj["xformOp:orient"], str) else obj["xformOp:orient"]
rotation = pxr.Gf.Quatd(orient[0], orient[1], orient[2], orient[3])
# orient_component.Set(rotation)
scale = obj["xformOp:scale"]
# scale_component.Set(tuple(scale))
xform = pxr.Gf.Matrix4d().SetScale(scale) * pxr.Gf.Matrix4d().SetRotate(rotation) * pxr.Gf.Matrix4d().SetTranslate(translate)
omni.kit.commands.execute(
"TransformPrimCommand",
path=prim.GetPath(),
new_transform_matrix=xform,
)
## or
# xform_geom.AddTranslateOp().Set(position)
# xform_geom.AddOrientOp().Set(orientation)
# xform_geom.AddScaleOp().Set(scale)
# set collision & rigidbody
should_add_rigidbody = False
for collision_type in RIGIDBODY_OBJ_TYPES:
if collision_type in obj["obj_type"]:
should_add_rigidbody = True
break
if should_add_rigidbody:
setRigidBody(prim, "convexDecomposition", False)
# set up physcial materials
# self._setup_physics_material(prim.GetPath())
# rename path
# TODO: set up name rules
old_prim_name = prim.GetPath().pathString
new_prim_path = prim.GetPath().GetParentPath().AppendChild("mobility_" + obj["obj_type"] + "_" + str(obj["obj_id"]))
new_prim_name = omni.usd.get_stage_next_free_path(self.stage, new_prim_path.pathString, False)
carb.log_info("rename:" + old_prim_name + ";" + new_prim_name)
rename_prim(old_prim_name, new_prim_name)
default_prim_path_str = self.stage.GetDefaultPrim().GetPath().pathString
## this is necessary because for standalone this might not be /World
if not default_prim_path_str:
default_prim_path_str = "/World"
#set up physics scene
# from omni.physx.scripts import utils
_gravityMagnitude = 100.0 # IN CM/s2 - use a lower gravity to avoid fluid compression at 60 FPS
_gravityDirection = Gf.Vec3f(0.0, -1.0, 0.0)
_solver = "TGS"
_gpuMaxNumPartitions = 4
physicsScenePath = os.path.join(default_prim_path_str, "physicsScene")
scene = UsdPhysics.Scene.Define(self.stage, physicsScenePath)
scene.CreateGravityDirectionAttr().Set(_gravityDirection)
scene.CreateGravityMagnitudeAttr().Set(_gravityMagnitude)
set_physics_scene_asyncsimrender(scene.GetPrim())
physxAPI = PhysxSchema.PhysxSceneAPI.Apply(scene.GetPrim())
physxAPI.CreateSolverTypeAttr(_solver)
physxAPI.CreateGpuMaxNumPartitionsAttr(_gpuMaxNumPartitions)
def add_distraction_objects(self):
pass
|
yizhouzhao/VRKitchen2.0-IndoorKit/exts/vrkitchen.indoor.kit/vrkitchen/indoor/kit/layout/utils.py | # utility functions
import omni
import pxr
from pxr import Gf, Semantics
import carb
import json
import numpy as np
def add_semantics(prim, semantic_label):
if not prim.HasAPI(Semantics.SemanticsAPI):
sem = Semantics.SemanticsAPI.Apply(prim, "Semantics")
sem.CreateSemanticTypeAttr()
sem.CreateSemanticDataAttr()
sem.GetSemanticTypeAttr().Set("class")
sem.GetSemanticDataAttr().Set(semantic_label)
def rename_prim(old_prim_name, new_prim_name):
# old_prim_name = prim.GetPath().pathString
# new_prim_name = prim.GetPath().GetParentPath()
# new_prim_name = new_prim_name.AppendChild("Door1")
# new_prim_name = omni.usd.get_stage_next_free_path(self.stage, new_prim_name.pathString, False)
# print("new_prim_name: ", new_prim_name)
move_dict = {old_prim_name: new_prim_name}
if pxr.Sdf.Path.IsValidPathString(new_prim_name):
move_dict = {old_prim_name: new_prim_name}
omni.kit.commands.execute("MovePrims", paths_to_move=move_dict, on_move_fn=None)
else:
carb.log_error(f"Cannot rename {old_prim_name} to {new_prim_name} as its not a valid USD path")
def freeze_prim(prim, scale = [1, 1, 1]):
"""
Perform free transform command to current x_form_prim
"""
stage = omni.usd.get_context().get_stage()
omni.kit.undo.begin_group()
prim_name = prim.GetPath().pathString
temp_name = prim_name + "_temp"
rename_prim(prim_name, temp_name)
temp_prim = stage.GetPrimAtPath(temp_name)
# transform to the correct scale
prim_xform = Gf.Matrix4d().SetScale(scale)
omni.kit.commands.execute(
"TransformPrimCommand",
path=temp_name,
new_transform_matrix=prim_xform,
)
# create an unit xform
omni.kit.commands.execute(
"CreatePrim",
prim_path=prim_name,
prim_type="Xform",
select_new_prim=False,
)
move_dict = {}
for prim in temp_prim.GetChildren():
old_prim_name = prim.GetPath().pathString
new_prim_name = old_prim_name.replace("_temp", "")
move_dict[old_prim_name] = new_prim_name
omni.kit.commands.execute("MovePrims", paths_to_move=move_dict, keep_world_transform = True, on_move_fn=None)
# print(0/0)
omni.kit.commands.execute("DeletePrims", paths=[temp_prim.GetPath()])
# return new root prim
return stage.GetPrimAtPath(prim_name)
def rotationXYZ_to_quaternion(rotationXYZ):
translate = Gf.Vec3d(0, 0, 0)
euler = rotationXYZ
scale = Gf.Vec3d(1, 1, 1)
rotation = (
Gf.Rotation(Gf.Vec3d.ZAxis(), euler[2])
* Gf.Rotation(Gf.Vec3d.YAxis(), euler[1])
* Gf.Rotation(Gf.Vec3d.XAxis(), euler[0])
)
xform = Gf.Matrix4d().SetScale(scale) * Gf.Matrix4d().SetRotate(rotation) * Gf.Matrix4d().SetTranslate(translate)
return xform.ExtractRotationQuat()
class NpEncoder(json.JSONEncoder):
def default(self, obj):
if isinstance(obj, np.integer):
return int(obj)
if isinstance(obj, np.floating):
# 👇️ alternatively use str()
return float(obj)
if isinstance(obj, np.ndarray):
return obj.tolist()
return json.JSONEncoder.default(self, obj) |
yizhouzhao/VRKitchen2.0-IndoorKit/exts/vrkitchen.indoor.kit/vrkitchen/indoor/kit/layout/randomizer.py | import omni
import pxr
from pxr import Gf
import carb
import os
import random
import json
from omni.kit.material.library import get_material_prim_path, create_mdl_material
from ..param import IS_IN_ISAAC_SIM, SAPIEN_ASSET_PATH, HOUSE_INFO_PATH, DATA_PATH_ROOT
class Randomizer():
def __init__(self, task_json_path=None, random_seed = 1) -> None:
# self.house = house
# self.layout = self.house.layout if house is not None else {}
self.task_json_path = task_json_path
self.random_seed = random_seed
# randomize index
self.light_rnd = -1 # light randomized index
self.location_rnd = -1 # game loc randomized index
self.material_rnd = -1 # material randomized index
if task_json_path:
if not os.path.exists(self.task_json_path):
raise Exception( "The json file at path {} provided wasn't found".format(self.task_json_path))
self.task_json = json.load(open(self.task_json_path))
else:
self.task_json = {}
# init randomization
if "random" not in self.task_json:
self.random_info = {
"lights":[],
"materials":{},
"locations":[{
"translate":[0,0,0],
"orient":[1,0,0,0],
"scale":[1.0,1.0,1.0]
}],
}
self.task_json["random"] = self.random_info
else:
self.random_info = self.task_json["random"]
# material
self.material_dict = {}
# @staticmethod
def get_water_material(self):
from pxr import Tf, Sdf, Usd, UsdShade
# self.setup_material_helper()
# print()
water_url = 'http://localhost:8080/omniverse://127.0.0.1/NVIDIA/Materials/Base/Natural/Water.mdl'
water_mtl_name = water_url.split("/")[-1][:-4]
# print("material dict: ", self.material_dict)
water_material_prim_path = get_material_prim_path(water_mtl_name)
# omni.kit.commands.execute(
# "CreatePrim", prim_path=water_material_prim_path, prim_type="Scope", select_new_prim=False
# )
def on_create(path):
pass
return create_mdl_material(omni.usd.get_context().get_stage(), water_url, water_mtl_name, on_create)
# stage = omni.usd.get_context().get_stage()
# if stage.HasDefaultPrim():
# mtl_path = omni.usd.get_stage_next_free_path(
# stage, "{}/Looks/{}".format(stage.GetDefaultPrim().GetPath(), Tf.MakeValidIdentifier(water_mtl_name)), False
# )
# else:
# mtl_path = omni.usd.get_stage_next_free_path(
# stage, "/Looks/{}".format(Tf.MakeValidIdentifier(water_mtl_name)), False
# )
# omni.kit.commands.execute("CreateMdlMaterialPrim", mtl_url=water_url, mtl_name=water_mtl_name,
# mtl_path=water_material_prim_path, select_new_prim=False)
# return water_material_prim_path
# omni.kit.commands.execute(
# "CreateMdlMaterialPrim",
# mtl_url=water_url,
# mtl_name=water_mtl_name,
# mtl_path=water_material_prim_path,
# select_new_prim=False,
# )
# omni.kit.commands.execute(
# 'BindMaterial',
# prim_path=prim.GetPath(),
# material_path = water_material_prim_path,
# strength=pxr.UsdShade.Tokens.strongerThanDescendants
# )
return water_material_prim_path
def set_seed(self, seed):
self.random_seed = seed
def randomize_light(self):
"""
Randomize light intensity
"""
self.random_info["lights"] = [0, 200, 400, 600, 800, 1000] # light intensity indexes
self.light_rnd = random.choice([_ for _ in range(len(self.random_info["lights"]))])
self.stage = omni.usd.get_context().get_stage()
self.default_prim = self.stage.GetDefaultPrim()
# print("?", self.default_prim.GetPath().pathString + "/defaultLight")
light_prim = self.stage.GetPrimAtPath(self.default_prim.GetPath().pathString + "/defaultLight")
assert light_prim.GetTypeName() == "DistantLight"
light_prim.GetAttribute("intensity").Set(self.random_info["lights"][self.light_rnd])
def randomize_game_location(self):
"""
Randomize light intensity
"""
assert len(self.random_info["locations"]) > 0
self.location_rnd = (self.location_rnd + 1) % len(self.random_info["locations"])
self.stage = omni.usd.get_context().get_stage()
self.default_prim = self.stage.GetDefaultPrim()
game_prim = self.stage.GetPrimAtPath(self.default_prim.GetPath().pathString + "/game")
game_layout = self.random_info["locations"][self.location_rnd]
assert "translate" in game_layout and "orient" in game_layout
translate = game_layout["translate"]
orient = game_layout["orient"]
rotation = Gf.Quatd(orient[0], orient[1], orient[2], orient[3])
# TODO: check whether scale can be randomized
scale = (1.0, 1.0, 1.0)
print("location")
xform = Gf.Matrix4d().SetScale(scale) * Gf.Matrix4d().SetRotate(rotation) * Gf.Matrix4d().SetTranslate(translate)
omni.kit.commands.execute(
"TransformPrimCommand",
path=game_prim.GetPath(),
new_transform_matrix=xform,
)
def setup_material_helper(self):
"""
set up material randomizer
"""
self.stage = omni.usd.get_context().get_stage()
# check if has material
if len(self.material_dict) > 0:
return
carb.log_info("loading necleu materials")
# load from saved params
try:
# load the materials from nucleus url link
mat_root_path = "http://localhost:8080/omniverse://127.0.0.1/NVIDIA/Materials/"
carb.log_info(f"Collecting files for {mat_root_path}")
result1, entries = omni.client.list(mat_root_path)
from .material.param import NECLEUS_MATERIALS
self.material_dict = NECLEUS_MATERIALS
except:
# load the materials from nucleus url link
mat_root_path = "http://localhost:8080/omniverse://127.0.0.1/NVIDIA/Materials/"
carb.log_info(f"Collecting files for {mat_root_path}")
result1, entries = omni.client.list(mat_root_path)
if result1 != omni.client.Result.OK:
raise Exception(f"nucleus connect error at path: {mat_root_path}")
for e in entries:
print("result: ", e.relative_path)
material_type_folder = mat_root_path + e.relative_path + "/"
result2, mat_type_entries = omni.client.list(material_type_folder)
for mat_type_e in mat_type_entries:
if mat_type_e.relative_path not in self.material_dict:
self.material_dict[mat_type_e.relative_path] = []
material_folder = material_type_folder + mat_type_e.relative_path + "/"
result3, mat_entries = omni.client.list(material_folder)
for mat_e in mat_entries:
if mat_e.relative_path.endswith(".mdl"):
mat_path = material_folder + mat_e.relative_path
self.material_dict[mat_type_e.relative_path].append(mat_path)
# filter_out_empty
temp_dict = {}
for key in self.material_dict:
if len(self.material_dict[key]) > 0:
temp_dict[key] = self.material_dict[key]
self.material_dict = temp_dict
# mtl_created_list = []
# omni.kit.commands.execute(
# "CreateAndBindMdlMaterialFromLibrary",
# mdl_name='http://localhost:8080/omniverse://127.0.0.1/NVIDIA/Materials/Base/Architecture/Ceiling_Tiles.mdl',
# mtl_name='Ceiling_Tiles',
# mtl_created_list=mtl_created_list,
# bind_selected_prims=True,
# select_new_prim=False,
# )
def randomize_house(self, rand = True, randomize_floor =True, randomize_wall = True):
"""
randomize house's floor and wall
by default, we only randomize floor
"""
self.setup_material_helper()
floor_parent = self.stage.GetPrimAtPath("/World/layout/floors")
wall_parent = self.stage.GetPrimAtPath("/World/layout/structure") # roomStruct
self.random_info["floor_materials"] = [x for k in ["Wood"] for x in self.material_dict[k]] # Carpet
self.random_info["wall_materials"] = [x for k in ["Wall_Board"] for x in self.material_dict[k]] # "Masonry", "Architecture"
# print(self.random_info["floor_materials"])
# len_floor = len(self.random_info["floor_materials"])
# len_wall = len(self.random_info["wall_materials"])
wall_mtl_url = random.choice(self.random_info["wall_materials"]) if rand else self.random_info["wall_materials"][0]
floor_mtl_url = random.choice(self.random_info["floor_materials"]) if rand else self.random_info["floor_materials"][0]
wall_mtl_name = wall_mtl_url.split("/")[-1][:-4]
floor_mtl_name = floor_mtl_url.split("/")[-1][:-4]
# change mtl
new_looks_path1, wall_material_prim_path = get_material_prim_path(wall_mtl_name)
if new_looks_path1 and randomize_wall:
omni.kit.commands.execute(
"CreatePrim", prim_path=new_looks_path1, prim_type="Scope", select_new_prim=False
)
new_looks_path2, floor_material_prim_path = get_material_prim_path(floor_mtl_name)
if new_looks_path2 and randomize_floor:
omni.kit.commands.execute(
"CreatePrim", prim_path=new_looks_path2, prim_type="Scope", select_new_prim=False
)
for prim in floor_parent.GetChildren():
if prim is None:
raise Exception("no house in scene!")
carb.log_info("changing material at path: " + prim.GetPath().pathString)
if floor_material_prim_path:
omni.kit.commands.execute(
"CreateMdlMaterialPrim",
mtl_url=floor_mtl_url,
mtl_name=floor_mtl_name,
mtl_path=floor_material_prim_path,
select_new_prim=False,
)
omni.kit.commands.execute(
'BindMaterial',
prim_path=prim.GetPath(),
material_path=floor_material_prim_path,
strength=pxr.UsdShade.Tokens.strongerThanDescendants
)
for prim in wall_parent.GetChildren():
if prim is None:
raise Exception("no house in scene!")
carb.log_info("changing material at path: " + prim.GetPath().pathString)
if wall_material_prim_path:
omni.kit.commands.execute(
"CreateMdlMaterialPrim",
mtl_url=wall_mtl_url,
mtl_name=wall_mtl_name,
mtl_path=wall_material_prim_path,
select_new_prim=False,
)
omni.kit.commands.execute(
'BindMaterial',
prim_path=prim.GetPath(),
material_path=wall_material_prim_path,
strength=pxr.UsdShade.Tokens.strongerThanDescendants
)
def randomize_material(self):
"""
randomize material for mobility
"""
self.setup_material_helper()
# print("house material_dict: ", self.material_dict)
# print(os.getcwd())
# if selected, update selection materials
prim_paths = omni.usd.get_context().get_selection().get_selected_prim_paths()
if prim_paths and len(prim_paths) > 0:
pass
else:
# find target object
target_obj_id = str(self.task_json["object_id"])
obj_prim = None
self.stage = omni.usd.get_context().get_stage()
game_parent = self.stage.GetPrimAtPath("/World/game")
for prim in game_parent.GetChildren():
# if no materials
if target_obj_id in prim.GetPath().pathString:
obj_prim = prim
break
# print("obj_path_string", obj_prim.GetPath().pathString)
if len(self.random_info["materials"]) == 0:
material_list = [x for v in self.material_dict.values() for x in v]
mat_urls = random.sample(material_list, 10) # random sample ten materials 80% train 20% test
self.random_info["materials"] = {"train":mat_urls[:8], "test":mat_urls[8:]}
# self.save_asset_info()
# if has materials, load train material type
self.material_rnd = (1 + self.material_rnd) % len(self.random_info["materials"]["train"])
mtl_url = self.random_info["materials"]["train"][self.material_rnd] #random.choice(self.random_info["materials"]["train"])
mtl_name = mtl_url.split("/")[-1][:-4]
if obj_prim is None:
raise Exception(f"must load mobility first (object id){target_obj_id}")
carb.log_info("changing material at path: " + obj_prim.GetPath().pathString)
# change mtl
new_looks_path, material_prim_path = get_material_prim_path(mtl_name)
if new_looks_path:
omni.kit.commands.execute(
"CreatePrim", prim_path=new_looks_path, prim_type="Scope", select_new_prim=False
)
if material_prim_path:
omni.kit.commands.execute(
"CreateMdlMaterialPrim",
mtl_url=mtl_url,
mtl_name=mtl_name,
mtl_path=material_prim_path,
select_new_prim=False,
)
omni.kit.commands.execute(
'BindMaterial',
prim_path=obj_prim.GetPath(),
material_path=material_prim_path,
strength=pxr.UsdShade.Tokens.strongerThanDescendants
)
# mat_type = random.choice(list(self.material_dict.keys()))
# mtl_url = random.choice(self.material_dict[mat_type])
# mtl_name = mtl_url.split("/")[-1][:-4]
# # mtl_url = "http://localhost:8080/omniverse://127.0.0.1/NVIDIA/Materials/Base/Architecture/Ceiling_Tiles.mdl"
# # mtl_name = "Ceiling_Tiles"
# new_looks_path, material_prim_path = get_material_prim_path(mtl_name)
# if new_looks_path:
# omni.kit.commands.execute(
# "CreatePrim", prim_path=new_looks_path, prim_type="Scope", select_new_prim=False
# )
# if material_prim_path:
# omni.kit.commands.execute(
# "CreateMdlMaterialPrim",
# mtl_url=mtl_url,
# mtl_name=mtl_name,
# mtl_path=material_prim_path,
# select_new_prim=False,
# )
# for prim_path in prim_paths:
# omni.kit.commands.execute(
# 'BindMaterial',
# prim_path=prim_path,
# material_path=material_prim_path,
# strength=pxr.UsdShade.Tokens.strongerThanDescendants
# )
def record_game_offset(self):
# record game xform position and rotation
self.stage = omni.usd.get_context().get_stage()
game_prim = self.stage.GetPrimAtPath("/World/game") #pxr.UsdGeom.Xform.Get(self.stage, "/World/game")
if game_prim:
quad = game_prim.GetAttribute("xformOp:orient").Get()
translate = game_prim.GetAttribute("xformOp:translate").Get()
# print("game_prim", game_prim, eval(str(quad)))
quad = eval(str(quad))
layout_offset = {
"translate": [translate[0], translate[1], translate[2]],
"orient": [quad[0], quad[1], quad[2], quad[3]],
"scale": [1.0, 1.0, 1.0],
}
# check if currect layout offset is already recorded
layout_offset_already_recorded = False
#if "layout_offsets" in self.random_info["locations"]:
for offset in self.random_info["locations"]:
#if offset == layout_offset:
print("offset", offset)
if offset["translate"] == layout_offset["translate"] and \
offset["orient"] == layout_offset["orient"] and \
offset["scale"] == layout_offset["scale"]:
layout_offset_already_recorded = True
break
# if not in record, add offset record
if not layout_offset_already_recorded:
self.random_info["locations"].append(layout_offset)
print("New game offset recorded at: ", layout_offset)
def record_randomization(self):
with open(self.task_json_path, "w") as f:
json.dump(self.task_json, f, indent=4)
def randomize_sky(self, sky_type:str = None, url= "http://omniverse-content-production.s3-us-west-2.amazonaws.com/Assets/Skies/Dynamic/"):
"""
Add sky to the environment
"""
# return
# FIXME: not compatible with new version
self.stage = omni.usd.get_context().get_stage()
ENVIRONMENT_ROOT = "/Environment"
sky_prim_path = f"{ENVIRONMENT_ROOT}/sky"
# disable light
# light_prim_path = "/World/defaultLight"
# light_prim = self.stage.GetPrimAtPath(light_prim_path)
# if light_prim:
# light_prim.GetAttribute('visibility').Set('invisible')
if sky_type:
sky_name = f"{sky_type}Sky" if not sky_type == "Overcast" else "Overcast"
else:
sky_list = ["ClearSky","CloudySky","Overcast","NightSky"]
sky_name = random.choice(sky_list)
sky_url = f"{url}{sky_name}.usd"
# if found existing env, return
sky_prim = self.stage.GetPrimAtPath(sky_prim_path)
if sky_prim:
carb.log_warn("Sky already in the env")
sky_prim.GetReferences().ClearReferences()
else:
sky_prim = self.stage.DefinePrim(sky_prim_path, "Xform")
if len(sky_type) == 0:
# invalid sky type:
return
sky_prim.GetReferences().AddReference(sky_url)
rot = pxr.Gf.Vec3d(0, 0, 0)
properties = sky_prim.GetPropertyNames()
if "xformOp:rotateXYZ" in properties:
rotation = sky_prim.GetAttribute("xformOp:rotateXYZ")
rotation.Set(rot)
elif "xformOp:rotateZYX" in properties:
rotation = sky_prim.GetAttribute("xformOp:rotateZYX")
rotation.Set(rot)
elif "xformOp:transform" in properties:
carb.log_info("Object missing rotation op. Adding it.")
xform = pxr.UsdGeom.Xformable(sky_prim)
xform_op = xform.AddXformOp(pxr.UsdGeom.XformOp.TypeRotateXYZ, pxr.UsdGeom.XformOp.PrecisionDouble, "")
rotate = Gf.Vec3d(rot[0], rot[1], rot[2])
xform_op.Set(rotate)
# if IS_IN_ISAAC_SIM:
# from omni.isaac.core.utils.stage import add_reference_to_stage
# add_reference_to_stage(sky_url ,sky_prim_path)
# else:
# omni.kit.commands.execute("CreateUsdSkyPrimCommand", sky_url=sky_url, sky_path=sky_prim_path)
# too light, lower intensity to pretect eyes
#
# domelight_prim = self.stage.GetPrimAtPath("/Environment/sky/DomeLight")
# domelight_prim.GetAttribute("intensity").Set(0)
|
yizhouzhao/VRKitchen2.0-IndoorKit/exts/vrkitchen.indoor.kit/vrkitchen/indoor/kit/layout/house_new.py | from cgitb import enable
import os
import json
from typing import Container
import numpy as np
import asyncio
import omni
import pxr
import carb
from omni.physx.scripts import physicsUtils
from omni.physx.scripts.utils import setCollider, setRigidBody, setStaticCollider
from omni.usd import get_world_transform_matrix, get_local_transform_matrix
from ..param import DATA_PATH_NEW, ASSET_PATH, HOUSE_INFO_PATH, IS_IN_ISAAC_SIM, RIGIDBODY_OBJ_TYPES, GAME_OBJ_NAMES, \
IS_IN_CREAT, CONTAINER_NAMES, OTHER_OBJ_NAMES
from .utils import rename_prim, rotationXYZ_to_quaternion, freeze_prim
from .modify import modify_game_obj_prim
# if IS_IN_CREAT or IS_IN_ISAAC_SIM:
# import omni.kit.viewport_widgets_manager as wm
# from ..ui.hud import LabelWidget
from .utils import NpEncoder
class House():
def __init__(self,
task_type:str,
task_id:int,
robot_id:int = 0,
mission_id:int = 0,
house_id:int = 0,
anchor_id:int=0,
annotator="",
):
self.task_type = task_type
self.task_id = str(task_id)
self.data_path = DATA_PATH_NEW
self.robot_id = str(robot_id)
self.anchor_id = str(anchor_id)
self.mission_id = str(mission_id)
self.house_id = str(house_id)
self.annotator = str(annotator)
# task saving dicts/lists
self.object_info = []
self.robot_info = {}
self.make_task_saving_folder()
# house saving dict
self.house_appearance = {}
self.house_task_anchor = {}
self.object_prims = []
def make_task_saving_folder(self):
"""
check task saving folder
"""
task_type_folder = os.path.join(self.data_path, self.annotator, "task", self.task_type)
if not os.path.exists(task_type_folder):
os.makedirs(task_type_folder)
task_folder = os.path.join(self.data_path, self.annotator, "task", self.task_type, str(self.task_id))
if not os.path.exists(task_folder):
os.makedirs(task_folder)
def record_obj_info(self):
"""
record game object information and save
"""
# scene
self.stage = omni.usd.get_context().get_stage()
# Get sapien asset name
#prims = [self.stage.GetDefaultPrim()]
game_prim = self.stage.GetPrimAtPath("/World/game")
if not game_prim:
raise Exception("Please move object and robot under /World/game")
#print("prims", prims)
for prim in game_prim.GetChildren():
# print("prim ", prim.GetPath())
# if prim is game obj, record information
is_game_obj = False
for game_name in GAME_OBJ_NAMES + CONTAINER_NAMES + OTHER_OBJ_NAMES:
if game_name in prim.GetPath().pathString.lower():
is_game_obj = True
break
if is_game_obj:
reference, _ = omni.usd.get_composed_references_from_prim(prim)[0]
print("mobility reference: ", reference.assetPath)
relative_path = omni.client.make_relative_url(ASSET_PATH, reference.assetPath)
relative_path = relative_path.replace("\\\\","/").replace("\\","/")
# get obj type from paths
path_splits = relative_path.split("/")
# print("path_splits", path_splits)
# asset_path = "/".join(path_splits[2:])
obj_info = {
"asset_path": relative_path,
"obj_type": path_splits[-3],
"obj_id": path_splits[-2],
"materials":[],
}
mat = get_world_transform_matrix(prim)
if prim.HasAttribute("xformOp:orient"):
quad = prim.GetAttribute("xformOp:orient").Get()
else:
rotateXYZ = prim.GetAttribute("xformOp:rotateXYZ").Get()
quad = rotationXYZ_to_quaternion(rotateXYZ)
# quad = prim.GetAttribute("xformOp:orient").Get() # eval(str(mat.ExtractRotationQuat())) #eval(str(mat.ExtractRotation().GetQuat()))
quad = eval(str(quad))
translate = mat.ExtractTranslation()
scale = prim.GetAttribute("xformOp:scale").Get()
#print("translate", translate)
#print("quad", prim.GetPath(), quad)
obj_info["translate"] = [translate[0], translate[1], translate[2]]
obj_info["orient"] = [quad[0], quad[1], quad[2], quad[3]]
obj_info["scale"] = [scale[0],scale[1],scale[2]]
print("obj_info", obj_info)
# task_identity = obj_info["obj_type"] + obj_info["obj_id"]
self.object_info.append(obj_info)
# IMPORTANT: if the object is unbalanced scale, freeze object by
# To enter this condition is very strict: open/close door, wrong proportion of scale
# 1. Create a new xform
# 2. Move the object under the unit xform
# 3. Save the obj as another usd variance
game_obj_info = self.object_info[0]
game_obj_scale = game_obj_info["scale"]
if self.task_type in ["open_door", "close_door"]:
need_freeze = abs(game_obj_scale[0] / game_obj_scale[1]) > 1.2 or \
abs(game_obj_scale[0] / game_obj_scale[1]) < 0.8 or \
abs(game_obj_scale[1] / game_obj_scale[2]) > 1.2 or \
abs(game_obj_scale[1] / game_obj_scale[2]) < 0.8 or \
abs(game_obj_scale[0] / game_obj_scale[2]) > 1.2 or \
abs(game_obj_scale[0] / game_obj_scale[2]) < 0.8
if need_freeze:
carb.log_warn("Found non-unit scale object, freezing transfrom...")
original_usd_path = os.path.join(ASSET_PATH, game_obj_info["asset_path"])
var_usd_path = original_usd_path.replace("mobility",
f"mobility_{self.annotator}_{self.task_type}_{self.task_id}_{self.robot_id}_{self.mission_id}_{self.house_id}_{self.anchor_id}")
import shutil
shutil.copyfile(original_usd_path, var_usd_path)
omni.usd.get_context().close_stage()
omni.usd.get_context().open_stage(var_usd_path)
stage = omni.usd.get_context().get_stage()
default_prim = stage.GetDefaultPrim()
# default_prim.GetAttribute("xformOp:scale").Set(pxr.Gf.Vec3f(1, 2, 1))
new_prim = freeze_prim(default_prim, game_obj_scale)
pxr.UsdPhysics.ArticulationRootAPI.Apply(new_prim)
stage.SetDefaultPrim(new_prim)
omni.usd.get_context().save_stage()
# time.sleep(1.0)
# omni.usd.get_context().close_stage()
relative_path = omni.client.make_relative_url(ASSET_PATH, var_usd_path)
relative_path.replace("\\", "/")
game_obj_info["asset_path"] = relative_path
new_size = (game_obj_scale[0] * game_obj_scale[1] * game_obj_scale[2]) ** (1/3)
game_obj_info["scale"] = [1 / new_size , 1 / new_size , 1 / new_size]
# save obj info
if len(self.object_info) > 0:
if self.house_id != "-1" and self.anchor_id != "-1":
obj_identifier = f"{self.house_id} {self.anchor_id}"
task_obj_path = os.path.join(self.data_path, self.annotator,"task", self.task_type, self.task_id, "objects_with_rooms.json")
objects_with_rooms = {} if not os.path.exists(task_obj_path) else json.load(open(task_obj_path))
objects_with_rooms[obj_identifier] = self.object_info
with open(task_obj_path, "w") as f:
json.dump(objects_with_rooms, f, indent=4, cls=NpEncoder)
else:
task_obj_path = os.path.join(self.data_path, self.annotator,"task", self.task_type, self.task_id, "objects.json")
with open(task_obj_path, "w") as f:
json.dump(self.object_info, f, indent=4, cls=NpEncoder)
carb.log_info(f"current objects info saving at: {task_obj_path}")
def load_obj_info(self, relative = False):
"""
Load objects for the task
if relative: put obj at the original position
"""
# scene
self.stage = omni.usd.get_context().get_stage()
# set up game root
default_prim_path_str = "/World"
self.xform_game_path = default_prim_path_str + "/game" # omni.usd.get_stage_next_free_path(self.stage, "/World/game", True)
# check if in house
self.object_info = None
if self.house_id != "-1" and self.anchor_id != "-1":
obj_identifier = f"{self.house_id} {self.anchor_id}"
task_obj_path = os.path.join(self.data_path, self.annotator,"task", self.task_type, self.task_id, "objects_with_rooms.json")
objects_with_rooms = {} if not os.path.exists(task_obj_path) else json.load(open(task_obj_path))
if obj_identifier in objects_with_rooms:
self.object_info = objects_with_rooms[obj_identifier]
if self.object_info is None:
task_obj_path = os.path.join(self.data_path, self.annotator, "task", self.task_type, self.task_id, "objects.json")
if not os.path.exists(task_obj_path):
raise Exception( "The json file at path {} provided wasn't found".format(task_obj_path) )
# load object info
self.object_info = json.load(open(task_obj_path))
for obj_idx, obj in enumerate(self.object_info):
# load object usd
obj_usd_path = os.path.join(ASSET_PATH, obj["asset_path"])
translate = obj["translate"]
orient = obj["orient"]
rotation = pxr.Gf.Quatd(orient[0], orient[1], orient[2], orient[3])
scale = obj["scale"]
# move game xform to the first object
# set up parent
if obj_idx == 0:
xform_game = self.stage.GetPrimAtPath(self.xform_game_path)
if not xform_game:
xform_game = pxr.UsdGeom.Xform.Define(self.stage, self.xform_game_path)
self.game_translate = translate if not relative else [0,0,0]
game_xform = pxr.Gf.Matrix4d().SetScale([1,1,1]) * \
pxr.Gf.Matrix4d().SetRotate(pxr.Gf.Quatf(1.0,0.0,0.0,0.0)) * pxr.Gf.Matrix4d().SetTranslate(self.game_translate)
omni.kit.commands.execute(
"TransformPrimCommand",
path=self.xform_game_path,
new_transform_matrix=game_xform,
)
# xform_game.AddTranslateOp().Set(pxr.Gf.Vec3f(*translate))
# xform_game.AddOrientOp().Set()
# xform_game.AddScaleOp().Set(pxr.Gf.Vec3f(1.0, 1.0, 1.0))
# move obj to the correct place
mobility_prim_path = xform_game.GetPath().pathString + "/mobility"
prim = self.stage.GetPrimAtPath(mobility_prim_path)
if not prim.IsValid():
prim = self.stage.DefinePrim(mobility_prim_path)
success_bool = prim.GetReferences().AddReference(obj_usd_path)
# print("get prim children", prim.GetChildren())
if not success_bool:
raise Exception("The usd file at path {} provided wasn't found".format(obj_usd_path))
# relative translate
if obj_idx == 0: # main object
rel_translate = [0,0,0]
else:
rel_translate = [self.game_translate[i] + obj["translate"][i] for i in range(3)]
xform = pxr.Gf.Matrix4d().SetScale(scale) * pxr.Gf.Matrix4d().SetRotate(rotation) * pxr.Gf.Matrix4d().SetTranslate(rel_translate)
omni.kit.commands.execute(
"TransformPrimCommand",
path=prim.GetPath(),
new_transform_matrix=xform,
)
if obj["obj_type"].lower() in GAME_OBJ_NAMES or obj_idx == 0: # main object
obj_prefix = "mobility_"
elif obj["obj_type"].lower() in CONTAINER_NAMES:
obj_prefix = "container_"
else:
obj_prefix = "other_"
# if IS_IN_ISAAC_SIM:
# add_update_semantics(prim, obj["obj_type"])
# TODO: set up name rules
old_prim_name = prim.GetPath().pathString
new_prim_path = prim.GetPath().GetParentPath().AppendChild(obj_prefix + obj["obj_type"] + "_" + str(obj["obj_id"]))
new_prim_name = omni.usd.get_stage_next_free_path(self.stage, new_prim_path.pathString, False)
# carb.log_info("rename:" + old_prim_name + ";" + new_prim_name ";" + prim.GetPath().pathString)
rename_prim(old_prim_name, new_prim_name)
target_obj_prim = self.stage.GetPrimAtPath(new_prim_name)
modify_game_obj_prim(target_obj_prim)
print("modify prim name: ", new_prim_name)
self.object_prims.append(new_prim_name)
def record_robot_info(self, robot_prim_path = "/World/game/franka"):
"""
Record robots infomation, and save it RELATIVE position from the main game obj
:params:
robot_prim_path: default robot path
"""
self.stage = omni.usd.get_context().get_stage()
# Get sapien asset name
#prims = [self.stage.GetDefaultPrim()]
game_prim = self.stage.GetPrimAtPath("/World/game")
if not game_prim:
raise Exception("Please move object and robot under /World/game")
#for game_prim in prims:
for prim in game_prim.GetChildren():
# print("prim ", prim.GetPath())
# if prim is game obj, record information
is_game_obj = False
for game_name in GAME_OBJ_NAMES:
if game_name in prim.GetPath().pathString:
is_game_obj = True
break
if is_game_obj:
mat = omni.usd.utils.get_world_transform_matrix(prim)
game_translate = mat.ExtractTranslation()
break
if not game_translate:
raise Exception("Before recording robot, there must be a game object")
# then, find robot and calcuate relative postion
"""
Get robot information at robot_prim_path
"""
robot_prim = self.stage.GetPrimAtPath(robot_prim_path)
if not robot_prim or not pxr.UsdGeom.Xform.Get(self.stage, robot_prim_path):
raise Exception(f"Must have a robot with XForm at path {robot_prim_path}")
# get robot world transform
# if IS_IN_ISAAC_SIM:
# from omni.isaac.core.prims import XFormPrim
# pos, rot = XFormPrim(robot_prim_path).get_local_pose()
# translate = np.array(pos)
# quad = np.array(rot)
# else:
mat = get_local_transform_matrix(robot_prim)
translate = mat.ExtractTranslation()
quad = eval(str(mat.ExtractRotation().GetQuat()))
rob_info = {
"type":"franka",
"translate": [round(translate[0], 3), round(translate[1],3), round(translate[2], 3)],
"orient": [round(quad[0], 3), round(quad[1], 3), round(quad[2], 3), round(quad[3], 3)],
}
if self.house_id != "-1" and self.anchor_id != "-1":
task_robot_path = os.path.join(self.data_path, self.annotator, "task", self.task_type, self.task_id, "robots_with_rooms.json")
robot_identifier = f"{self.robot_id} {self.house_id} {self.anchor_id} {self.mission_id}"
objects_with_rooms = {} if not os.path.exists(task_robot_path) else json.load(open(task_robot_path))
objects_with_rooms[robot_identifier] = rob_info
with open(task_robot_path, "w") as f:
json.dump(objects_with_rooms, f, indent=4, cls=NpEncoder)
else:
task_robot_path = os.path.join(self.data_path, self.annotator, "task", self.task_type, self.task_id, "robots.json")
if os.path.exists(task_robot_path):
self.robot_info = json.load(open(task_robot_path))
robot_identifier = str(self.robot_id)
self.robot_info[robot_identifier] = rob_info
with open(task_robot_path, "w") as f:
json.dump(self.robot_info, f, indent=4, cls=NpEncoder)
carb.log_info(f"Saving robot json file at {task_robot_path}")
def load_robot_info(self):
"""
Load robot for currect task
"""
# if append house and anchor info
rot_info = None
if self.house_id != "-1" and self.anchor_id != "-1":
task_robot_path = os.path.join(self.data_path, self.annotator, "task", self.task_type, self.task_id, "robots_with_rooms.json")
robot_identifier = f"{self.robot_id} {self.house_id} {self.anchor_id}"
robot_identifier = f"{self.robot_id} {self.house_id} {self.anchor_id} {self.mission_id}"
objects_with_rooms = {} if not os.path.exists(task_robot_path) else json.load(open(task_robot_path))
if robot_identifier in objects_with_rooms:
rot_info = objects_with_rooms[robot_identifier]
if rot_info is None:
task_robot_path = os.path.join(self.data_path, self.annotator, "task", self.task_type, self.task_id, "robots.json")
if not os.path.exists(task_robot_path):
raise Exception( "The json file at path {} provided wasn't found".format(task_robot_path) )
# load json information
self.robot_info = json.load(open(task_robot_path))
# assert self.robot_id in self.robot_info, \
# f"Please record robot id variation first {self.task_type}, task_id {self.task_id}, robot_id {self.robot_id}"
if self.robot_id in self.robot_info:
rot_info = self.robot_info[self.robot_id]
else:
return None, None
return rot_info["translate"], rot_info["orient"]
def record_house_info(self):
"""
Record house information
::params:
anchor_id: postion of the game root
"""
# scene
self.stage = omni.usd.get_context().get_stage()
relative_path = None # house/layer asset relative path
# Get room name
room_path = self.stage.GetRootLayer().realPath
# print("room_path: ", room_path)
if room_path:
relative_path = omni.client.make_relative_url(HOUSE_INFO_PATH, room_path)
relative_path = relative_path.replace("\\\\", "/").replace("\\", "/")
# print("room_name: ", relative_path)
# self.layout["asset"]["room_name"] = relative_path
else:
self.layer = self.stage.GetRootLayer()
# print("layer: ", )
for ref in self.layer.GetExternalReferences():
if "layout" in str(ref):
#PathUtils.compute_relative_path(self.house_info_path,str(ref))
relative_path = omni.client.make_relative_url(HOUSE_INFO_PATH, str(ref))
relative_path = relative_path.replace("\\\\", "/").replace("\\", "/")
# print("relative_path", relative_path)
# self.layout["asset"]["room_name"] = relative_path
break
# make house saving folder
assert relative_path is not None
house_id = relative_path.split("/")[-2]
house_folder = os.path.join(self.data_path, self.annotator,"house", house_id)
if not os.path.exists(house_folder):
os.makedirs(house_folder)
# # make appearance
# appearance_json_path = os.path.join(house_folder, "appearance.json")
# if os.path.exists(appearance_json_path):
# self.house_appearance = json.load(open(appearance_json_path))
# self.house_appearance["asset_path"] = relative_path
# with open(appearance_json_path, "w") as f:
# json.dump(self.house_appearance, f, indent=4)
# carb.log_info(f"Saving hosue appearce json file at {appearance_json_path}")
# find game, task, anchor information
default_prim_path_str = "/World" #self.stage.GetDefaultPrim().GetPath().pathString
game_prim = self.stage.GetPrimAtPath(default_prim_path_str + "/game")
# if game information exists
if game_prim:
# load anchor
anchor_json_path = os.path.join(house_folder, "anchor.json")
if os.path.exists(anchor_json_path):
self.house_task_anchor = json.load(open(anchor_json_path))
# get game transform
mat = omni.usd.utils.get_world_transform_matrix(game_prim)
quad = eval(str(mat.ExtractRotation().GetQuat()))
translate = mat.ExtractTranslation()
translate = [i for i in translate]
anchor_info = {
"task_type": self.task_type,
"task_id": self.task_id,
"robot_id": self.robot_id,
"anchor_id": self.anchor_id,
"game_location": {
"translate": translate,
"orient":quad,
}
}
anchor_info["additional_collisions"] = [] # self.get_furniture_collisions()
# print("anchor_info", anchor_info)
anchor_identifier = self.task_type + " " + self.task_id + " " + self.robot_id + " " + self.anchor_id
self.house_task_anchor[anchor_identifier] = anchor_info
with open(anchor_json_path, "w") as f:
json.dump(self.house_task_anchor, f, indent=4, cls=NpEncoder)
carb.log_info(f"Saving anchor json file at {anchor_json_path}")
def load_house_info(self, enable_collision=True):
"""
load house infomation from house_id, and anchor_id
"""
print("loading house")
# scene
self.stage = omni.usd.get_context().get_stage()
# self.layer = self.stage.GetRootLayer()
house_path = os.path.join(HOUSE_INFO_PATH, self.house_id, "layout.usd")
# omni.kit.commands.execute(
# "CreateSublayer",
# layer_identifier=self.layer.identifier,
# sublayer_position=0,
# new_layer_path=house_path,
# transfer_root_content=False,
# create_or_insert=False,
# layer_name="house",
# )
# Check anchor exists, if not, then only the scene
house_folder = os.path.join(self.data_path, self.annotator, "house", self.house_id)
anchor_json_path = os.path.join(house_folder, "anchor.json")
if not os.path.exists(anchor_json_path):
carb.log_warn("No anchor file found, record anchor information first")
return False
# print("anchor_json_path: ", anchor_json_path)
try:
self.house_task_anchor = json.load(open(anchor_json_path))
except:
carb.log_error("anchro_json path not correct: " + str(anchor_json_path))
return False
anchor_identifier_prefix = self.task_type + " " + self.task_id # + " " + self.robot_id + " " + self.anchor_id
has_anchor = False
for key in self.house_task_anchor:
if key.startswith(anchor_identifier_prefix):
has_anchor = True
anchor_identifier = key
break
if not has_anchor:
carb.log_warn(f"No anchor id: {self.anchor_id}, please record anchor at {anchor_json_path}")
return False
# move obj to the correct place
house_prim_path = "/World/layout"
house_prim = self.stage.GetPrimAtPath(house_prim_path)
if not house_prim.IsValid():
house_prim = self.stage.DefinePrim(house_prim_path)
success_bool = house_prim.GetReferences().AddReference(house_path)
if not success_bool:
raise Exception(f"The house is not load at {house_path}")
# static collider
# print("set collisiton")
# furniture_prim = self.stage.GetPrimAtPath(house_prim_path + "/furniture/furniture_87879")
# setStaticCollider(furniture_prim, approximationShape="convexDecomposition")
furniture_prim = self.stage.GetPrimAtPath(house_prim_path + "/furniture")
# if furniture_prim:
# setStaticCollider(furniture_prim, approximationShape="convexHull")
# else:
# return False
# if not self.task_type in ["tap_water", "transfer_water", "pour_water"] and enable_collision:
# room_struct_prim = self.stage.GetPrimAtPath(house_prim_path + "/roomStruct")
# setStaticCollider(room_struct_prim, approximationShape="none")
# check task/task_type/robot
anchor_info = self.house_task_anchor[anchor_identifier]
# if anchor_info["task_type"] != self.task_type or \
# anchor_info["task_id"] != self.task_id or \
# anchor_info["robot_id"] != self.robot_id:
# raise Exception("Anchor information at {} does not match UI inputs".format(anchor_json_path))
# find game, task, anchor information
default_prim_path_str = "/World"
game_prim = self.stage.GetPrimAtPath(default_prim_path_str + "/game")
# if game information exists
if not game_prim:
carb.log_error(f"must have game obj at path {default_prim_path_str} + /game ")
return False
print("anchor_info", anchor_info)
orient = anchor_info["game_location"]["orient"]
translate = anchor_info["game_location"]["translate"]
rotation = pxr.Gf.Quatd(orient[0], orient[1], orient[2], orient[3])
game_xform = pxr.Gf.Matrix4d().SetScale([1,1,1]) * \
pxr.Gf.Matrix4d().SetRotate(rotation) * pxr.Gf.Matrix4d().SetTranslate(translate)
omni.kit.commands.execute(
"TransformPrimCommand",
path=default_prim_path_str + "/game",
new_transform_matrix=game_xform,
)
# set up additional collision
# for furni_path in anchor_info["additional_collisions"]:
# prim = self.stage.GetPrimAtPath(furni_path)
# # set rigidbody and disable it, only leave with collision
# setRigidBody(prim, "convexDecomposition", False)
# prim.GetAttribute("physics:rigidBodyEnabled").Set(False)
# print("try to set collider: ", furni_path)
## add ground
ground_prim = self.stage.GetPrimAtPath(default_prim_path_str + '/groundPlane')
if not ground_prim:
physicsUtils.add_ground_plane(self.stage, '/groundPlane', "Y", 1000.0,
pxr.Gf.Vec3f(0.0, 0.0, 0), pxr.Gf.Vec3f(0.2))
ground_prim = self.stage.GetPrimAtPath(default_prim_path_str + '/groundPlane')
# prim_list = list(self.stage.TraverseAll())
# prim_list = [ item for item in prim_list if 'groundPlane' in item.GetPath().pathString and item.GetTypeName() == 'Mesh' ]
# for prim in prim_list:
ground_prim.GetAttribute('visibility').Set('invisible')
# if ground_prim:
# omni.kit.commands.execute("DeletePrims", paths=[ground_prim.GetPath()])
# ground_prim = self.stage.GetPrimAtPath("/World/groundPlane")
# if ground_prim:
# omni.kit.commands.execute("DeletePrims", paths=[ground_prim.GetPath()])
# gui = self.stage.GetPrimAtPath("/World/GUI")
# if gui:
# omni.kit.commands.execute("DeletePrims", paths=[gui.GetPath()])
return True
#----------------------------------------utils---------------------------------------------
def get_furniture_collisions(self):
"""
Get furniture information especially for collision from current scene
"""
# scene # furniture parent
self.stage = omni.usd.get_context().get_stage()
additional_collisions = []
furni_parent = self.stage.GetPrimAtPath("/World/furniture")
# if has furniture
if furni_parent:
for prim in furni_parent.GetChildren():
if prim.HasAPI(pxr.UsdPhysics.RigidBodyAPI) or prim.HasAPI(pxr.UsdPhysics.CollisionAPI):
# prim.GetAttribute("physics:rigidBodyEnabled").Set(False)
print("collision prim name", prim.GetPath(), prim.GetAttribute("physics:rigidBodyEnabled").Get())
# robot_prim.GetAttribute("xformOp:orient").Get()
additional_collisions.append(prim.GetPath().pathString)
return additional_collisions
def regularizing_game_robot_obj_location(self):
"""
Regulariting game/robot/obj locations: put /World/game translate as the obj location
"""
carb.log_info("Regularizing game/robot/obj locations")
# move game to main object
stage = omni.usd.get_context().get_stage()
game_prim = stage.GetPrimAtPath("/World/game")
if game_prim:
for obj_prim in game_prim.GetChildren():
if "mobility" in obj_prim.GetPath().pathString:
pos = pxr.UsdGeom.Xformable(obj_prim).ComputeLocalToWorldTransform(0).ExtractTranslation()
# rot = pos = pxr.UsdGeom.Xformable(obj_prim).ComputeLocalToWorldTransform(0).ExtractRotation().GetQuat()
# print("pos", pos, "rot", rot)
pos = [i for i in pos]
game_xform = pxr.Gf.Matrix4d().SetScale([1,1,1]) * \
pxr.Gf.Matrix4d().SetRotate(pxr.Gf.Quatf(1.0,0.0,0.0,0.0)) * pxr.Gf.Matrix4d().SetTranslate(pos)
omni.kit.commands.execute(
"TransformPrimCommand",
path=game_prim.GetPath().pathString,
new_transform_matrix=game_xform,
)
obj_prim.GetAttribute("xformOp:translate").Set(pxr.Gf.Vec3f(0.0, 0.0, 0.0))
# also transfer the location of the robot
robot_prim = stage.GetPrimAtPath("/World/game/franka")
if robot_prim:
robot_translate = robot_prim.GetAttribute("xformOp:translate").Get()
new_robot_translate = [robot_translate[i] - pos[i] for i in range(3)]
robot_prim.GetAttribute("xformOp:translate").Set(pxr.Gf.Vec3f(*new_robot_translate))
break
def house_anchor_id_suggestion(self):
"""
Get house ids that are possible for current task_type/task_id/anchor
"""
suggested_house_ids = []
suggested_anchor_ids = []
anchor_identifier_prefix = self.task_type + " " + self.task_id + " " + self.robot_id
house_root = os.path.join(self.data_path, self.annotator, "house")
print("os.listdir(house_root)", house_root)
for house_name in os.listdir(house_root):
anchor_json_path = os.path.join(house_root, house_name, "anchor.json")
if not os.path.exists(anchor_json_path):
carb.log_warn("please add anchor.json to current task")
return ""
with open(anchor_json_path, "r") as f:
anchor_info = json.load(f)
for identifier in anchor_info.keys():
if identifier.startswith(anchor_identifier_prefix):
suggested_house_ids.append(house_name)
anchod_id = identifier.split()[-1]
suggested_anchor_ids.append(anchod_id)
return [str((i,j)) for i,j in zip(suggested_house_ids, suggested_anchor_ids)]
# def build_HUD(self):
# if IS_IN_CREAT or IS_IN_ISAAC_SIM:
# self.stage = omni.usd.get_context().get_stage()
# gui_path = self.stage.GetDefaultPrim().GetPath().pathString + "/GUI"
# gui = self.stage.GetPrimAtPath(gui_path)
# if not gui:
# gui = pxr.UsdGeom.Xform.Define(self.stage, gui_path)
# gui_location = pxr.Gf.Vec3f(0, 100, 100)
# gui.AddTranslateOp().Set(gui_location)
# self.wiget_id = wm.add_widget(gui_path, LabelWidget(f"House id: {self.house_id}"), wm.WidgetAlignment.TOP)
|
yizhouzhao/VRKitchen2.0-IndoorKit/exts/vrkitchen.indoor.kit/vrkitchen/indoor/kit/layout/modify.py | import omni
import pxr
import carb
from pxr import UsdPhysics, UsdShade, Gf, Semantics
from omni.physx.scripts import physicsUtils
from omni.physx.scripts.utils import setCollider, setRigidBody, setStaticCollider, removeCollider
from ..param import IS_IN_ISAAC_SIM
from .utils import add_semantics
if IS_IN_ISAAC_SIM:
from omni.isaac.core.utils.semantics import add_update_semantics
def modify_game_obj_prim(prim):
"""
modify game object attributes:
if Bottle, add rigibody, physical material, and mass
"""
# add game object semantic
add_semantics(prim, "game_obj")
# print("modifyiing: " + prim.GetPath().pathString)
if "Bottle" in prim.GetPath().pathString or "standalone" in prim.GetPath().pathString:
"""
Set bottle rigidbox and physical material
"""
setRigidBody(prim, "convexDecomposition", False)
#prim.GetAttribute("physics:rigidBodyEnabled").Set(False)
setup_physics_material(prim)
add_mass_to_prim(prim)
# stage = omni.usd.get_context().get_stage()
# physicsUtils.add_ground_plane(stage, "/groundPlane", "Y", 750.0, Gf.Vec3f(0.0, -10.0, 0), Gf.Vec3f(0.5))
# if 'Faucet' in prim.GetPath().pathString:
# setup_physics_material(prim)
# add_mass_to_prim(prim)
if IS_IN_ISAAC_SIM and "Bottle" in prim.GetPath().pathString :
add_update_semantics(prim, "Bottle")
if "StorageFurniture" in prim.GetPath().pathString:
"""
Set up physical material for handles
"""
# setup_physics_material(prim)
# add_physical_material_to("coll")
fix_handle('StorageFurniture')
# remove_collider_to("visuals")
# if IS_IN_ISAAC_SIM:
# add_update_semantics(prim, "StorageFurniture")
# add_semantics("handle")
if "Basin" in prim.GetPath().pathString:
approximationShape = "convexDecomposition"
# convex decomp basin
stage = omni.usd.get_context().get_stage()
collision_api = UsdPhysics.MeshCollisionAPI.Get(stage, prim.GetPath())
if not collision_api:
collision_api = UsdPhysics.MeshCollisionAPI.Apply(prim)
collision_api.CreateApproximationAttr().Set(approximationShape)
# set up physical metarial
# add_physical_material_to("Basin")
if IS_IN_ISAAC_SIM:
add_update_semantics(prim, "Basin")
elif "Faucet" in prim.GetPath().pathString:
from .fluid.cup_data import FAUCET_INFO
faucet_id = prim.GetPath().pathString.split("_")[-1]
inflow_position = FAUCET_INFO[faucet_id]["inflow_pos"]
omni.kit.commands.execute(
"CreatePrim",
prim_path="/World/game/inflow",
prim_type="Xform",
select_new_prim=False,
)
inflow_xform = pxr.Gf.Matrix4d().SetTranslate(inflow_position)
omni.kit.commands.execute(
"TransformPrimCommand",
path="/World/game/inflow",
new_transform_matrix=inflow_xform,
)
stage = omni.usd.get_context().get_stage()
import re
link_pattern = re.compile('.*'+'link_[0-9]+$')
links = list(filter( lambda x : link_pattern.findall(x.GetPath().pathString) , list(stage.TraverseAll()) ))
for link in links:
add_mass_to_prim(link, 0.1)
if IS_IN_ISAAC_SIM:
add_update_semantics(prim, "Faucet")
def add_mass_to_prim(prim, mass:float=0.02, density:float=1):
stage = omni.usd.get_context().get_stage()
mass_api = UsdPhysics.MassAPI.Get(stage, prim.GetPath())
if not mass_api:
mass_api = UsdPhysics.MassAPI.Apply(prim)
mass_api.CreateMassAttr().Set(mass)
# mass_api.CreateDensityAttr().Set(density)
else:
mass_api.GetMassAttr().Set(mass)
# mass_api.GetDensityAttr().Set(density)
def setup_physics_material(prim):
"""
Set up physic material for prim at Path
"""
# def _setup_physics_material(self, path: Sdf.Path):
stage = omni.usd.get_context().get_stage()
_material_static_friction = 100.0
_material_dynamic_friction = 100.0
_material_restitution = 0.0
_physicsMaterialPath = None
if _physicsMaterialPath is None:
# _physicsMaterialPath = stage.GetDefaultPrim().GetPath().AppendChild("physicsMaterial")
_physicsMaterialPath = prim.GetPath().AppendChild("physicsMaterial")
# print("physics_material_path: ", _physicsMaterialPath)
UsdShade.Material.Define(stage, _physicsMaterialPath)
material = UsdPhysics.MaterialAPI.Apply(stage.GetPrimAtPath(_physicsMaterialPath))
material.CreateStaticFrictionAttr().Set(_material_static_friction)
material.CreateDynamicFrictionAttr().Set(_material_dynamic_friction)
material.CreateRestitutionAttr().Set(_material_restitution)
collisionAPI = UsdPhysics.CollisionAPI.Get(stage, prim.GetPath())
# prim = stage.GetPrimAtPath(path)
if not collisionAPI:
collisionAPI = UsdPhysics.CollisionAPI.Apply(prim)
# apply material
physicsUtils.add_physics_material_to_prim(stage, prim, _physicsMaterialPath)
print("physics material: path: ", _physicsMaterialPath)
def add_ground_plane(prim_path = "/World/game", visiable = False):
stage = omni.usd.get_context().get_stage()
ground_prim = stage.GetPrimAtPath("/World/groundPlane")
if not ground_prim: #IS_IN_ISAAC_SIM:
purposes = [pxr.UsdGeom.Tokens.default_]
bboxcache = pxr.UsdGeom.BBoxCache(pxr.Usd.TimeCode.Default(), purposes)
prim = stage.GetPrimAtPath(prim_path)
bboxes = bboxcache.ComputeWorldBound(prim)
# print("bboxes", bboxes)
y = bboxes.ComputeAlignedRange().GetMin()[1]
physicsUtils.add_ground_plane(stage, "/World/groundPlane", "Y", 750.0, pxr.Gf.Vec3f(0.0, y, 0), pxr.Gf.Vec3f(0.2))
# select ground
selection = omni.usd.get_context().get_selection()
selection.clear_selected_prim_paths()
selection.set_prim_path_selected("/World/groundPlane", True, True, True, True)
ground_prim = stage.GetPrimAtPath("/World/groundPlane")
visibility = "visible" if visiable else 'invisible'
ground_prim.GetAttribute('visibility').Set(visibility)
# prim_list = list(stage.TraverseAll())
# prim_list = [ item for item in prim_list if 'groundPlane' in item.GetPath().pathString and item.GetTypeName() == 'Mesh' ]
# for prim in prim_list:
# prim.GetAttribute('visibility').Set('invisible')
# else:
# # prim_path = stage.GetDefaultPrim().GetPath().pathString
# usd_context = omni.usd.get_context()
# bboxes = usd_context.compute_path_world_bounding_box(prim_path)
# physicsUtils.add_ground_plane(stage, "/groundPlane", "Y", 750.0, pxr.Gf.Vec3f(0.0, bboxes[0][1], 0), pxr.Gf.Vec3f(0.2))
def add_physical_material_to(keyword:str):
"""
Set up physical material
"""
stage = omni.usd.get_context().get_stage()
prim_list = list(stage.TraverseAll())
prim_list = [ item for item in prim_list if keyword in item.GetPath().pathString and 'visuals' not in item.GetPath().pathString ]
for prim in prim_list:
setup_physics_material(prim)
print("add physics material to handle")
setStaticCollider(prim, approximationShape = "convexDecomposition")
def fix_handle(keyword):
"""
Set up physical material
and change collision type ot covex decomposition
"""
stage = omni.usd.get_context().get_stage()
prim_list = list(stage.TraverseAll())
#=========================
prim_list = [ item for item in prim_list if keyword in item.GetPath().pathString and \
'handle' in item.GetPath().pathString and item.GetTypeName() == 'Mesh' ]
# print("prim_list: ", prim_list)
for prim in prim_list:
setStaticCollider(prim, approximationShape = "convexDecomposition")
setup_physics_material(prim)
# table = {}
# for prim_path in prim_list:
# prefix, suffix = "/".join(prim_path.split('/')[:-1]), prim_path.split('/')[-1]
# if prefix not in table:
# table[prefix] = []
# table[prefix].append(suffix)
# for prefix, value in table.items():
# handle = value[-1]
# import os
# from omni.isaac.core.utils.prims import get_prim_at_path
# handle_path =str(os.path.join(prefix, handle))
# handle_prim = get_prim_at_path(handle_path)
# setup_physics_material(handle_prim)
# setStaticCollider(handle_prim, approximationShape = "convexDecomposition")
#=================================
# prim_list = list(stage.TraverseAll())
# prim_list = [ item for item in prim_list if keyword in item.GetPath().pathString and \
# 'visuals' in item.GetPath().pathString and item.GetTypeName() == 'Mesh' ]
# print(prim_list)
# for prim in prim_list:
# setup_physics_material(prim)
# setStaticCollider(prim, approximationShape = "convexDecomposition")
def remove_collider_to(keyword:str):
"""
Set up physical material
"""
stage = omni.usd.get_context().get_stage()
prim_list = list(stage.TraverseAll())
prim_list = [ item for item in prim_list if keyword in item.GetPath().pathString ]
for prim in prim_list:
removeCollider(prim.GetPath().pathString)
|
yizhouzhao/VRKitchen2.0-IndoorKit/exts/vrkitchen.indoor.kit/vrkitchen/indoor/kit/layout/fix_house_legacy.txt | ### do not delete this file
## UI design for house fixing
ui.Label("\n Fix house", height=30, style = {"font_size": 20}, alignment=ui.Alignment.CENTER, visible=False)
with ui.HStack(height=30, visible=False):
ui.Button("Fix material path", clicked_fn=self.fix_material_path)
ui.Button("Add default light", clicked_fn=self.add_default_light)
with ui.HStack(height=30, visible=False):
ui.Label("Fix house start index:", width=100)
self.house_start_index_ui = omni.ui.IntField(
height= 20,
style={ "margin": 8, "padding_height": 18 },
)
self.house_start_index_ui.model.set_value(100)
ui.Button("Fix all", height = 20, clicked_fn=self.fix_all_houses, style={ "margin": 8})
ui.Label("\n Fix Storage", height=30, style = {"font_size": 20}, alignment=ui.Alignment.CENTER, visible=False)
with ui.HStack(height=30):
ui.Label("Storage folder: ", width=20)
self.storage_folder_ui = omni.ui.StringField(height=20, style={ "margin_height": 8 })
self.storage_folder_ui.model.set_value(STORAGE_ASSET_PATH)
with ui.HStack(height=30, visible=False):
ui.Button("Fix unit/axis", clicked_fn=self.fix_unit_and_axis, height = 30)
ui.Button("Fix linear joint", clicked_fn=self.fix_linear_joint, height = 30)
with ui.HStack(height=30, visible=False):
ui.Label("Fix storage start index:",width=100)
self.storage_start_index_ui = omni.ui.IntField(
height= 20, width = 80,
style={ "margin": 8, "padding_height": 18 },
)
self.storage_start_index_ui.model.set_value(46440)
ui.Button("Fix all storage", clicked_fn=self.fix_all_storages)
### functions
def fix_material_path(self):
self.stage = omni.usd.get_context().get_stage()
looks_prim = self.stage.GetPrimAtPath("/World/Looks")
print("looks", looks_prim.GetPath())
for index, prim in enumerate(looks_prim.GetChildren()):
prim_path = str(prim.GetPath())
wire_name = prim_path.split("/")[-1]
mat_prim = self.stage.GetPrimAtPath("/World/Looks" + "/" + wire_name + "/" + wire_name)
if mat_prim:
# print("mat_prim", mat_prim)
attr = mat_prim.GetAttribute("inputs:diffuse_texture").Get()
if attr:
new_asset_path = str(attr).replace(":","_").replace("@","")
mat_prim.CreateAttribute("inputs:diffuse_texture", pxr.Sdf.ValueTypeNames.String,
False).Set(new_asset_path)
# # print("prim: ", prim)
# test_prim = self.stage.GetPrimAtPath("/World/Looks/component_45146_solid_001_wire1/component_45146_solid_001_wire1")
# # shader = pxr.UsdShade.Shader(test_prim)
# # asset = shader.GetSourceAsset("mdl")
# # print("shader", asset)
# attr = test_prim.GetAttribute("inputs:diffuse_texture").Get()
# new_asset_path = str(attr).replace(":","_").replace("@","")
# print("attr", str(attr), new_asset_path)
# test_prim.CreateAttribute("inputs:diffuse_texture", pxr.Sdf.ValueTypeNames.String, False).Set(new_asset_path)
# # print(attr.GetTypeName())
def add_default_light(self):
# prim_path=f"{self.stage.GetDefaultPrim().GetPath().pathString}/defaultLight"
# carb.log_info("light prim path: " + prim_path)
omni.kit.commands.execute(
"CreatePrim",
prim_path="/World/defaultLight",
prim_type="DistantLight",
select_new_prim=False,
attributes={pxr.UsdLux.Tokens.angle: 1.0, pxr.UsdLux.Tokens.intensity: 500},
create_default_xform=True,
)
def fix_unit_and_axis(self):
# carb.log_info("Up axis: y Unit: 1.00s")
self.stage = omni.usd.get_context().get_stage()
pxr.UsdGeom.SetStageUpAxis(self.stage, UsdGeom.Tokens.y)
default_prim = self.stage.GetDefaultPrim()
default_xform = pxr.UsdGeom.Xformable.Get(self.stage, default_prim.GetPath())
#default_xform.ClearXformOpOrder()
#translate_component = default_xform.AddXformOp(pxr.UsdGeom.XformOp.TypeTranslate)
#rotation_translate = default_xform.AddXformOp(pxr.UsdGeom.XformOp.TypeTranslate)
# print("GetXformOpOrderAttr", default_xform.GetXformOpOrderAttr())
translate_component = default_xform.GetOrderedXformOps()[0]
orient_component = default_xform.GetOrderedXformOps()[1]
scale_component = default_xform.GetOrderedXformOps()[2]
# print(translate_component.Get())
# print(orient_component.Get())
# print(scale_component.Get())
scale_component.Set((100, 100, 100))
orient_component.Set(pxr.Gf.Quatd(0.7071067811865475, -0.7071067811865476, 0, 0))
def fix_all_storages(self):
storage_asset_path = self.storage_folder_ui.model.get_value_as_string()
storage_start_index = self.storage_start_index_ui.model.get_value_as_int()
async def fix_storages():
for c, storage_folder in enumerate(os.listdir(storage_asset_path)):
if int(storage_folder) < storage_start_index:
continue
storage_usd_path = os.path.join(storage_asset_path, storage_folder, "mobility.usd")
success, error = await omni.usd.get_context().open_stage_async(storage_usd_path)
if not success:
raise Exception(f"Failed to open usd file: {error}")
await omni.kit.app.get_app().next_update_async()
self.fix_unit_and_axis()
self.fix_linear_joint()
(result, err, saved_layers) = await omni.usd.get_context().save_as_stage_async(storage_usd_path)
asyncio.ensure_future(fix_storages())
def fix_all_houses(self):
house_info_path = self.house_info_path_ui.model.get_value_as_string()
async def fix_houses():
for house_folder in os.listdir(house_info_path):
house_start_index = self.house_start_index_ui.model.get_value_as_int()
if int(house_folder) < house_start_index:
continue
house_layout_usd_path = os.path.join(house_info_path, house_folder, "layout.usd")
success, error = await omni.usd.get_context().open_stage_async(house_layout_usd_path)
if not success:
raise Exception(f"Failed to open usd file: {error}")
await omni.kit.app.get_app().next_update_async()
stage = omni.usd.get_context().get_stage()
prim_list = stage.TraverseAll()
has_light = False
for prim in prim_list:
# lowercase string
if "/world/defaultlight" in prim.GetPath().pathString.lower():
has_light = True
break
carb.log_info(f"House at {house_folder}; Has light {has_light}")
# if has light, the scene is fixed
if not has_light:
self.add_default_light()
self.fix_material_path()
time.sleep(5)
(result, err, saved_layers) = await omni.usd.get_context().save_as_stage_async(house_layout_usd_path)
asyncio.ensure_future(fix_houses())
async def load_world_async(self):
"""Function called when clicking load buttton
"""
if World.instance() is None:
# await create_new_stage_async()
# self._world = World(**self._world_settings)
self._world = World()
await self._world.init_simulation_context_async()
else:
self._world = World.instance()
await self._world.reset_async()
await self._world.pause_async()
pxr.UsdGeom.SetStageUpAxis(get_current_stage(), pxr.UsdGeom.Tokens.y)
return
## randomization
# ui.Label("\n Randomization", height=30, style = {"font_size": 20}, alignment=ui.Alignment.CENTER)
# with ui.HStack(height=30):
# ui.Button("Randomize light", clicked_fn=self.randomize_light, style={ "margin": 8})
# ui.Button("Randomize material", clicked_fn=self.randomize_material, style={ "margin": 8})
# ui.Button("Randomize offset", clicked_fn=self.randomize_offset, style={ "margin": 8})
# with ui.HStack(height=30):
# ui.Button("Record game offset", clicked_fn=self.randomize_option, style={ "margin_bottom": 8})
def randomize_material(self):
"""
randomize mobility materials
"""
self.randomize_option("material")
def randomize_light(self):
self.randomize_option("light")
def randomize_offset(self):
self.randomize_option("offset")
def randomize_option(self, option:str="record"):
"""
Randomize scene conditions with option
::param:
option: light, material, game location
if option == record:
record game position and rotation
"""
# load json info from example
task_index = self.task_type_ui.model.get_item_value_model().get_value_as_int()
task_type = self.task_types[task_index]
task_id = self.task_id_ui.model.get_value_as_int()
house_id = self.house_id_ui.model.get_value_as_int()
object_id = self.object_id_ui.model.get_value_as_int()
task_json = os.path.join(DATA_PATH, "tasks", task_type, str(house_id), str(object_id), str(task_id) + ".json")
# print("task_randomization_json_path: ", task_json)
if not hasattr(self, "randomizer"):
self.randomizer = Randomizer(task_json)
if option == "light":
print("randomize lighting condition")
self.randomizer.randomize_light()
elif option == "material":
self.randomizer.randomize_material()
elif option == "offset":
self.randomizer.randomize_game_location()
else:
# record game offset
self.randomizer.record_game_offset()
self.randomizer.record_randomization()
# def check_grasp(self):
# if self.franka is None:
# import sys
# print( "please setup robot first", file=sys.stderr)
# return
# self.franka.check_grasp()
def delete_house(self):
"""
Delete house info json from house id
"""
house_id = self.house_id_ui.model.get_value_as_int()
os.remove(os.path.join(DATA_PATH, "house", f"{house_id}.json"))
print(f"House {house_id} removed!")
def delete_task(self):
"""
Delete house info json from house id
"""
task_index = self.task_type_ui.model.get_item_value_model().get_value_as_int()
task_type = self.task_types[task_index]
house_id = self.house_id_ui.model.get_value_as_int()
object_id = self.object_id_ui.model.get_value_as_int()
task_id = self.task_id_ui.model.get_value_as_int()
os.remove(os.path.join(DATA_PATH, "tasks", task_type, str(house_id), str(object_id), f"{task_id}.json"))
print(f"Task {task_type}/{house_id}/{object_id}/{task_id} removed!")
def record_house(self):
# setup house layout recorder
self.build_house_info()
self.house.get_asset_info()
self.house.save_asset_info()
def record_task(self, overwrite=True):
task = {}
if self.stage.GetPrimAtPath("/World/game/franka"):
# if has robot
task["robot"] = self.get_robot_info("/World/game/franka")
elif self.stage.GetPrimAtPath("/World/franka"):
# if has robot
task["robot"] = self.get_robot_info("/World/franka")
else:
raise Exception(f"Robot not found: franka must be in /World or /World/game!")
# set task info
task["house_id"] = self.house_id_ui.model.get_value_as_int()
task["object_id"] = self.object_id_ui.model.get_value_as_int()
task_index = self.task_type_ui.model.get_item_value_model().get_value_as_int()
task["task_type"] = self.task_types[task_index]
task["task_id"] = self.task_id_ui.model.get_value_as_int()
# output to json file
if overwrite:
filename = os.path.join(DATA_PATH, "tasks", task["task_type"], str(task["house_id"]), str(task["object_id"]), str(task["task_id"]) + ".json")
os.makedirs(os.path.dirname(filename), exist_ok=True)
with open(filename, "w") as f:
json.dump(task, f, sort_keys=True, indent=4)
def load_house(self):
"""
Load house information from house id
"""
# load layout information and set up layout
house_id = self.house_id_ui.model.get_value_as_int()
object_id = self.object_id_ui.model.get_value_as_int()
self.build_house_info()
self.house.load_asset_info(house_id, object_id)
# fix linear joint scale
self.fix_linear_joint(fix_driver=True)
#asyncio.ensure_future(load_house_async())
def build_house_info(self):
# scene_asset_path = self.scene_asset_path_ui.model.get_value_as_string()
sapien_asset_path = self.sapien_asset_path_ui.model.get_value_as_string()
house_info_path = self.house_info_path_ui.model.get_value_as_string()
self.house = House(DATA_PATH, sapien_asset_path, house_info_path)
self.house.set_id(self.house_id_ui.model.get_value_as_int())
# self.house.set_task(task_type)
## miror task legacy
default_task_index = self.task_types.index("put_object_into_box")
self.task_type_ui.model.get_item_value_model().set_value(default_task_index)
self.load_obj_new()
task_index = self.task_type_ui.model.get_item_value_model().get_value_as_int()
task_type = self.task_types[task_index]
task_id = self.task_id_ui.model.get_value_as_int()
missions = json.load(open(os.path.join(DATA_PATH_NEW, "task", task_type, str(task_id), "missions.json")))
mission_info = list(missions.values())[0]
print("mission_info", mission_info)
joint_name = mission_info["goal"]["condition"]["joint"]
mobility_name = mission_info["goal"]["condition"]["target"]
# self.stage = omni.usd.get_context().get_stage()
# prim_list = list(self.stage.TraverseAll())
# joint_list = [ item for item in prim_list if joint_name in
# item.GetPath().pathString and item.GetPath().pathString.startswith("/World/game/" + mobility_name)]
# print("joint_list", joint_list)
# assert len(joint_list) == 1
mobility_prim_path = "/World/game/" + mobility_name
# print("mobility_prim_path", mobility_prim_path)
# selection = omni.usd.get_context().get_selection()
# selection.clear_selected_prim_paths()
# selection.set_prim_path_selected(joint_list[0].GetPath().pathString, True, True, True, True)
# selection.set_prim_path_selected(mobility_prim_path, True, True, True, True)
xform = pxr.Gf.Matrix4d().SetTranslate([0,0,0])
omni.kit.commands.execute(
"TransformPrimCommand",
path=mobility_prim_path,
new_transform_matrix=xform,
)
default_task_index = self.task_types.index("take_object_out_box")
self.task_type_ui.model.get_item_value_model().set_value(default_task_index)
# self.auto_add_robot()
# self.record_obj_new()
# self.record_robot_new()
# self.auto_add_task()
# omni.usd.get_context().new_stage_async()
# omni.kit.app.get_app().next_update_async()
## fix collision/rigid body
from omni.physx.scripts.utils import setCollider, setRigidBody, setStaticCollider
async def fix_something():
asset_path = os.path.join(CUSTOM_ASSET_PATH, "Cup")
for asset in sorted(os.listdir(asset_path), key = lambda x: int(x)):
if int(asset) < 1:
continue
usd_path = os.path.join(asset_path, asset, "cup.usd")
success, error = await omni.usd.get_context().open_stage_async(usd_path)
if not success:
raise Exception(f"Failed to open usd file: {error}")
await omni.kit.app.get_app().next_update_async()
await asyncio.sleep(2)
stage = omni.usd.get_context().get_stage()
prim = stage.GetPrimAtPath("/cup/cupShape")
print("setRigidBody")
setRigidBody(prim, "convexDecomposition", False)
(result, err, saved_layers) = await omni.usd.get_context().save_as_stage_async(usd_path)
# break
asyncio.ensure_future(fix_something())
# auto add task
async def generate_pour_water_task():
self.auto_add_obj()
self.auto_add_robot()
await asyncio.sleep(1.0)
self.record_obj_new()
self.record_robot_new()
self.auto_add_task()
await asyncio.sleep(1.0)
self.auto_next_obj_only()
await asyncio.sleep(2.0)
self.add_mission_variances()
asyncio.ensure_future(generate_pour_water_task())
# -------------------------------------replay------------------------------------
# asyncio.ensure_future(fix_houses())
BaseChecker.IS_REPLAY = True # Set up task checker status
# load mission and replay
BaseChecker.IS_REPLAY = True # Set up task checker status
self.load_mission()
"""
Replay trajectory
"""
if self.franka is None:
import sys
print( "please setup robot first", file=sys.stderr)
return
# example_id = self.house_id_ui.model.get_value_as_int()
# room_layout_json = os.path.join(DATA_PATH, str(example_id) + ".json")
# if not os.path.exists(room_layout_json):
# raise Exception( "The json file at path {} provided wasn't found".format(room_layout_json) )
# layout = json.load(open(room_layout_json))
# root_dir = SAVE_ROOT + layout["task"] + "-" + str(layout["task_id"])
task_index = self.task_type_ui.model.get_item_value_model().get_value_as_int()
task_type = self.task_types[task_index]
task_id = self.task_id_ui.model.get_value_as_int()
robot_id = self.robot_id_ui.model.get_value_as_int()
mission_id = self.mission_id_ui.model.get_value_as_int()
trial_id = self.trial_id_ui.model.get_value_as_int()
house_id = self.house_id_ui.model.get_value_as_int()
anchor_id = self.anchor_id_ui.model.get_value_as_int()
annotator_index = self.annotator_ui.model.get_item_value_model().get_value_as_int()
annotator = ANNOTATORS[annotator_index]
# root_dir = SAVE_ROOT + task_type + "-" + str(task_id) + "-" + str(robot_id) + "-" + str(mission_id) + "_" + str(trial_id)
root_dir = '-'.join([str(os.path.join(SAVE_ROOT, annotator, task_type)),str(task_id), \
str(robot_id), str(mission_id), str(house_id), str(anchor_id), str(trial_id) ])
print("root_dir", root_dir)
traj_dir = os.path.join(root_dir, TRAJ_FOLDER)
self.timeline.play()
FrankabotGamePad.DISCREET_CONTROL = True
self.franka.replay(traj_dir) |
yizhouzhao/VRKitchen2.0-IndoorKit/exts/vrkitchen.indoor.kit/vrkitchen/indoor/kit/layout/param.py | from ..param import ROOT, APP_VERION |
yizhouzhao/VRKitchen2.0-IndoorKit/exts/vrkitchen.indoor.kit/vrkitchen/indoor/kit/layout/fluid/cup_setup.py | import math
import os
from ..param import ROOT as root
from ...param import IS_IN_ISAAC_SIM, APP_VERION, USE_ISO_SURFACE
import carb
import omni
import pxr
from pxr import Gf, UsdPhysics, Sdf, Usd, UsdGeom, PhysxSchema, Vt
from omni.physx.scripts import utils, physicsUtils
if APP_VERION.startswith("2022"):
from omni.physx.scripts import particleUtils
import numpy as np
from .constants import PARTICLE_PROPERTY
# from omni.isaac.core.utils.stage import add_reference_to_stage
from .schemaHelpers import addPhysxParticleSystem, addPhysxParticlesSimple, PhysxParticleInstancePrototype
from .utils import generate_cylinder_y, generate_inside_point_cloud, get_quat_from_extrinsic_xyz_rotation
from .cup_data import CUP_PARTICLE_INFO
def setGridFilteringPass(gridFilteringFlags: int, passIndex: int, operation: int, numRepetitions: int = 1):
numRepetitions = max(0, numRepetitions - 1)
shift = passIndex * 4
gridFilteringFlags &= ~(3 << shift)
gridFilteringFlags |= (((operation) << 2) | numRepetitions) << shift
return gridFilteringFlags
class CupFluidHelper():
def __init__(self, use_isosurface = USE_ISO_SURFACE, cup_id = 0, r = 0.1, g = 0.4, b =0.6, material = None, height = None) -> None:
self.stage = omni.usd.get_context().get_stage()
self.cup_id = cup_id
self.rgb =[r,g,b]
self.material = material
self.height = height
self.use_isosurface = use_isosurface
def create(self):
# needs to be called first: set_up_fluid_physical_scene
self.set_up_fluid_physical_scene()
self.set_cup()
self.set_up_particle_system()
self.set_color()
self.set_particle_offset()
def modify_cup_scene(self, cup_prim, add_liquid = True, set_physics=True):
"""
Modify cup scene given the cup_prim,
1. setup physical scene and fluid scene
2. add particles
:param::
: cup_prim
"""
print("modify cup at path: ", cup_prim.GetPath().pathString)
game_prim = cup_prim.GetParent()
# set up physical
self.set_up_fluid_physical_scene()
carb.log_warn("APP_VERION 1: " + APP_VERION)
# modify particleSystemStr
if add_liquid:
particleSystemStr = "/World/Fluid" # game_prim.GetPath().AppendPath("Fluid").pathString
self.particleSystemPath = pxr.Sdf.Path(particleSystemStr)
self.particleInstanceStr = game_prim.GetPath().AppendPath("Particles").pathString
# modify cup
cup_shape_prim_path = cup_prim.GetPath().AppendPath("cupShape").pathString
cup_shape_prim = self.stage.GetPrimAtPath(cup_shape_prim_path)
cup_volume_prim_path = cup_prim.GetPath().AppendPath("cup_volume").pathString
cup_volume_prim = self.stage.GetPrimAtPath(cup_volume_prim_path)
if not cup_shape_prim:
raise Exception(f"Cup shape must exist at path {cup_shape_prim_path}")
# if IS_IN_ISAAC_SIM :
# from omni.isaac.core.utils.semantics import add_update_semantics
# add_update_semantics(cup_shape_prim, "Cup")
# utils.setPhysics(prim=cup_shape_prim, kinematic=False)
# utils.setCollider(prim=cup_shape_prim, approximationShape="convexDecomposition")
# if not set_physics:
# physicsAPI = UsdPhysics.RigidBodyAPI.Apply(cup_shape_prim)
# physicsAPI.CreateRigidBodyEnabledAttr(False)
physxCollisionAPI = pxr.PhysxSchema.PhysxCollisionAPI.Get(self.stage, cup_shape_prim.GetPath())
if not physxCollisionAPI:
physxCollisionAPI = pxr.PhysxSchema.PhysxCollisionAPI.Apply(cup_shape_prim)
self._setup_physics_material(cup_shape_prim.GetPath())
# Mug parameters
restOffset = PARTICLE_PROPERTY._cup_rest_offset
contactOffset = PARTICLE_PROPERTY._cup_contact_offset
assert physxCollisionAPI.GetRestOffsetAttr().Set(restOffset)
assert physxCollisionAPI.GetContactOffsetAttr().Set(contactOffset)
assert cup_shape_prim.CreateAttribute("physxMeshCollision:minThickness", pxr.Sdf.ValueTypeNames.Float).Set(0.001)
self._fluidPositionOffset = Gf.Vec3f(0,0,0)
massAPI = UsdPhysics.MassAPI.Apply(cup_shape_prim)
massAPI.GetMassAttr().Set(PARTICLE_PROPERTY._cup_mass)
# utils.setPhysics(prim=cup_prim, kinematic=False)
utils.removeRigidBody(cup_shape_prim)
utils.setRigidBody(cup_prim, "convexDecomposition", False)
utils.removeCollider(cup_volume_prim)
# add material
# create material 2
mtl_created_list = []
omni.kit.commands.execute(
"CreateAndBindMdlMaterialFromLibrary",
mdl_name="OmniGlass.mdl",
mtl_name="OmniGlass",
mtl_created_list=mtl_created_list,
)
mtl_path = mtl_created_list[0]
omni.kit.commands.execute(
"BindMaterial", prim_path=pxr.Sdf.Path(cup_shape_prim_path), material_path=mtl_path, strength=pxr.UsdShade.Tokens.strongerThanDescendants
)
if add_liquid:
self.volume_mesh = pxr.UsdGeom.Mesh.Get(self.stage, cup_prim.GetPath().AppendPath(f"cup_volume"))
self.set_up_particle_system()
carb.log_warn("APP_VERION 1: " + APP_VERION)
self.set_color()
from omni.physx import acquire_physx_interface
physx = acquire_physx_interface()
physx.overwrite_gpu_setting(1)
physx.reset_simulation()
def set_up_fluid_physical_scene(self, gravityMagnitude = PARTICLE_PROPERTY._gravityMagnitude):
"""
Fluid / PhysicsScene
"""
default_prim_path = self.stage.GetDefaultPrim().GetPath()
if default_prim_path.pathString == '':
# default_prim_path = pxr.Sdf.Path('/World')
root = UsdGeom.Xform.Define(self.stage, "/World").GetPrim()
self.stage.SetDefaultPrim(root)
default_prim_path = self.stage.GetDefaultPrim().GetPath()
# if self.stage.GetPrimAtPath("/World/physicsScene"):
# self.physicsScenePath = default_prim_path.AppendChild("physicsScene")
# return
particleSystemStr = default_prim_path.AppendPath("Fluid").pathString
self.physicsScenePath = default_prim_path.AppendChild("physicsScene")
self.particleSystemPath = pxr.Sdf.Path(particleSystemStr)
self.particleInstanceStr = default_prim_path.AppendPath("Particles").pathString
# Physics scene
self._gravityMagnitude = gravityMagnitude # IN CM/s2 - use a lower gravity to avoid fluid compression at 60 FPS
self._gravityDirection = Gf.Vec3f(0.0, -1.0, 0.0)
physicsScenePath = default_prim_path.AppendChild("physicsScene")
if self.stage.GetPrimAtPath("/World/physicsScene"):
scene = UsdPhysics.Scene.Get(self.stage, physicsScenePath)
else:
scene = UsdPhysics.Scene.Define(self.stage, physicsScenePath)
scene.CreateGravityDirectionAttr().Set(self._gravityDirection)
scene.CreateGravityMagnitudeAttr().Set(self._gravityMagnitude)
physxSceneAPI = PhysxSchema.PhysxSceneAPI.Apply(scene.GetPrim())
physxSceneAPI.CreateEnableCCDAttr().Set(True)
physxSceneAPI.GetTimeStepsPerSecondAttr().Set(60)
physxSceneAPI.CreateEnableGPUDynamicsAttr().Set(True)
physxSceneAPI.CreateEnableEnhancedDeterminismAttr().Set(True)
def set_up_particle_system(self):
self._fluidSphereDiameter = PARTICLE_PROPERTY._fluidSphereDiameter
self._particleSystemSchemaParameters = PARTICLE_PROPERTY._particleSystemSchemaParameters
self._particleSystemAttributes = PARTICLE_PROPERTY._particleSystemAttributes
if APP_VERION.startswith("2022"):
self._particleSystem = particleUtils.add_physx_particle_system(
self.stage, self.particleSystemPath, **self._particleSystemSchemaParameters, simulation_owner=Sdf.Path(self.physicsScenePath.pathString)
)
# materialPathStr = "/World/Looks/OmniGlass"
# particleUtils.add_pbd_particle_material(self.stage, materialPathStr, **PARTICLE_PROPERTY._particleMaterialAttributes)
# physicsUtils.add_physics_material_to_prim(self.stage, self._particleSystem.GetPrim(), materialPathStr)
else:
addPhysxParticleSystem(
self.stage, self.particleSystemPath, **self._particleSystemSchemaParameters, \
scenePath=pxr.Sdf.Path(self.physicsScenePath.pathString)
)
particleSystem = self.stage.GetPrimAtPath(self.particleSystemPath)
if APP_VERION.startswith("2022"):
pass
else:
for key, value in self._particleSystemAttributes.items():
particleSystem.GetAttribute(key).Set(value)
particleInstancePath = pxr.Sdf.Path(self.particleInstanceStr)
proto = PhysxParticleInstancePrototype()
proto.selfCollision = True
proto.fluid = True
proto.collisionGroup = 0
proto.mass = PARTICLE_PROPERTY._particle_mass
protoArray = [proto]
positions_list = []
velocities_list = []
protoIndices_list = []
lowerCenter = pxr.Gf.Vec3f(0, 0, 0)
particle_rest_offset = self._particleSystemSchemaParameters["fluid_rest_offset"]
####################################
if not hasattr(self, "volume_mesh") or self.volume_mesh is None: # not "volume_container" in CUP_PARTICLE_INFO[self.cup_id]:
################DATA####################
if self.height is None:
cylinder_height = CUP_PARTICLE_INFO[self.cup_id]["cylinder_height"]
else:
cylinder_height = self.height
cylinder_radius = CUP_PARTICLE_INFO[self.cup_id]["cylinder_radius"]
positions_list = generate_cylinder_y(lowerCenter, h=cylinder_height, radius=cylinder_radius, sphereDiameter=particle_rest_offset * 2.0)
# positions_list = generate_inside_mesh(lowerCenter, h=cylinder_height, radius=cylinder_radius,
# sphereDiameter=particle_rest_offset * 2.0, mesh= self.mesh, scale=self.scale)
else:
self.cloud_points = np.array(self.volume_mesh.GetPointsAttr().Get())
# two crowded, add 0.08
positions_list = generate_inside_point_cloud(sphereDiameter=particle_rest_offset * (2.0 + 0.08), cloud_points = self.cloud_points, scale=1.0)
for _ in range(len(positions_list)):
# print("position:", positions_list[_])
velocities_list.append(pxr.Gf.Vec3f(0, 0, 0))
protoIndices_list.append(0)
# print("positions_list", len(positions_list))
# positions_list -= np.array([228, 0, -231])
# positions_list = positions_list.tolist()
self.positions_list = positions_list
protoIndices = pxr.Vt.IntArray(protoIndices_list)
positions = pxr.Vt.Vec3fArray(positions_list)
velocities = pxr.Vt.Vec3fArray(velocities_list)
# if APP_VERION.startswith("2022"):
# particleUtils.add_physx_particleset_pointinstancer(
# self.stage,
# particleInstancePath,
# positions,
# velocities,
# self.particleSystemPath,
# self_collision=True,
# fluid=True,
# particle_group=0,
# particle_mass=PARTICLE_PROPERTY._particle_mass,
# density=0.0,
# )
# else:
# addPhysxParticlesSimple(
# self.stage, particleInstancePath, protoArray, protoIndices, positions, velocities, self.particleSystemPath
# )
if self.use_isosurface:
print("isosurface settings")
particle_system = self._particleSystem
mtl_created = []
omni.kit.commands.execute(
"CreateAndBindMdlMaterialFromLibrary",
mdl_name="OmniSurfacePresets.mdl",
mtl_name="OmniSurface_ClearWater",
mtl_created_list=mtl_created,
)
pbd_particle_material_path = mtl_created[0]
omni.kit.commands.execute(
"BindMaterial", prim_path=self.particleSystemPath, material_path=pbd_particle_material_path
)
# Create a pbd particle material and set it on the particle system
particleUtils.add_pbd_particle_material(
self.stage,
pbd_particle_material_path,
cohesion=0.01,
viscosity=0.0091,
surface_tension=0.0074,
friction=0.1,
)
physicsUtils.add_physics_material_to_prim(self.stage, particle_system.GetPrim(), pbd_particle_material_path)
particle_system.CreateMaxVelocityAttr().Set(20)
# add particle anisotropy
anisotropyAPI = PhysxSchema.PhysxParticleAnisotropyAPI.Apply(particle_system.GetPrim())
anisotropyAPI.CreateParticleAnisotropyEnabledAttr().Set(True)
aniso_scale = 5.0
anisotropyAPI.CreateScaleAttr().Set(aniso_scale)
anisotropyAPI.CreateMinAttr().Set(1.0)
anisotropyAPI.CreateMaxAttr().Set(2.0)
# add particle smoothing
smoothingAPI = PhysxSchema.PhysxParticleSmoothingAPI.Apply(particle_system.GetPrim())
smoothingAPI.CreateParticleSmoothingEnabledAttr().Set(True)
smoothingAPI.CreateStrengthAttr().Set(0.5)
fluidRestOffset = self._particleSystemSchemaParameters["rest_offset"]
# apply isosurface params
isosurfaceAPI = PhysxSchema.PhysxParticleIsosurfaceAPI.Apply(particle_system.GetPrim())
isosurfaceAPI.CreateIsosurfaceEnabledAttr().Set(True)
isosurfaceAPI.CreateMaxVerticesAttr().Set(1024 * 1024)
isosurfaceAPI.CreateMaxTrianglesAttr().Set(2 * 1024 * 1024)
isosurfaceAPI.CreateMaxSubgridsAttr().Set(1024 * 4)
isosurfaceAPI.CreateGridSpacingAttr().Set(fluidRestOffset * 1.5)
isosurfaceAPI.CreateSurfaceDistanceAttr().Set(fluidRestOffset * 1.6)
isosurfaceAPI.CreateGridFilteringPassesAttr().Set("")
isosurfaceAPI.CreateGridSmoothingRadiusAttr().Set(fluidRestOffset * 2)
isosurfaceAPI.CreateNumMeshSmoothingPassesAttr().Set(1)
primVarsApi = UsdGeom.PrimvarsAPI(particle_system)
primVarsApi.CreatePrimvar("doNotCastShadows", Sdf.ValueTypeNames.Bool).Set(True)
self.stage.SetInterpolationType(Usd.InterpolationTypeHeld)
particleUtils.add_physx_particleset_pointinstancer(
stage=self.stage,
path= particleInstancePath, #
positions=Vt.Vec3fArray(positions),
velocities=Vt.Vec3fArray(velocities),
particle_system_path=self.particleSystemPath,
self_collision=True,
fluid=True,
particle_group=0,
particle_mass=PARTICLE_PROPERTY._particle_mass,
density=0.0,
)
# if self.use_isosurface:
# particle_instance_prim = self.stage.GetPrimAtPath(particleInstancePath.pathString)
# # set partile up offset
# particles = pxr.UsdGeom.Xformable(particle_instance_prim)
# particles.AddTranslateOp()
def set_color(self):
# Set color
color_rgb = self.rgb#[0.1, 0.4, 0.6]
color = pxr.Vt.Vec3fArray([pxr.Gf.Vec3f(color_rgb[0], color_rgb[1], color_rgb[2])])
colorPathStr = self.particleInstanceStr + "/particlePrototype0"
gprim = pxr.UsdGeom.Sphere.Define(self.stage, pxr.Sdf.Path(colorPathStr))
gprim.CreateDisplayColorAttr(color)
# prototypePathStr = particleInstanceStr + "/particlePrototype0"
# gprim = UsdGeom.Sphere.Define(stage, Sdf.Path(prototypePathStr))
# gprim.CreateVisibilityAttr("invisible")
# TODO: debug transperency
gprim.CreateDisplayOpacityAttr([float(0.1)])
if self.use_isosurface:
gprim.GetPrim().GetAttribute('visibility').Set('invisible')
# usdPrim = stage.GetPrimAtPath(particleInstancePath)
usdPrim = self.stage.GetPrimAtPath(colorPathStr)
usdPrim.CreateAttribute("enableAnisotropy", pxr.Sdf.ValueTypeNames.Bool, True).Set(True)
usdPrim.CreateAttribute("radius", pxr.Sdf.ValueTypeNames.Double, True).Set(0.3)
gprim.GetRadiusAttr().Set(self._fluidSphereDiameter)
def set_cup(self):
# get cup info from data
abspath = CUP_PARTICLE_INFO[self.cup_id]["usd_path"]
mesh_name = CUP_PARTICLE_INFO[self.cup_id]["mesh_name"]
scale = CUP_PARTICLE_INFO[self.cup_id]["scale"]
particle_offset = CUP_PARTICLE_INFO[self.cup_id]["particle_offset"]
cup_offset = CUP_PARTICLE_INFO[self.cup_id]["cup_offset"]
self.scale = scale
default_prim_path = self.stage.GetDefaultPrim().GetPath()
self.stage.DefinePrim(default_prim_path.AppendPath(f"Cup")).GetReferences().AddReference(abspath)
mug = pxr.UsdGeom.Mesh.Get(self.stage, default_prim_path.AppendPath(f"Cup/{mesh_name}"))
utils.setPhysics(prim=mug.GetPrim(), kinematic=False)
utils.setCollider(prim=mug.GetPrim(), approximationShape="convexDecomposition")
if "volume_container" in CUP_PARTICLE_INFO[self.cup_id]:
volume_container = CUP_PARTICLE_INFO[self.cup_id]["volume_container"]
self.volume_mesh = pxr.UsdGeom.Mesh.Get(self.stage, default_prim_path.AppendPath(f"Cup/{volume_container}"))
prim = mug.GetPrim()
self.mug = mug
# self._setup_rb_collision_parameters(mug.GetPrim(), restOffset=self._mugRestOffset, contactOffset=self._mugContactOffset)
physxCollisionAPI = pxr.PhysxSchema.PhysxCollisionAPI.Get(self.stage, prim.GetPath())
if not physxCollisionAPI:
physxCollisionAPI = pxr.PhysxSchema.PhysxCollisionAPI.Apply(prim)
self._setup_physics_material(prim.GetPath())
# Mug parameters
restOffset = 0.0
contactOffset = 1.0
assert physxCollisionAPI.GetRestOffsetAttr().Set(restOffset)
assert physxCollisionAPI.GetContactOffsetAttr().Set(contactOffset)
assert prim.CreateAttribute("physxMeshCollision:minThickness", pxr.Sdf.ValueTypeNames.Float).Set(0.001)
# assert (
# mug.GetPrim().CreateAttribute("physxMeshCollision:maxConvexHulls", Sdf.ValueTypeNames.Float).Set(32)
# )
self._mugInitPos = Gf.Vec3f(cup_offset[0], cup_offset[1], cup_offset[2]) * scale
self._mugInitRot = get_quat_from_extrinsic_xyz_rotation(angleYrad=-0.7 * math.pi)
self._fluidPositionOffset = Gf.Vec3f(particle_offset[0], particle_offset[1], particle_offset[2])
self._mugScale = Gf.Vec3f(scale)
self._mugOffset = Gf.Vec3f(0, 0, 0) * scale
self.transform_mesh(mug, self._mugInitPos + self._mugOffset * 0, self._mugInitRot, self._mugScale)
massAPI = UsdPhysics.MassAPI.Apply(prim)
massAPI.GetMassAttr().Set(PARTICLE_PROPERTY._cup_mass)
def transform_mesh(self, mesh, loc, orient=pxr.Gf.Quatf(1.0), scale=pxr.Gf.Vec3d(1.0, 1.0, 1.0)):
for op in mesh.GetOrderedXformOps():
if op.GetOpType() == pxr.UsdGeom.XformOp.TypeTranslate:
op.Set(loc)
if op.GetOpType() == pxr.UsdGeom.XformOp.TypeOrient:
op.Set(orient)
if op.GetOpType() == pxr.UsdGeom.XformOp.TypeScale:
op.Set(scale)
def _setup_physics_material(self, path: pxr.Sdf.Path):
# and ground plane
self._material_static_friction = 10.0
self._material_dynamic_friction = 10.0
self._material_restitution = 0.0
self._physicsMaterialPath = None
if self._physicsMaterialPath is None:
self._physicsMaterialPath = self.stage.GetDefaultPrim().GetPath().AppendChild("physicsMaterial")
pxr.UsdShade.Material.Define(self.stage, self._physicsMaterialPath)
material = pxr.UsdPhysics.MaterialAPI.Apply(self.stage.GetPrimAtPath(self._physicsMaterialPath))
material.CreateStaticFrictionAttr().Set(self._material_static_friction)
material.CreateDynamicFrictionAttr().Set(self._material_dynamic_friction)
material.CreateRestitutionAttr().Set(self._material_restitution)
collisionAPI = pxr.UsdPhysics.CollisionAPI.Get(self.stage, path)
prim = self.stage.GetPrimAtPath(path)
if not collisionAPI:
collisionAPI = pxr.UsdPhysics.CollisionAPI.Apply(prim)
# apply material
physicsUtils.add_physics_material_to_prim(self.stage, prim, self._physicsMaterialPath)
|
yizhouzhao/VRKitchen2.0-IndoorKit/exts/vrkitchen.indoor.kit/vrkitchen/indoor/kit/layout/fluid/list_of_faucet_tested.txt | 156 fluid_fill = Faucet(particle_params=particle_params, iso_surface_params=iso_surface_params,
liquid_material_path = "/World/Looks/OmniSurface_ClearWater",
inflow_path = "/World/mobility/inflow",
link_paths = ["/World/mobility/link_1/joint_0"])
1034 fluid_fill = Faucet(particle_params=particle_params, iso_surface_params=iso_surface_params,
liquid_material_path = "/World/Looks/OmniSurface_ClearWater",
inflow_path = "/World/mobility/inflow",
link_paths = ["/World/mobility/link_1/joint_0"])
1052 fluid_fill = Faucet(particle_params=particle_params, iso_surface_params=iso_surface_params,
liquid_material_path = "/World/Looks/OmniSurface_ClearWater",
inflow_path = "/World/mobility/inflow",
link_paths = ["/World/mobility/link_2/joint_0"])
|
yizhouzhao/VRKitchen2.0-IndoorKit/exts/vrkitchen.indoor.kit/vrkitchen/indoor/kit/layout/fluid/new_faucet.py | import carb
import math
from pathlib import Path
import pxr
from pxr import Usd, UsdLux, UsdGeom, Sdf, Gf, Vt, UsdPhysics, PhysxSchema
import sys
#put schemaHelpers.py into path
from omni.kitchen.asset.layout.fluid.schemaHelpers import PhysxParticleInstancePrototype, \
addPhysxParticleSystem, addPhysxParticlesSimple
import omni.timeline
from typing import List
from omni.kitchen.asset.task_check.newJointCheck import JointCheck
import math
from .utils import generate_cylinder_y, point_sphere
from ...param import IS_IN_ISAAC_SIM
from .constants import PARTICLE_PROPERTY, particel_scale
from omni.physx.scripts import particleUtils
def setGridFilteringPass(gridFilteringFlags: int, passIndex: int, operation: int, numRepetitions: int = 1):
numRepetitions = max(0, numRepetitions - 1)
shift = passIndex * 4
gridFilteringFlags &= ~(3 << shift)
gridFilteringFlags |= (((operation) << 2) | numRepetitions) << shift
return gridFilteringFlags
class Faucet():
def __init__(self,
liquid_material_path = "/World/Looks/OmniSurface_ClearWater", inflow_path:str = "/World/faucet/inflow",
link_paths:List[str] = ["/World/faucet/link_0"]
):
"""! Faucet class
@param particle_params : parameters for particles
@param iso_surface_params: parameters for iso_surface
@param liquid_material_path: parameters for liquid materials
@param inflow_path: used to compute the location of water drops
@param link_paths: used to compute the rotation of faucet handle and determine the speed and size of water drops
@param particle_params: parameters related to particle systems
@return an instance of Faucet class
"""
# particle Instance path
# self.particleInstanceStr_tmp = "/particlesInstance"
# self.particle_params = particle_params
# self.iso_surface_params = iso_surface_params
self.liquid_material_path = liquid_material_path
# inflow position
self.stage = omni.usd.get_context().get_stage()
self.inflow_path = inflow_path
self.inflow_prim = self.stage.GetPrimAtPath(inflow_path)
mat = omni.usd.utils.get_world_transform_matrix(self.inflow_prim)
# if IS_IN_ISAAC_SIM:
# from omni.isaac.core.prims import XFormPrim
# self.inflow_position, _ = XFormPrim(self.inflow_path).get_world_pose()
# self.inflow_position = Gf.Vec3f(*self.inflow_position.tolist())
# else:
self.inflow_position = Gf.Vec3f(*mat.ExtractTranslation())
self.link_paths = link_paths
self.list_of_point_instancers = []
self.active_indexes_for_point_instancers = []
self.rate_checkers = []
for link in link_paths:
path = Path(link)
self.rate_checkers.append(JointCheck( str(path.parent), str(path.name) ))
self.create()
# print("particleSystemPath", self.particleSystemPath)
def is_off(self):
rate = self.rate_checkers[0].compute_distance()/100.0
return rate < 0.1
def point_sphere(self, samples, scale):
"""! create locations for each particles
@param samples: the number of particles per sphere
@param scale: the scale(radius) of the water drop
"""
indices = [x + 0.5 for x in range(0, samples)]
phi = [math.acos(1 - 2 * x / samples) for x in indices]
theta = [math.pi * (1 + 5**0.5) * x for x in indices]
x = [math.cos(th) * math.sin(ph) * scale for (th, ph) in zip(theta, phi)]
y = [math.sin(th) * math.sin(ph) * scale for (th, ph) in zip(theta, phi)]
z = [math.cos(ph) * scale for ph in phi]
points = [Gf.Vec3f(x, y, z) for (x, y, z) in zip(x, y, z)]
return points
def create_ball(self, rate = 1):
"""! create a water drop
@param pos: the center of the water drop
@param rate: the number of particles for each water drop
"""
# create sphere on points
self.set_up_particle_system(rate)
def set_up_particle_system(self, rate):
self.particleInstanceStr_tmp = self.particleInstanceStr + "/particlesInstance" + str(self.it)
particleInstancePath = omni.usd.get_stage_next_free_path(self.stage, self.particleInstanceStr_tmp, False)
particleInstancePath = pxr.Sdf.Path(particleInstancePath)
proto = PhysxParticleInstancePrototype()
proto.selfCollision = True
proto.fluid = True
proto.collisionGroup = 0
proto.mass = PARTICLE_PROPERTY._particle_mass
protoArray = [proto]
positions_list = []
velocities_list = []
protoIndices_list = []
cylinder_height = 2
cylinder_radius = 1.5
lowerCenter = Gf.Vec3f(0, -cylinder_height, 0) # self.inflow_position
# lowerCenter = self.inflow_position
particle_rest_offset = self._particleSystemSchemaParameters["fluid_rest_offset"]
positions_list = generate_cylinder_y(lowerCenter, h=cylinder_height, radius=cylinder_radius, sphereDiameter=particle_rest_offset * 4.0)
for _ in range(len(positions_list)):
velocities_list.append(pxr.Gf.Vec3f(0, 0, 0))
protoIndices_list.append(0)
# print("positions_list", len(positions_list))
self.positions_list = positions_list
protoIndices = pxr.Vt.IntArray(protoIndices_list)
positions = pxr.Vt.Vec3fArray(positions_list)
velocities = pxr.Vt.Vec3fArray(velocities_list)
print("particleInstancePath", particleInstancePath.pathString)
particleUtils.add_physx_particleset_pointinstancer(
self.stage,
particleInstancePath,
positions,
velocities,
self.particleSystemPath,
self_collision=True,
fluid=True,
particle_group=0,
particle_mass=PARTICLE_PROPERTY._particle_mass,
density=0.0,
)
prototypePath = particleInstancePath.pathString + "/particlePrototype0"
sphere = UsdGeom.Sphere.Define(self.stage, Sdf.Path(prototypePath))
spherePrim = sphere.GetPrim()
# spherePrim.GetAttribute('visibility').Set('invisible')
color_rgb = [207/255.0, 244/255.0, 254/255.0]
color = pxr.Vt.Vec3fArray([pxr.Gf.Vec3f(color_rgb[0], color_rgb[1], color_rgb[2])])
sphere.CreateDisplayColorAttr(color)
# spherePrim.CreateAttribute("enableAnisotropy", Sdf.ValueTypeNames.Bool, True).Set(True)
def create(self):
"""! initialize the related parameters for faucet
create physics scenes
create particle systems
create isosurface
"""
self._setup_callbacks()
self.it = 0
self.counter = 10
self.set_up_fluid_physical_scene()
def set_up_fluid_physical_scene(self, gravityMagnitude = 100.0):
"""
Fluid / PhysicsScene
"""
default_prim_path = self.stage.GetDefaultPrim().GetPath()
if default_prim_path.pathString == '':
# default_prim_path = pxr.Sdf.Path('/World')
root = UsdGeom.Xform.Define(self.stage, "/World").GetPrim()
self.stage.SetDefaultPrim(root)
default_prim_path = self.stage.GetDefaultPrim().GetPath()
self.stage = omni.usd.get_context().get_stage()
particleSystemStr = default_prim_path.AppendPath("Fluid").pathString
self.physicsScenePath = default_prim_path.AppendChild("physicsScene")
self.particleSystemPath = Sdf.Path(particleSystemStr)
self.particleInstanceStr = "/World/game/inflow"
# print("particleInstanceStr", self.particleInstanceStr)
# Physics scene
self._gravityMagnitude = gravityMagnitude
self._gravityDirection = Gf.Vec3f(0.0, -1.0, 0.0)
physicsScenePath = default_prim_path.AppendChild("physicsScene")
if self.stage.GetPrimAtPath('/World/physicsScene'):
scene = UsdPhysics.Scene.Get(self.stage, physicsScenePath)
else:
scene = UsdPhysics.Scene.Define(self.stage, physicsScenePath)
scene.CreateGravityDirectionAttr().Set(self._gravityDirection)
scene.CreateGravityMagnitudeAttr().Set(self._gravityMagnitude)
physxSceneAPI = PhysxSchema.PhysxSceneAPI.Apply(scene.GetPrim())
physxSceneAPI.CreateEnableCCDAttr().Set(True)
physxSceneAPI.GetTimeStepsPerSecondAttr().Set(120)
self._fluidSphereDiameter = PARTICLE_PROPERTY._fluidSphereDiameter #0.24
# solver parameters:
# self._solverPositionIterations = 10
# self._solverVelocityIterations = 10
# self._particleSystemSchemaParameters = {
# "contact_offset": 0.3,
# "particle_contact_offset": 0.25,
# "rest_offset": 0.25,
# "solid_rest_offset": 0,
# "fluid_rest_offset": 0.5 * self._fluidSphereDiameter + 0.03,
# "solver_position_iterations": self._solverPositionIterations,
# "solver_velocity_iterations": self._solverVelocityIterations,
# "wind": Gf.Vec3f(0, 0, 0),
# }
self._particleSystemSchemaParameters = PARTICLE_PROPERTY._particleSystemSchemaParameters
# self._particleSystemAttributes = {
# "cohesion": 7.4,
# "smoothing": 0.8,
# "anisotropyScale": 1.0,
# "anisotropyMin": 0.2,
# "anisotropyMax": 2.0,
# "surfaceTension": 2.0, #0.74,
# "vorticityConfinement": 0.5,
# "viscosity": 5.0,
# "particleFriction": 0.34,
# "maxParticles": 20000,
# }
self._particleSystemAttributes = PARTICLE_PROPERTY._particleSystemAttributes
self._particleSystemAttributes["maxParticles"] = 2000
self._particleSystemAttributes["viscosity"] = 0.001
self._particleSystem = particleUtils.add_physx_particle_system(
self.stage, self.particleSystemPath, **self._particleSystemSchemaParameters, simulation_owner=Sdf.Path(self.physicsScenePath.pathString)
)
# addPhysxParticleSystem(
# self.stage, self.particleSystemPath, **self._particleSystemSchemaParameters, \
# scenePath=pxr.Sdf.Path(self.physicsScenePath.pathString)
# )
# particleSystem = self.stage.GetPrimAtPath(self.particleSystemPath)
# for key, value in self._particleSystemAttributes.items():
# particleSystem.GetAttribute(key).Set(value)
# filterSmooth = 1
# filtering = 0
# passIndex = 0
# filtering = setGridFilteringPass(filtering, passIndex, filterSmooth)
# passIndex = passIndex + 1
# filtering = setGridFilteringPass(filtering, passIndex, filterSmooth)
# passIndex = passIndex + 1
# self.iso_surface_params = {
# "maxIsosurfaceVertices": [Sdf.ValueTypeNames.Int, True, 1024 * 1024],
# "maxIsosurfaceTriangles": [Sdf.ValueTypeNames.Int, True, 2 * 1024 * 1024],
# "maxNumIsosurfaceSubgrids": [Sdf.ValueTypeNames.Int, True, 1024 * 4],
# "isosurfaceGridSpacing": [Sdf.ValueTypeNames.Float, True, 0.2],
# "isosurfaceKernelRadius": [Sdf.ValueTypeNames.Float, True, 0.5 ],
# "isosurfaceLevel": [ Sdf.ValueTypeNames.Float, True, -0.3 ],
# "isosurfaceGridFilteringFlags": [Sdf.ValueTypeNames.Int, True, filtering ],
# "isosurfaceGridSmoothingRadiusRelativeToCellSize": [Sdf.ValueTypeNames.Float, True, 0.3 ],
# "isosurfaceEnableAnisotropy": [Sdf.ValueTypeNames.Bool, True, False ],
# "isosurfaceAnisotropyMin": [ Sdf.ValueTypeNames.Float, True, 0.1 ],
# "isosurfaceAnisotropyMax": [ Sdf.ValueTypeNames.Float, True, 2.0 ],
# "isosurfaceAnisotropyRadius": [ Sdf.ValueTypeNames.Float, True, 0.5 ],
# "numIsosurfaceMeshSmoothingPasses": [ Sdf.ValueTypeNames.Int, True, 5 ],
# "numIsosurfaceMeshNormalSmoothingPasses": [ Sdf.ValueTypeNames.Int, True, 5 ],
# "isosurfaceDoNotCastShadows": [Sdf.ValueTypeNames.Bool, True, True ]
# }
# particleSystem.CreateAttribute("enableIsosurface", Sdf.ValueTypeNames.Bool, True).Set(True)
# for key,value in self.iso_surface_params.items():
# if isinstance(value, list):
# particleSystem.CreateAttribute(key, value[0], value[1]).Set(value[2])
# else:
# particleSystem.GetAttribute(key).Set(value)
# self.stage.SetInterpolationType(Usd.InterpolationTypeHeld)
def _setup_callbacks(self):
"""! callbacks registered with timeline and physics steps to drop water
"""
# callbacks
self._timeline = omni.timeline.get_timeline_interface()
stream = self._timeline.get_timeline_event_stream()
self._timeline_subscription = stream.create_subscription_to_pop(self._on_timeline_event)
# subscribe to Physics updates:
self._physics_update_subscription = omni.physx.get_physx_interface().subscribe_physics_step_events(
self.on_physics_step
)
# events = omni.physx.get_physx_interface().get_simulation_event_stream()
# self._simulation_event_sub = events.create_subscription_to_pop(self._on_simulation_event)
def _on_timeline_event(self, e):
if e.type == int(omni.timeline.TimelineEventType.STOP):
self.it = 0
self._physics_update_subscription = None
self._timeline_subscription = None
def on_physics_step(self, dt):
xformCache = UsdGeom.XformCache()
# compute location to dispense water
pose = xformCache.GetLocalToWorldTransform(self.stage.GetPrimAtPath(self.inflow_path))
pos_faucet = Gf.Vec3f(pose.ExtractTranslation())
##TODO hangle multiple faucet handles
rate = self.rate_checkers[0].compute_distance()/100.0
if rate > 1:
rate = 1
# if self.it == 0:
# iso2Prim = self.stage.GetPrimAtPath(self.particleSystemPath.pathString +"/Isosurface")
# rel = iso2Prim.CreateRelationship("material:binding", False)
# # rel.SetTargets([Sdf.Path(self.liquid_material_path)])
# rel.SetTargets([Sdf.Path("/World/game/other_Basin_1/Looks/OmniSurface_ClearWater")])
#TODO we can have the water keep running, but we should delete some particles that are too old and not in containers.
#this implementation will stop after 200 balls
if self.it > 200:
return
if rate < 0.1:
return
# emit a ball based on rate
rate = min(0.35, rate)
if (self.counter < 100 - rate*200 ):
self.counter = self.counter + 1
return
self.counter = 0
self.it = self.it + 1
self.create_ball(rate)
def __del__(self):
self._physics_update_subscription = None
self._timeline_subscription = None
|
yizhouzhao/VRKitchen2.0-IndoorKit/exts/vrkitchen.indoor.kit/vrkitchen/indoor/kit/layout/fluid/constants.py | from ...param import APP_VERION
from pxr import Gf
particel_scale = 2.5
if APP_VERION.startswith("2022"):
class PARTICLE_PROPERTY:
_fluidSphereDiameter = 0.24 * particel_scale
_particleSystemSchemaParameters = {
"contact_offset": 0.3 * particel_scale,
"particle_contact_offset": 0.25 * particel_scale,
"rest_offset": 0.25 * particel_scale,
"solid_rest_offset": 0,
"fluid_rest_offset": 0.5 * _fluidSphereDiameter + 0.03 * particel_scale,
"solver_position_iterations": 10,
"wind": Gf.Vec3f(0, 0, 0),
"max_velocity": 40 ,
}
_particleMaterialAttributes = {
"friction": 0.34,
"viscosity": 0.0,
"vorticity_confinement": 0.5,
"surface_tension": 0.74,
"cohesion": 0.1,
# "cfl_coefficient": 1.0,
}
_particleSystemAttributes = {
"cohesion": 0.0,
"smoothing": 0.8,
"anisotropyScale": 1.0,
"anisotropyMin": 0.2,
"anisotropyMax": 2.0,
"surfaceTension": 0.74,
"vorticityConfinement": 0.5,
"viscosity": 0.0,
"particleFriction": 0.34,
"maxVelocity": 40,
}
_particle_mass = 1e-6 * particel_scale*particel_scale
_particle_scale = (0.5, 0.5, 0.5)
_cup_rest_offset = 0.0
_cup_contact_offset = 1.0
_cup_mass = 1
_gravityMagnitude = 100
else:
class PARTICLE_PROPERTY:
_fluidSphereDiameter = 0.24 * particel_scale
_particleSystemSchemaParameters = {
"contact_offset": 0.3 * particel_scale,
"particle_contact_offset": 0.25 * particel_scale,
"rest_offset": 0.25 * particel_scale,
"solid_rest_offset": 0,
"fluid_rest_offset": 0.5 * _fluidSphereDiameter + 0.03 * particel_scale,
"solver_position_iterations": 10,
"solver_velocity_iterations": 10,
"wind": Gf.Vec3f(0, 0, 0),
}
_particleSystemAttributes = {
"cohesion": 7.4,
"smoothing": 0.8,
"anisotropyScale": 1.0,
"anisotropyMin": 0.2,
"anisotropyMax": 2.0,
"surfaceTension": 0.74,
"vorticityConfinement": 0.5,
"viscosity": 5.0,
"particleFriction": 0.34,
"maxVelocity": 40,
}
_particle_mass = 1e-6 * particel_scale
_particle_scale = (0.5, 0.5, 0.5)
_cup_rest_offset = 0.0
_cup_contact_offset = 1.0
_cup_mass = 1
_gravityMagnitude = 100
|
yizhouzhao/VRKitchen2.0-IndoorKit/exts/vrkitchen.indoor.kit/vrkitchen/indoor/kit/layout/fluid/cup_data.py | from ..param import ROOT
CUP_ROOT = ROOT + "/3dmodels/cup/"
NEW_CUP_ROOT = ROOT + "/sample/custom/Cup/"
FAUCET_INFO = {
"1028": {
"inflow_pos": [-17.4121, 4.63152, 0],
"joints":[
"link_2/joint_0",
"link_2/joint_1",
]
},
"148": {
"inflow_pos": [-17.30, 4.10 , 0],
"joints":[
"link_1/joint_0",
]
},
"149": {
"inflow_pos": [-10.80, 7.0 , 0],
"joints":[
"link_3/joint_0",
"link_3/joint_1",
]
},
"153": {
"inflow_pos": [-13.4587, 7.00 , -2.5],
"joints":[
"link_1/joint_0",
]
},
"154": {
"inflow_pos": [-7.0, 19.00 , 0.0],
"joints":[
"link_2/joint_0",
"link_2/joint_1",
]
},
"156": {
"inflow_pos": [-17.00, 6.00 , 0.0],
"joints":[
"link_1/joint_0",
]
},
"693": {
"inflow_pos": [-14.3453, -6.21179, -0.20894],
"joints":[
"link_2/joint_1",
]
},
"1034": {
"inflow_pos": [-17.967, 4.04622, 4.11386],
"joints":[
"link_1/joint_0",
]
},
"1052": {
"inflow_pos": [-14.8737, 4.21977, 1.06383],
"joints":[
"link_2/joint_0",
]
},
"1053": {
"inflow_pos": [-9.99254, 1.0, 0],
"joints":[
"link_1/joint_0",
]
}
}
CUP_PARTICLE_INFO = [
{
"usd_path": NEW_CUP_ROOT + "0/cup.usd",
"mesh_name": "cupShape",
#"volume_container": "cup_volume",
"cylinder_height": 15.0,
"cylinder_radius": 4.5,
"particle_offset": [0, 1.05, 0],
"cup_offset": [0, 0, 0],
"scale": 1.0
},
{
"usd_path": NEW_CUP_ROOT + "1/cup.usd",
"mesh_name": "cupShape",
"volume_container": "cup_volume",
"cylinder_height": 15.0,
"cylinder_radius": 4.5,
"particle_offset": [0, 1.05, 0],
"cup_offset": [0, 0, 0],
"scale": 1.0
},
{
"usd_path": CUP_ROOT + "bottle0.usd",
"mesh_name": "D_printable_bottle",
"cylinder_height": 15.0,
"cylinder_radius": 4.5,
"particle_offset": [2.0, 1.05, 0],
"cup_offset": [0, 0, 0],
"scale": 0.25
},
{
"usd_path": CUP_ROOT + "bottle1.usd",
"mesh_name": "bioshock_salts_bottle_final",
"cylinder_height": 14.0,
"cylinder_radius": 3.0,
"particle_offset": [0.0, -10, -2.7],
# "particle_offset": [0.0, 0, -5],
"cup_offset": [0, 2.1, 0],
# "cup_offset": [0, 0, 0],
"scale": 5.0
},
{
"usd_path": CUP_ROOT + "mug0.usd",
"mesh_name": "geom",
"cylinder_height": 15.0,
"cylinder_radius": 3.0,
"particle_offset": [0.0, 1.05, 0],
"cup_offset": [0, 0, 0],
"scale": 1.2
},
{
"usd_path": CUP_ROOT + "mug1.usd",
"mesh_name": "SM_mug_2_mesh",
"cylinder_height": 15.0,
"cylinder_radius": 3.0,
"particle_offset": [0.0, 1.05, 0],
"cup_offset": [0, 0, 0],
"scale": 1.2
},
{
"usd_path": CUP_ROOT + "jar0.usd",
"mesh_name": "mesh",
"cylinder_height": 18.0,
"cylinder_radius": 5.0,
"particle_offset": [0.0, 1.05, 0],
"cup_offset": [0, 0, 0],
"scale": 1.2
},
] |
yizhouzhao/VRKitchen2.0-IndoorKit/exts/vrkitchen.indoor.kit/vrkitchen/indoor/kit/layout/fluid/__init__.py | # from .faucet import Faucet, particle_params, iso_surface_params |
yizhouzhao/VRKitchen2.0-IndoorKit/exts/vrkitchen.indoor.kit/vrkitchen/indoor/kit/layout/fluid/utils.py | import math
from pxr import Gf
import numpy as np
import copy
def point_sphere(samples, scale):
indices = [x + 0.5 for x in range(0, samples)]
phi = [math.acos(1 - 2 * x / samples) for x in indices]
theta = [math.pi * (1 + 5**0.5) * x for x in indices]
x = [math.cos(th) * math.sin(ph) * scale for (th, ph) in zip(theta, phi)]
y = [math.sin(th) * math.sin(ph) * scale for (th, ph) in zip(theta, phi)]
z = [math.cos(ph) * scale for ph in phi]
points = [Gf.Vec3f(x, y, z) for (x, y, z) in zip(x, y, z)]
return points
#generate inside mesh
def swapPositions(list, pos1, pos2):
list[pos1], list[pos2] = list[pos2], list[pos1]
return list
def generate_inside_mesh(lowerCenter: Gf.Vec3f, h: float, radius: float, sphereDiameter: float, mesh, scale):
# print("bounds: ", mesh.bounds)
# samples = generate_hcp_samples(Gf.Vec3f(-radius, 0, -radius), Gf.Vec3f(radius, h, radius), sphereDiameter)
min_bound = list(mesh.bounds[0])
max_bound = list(mesh.bounds[1])
min_bound = [min_bound[0], min_bound[2], min_bound[1]]
max_bound = [max_bound[0], max_bound[2], max_bound[1]]
min_bound = (item * scale for item in min_bound)
max_bound = (item * scale for item in max_bound)
samples = generate_hcp_samples(Gf.Vec3f(*min_bound), Gf.Vec3f(*max_bound), sphereDiameter*2)
finalSamples = []
import copy
import trimesh
samples_copy = copy.deepcopy(samples)
samples_copy = [ [ sample_copy[0]/scale, sample_copy[1]/scale, sample_copy[2]/scale ] for sample_copy in samples_copy ]
samples_copy = [ [ sample_copy[0], sample_copy[2], sample_copy[1] ] for sample_copy in samples_copy ]
# print("num particles: ", len(samples_copy))
print("eva contains:")
contains = mesh.contains(samples_copy)
# signed_distance = trimesh.proximity.ProximityQuery(mesh).signed_distance(samples_copy)
# contains = signed_distance >= 0
print("eva done:")
for contain, sample in zip(contains, samples):
if contain:
finalSamples.append(sample)
print("length: ", len(finalSamples) )
return finalSamples
def in_hull(p, hull):
"""
Test if points in `p` are in `hull`
`p` should be a `NxK` coordinates of `N` points in `K` dimensions
`hull` is either a scipy.spatial.Delaunay object or the `MxK` array of the
coordinates of `M` points in `K`dimensions for which Delaunay triangulation
will be computed
"""
try:
from scipy.spatial import Delaunay
except:
import omni
omni.kit.pipapi.install("scipy")
from scipy.spatial import Delaunay
if not isinstance(hull,Delaunay):
hull = Delaunay(hull)
return hull.find_simplex(p)>=0
def generate_inside_point_cloud(sphereDiameter, cloud_points, scale = 1):
"""
Generate sphere packs inside a point cloud
"""
offset = 2
min_x = np.min(cloud_points[:, 0]) + offset
min_y = np.min(cloud_points[:, 1]) + offset
min_z = np.min(cloud_points[:, 2]) + offset
max_x = np.max(cloud_points[:, 0])
max_y = np.max(cloud_points[:, 1])
max_z = np.max(cloud_points[:, 2])
min_bound = [min_x, min_y, min_z]
max_bound = [max_x, max_y, max_z]
min_bound = [item * scale for item in min_bound]
max_bound = [item * scale for item in max_bound]
samples = generate_hcp_samples(Gf.Vec3f(*min_bound), Gf.Vec3f(*max_bound), sphereDiameter)
samples_copy = np.array(copy.deepcopy(samples))
print("samples_copy", samples_copy.shape)
finalSamples = []
contains = in_hull(samples, cloud_points)
max_particles = 2000
for contain, sample in zip(contains, samples):
if contain and len(finalSamples) < max_particles:
finalSamples.append(sample)
print("length: ", len(finalSamples) )
return finalSamples
# generate cylinder points
def generate_cylinder_y(lowerCenter: Gf.Vec3f, h: float, radius: float, sphereDiameter: float):
samples = generate_hcp_samples(Gf.Vec3f(-radius, 0, -radius), Gf.Vec3f(radius, h, radius), sphereDiameter)
finalSamples = []
for p in samples:
r2 = p[0] * p[0] + p[2] * p[2]
if r2 <= radius * radius:
finalSamples.append(p + lowerCenter)
return finalSamples
# Generates hexagonal close packed samples inside an axis aligned bounding box
def generate_hcp_samples(boxMin: Gf.Vec3f, boxMax: Gf.Vec3f, sphereDiameter: float):
layerDistance = math.sqrt(2.0 / 3.0) * sphereDiameter
rowShift = math.sqrt(3.0) / 2.0 * sphereDiameter
result = []
layer1Offset = (1.0 / 3.0) * (
Gf.Vec2f(0, 0) + Gf.Vec2f(0.5 * sphereDiameter, rowShift) + Gf.Vec2f(sphereDiameter, 0)
)
zIndex = 0
while True:
z = boxMin[2] + zIndex * layerDistance
if z > boxMax[2]:
break
yOffset = layer1Offset[1] if zIndex % 2 == 1 else 0
yIndex = 0
while True:
y = boxMin[1] + yIndex * rowShift + yOffset
if y > boxMax[1]:
break
xOffset = 0
if zIndex % 2 == 1:
xOffset += layer1Offset[0]
if yIndex % 2 == 1:
xOffset -= 0.5 * sphereDiameter
elif yIndex % 2 == 1:
xOffset += 0.5 * sphereDiameter
xIndex = 0
while True:
x = boxMin[0] + xIndex * sphereDiameter + xOffset
if x > boxMax[0]:
break
result.append(Gf.Vec3f(x, y, z))
xIndex += 1
yIndex += 1
zIndex += 1
return result
def get_quat_from_extrinsic_xyz_rotation(angleXrad: float = 0.0, angleYrad: float = 0.0, angleZrad: float = 0.0):
def rotate_around_axis(x, y, z, angle):
s = math.sin(0.5 * angle)
return Gf.Quatf(math.cos(0.5 * angle), s * x, s * y, s * z)
# angles are in radians
rotX = rotate_around_axis(1, 0, 0, angleXrad)
rotY = rotate_around_axis(0, 1, 0, angleYrad)
rotZ = rotate_around_axis(0, 0, 1, angleZrad)
return rotZ * rotY * rotX |
yizhouzhao/VRKitchen2.0-IndoorKit/exts/vrkitchen.indoor.kit/vrkitchen/indoor/kit/layout/fluid/fluid_setup.py | import carb
import math
from pxr import Usd, UsdGeom, Sdf, Gf, Vt, UsdPhysics, PhysxSchema
import omni.timeline
import omni.physxdemos as demo
from .schemaHelpers import PhysxParticleInstancePrototype, addPhysxParticleSystem
ASYNC_SIMULATION = "/persistent/physics/asyncSimRender"
def setGridFilteringPass(gridFilteringFlags: int, passIndex: int, operation: int, numRepetitions: int = 1):
numRepetitions = max(0, numRepetitions - 1)
shift = passIndex * 4
gridFilteringFlags &= ~(3 << shift)
gridFilteringFlags |= (((operation) << 2) | numRepetitions) << shift
return gridFilteringFlags
class FluidFill(demo.Base):
def __init__(self, pos = Gf.Vec3f(0 , 20, 0.0)):
self.stage = omni.usd.get_context().get_stage()
self.pos = pos
xformCache = UsdGeom.XformCache()
pose = xformCache.GetLocalToWorldTransform(self.stage.GetPrimAtPath("/World/mobility/link_0"))
pos_link = Gf.Vec3f(pose.ExtractTranslation())
self.rot_link_init = Gf.Quatf(pose.ExtractRotationQuat())
# print("attributes: ", self.stage.GetPrimAtPath("/World/faucet/link_0").GetAttributes())
self.init_orient = self.stage.GetPrimAtPath("/World/mobility/link_0").GetAttribute("xformOp:orient").Get()
def point_sphere(self, samples, scale):
indices = [x + 0.5 for x in range(0, samples)]
phi = [math.acos(1 - 2 * x / samples) for x in indices]
theta = [math.pi * (1 + 5**0.5) * x for x in indices]
x = [math.cos(th) * math.sin(ph) * scale for (th, ph) in zip(theta, phi)]
y = [math.sin(th) * math.sin(ph) * scale for (th, ph) in zip(theta, phi)]
z = [math.cos(ph) * scale for ph in phi]
points = [Gf.Vec3f(x, y, z) for (x, y, z) in zip(x, y, z)]
return points
def create_ball(self, stage, pos, rate = 1):
# create sphere on points
# print("scale: ", rate)
points = self.point_sphere( 10+int(90 * rate), 1)
# points = self.point_sphere( int(80 * rate), 1)
# basePos = Gf.Vec3f(11.0, 12.0, 35.0) + pos
basePos = pos
positions = [Gf.Vec3f(x) + Gf.Vec3f(basePos) for x in points]
radius = 0.1
# particleSpacing = 2.0 * radius * 0.6
particleSpacing = 2.0 * radius * 0.6
positions_list = positions
velocities_list = [Gf.Vec3f(0.0, 0.0, 0.0)] * len(positions)
protoIndices_list = [0] * len(positions)
protoIndices = Vt.IntArray(protoIndices_list)
positions = Vt.Vec3fArray(positions_list)
velocities = Vt.Vec3fArray(velocities_list)
particleInstanceStr = "/particlesInstance" + str(self.it)
particleInstancePath = Sdf.Path(particleInstanceStr)
# Create point instancer
pointInstancer = UsdGeom.PointInstancer.Define(stage, particleInstancePath)
prototypeRel = pointInstancer.GetPrototypesRel()
# Create particle instance prototypes
particlePrototype = PhysxParticleInstancePrototype()
particlePrototype.selfCollision = True
particlePrototype.fluid = True
particlePrototype.collisionGroup = 0
particlePrototype.mass = 0.001
prototypePath = particleInstancePath.pathString + "/particlePrototype"
sphere = UsdGeom.Sphere.Define(stage, Sdf.Path(prototypePath))
spherePrim = sphere.GetPrim()
sphere.GetRadiusAttr().Set(particleSpacing)
# color_rgb = [0.0, 0.08, 0.30]
# color = Vt.Vec3fArray([Gf.Vec3f(color_rgb[0], color_rgb[1], color_rgb[2])])
# sphere.CreateDisplayColorAttr(color)
spherePrim = sphere.GetPrim()
spherePrim.GetAttribute('visibility').Set('invisible')
# spherePrim.GetVisibilityAttr().Set(False)
spherePrim.CreateAttribute("enableAnisotropy", Sdf.ValueTypeNames.Bool, True).Set(True)
particleInstanceApi = PhysxSchema.PhysxParticleAPI.Apply(spherePrim)
particleInstanceApi.CreateSelfCollisionAttr().Set(particlePrototype.selfCollision)
particleInstanceApi.CreateFluidAttr().Set(particlePrototype.fluid)
particleInstanceApi.CreateParticleGroupAttr().Set(particlePrototype.collisionGroup)
particleInstanceApi.CreateMassAttr().Set(particlePrototype.mass)
# Reference simulation owner using PhysxPhysicsAPI
physicsApi = PhysxSchema.PhysxPhysicsAPI.Apply(spherePrim)
physicsApi.CreateSimulationOwnerRel().SetTargets([self.particleSystemPath])
# add prototype references to point instancer
prototypeRel.AddTarget(Sdf.Path(prototypePath))
# Set active particle indices
activeIndices = []
for i in range(len(positions)):
activeIndices.append(protoIndices[i])
orientations = [Gf.Quath(1.0, Gf.Vec3h(0.0, 0.0, 0.0))] * len(positions)
angular_velocities = [Gf.Vec3f(0.0, 0.0, 0.0)] * len(positions)
pointInstancer.GetProtoIndicesAttr().Set(activeIndices)
pointInstancer.GetPositionsAttr().Set(positions)
pointInstancer.GetOrientationsAttr().Set(orientations)
pointInstancer.GetVelocitiesAttr().Set(velocities)
pointInstancer.GetAngularVelocitiesAttr().Set(angular_velocities)
def create(self, stage):
self._setup_callbacks()
self.stage = stage
self.it = 0
self.counter = 10
# set up axis to z
UsdGeom.SetStageUpAxis(stage, UsdGeom.Tokens.y)
UsdGeom.SetStageMetersPerUnit(stage, 0.01)
# light
# sphereLight = UsdLux.SphereLight.Define(stage, Sdf.Path("/SphereLight"))
# sphereLight.CreateRadiusAttr(150)
# sphereLight.CreateIntensityAttr(30000)
# sphereLight.AddTranslateOp().Set(Gf.Vec3f(650.0, 0.0, 1150.0))
# Physics scene
scenePath = Sdf.Path("/physicsScene")
scene = UsdPhysics.Scene.Define(stage, scenePath)
scene.CreateGravityDirectionAttr().Set(Gf.Vec3f(0.0, -1.0, 0.0))
scene.CreateGravityMagnitudeAttr().Set(9.81)
# Particle System
particleSystemPath = Sdf.Path("/particleSystem0")
self.particleSystemPath = particleSystemPath
particleSpacing = 0.2
restOffset = particleSpacing * 0.9
solidRestOffset = restOffset
fluidRestOffset = restOffset * 0.6
particleContactOffset = max(solidRestOffset + 0.001, fluidRestOffset / 0.6)
contactOffset = restOffset + 0.001
addPhysxParticleSystem(
stage,
particleSystemPath,
contactOffset,
restOffset,
particleContactOffset,
solidRestOffset,
fluidRestOffset,
4,
1,
Gf.Vec3f(0, 0, 0),
scenePath
)
particleSystem = stage.GetPrimAtPath(particleSystemPath)
# particle system settings
particleSystem.GetAttribute("cohesion").Set(0.002)
particleSystem.GetAttribute("smoothing").Set(0.8)
particleSystem.GetAttribute("anisotropyScale").Set(1.0)
particleSystem.GetAttribute("anisotropyMin").Set(0.2)
particleSystem.GetAttribute("anisotropyMax").Set(2.0)
particleSystem.GetAttribute("viscosity").Set(0.0091)
particleSystem.GetAttribute("surfaceTension").Set(0.0074)
particleSystem.GetAttribute("particleFriction").Set(0.1)
particleSystem.CreateAttribute("maxParticleNeighborhood", Sdf.ValueTypeNames.Int, True).Set(64)
particleSystem.GetAttribute("maxParticles").Set(20000)
# apply isoSurface params
particleSystem.CreateAttribute("enableIsosurface", Sdf.ValueTypeNames.Bool, True).Set(True)
particleSystem.CreateAttribute("maxIsosurfaceVertices", Sdf.ValueTypeNames.Int, True).Set(1024 * 1024)
particleSystem.CreateAttribute("maxIsosurfaceTriangles", Sdf.ValueTypeNames.Int, True).Set(2 * 1024 * 1024)
particleSystem.CreateAttribute("maxNumIsosurfaceSubgrids", Sdf.ValueTypeNames.Int, True).Set(1024 * 4)
particleSystem.CreateAttribute("isosurfaceGridSpacing", Sdf.ValueTypeNames.Float, True).Set(0.2)
filterSmooth = 1
filtering = 0
passIndex = 0
filtering = setGridFilteringPass(filtering, passIndex, filterSmooth)
passIndex = passIndex + 1
filtering = setGridFilteringPass(filtering, passIndex, filterSmooth)
passIndex = passIndex + 1
particleSystem.CreateAttribute("isosurfaceKernelRadius", Sdf.ValueTypeNames.Float, True).Set(0.5)
particleSystem.CreateAttribute("isosurfaceLevel", Sdf.ValueTypeNames.Float, True).Set(-0.3)
particleSystem.CreateAttribute("isosurfaceGridFilteringFlags", Sdf.ValueTypeNames.Int, True).Set(filtering)
particleSystem.CreateAttribute(
"isosurfaceGridSmoothingRadiusRelativeToCellSize", Sdf.ValueTypeNames.Float, True
).Set(0.3)
particleSystem.CreateAttribute("isosurfaceEnableAnisotropy", Sdf.ValueTypeNames.Bool, True).Set(False)
particleSystem.CreateAttribute("isosurfaceAnisotropyMin", Sdf.ValueTypeNames.Float, True).Set(0.1)
particleSystem.CreateAttribute("isosurfaceAnisotropyMax", Sdf.ValueTypeNames.Float, True).Set(2.0)
particleSystem.CreateAttribute("isosurfaceAnisotropyRadius", Sdf.ValueTypeNames.Float, True).Set(0.5)
particleSystem.CreateAttribute("numIsosurfaceMeshSmoothingPasses", Sdf.ValueTypeNames.Int, True).Set(5)
particleSystem.CreateAttribute("numIsosurfaceMeshNormalSmoothingPasses", Sdf.ValueTypeNames.Int, True).Set(5)
particleSystem.CreateAttribute("isosurfaceDoNotCastShadows", Sdf.ValueTypeNames.Bool, True).Set(True)
stage.SetInterpolationType(Usd.InterpolationTypeHeld)
def _setup_callbacks(self):
# callbacks
self._timeline = omni.timeline.get_timeline_interface()
stream = self._timeline.get_timeline_event_stream()
self._timeline_subscription = stream.create_subscription_to_pop(self._on_timeline_event)
# subscribe to Physics updates:
self._physics_update_subscription = omni.physx.get_physx_interface().subscribe_physics_step_events(
self.on_physics_step
)
def _on_timeline_event(self, e):
if e.type == int(omni.timeline.TimelineEventType.STOP):
self.it = 0
self.on_shutdown()
def step(self):
self.on_physics_step(None)
def on_physics_step(self, dt):
# import transforms3d
import math
xformCache = UsdGeom.XformCache()
# stop after 80 balls
# if (self.it > 80):
# return
pose = xformCache.GetLocalToWorldTransform(self.stage.GetPrimAtPath("/World/faucet/inflow"))
pos_faucet = Gf.Vec3f(pose.ExtractTranslation())
rot_faucet = Gf.Quatf(pose.ExtractRotationQuat())
pose = xformCache.GetLocalToWorldTransform(self.stage.GetPrimAtPath("/World/faucet/link_0"))
pos_link = Gf.Vec3f(pose.ExtractTranslation())
rot_link = Gf.Quatf(pose.ExtractRotationQuat())
diff = rot_link * self.rot_link_init.GetInverse()
real = diff.GetReal()
img = [diff.GetImaginary()[0],diff.GetImaginary()[1], diff.GetImaginary()[2] ]
#angle = transforms3d.euler.quat2euler([real, img[0], img[1], img[2]], axes='sxyz')
#sum_angle = abs(math.degrees(angle[0])) + abs(math.degrees(angle[1])) + abs(math.degrees(angle[2]))
rate = 1 #(sum_angle/30.0)
# print("pre rate:", rate)
if rate > 1:
rate = 1
# print("rate: ", rate)
# print("sum_angle", sum_angle)
if self.it == 0:
iso2Prim = self.stage.GetPrimAtPath("/particleSystem0/Isosurface")
rel = iso2Prim.CreateRelationship("material:binding", False)
rel.SetTargets([Sdf.Path("/World/Looks/OmniSurface_ClearWater")])
# rel.SetTargets([Sdf.Path("/World/Looks/OmniSurface_OrangeJuice")])
if self.it > 200:
return
# emit a ball every 10 physics steps
if (self.counter < 20 - rate):
self.counter = self.counter + 1
return
self.counter = 0
self.it = self.it + 1
# print(faucet_prim.GetAttribute('xformOp:translate'))
# openness = 0.6 + 0.5 * rate
# print("openess", openness)
if rate < 0.1:
return
self.create_ball(self.stage, pos_faucet, rate)
def on_shutdown(self):
self._physics_update_subscription = None
self._timeline_subscription = None
# restore settings
# isregistry = carb.settings.acquire_settings_interface()
# isregistry.set_bool(ASYNC_SIMULATION, self._async_simulation)
def on_startup(self):
isregistry = carb.settings.acquire_settings_interface()
self._async_simulation = carb.settings.get_settings().get_as_bool(ASYNC_SIMULATION)
isregistry.set_bool(ASYNC_SIMULATION, True)
isregistry.set_int("persistent/simulation/minFrameRate", 60)
from omni.physx import acquire_physx_interface
physx = acquire_physx_interface()
physx.overwrite_gpu_setting(1)
physx.reset_simulation()
fluid_fill = FluidFill()
stage = omni.usd.get_context().get_stage()
fluid_fill.create(stage)
_timeline = omni.timeline.get_timeline_interface()
stream = _timeline.get_timeline_event_stream()
def _on_timeline_event(e):
if e.type == int(omni.timeline.TimelineEventType.STOP):
fluid_fill.on_shutdown()
_timeline_subscription = stream.create_subscription_to_pop(_on_timeline_event)
# for i in range(10):
# fluid_fill.step()
|
yizhouzhao/VRKitchen2.0-IndoorKit/exts/vrkitchen.indoor.kit/vrkitchen/indoor/kit/layout/fluid/schemaHelpers.py | from pxr import Usd, UsdGeom, Sdf, Gf, Vt, PhysxSchema
class PhysxParticleInstancePrototype:
def __init__(self, mass=0.0, phase=0):
self.mass = mass
self.phase = phase
def addPhysxParticleSystem(
stage,
particle_system_path,
contact_offset,
rest_offset,
particle_contact_offset,
solid_rest_offset,
fluid_rest_offset,
solver_position_iterations,
solver_velocity_iterations,
wind,
scenePath,
):
particle_system = PhysxSchema.PhysxParticleSystem.Define(stage, particle_system_path)
if particle_system:
particle_system.CreateContactOffsetAttr().Set(contact_offset)
particle_system.CreateRestOffsetAttr().Set(rest_offset)
particle_system.CreateParticleContactOffsetAttr().Set(particle_contact_offset)
particle_system.CreateSolidRestOffsetAttr().Set(solid_rest_offset)
particle_system.CreateFluidRestOffsetAttr().Set(fluid_rest_offset)
particle_system.CreateSolverPositionIterationCountAttr().Set(solver_position_iterations)
particle_system.CreateSolverVelocityIterationCountAttr().Set(solver_velocity_iterations)
particle_system.CreateWindAttr().Set(wind)
# Reference simulation owner using PhysxPhysicsAPI
physics_api = PhysxSchema.PhysxPhysicsAPI.Apply(particle_system.GetPrim())
physics_api.CreateSimulationOwnerRel().SetTargets([scenePath])
return particle_system
else:
return None
def addPhysxParticlesSimple(stage, path, prototypes, prototype_indices, positions, velocities, particle_system_path):
prototype_base_path = path.pathString + "/particlePrototype"
# Create point instancer
shape_list = UsdGeom.PointInstancer.Define(stage, path)
mesh_list = shape_list.GetPrototypesRel()
# Create particle instance prototypes
for i in range(len(prototypes)):
prototype_path = prototype_base_path + str(i)
geom_sphere = UsdGeom.Sphere.Define(stage, Sdf.Path(prototype_path))
particle_instance_api = PhysxSchema.PhysxParticleAPI.Apply(geom_sphere.GetPrim())
particle_instance_api.CreateSelfCollisionAttr().Set(prototypes[i].selfCollision)
particle_instance_api.CreateFluidAttr().Set(prototypes[i].fluid)
particle_instance_api.CreateParticleGroupAttr().Set(prototypes[i].collisionGroup)
particle_instance_api.CreateMassAttr().Set(prototypes[i].mass)
# Reference simulation owner using PhysxPhysicsAPI
physics_api = PhysxSchema.PhysxPhysicsAPI.Apply(geom_sphere.GetPrim())
physics_api.CreateSimulationOwnerRel().SetTargets([particle_system_path])
# add mesh references to point instancer
mesh_list.AddTarget(Sdf.Path(prototype_path))
# Set particle instance data
mesh_indices = []
for i in range(len(positions)):
mesh_indices.append(prototype_indices[i])
orientations = [Gf.Quath(1.0, Gf.Vec3h(0.0, 0.0, 0.0))] * len(positions)
angular_velocities = [Gf.Vec3f(0.0, 0.0, 0.0)] * len(positions)
shape_list.GetProtoIndicesAttr().Set(mesh_indices)
shape_list.GetPositionsAttr().Set(positions)
shape_list.GetOrientationsAttr().Set(orientations)
shape_list.GetVelocitiesAttr().Set(velocities)
shape_list.GetAngularVelocitiesAttr().Set(angular_velocities)
def addPhysxClothWithConstraints(
stage,
path,
positions,
normals,
rest_positions,
velocities,
inv_masses,
triangle_indices,
spring_connections,
spring_stiffnesses,
spring_dampings,
spring_rest_lengths,
self_collision,
self_collision_filter,
inv_gravity,
particle_group,
particle_system_path,
):
mesh = UsdGeom.Mesh.Define(stage, path)
prim = mesh.GetPrim()
mesh.CreateDoubleSidedAttr().Set(True)
vertex_count_attr = mesh.CreateFaceVertexCountsAttr()
vertex_indices_attr = mesh.CreateFaceVertexIndicesAttr()
norm_attr = mesh.CreateNormalsAttr()
point_attr = mesh.CreatePointsAttr()
# Triangle array's vertex count per face is always 3
vertex_count = 3
array_size = int(len(triangle_indices) / 3)
index_array = Vt.IntArray(array_size, vertex_count)
vertex_count_attr.Set(index_array)
vertex_indices_attr.Set(triangle_indices)
norm_attr.Set(normals)
point_attr.Set(positions)
cloth_api = PhysxSchema.PhysxClothAPI.Apply(prim)
cloth_api.CreateSelfCollisionAttr().Set(self_collision)
cloth_api.CreateSelfCollisionFilterAttr().Set(self_collision_filter)
cloth_api.CreateParticleGroupAttr().Set(particle_group)
# Reference simulation owner using PhysxPhysicsAPI
physics_api = PhysxSchema.PhysxPhysicsAPI.Apply(prim)
physics_api.CreateSimulationOwnerRel().SetTargets([particle_system_path])
# Custom attributes
prim.CreateAttribute("invGravity", Sdf.ValueTypeNames.Bool).Set(inv_gravity)
prim.CreateAttribute("springConnections", Sdf.ValueTypeNames.Int2Array).Set(spring_connections)
prim.CreateAttribute("springStiffnesses", Sdf.ValueTypeNames.FloatArray).Set(spring_stiffnesses)
prim.CreateAttribute("springDampings", Sdf.ValueTypeNames.FloatArray).Set(spring_dampings)
prim.CreateAttribute("springRestLengths", Sdf.ValueTypeNames.FloatArray).Set(spring_rest_lengths)
prim.CreateAttribute("restPositions", Sdf.ValueTypeNames.Point3fArray).Set(rest_positions)
prim.CreateAttribute("velocities", Sdf.ValueTypeNames.Point3fArray).Set(velocities)
prim.CreateAttribute("inverseMasses", Sdf.ValueTypeNames.FloatArray).Set(inv_masses)
def addPhysxCloth(
stage,
path,
dynamic_mesh_path,
initial_velocity,
initial_mass,
stretch_stiffness,
bend_stiffness,
shear_stiffness,
self_collision,
self_collision_filter,
inv_gravity,
particle_group,
particle_system_path,
):
mesh = UsdGeom.Mesh.Define(stage, path)
prim = mesh.GetPrim()
if dynamic_mesh_path:
prim.GetReferences().AddReference(dynamic_mesh_path)
cloth_api = PhysxSchema.PhysxClothAPI.Apply(prim)
cloth_api.CreateDefaultParticleVelocityAttr().Set(initial_velocity)
cloth_api.CreateDefaultParticleMassAttr().Set(initial_mass)
cloth_api.CreateStretchStiffnessAttr().Set(stretch_stiffness)
cloth_api.CreateBendStiffnessAttr().Set(bend_stiffness)
cloth_api.CreateShearStiffnessAttr().Set(shear_stiffness)
cloth_api.CreateSelfCollisionAttr().Set(self_collision)
cloth_api.CreateSelfCollisionFilterAttr().Set(self_collision_filter)
cloth_api.CreateParticleGroupAttr().Set(particle_group)
# Reference simulation owner using PhysxPhysicsAPI
physics_api = PhysxSchema.PhysxPhysicsAPI.Apply(prim)
physics_api.CreateSimulationOwnerRel().SetTargets([particle_system_path])
# Custom attributes
prim.CreateAttribute("invGravity", Sdf.ValueTypeNames.Bool).Set(inv_gravity)
def applyInflatableApi(stage, path, pressure):
prim = stage.GetPrimAtPath(path)
# TODO: Add more checks here
if prim.IsValid():
inflatable_api = PhysxSchema.PhysxInflatableAPI.Apply(prim)
inflatable_api.CreatePressureAttr().Set(pressure)
def _get_rigid_attachments(stage, prim: Usd.Prim):
attachments = []
rigidAttachmentRel = prim.CreateRelationship("physxRigidAttachments")
for attachment_path in rigidAttachmentRel.GetTargets():
attachment = PhysxSchema.PhysxRigidAttachment.Get(stage, attachment_path)
if attachment:
attachments.append(attachment)
return attachments
# def _get_rigid_attachment_target(attachment: PhysxSchema.PhysxRigidAttachment):
# targets = attachment.GetRigidRel().GetTargets()
# if len(targets) <= 0:
# return Sdf.Path()
# else:
# return targets[0]
# def _create_rigid_attachment(
# stage, attachment_path: Sdf.Path, rigidbody_path: Sdf.Path, deformable_path: Sdf.Path
# ) -> PhysxSchema.PhysxRigidAttachment:
# attachment = PhysxSchema.PhysxRigidAttachment.Define(stage, attachment_path)
# attachment.GetRigidRel().SetTargets([rigidbody_path])
# attachment.GetDeformableRel().SetTargets([deformable_path])
# return attachment
# def add_deformable_to_rigid_body_attachment(
# stage, target_attachment_path: Sdf.Path, deformable_path: Sdf.Path, rigid_path: Sdf.Path
# ):
# deformable_prim = stage.GetPrimAtPath(deformable_path)
# softbody_xformable = UsdGeom.Xformable(deformable_prim)
# rigidbody_prim = stage.GetPrimAtPath(rigid_path)
# rigidbody_xformable = UsdGeom.Xformable(rigidbody_prim)
# attachments = _get_rigid_attachments(stage, deformable_prim)
# if any(_get_rigid_attachment_target(attachment) == rigid_path for attachment in attachments):
# return False
# # Create new attachment
# attachment = _create_rigid_attachment(stage, target_attachment_path, rigid_path, deformable_path)
# attachment_prim = attachment.GetPrim()
# attachment_prim.CreateAttribute("physxEnableHaloParticleFiltering", Sdf.ValueTypeNames.Bool).Set(True)
# attachment_prim.CreateAttribute("physxEnableVolumeParticleAttachments", Sdf.ValueTypeNames.Bool).Set(True)
# attachment_prim.CreateAttribute("physxEnableSurfaceTetraAttachments", Sdf.ValueTypeNames.Bool).Set(False)
# sb_bound = softbody_xformable.ComputeLocalBound(
# Usd.TimeCode.Default(), purpose1=softbody_xformable.GetPurposeAttr().Get()
# )
# sb_size = sb_bound.ComputeAlignedBox().GetSize()
# avg_dim = (sb_size[0] + sb_size[1] + sb_size[2]) / 3.0
# default_rad = avg_dim * 0.05
# attachment_prim.CreateAttribute("physxHaloParticleFilteringRadius", Sdf.ValueTypeNames.Float).Set(default_rad * 4)
# attachment_prim.CreateAttribute("physxVolumeParticleAttachmentRadius", Sdf.ValueTypeNames.Float).Set(default_rad)
# attachment_prim.CreateAttribute("physxSurfaceSamplingRadius", Sdf.ValueTypeNames.Float).Set(default_rad)
# # Update soft body relationship
# attachments.append(attachment)
# attachment_paths = [attachment.GetPath() for attachment in attachments]
# deformable_prim.CreateRelationship("physxRigidAttachments").SetTargets(attachment_paths)
# # Store the global xforms
# globalPose = rigidbody_xformable.ComputeLocalToWorldTransform(Usd.TimeCode.Default())
# attachment_prim.CreateAttribute("physxRigidBodyXform", Sdf.ValueTypeNames.Matrix4d).Set(globalPose)
# globalPose = softbody_xformable.ComputeLocalToWorldTransform(Usd.TimeCode.Default())
# attachment_prim.CreateAttribute("physxDeformableXform", Sdf.ValueTypeNames.Matrix4d).Set(globalPose)
|
yizhouzhao/VRKitchen2.0-IndoorKit/exts/vrkitchen.indoor.kit/vrkitchen/indoor/kit/layout/fluid/faucet.py | import carb
import math
from pathlib import Path
from pxr import Usd, UsdLux, UsdGeom, Sdf, Gf, Vt, UsdPhysics, PhysxSchema
import sys
#put schemaHelpers.py into path
from omni.kitchen.asset.layout.fluid.schemaHelpers import PhysxParticleInstancePrototype, addPhysxParticleSystem
import omni.timeline
from typing import List
from omni.kitchen.asset.task_check.newJointCheck import JointCheck
import math
ASYNC_SIMULATION = "/persistent/physics/asyncSimRender"
def setGridFilteringPass(gridFilteringFlags: int, passIndex: int, operation: int, numRepetitions: int = 1):
numRepetitions = max(0, numRepetitions - 1)
shift = passIndex * 4
gridFilteringFlags &= ~(3 << shift)
gridFilteringFlags |= (((operation) << 2) | numRepetitions) << shift
return gridFilteringFlags
def norm(a):
square_sum = 0
for item in a:
square_sum += item * item
return math.sqrt(square_sum)
# https://math.stackexchange.com/questions/2346982/slerp-inverse-given-3-quaternions-find-t
def quarternion_slerp_inverse(q0, q1, q):
q1_inv = q1.GetInverse()
q0_inv = q0.GetInverse()
q_inv = q.GetInverse()
tmp_1 = (q0_inv * q).GetNormalized()
real = tmp_1.GetReal()
img = [ tmp_1.GetImaginary()[0], tmp_1.GetImaginary()[1], tmp_1.GetImaginary()[2] ]
# print("1: ", real)
# print("term 1 cos: ", math.acos(real))
term21 = [ math.acos(real) / norm(img) * item for item in img]
log_tmp1 = [0, term21[0], term21[1], term21[2]]
tmp_2 = (q0_inv * q1).GetNormalized()
real = tmp_2.GetReal()
img = [ tmp_2.GetImaginary()[0], tmp_2.GetImaginary()[1], tmp_2.GetImaginary()[2] ]
# print("2: ", real)
# print("term 2 cos: ", math.acos(real))
term22 = [ math.acos(real) / norm(img) * item for item in img ]
log_tmp2 = [0, term22[0], term22[1], term22[2]]
rates = []
if abs(term21[0]) < 0.0001 and abs(term22[0]) < 0.0001:
rates.append(None)
else:
t1 = (term21[0] / term22[0])
rates.append(t1)
if abs(term21[1]) < 0.0001 and abs(term22[1]) < 0.0001:
rates.append(None)
else:
t2 = (term21[1] / term22[1])
rates.append(t2)
if abs(term21[2]) < 0.0001 and abs(term22[2]) < 0.0001:
rates.append(None)
else:
t3 = (term21[2] / term22[2])
rates.append(t3)
# print("rates pre: ", rates)
rates = list(filter(lambda x: x is not None, rates))
# print("rates post: ", rates)
# length = len(rates)
# for i in range(length):
# for j in range(i+1, length):
# if not abs(rates[i] - rates[j]) <= 0.001:
# raise Exception("not the same")
# print("rates: ", rates)
return max(rates)
# https://math.stackexchange.com/questions/167827/compute-angle-between-quaternions-in-matlab
def rotation_diff(q0, q1):
z = q0.GetNormalized() * q1.GetNormalized().GetConjugate()
z_real = abs(z.GetReal())
if z_real > 1:
z_real = 1
elif z_real < -1:
z_real = -1
angle = math.acos(abs(z_real)) * 2
return math.degrees(angle)
class Faucet():
def __init__(self, particle_params = None, iso_surface_params = None,
liquid_material_path = "/World/Looks/OmniSurface_ClearWater", inflow_path:str = "/World/faucet/inflow",
link_paths:List[str] = ["/World/faucet/link_0"]
):
"""! Faucet class
@param particle_params : parameters for particles
@param iso_surface_params: parameters for iso_surface
@param liquid_material_path: parameters for liquid materials
@param inflow_path: used to compute the location of water drops
@param link_paths: used to compute the rotation of faucet handle and determine the speed and size of water drops
@param particle_params: parameters related to particle systems
@return an instance of Faucet class
"""
# particle Instance path
self.particleInstanceStr_tmp = "/particlesInstance"
self.particle_params = particle_params
self.iso_surface_params = iso_surface_params
self.liquid_material_path = liquid_material_path
#Not sure if the isregistry thing works
isregistry = carb.settings.acquire_settings_interface()
self._async_simulation = carb.settings.get_settings().get_as_bool(ASYNC_SIMULATION)
isregistry.set_bool(ASYNC_SIMULATION, True)
isregistry.set_int("persistent/simulation/minFrameRate", 30)
self.stage = omni.usd.get_context().get_stage()
self.inflow_path = inflow_path
self.link_paths = link_paths
self.list_of_point_instancers = []
self.active_indexes_for_point_instancers = []
self.rate_checkers = []
for link in link_paths:
path = Path(link)
self.rate_checkers.append(JointCheck( str(path.parent), str(path.name) ))
self.create()
def point_sphere(self, samples, scale):
"""! create locations for each particles
@param samples: the number of particles per sphere
@param scale: the scale(radius) of the water drop
"""
indices = [x + 0.5 for x in range(0, samples)]
phi = [math.acos(1 - 2 * x / samples) for x in indices]
theta = [math.pi * (1 + 5**0.5) * x for x in indices]
x = [math.cos(th) * math.sin(ph) * scale for (th, ph) in zip(theta, phi)]
y = [math.sin(th) * math.sin(ph) * scale for (th, ph) in zip(theta, phi)]
z = [math.cos(ph) * scale for ph in phi]
points = [Gf.Vec3f(x, y, z) for (x, y, z) in zip(x, y, z)]
return points
def create_ball(self, pos, rate = 1):
"""! create a water drop
@param pos: the center of the water drop
@param rate: the number of particles for each water drop
"""
# create sphere on points
points = self.point_sphere( 10+int(90 * rate), 1)
# basePos = Gf.Vec3f(11.0, 12.0, 35.0) + pos
basePos = pos
positions = [Gf.Vec3f(x) + Gf.Vec3f(basePos) for x in points]
radius = 0.2
# particleSpacing = 2.0 * radius * 0.6
particleSpacing = 2.0 * radius * 0.6
positions_list = positions
velocities_list = [Gf.Vec3f(0.0, 0.0, 0.0)] * len(positions)
protoIndices_list = [0] * len(positions)
protoIndices = Vt.IntArray(protoIndices_list)
positions = Vt.Vec3fArray(positions_list)
velocities = Vt.Vec3fArray(velocities_list)
# particleInstanceStr = "/particlesInstance" + str(self.it)
particleInstanceStr = omni.usd.get_stage_next_free_path(self.stage, self.particleInstanceStr_tmp, False)
particleInstancePath = Sdf.Path(particleInstanceStr)
# Create point instancer
pointInstancer = UsdGeom.PointInstancer.Define(self.stage, particleInstancePath)
prototypeRel = pointInstancer.GetPrototypesRel()
# Create particle instance prototypes
particlePrototype = PhysxParticleInstancePrototype()
particlePrototype.selfCollision = True
particlePrototype.fluid = True
particlePrototype.collisionGroup = 0
particlePrototype.mass = 0.5e-5
prototypePath = particleInstancePath.pathString + "/particlePrototype"
sphere = UsdGeom.Sphere.Define(self.stage, Sdf.Path(prototypePath))
spherePrim = sphere.GetPrim()
sphere.GetRadiusAttr().Set(particleSpacing)
spherePrim = sphere.GetPrim()
spherePrim.GetAttribute('visibility').Set('invisible')
spherePrim.CreateAttribute("enableAnisotropy", Sdf.ValueTypeNames.Bool, True).Set(True)
particleInstanceApi = PhysxSchema.PhysxParticleAPI.Apply(spherePrim)
particleInstanceApi.CreateSelfCollisionAttr().Set(particlePrototype.selfCollision)
particleInstanceApi.CreateFluidAttr().Set(particlePrototype.fluid)
particleInstanceApi.CreateParticleGroupAttr().Set(particlePrototype.collisionGroup)
particleInstanceApi.CreateMassAttr().Set(particlePrototype.mass)
# Reference simulation owner using PhysxPhysicsAPI
physicsApi = PhysxSchema.PhysxPhysicsAPI.Apply(spherePrim)
physicsApi.CreateSimulationOwnerRel().SetTargets([self.particleSystemPath])
# add prototype references to point instancer
prototypeRel.AddTarget(Sdf.Path(prototypePath))
# Set active particle indices
activeIndices = []
for i in range(len(positions)):
activeIndices.append(protoIndices[i])
orientations = [Gf.Quath(1.0, Gf.Vec3h(0.0, 0.0, 0.0))] * len(positions)
angular_velocities = [Gf.Vec3f(0.0, 0.0, 0.0)] * len(positions)
pointInstancer.GetProtoIndicesAttr().Set(activeIndices)
pointInstancer.GetPositionsAttr().Set(positions)
pointInstancer.GetOrientationsAttr().Set(orientations)
pointInstancer.GetVelocitiesAttr().Set(velocities)
pointInstancer.GetAngularVelocitiesAttr().Set(angular_velocities)
self.list_of_point_instancers.append(pointInstancer)
self.active_indexes_for_point_instancers.append(activeIndices)
def create(self):
"""! initialize the related parameters for faucet
create physics scenes
create particle systems
create isosurface
"""
self._setup_callbacks()
self.it = 0
self.counter = 10
# Physics scene
scenePath = Sdf.Path("/physicsScene")
# Particle System
self.particleSystemPath = omni.usd.get_stage_next_free_path(self.stage, "/particleSystem", False)
# particleSystemPath = Sdf.Path("/particleSystem0")
self.particleSystemPath = self.particleSystemPath
_fluidSphereDiameter = 0.24
_solverPositionIterations = 10
_solverVelocityIterations = 1
_particleSystemSchemaParameters = {
"contact_offset": 0.3,
"particle_contact_offset": 0.25,
"rest_offset": 0.25,
"solid_rest_offset": 0,
"fluid_rest_offset": 0.5 * _fluidSphereDiameter + 0.03,
"solver_position_iterations": _solverPositionIterations,
"solver_velocity_iterations": _solverVelocityIterations,
"wind": Gf.Vec3f(0, 0, 0),
}
addPhysxParticleSystem(
self.stage,
self.particleSystemPath,
**_particleSystemSchemaParameters,
scenePath = scenePath
)
particleSystem = self.stage.GetPrimAtPath(self.particleSystemPath)
# particle system settings
if self.particle_params is not None:
for key,value in self.particle_params.items():
if isinstance(value, list):
particleSystem.CreateAttribute(key, value[0], value[1]).Set(value[2])
else:
particleSystem.GetAttribute(key).Set(value)
# apply isoSurface params
if self.iso_surface_params is not None:
particleSystem.CreateAttribute("enableIsosurface", Sdf.ValueTypeNames.Bool, True).Set(True)
for key,value in self.iso_surface_params.items():
if isinstance(value, list):
particleSystem.CreateAttribute(key, value[0], value[1]).Set(value[2])
else:
particleSystem.GetAttribute(key).Set(value)
self.stage.SetInterpolationType(Usd.InterpolationTypeHeld)
def _setup_callbacks(self):
"""! callbacks registered with timeline and physics steps to drop water
"""
# callbacks
self._timeline = omni.timeline.get_timeline_interface()
stream = self._timeline.get_timeline_event_stream()
self._timeline_subscription = stream.create_subscription_to_pop(self._on_timeline_event)
# subscribe to Physics updates:
self._physics_update_subscription = omni.physx.get_physx_interface().subscribe_physics_step_events(
self.on_physics_step
)
# events = omni.physx.get_physx_interface().get_simulation_event_stream()
# self._simulation_event_sub = events.create_subscription_to_pop(self._on_simulation_event)
def _on_timeline_event(self, e):
if e.type == int(omni.timeline.TimelineEventType.STOP):
self.it = 0
self._physics_update_subscription = None
self._timeline_subscription = None
def on_physics_step(self, dt):
xformCache = UsdGeom.XformCache()
# compute location to dispense water
pose = xformCache.GetLocalToWorldTransform(self.stage.GetPrimAtPath(self.inflow_path))
pos_faucet = Gf.Vec3f(pose.ExtractTranslation())
##TODO hangle multiple faucet handles
rate = self.rate_checkers[0].compute_distance()/100.0
if rate > 1:
rate = 1
if self.it == 0:
iso2Prim = self.stage.GetPrimAtPath(self.particleSystemPath+"/Isosurface")
rel = iso2Prim.CreateRelationship("material:binding", False)
# rel.SetTargets([Sdf.Path(self.liquid_material_path)])
# rel.SetTargets([Sdf.Path("/World/Looks/OmniSurface_OrangeJuice")])
#TODO we can have the water keep running, but we should delete some particles that are too old and not in containers.
#this implementation will stop after 300 balls
if self.it > 300:
return
if rate < 0.1:
return
# emit a ball based on rate
if (self.counter < 20 - rate):
self.counter = self.counter + 1
return
self.counter = 0
self.it = self.it + 1
self.create_ball( pos_faucet, rate)
def __del__(self):
self._physics_update_subscription = None
self._timeline_subscription = None
#TODO not sure if this works
isregistry = carb.settings.acquire_settings_interface()
isregistry.set_bool(ASYNC_SIMULATION, self._async_simulation)
# if __name__ == '__main__':
from omni.physx import acquire_physx_interface
physx = acquire_physx_interface()
physx.overwrite_gpu_setting(1)
physx.reset_simulation()
particle_params = {
"cohesion": 0.02,
"smoothing": 0.8,
"anisotropyScale": 1.0,
"anisotropyMin": 0.2,
"anisotropyMax": 2.0,
"viscosity": 0.0091,
"surfaceTension": 0.0074,
"particleFriction": 0.1,
"maxParticleNeighborhood": [ Sdf.ValueTypeNames.Int, True, 64],
"maxParticles": 20000
}
filterSmooth = 1
filtering = 0
passIndex = 0
filtering = setGridFilteringPass(filtering, passIndex, filterSmooth)
passIndex = passIndex + 1
filtering = setGridFilteringPass(filtering, passIndex, filterSmooth)
passIndex = passIndex + 1
iso_surface_params = {
"maxIsosurfaceVertices": [Sdf.ValueTypeNames.Int, True, 1024 * 1024],
"maxIsosurfaceTriangles": [Sdf.ValueTypeNames.Int, True, 2 * 1024 * 1024],
"maxNumIsosurfaceSubgrids": [Sdf.ValueTypeNames.Int, True, 1024 * 4],
"isosurfaceGridSpacing": [Sdf.ValueTypeNames.Float, True, 0.2],
"isosurfaceKernelRadius": [Sdf.ValueTypeNames.Float, True, 0.5 ],
"isosurfaceLevel": [ Sdf.ValueTypeNames.Float, True, -0.3 ],
"isosurfaceGridFilteringFlags": [Sdf.ValueTypeNames.Int, True, filtering ],
"isosurfaceGridSmoothingRadiusRelativeToCellSize": [Sdf.ValueTypeNames.Float, True, 0.3 ],
"isosurfaceEnableAnisotropy": [Sdf.ValueTypeNames.Bool, True, False ],
"isosurfaceAnisotropyMin": [ Sdf.ValueTypeNames.Float, True, 0.1 ],
"isosurfaceAnisotropyMax": [ Sdf.ValueTypeNames.Float, True, 2.0 ],
"isosurfaceAnisotropyRadius": [ Sdf.ValueTypeNames.Float, True, 0.5 ],
"numIsosurfaceMeshSmoothingPasses": [ Sdf.ValueTypeNames.Int, True, 5 ],
"numIsosurfaceMeshNormalSmoothingPasses": [ Sdf.ValueTypeNames.Int, True, 5 ],
"isosurfaceDoNotCastShadows": [Sdf.ValueTypeNames.Bool, True, True ]
}
# fluid_fill = Faucet(particle_params=particle_params, iso_surface_params=iso_surface_params,
# liquid_material_path = "/World/Looks/OmniSurface_ClearWater",
# inflow_path = "/World/faucet/inflow",
# link_paths = ["/World/faucet/link_1/joint_0"])
# fluid_fill = Faucet(particle_params=particle_params, iso_surface_params=iso_surface_params,
# liquid_material_path = "/World/Looks/OmniSurface_ClearWater",
# inflow_path = "/World/mobility/inflow",
# link_paths = ["/World/mobility/link_1/joint_0"])
|
yizhouzhao/VRKitchen2.0-IndoorKit/exts/vrkitchen.indoor.kit/vrkitchen/indoor/kit/layout/material/param.py | NECLEUS_MATERIALS = {'Architecture': ['http://localhost:8080/omniverse://127.0.0.1/NVIDIA/Materials/Base/Architecture/Ceiling_Tiles.mdl', 'http://localhost:8080/omniverse://127.0.0.1/NVIDIA/Materials/Base/Architecture/Roof_Tiles.mdl', 'http://localhost:8080/omniverse://127.0.0.1/NVIDIA/Materials/Base/Architecture/Shingles_01.mdl'], 'Carpet': ['http://localhost:8080/omniverse://127.0.0.1/NVIDIA/Materials/Base/Carpet/Carpet_Beige.mdl', 'http://localhost:8080/omniverse://127.0.0.1/NVIDIA/Materials/Base/Carpet/Carpet_Berber_Gray.mdl', 'http://localhost:8080/omniverse://127.0.0.1/NVIDIA/Materials/Base/Carpet/Carpet_Berber_Multi.mdl', 'http://localhost:8080/omniverse://127.0.0.1/NVIDIA/Materials/Base/Carpet/Carpet_Charcoal.mdl', 'http://localhost:8080/omniverse://127.0.0.1/NVIDIA/Materials/Base/Carpet/Carpet_Cream.mdl', 'http://localhost:8080/omniverse://127.0.0.1/NVIDIA/Materials/Base/Carpet/Carpet_Diamond_Olive.mdl', 'http://localhost:8080/omniverse://127.0.0.1/NVIDIA/Materials/Base/Carpet/Carpet_Diamond_Yellow.mdl', 'http://localhost:8080/omniverse://127.0.0.1/NVIDIA/Materials/Base/Carpet/Carpet_Forest.mdl', 'http://localhost:8080/omniverse://127.0.0.1/NVIDIA/Materials/Base/Carpet/Carpet_Gray.mdl', 'http://localhost:8080/omniverse://127.0.0.1/NVIDIA/Materials/Base/Carpet/Carpet_Pattern_Leaf_Squares_Tan.mdl', 'http://localhost:8080/omniverse://127.0.0.1/NVIDIA/Materials/Base/Carpet/Carpet_Pattern_Loop.mdl', 'http://localhost:8080/omniverse://127.0.0.1/NVIDIA/Materials/Base/Carpet/Carpet_Pattern_Squares_Multi.mdl', 'http://localhost:8080/omniverse://127.0.0.1/NVIDIA/Materials/vMaterials_2/Carpet/Carpet_Woven.mdl', 'http://localhost:8080/omniverse://127.0.0.1/NVIDIA/Materials/vMaterials_2/Carpet/Fabric_Carpet_Long_Floor.mdl'], 'Emissives': ['http://localhost:8080/omniverse://127.0.0.1/NVIDIA/Materials/Base/Emissives/Light_12000K.mdl', 'http://localhost:8080/omniverse://127.0.0.1/NVIDIA/Materials/Base/Emissives/Light_1900K.mdl', 'http://localhost:8080/omniverse://127.0.0.1/NVIDIA/Materials/Base/Emissives/Light_2600K.mdl', 'http://localhost:8080/omniverse://127.0.0.1/NVIDIA/Materials/Base/Emissives/Light_2900K.mdl', 'http://localhost:8080/omniverse://127.0.0.1/NVIDIA/Materials/Base/Emissives/Light_5000K.mdl', 'http://localhost:8080/omniverse://127.0.0.1/NVIDIA/Materials/Base/Emissives/Light_5500K.mdl', 'http://localhost:8080/omniverse://127.0.0.1/NVIDIA/Materials/Base/Emissives/Light_6000K.mdl', 'http://localhost:8080/omniverse://127.0.0.1/NVIDIA/Materials/Base/Emissives/Light_7000K.mdl'], 'Glass': ['http://localhost:8080/omniverse://127.0.0.1/NVIDIA/Materials/Base/Glass/Blue_Glass.mdl', 'http://localhost:8080/omniverse://127.0.0.1/NVIDIA/Materials/Base/Glass/Clear_Glass.mdl', 'http://localhost:8080/omniverse://127.0.0.1/NVIDIA/Materials/Base/Glass/Dull_Glass.mdl', 'http://localhost:8080/omniverse://127.0.0.1/NVIDIA/Materials/Base/Glass/Frosted_Glass.mdl', 'http://localhost:8080/omniverse://127.0.0.1/NVIDIA/Materials/Base/Glass/Glazed_Glass.mdl', 'http://localhost:8080/omniverse://127.0.0.1/NVIDIA/Materials/Base/Glass/Green_Glass.mdl', 'http://localhost:8080/omniverse://127.0.0.1/NVIDIA/Materials/Base/Glass/Mirror.mdl', 'http://localhost:8080/omniverse://127.0.0.1/NVIDIA/Materials/Base/Glass/Red_Glass.mdl', 'http://localhost:8080/omniverse://127.0.0.1/NVIDIA/Materials/Base/Glass/Tinted_Glass.mdl', 'http://localhost:8080/omniverse://127.0.0.1/NVIDIA/Materials/Base/Glass/Tinted_Glass_R02.mdl', 'http://localhost:8080/omniverse://127.0.0.1/NVIDIA/Materials/Base/Glass/Tinted_Glass_R25.mdl', 'http://localhost:8080/omniverse://127.0.0.1/NVIDIA/Materials/Base/Glass/Tinted_Glass_R50.mdl', 'http://localhost:8080/omniverse://127.0.0.1/NVIDIA/Materials/Base/Glass/Tinted_Glass_R75.mdl', 'http://localhost:8080/omniverse://127.0.0.1/NVIDIA/Materials/Base/Glass/Tinted_Glass_R85.mdl', 'http://localhost:8080/omniverse://127.0.0.1/NVIDIA/Materials/Base/Glass/Tinted_Glass_R98.mdl', 'http://localhost:8080/omniverse://127.0.0.1/NVIDIA/Materials/vMaterials_2/Glass/Glass_Clear.mdl', 'http://localhost:8080/omniverse://127.0.0.1/NVIDIA/Materials/vMaterials_2/Glass/Glass_Colored.mdl', 'http://localhost:8080/omniverse://127.0.0.1/NVIDIA/Materials/vMaterials_2/Glass/Glass_Optical.mdl', 'http://localhost:8080/omniverse://127.0.0.1/NVIDIA/Materials/vMaterials_2/Glass/Glass_Smudged.mdl', 'http://localhost:8080/omniverse://127.0.0.1/NVIDIA/Materials/vMaterials_2/Glass/Glazing_Clear.mdl', 'http://localhost:8080/omniverse://127.0.0.1/NVIDIA/Materials/vMaterials_2/Glass/Glazing_Float.mdl', 'http://localhost:8080/omniverse://127.0.0.1/NVIDIA/Materials/vMaterials_2/Glass/Mirror.mdl'], 'Masonry': ['http://localhost:8080/omniverse://127.0.0.1/NVIDIA/Materials/Base/Masonry/Adobe_Brick.mdl', 'http://localhost:8080/omniverse://127.0.0.1/NVIDIA/Materials/Base/Masonry/Brick_Pavers.mdl', 'http://localhost:8080/omniverse://127.0.0.1/NVIDIA/Materials/Base/Masonry/Brick_Wall_Brown.mdl', 'http://localhost:8080/omniverse://127.0.0.1/NVIDIA/Materials/Base/Masonry/Brick_Wall_Red.mdl', 'http://localhost:8080/omniverse://127.0.0.1/NVIDIA/Materials/Base/Masonry/Concrete_Block.mdl', 'http://localhost:8080/omniverse://127.0.0.1/NVIDIA/Materials/Base/Masonry/Concrete_Formed.mdl', 'http://localhost:8080/omniverse://127.0.0.1/NVIDIA/Materials/Base/Masonry/Concrete_Polished.mdl', 'http://localhost:8080/omniverse://127.0.0.1/NVIDIA/Materials/Base/Masonry/Concrete_Rough.mdl', 'http://localhost:8080/omniverse://127.0.0.1/NVIDIA/Materials/Base/Masonry/Concrete_Smooth.mdl', 'http://localhost:8080/omniverse://127.0.0.1/NVIDIA/Materials/Base/Masonry/Stucco.mdl', 'http://localhost:8080/omniverse://127.0.0.1/NVIDIA/Materials/vMaterials_2/Masonry/Facade_Brick_Red_Clinker.mdl'], 'Metals': ['http://localhost:8080/omniverse://127.0.0.1/NVIDIA/Materials/Base/Metals/Aluminum_Anodized.mdl', 'http://localhost:8080/omniverse://127.0.0.1/NVIDIA/Materials/Base/Metals/Aluminum_Anodized_Black.mdl', 'http://localhost:8080/omniverse://127.0.0.1/NVIDIA/Materials/Base/Metals/Aluminum_Anodized_Blue.mdl', 'http://localhost:8080/omniverse://127.0.0.1/NVIDIA/Materials/Base/Metals/Aluminum_Anodized_Charcoal.mdl', 'http://localhost:8080/omniverse://127.0.0.1/NVIDIA/Materials/Base/Metals/Aluminum_Anodized_Red.mdl', 'http://localhost:8080/omniverse://127.0.0.1/NVIDIA/Materials/Base/Metals/Aluminum_Cast.mdl', 'http://localhost:8080/omniverse://127.0.0.1/NVIDIA/Materials/Base/Metals/Aluminum_Polished.mdl', 'http://localhost:8080/omniverse://127.0.0.1/NVIDIA/Materials/Base/Metals/Brass.mdl', 'http://localhost:8080/omniverse://127.0.0.1/NVIDIA/Materials/Base/Metals/Bronze.mdl', 'http://localhost:8080/omniverse://127.0.0.1/NVIDIA/Materials/Base/Metals/Brushed_Antique_Copper.mdl', 'http://localhost:8080/omniverse://127.0.0.1/NVIDIA/Materials/Base/Metals/Cast_Metal_Silver_Vein.mdl', 'http://localhost:8080/omniverse://127.0.0.1/NVIDIA/Materials/Base/Metals/Chrome.mdl', 'http://localhost:8080/omniverse://127.0.0.1/NVIDIA/Materials/Base/Metals/Copper.mdl', 'http://localhost:8080/omniverse://127.0.0.1/NVIDIA/Materials/Base/Metals/CorrugatedMetal.mdl', 'http://localhost:8080/omniverse://127.0.0.1/NVIDIA/Materials/Base/Metals/Gold.mdl', 'http://localhost:8080/omniverse://127.0.0.1/NVIDIA/Materials/Base/Metals/Iron.mdl', 'http://localhost:8080/omniverse://127.0.0.1/NVIDIA/Materials/Base/Metals/Metal_Door.mdl', 'http://localhost:8080/omniverse://127.0.0.1/NVIDIA/Materials/Base/Metals/Metal_Seamed_Roof.mdl', 'http://localhost:8080/omniverse://127.0.0.1/NVIDIA/Materials/Base/Metals/RustedMetal.mdl', 'http://localhost:8080/omniverse://127.0.0.1/NVIDIA/Materials/Base/Metals/Silver.mdl', 'http://localhost:8080/omniverse://127.0.0.1/NVIDIA/Materials/Base/Metals/Steel_Blued.mdl', 'http://localhost:8080/omniverse://127.0.0.1/NVIDIA/Materials/Base/Metals/Steel_Carbon.mdl', 'http://localhost:8080/omniverse://127.0.0.1/NVIDIA/Materials/Base/Metals/Steel_Cast.mdl', 'http://localhost:8080/omniverse://127.0.0.1/NVIDIA/Materials/Base/Metals/Steel_Stainless.mdl'], 'Miscellaneous': ['http://localhost:8080/omniverse://127.0.0.1/NVIDIA/Materials/Base/Miscellaneous/Chain_Link_Fence.mdl', 'http://localhost:8080/omniverse://127.0.0.1/NVIDIA/Materials/Base/Miscellaneous/Paint_Gloss.mdl', 'http://localhost:8080/omniverse://127.0.0.1/NVIDIA/Materials/Base/Miscellaneous/Paint_Gloss_Finish.mdl', 'http://localhost:8080/omniverse://127.0.0.1/NVIDIA/Materials/Base/Miscellaneous/Paint_Matte.mdl', 'http://localhost:8080/omniverse://127.0.0.1/NVIDIA/Materials/Base/Miscellaneous/Paint_Matte_Finish.mdl', 'http://localhost:8080/omniverse://127.0.0.1/NVIDIA/Materials/Base/Miscellaneous/Paint_Satin.mdl', 'http://localhost:8080/omniverse://127.0.0.1/NVIDIA/Materials/Base/Miscellaneous/Paint_Satin_Finish.mdl'], 'Natural': ['http://localhost:8080/omniverse://127.0.0.1/NVIDIA/Materials/Base/Natural/Asphalt.mdl', 'http://localhost:8080/omniverse://127.0.0.1/NVIDIA/Materials/Base/Natural/Dirt.mdl', 'http://localhost:8080/omniverse://127.0.0.1/NVIDIA/Materials/Base/Natural/Grass_Countryside.mdl', 'http://localhost:8080/omniverse://127.0.0.1/NVIDIA/Materials/Base/Natural/Grass_Cut.mdl', 'http://localhost:8080/omniverse://127.0.0.1/NVIDIA/Materials/Base/Natural/Grass_Winter.mdl', 'http://localhost:8080/omniverse://127.0.0.1/NVIDIA/Materials/Base/Natural/Leaves.mdl', 'http://localhost:8080/omniverse://127.0.0.1/NVIDIA/Materials/Base/Natural/Mulch_Brown.mdl', 'http://localhost:8080/omniverse://127.0.0.1/NVIDIA/Materials/Base/Natural/Sand.mdl', 'http://localhost:8080/omniverse://127.0.0.1/NVIDIA/Materials/Base/Natural/Soil_Rocky.mdl', 'http://localhost:8080/omniverse://127.0.0.1/NVIDIA/Materials/Base/Natural/Water.mdl', 'http://localhost:8080/omniverse://127.0.0.1/NVIDIA/Materials/Base/Natural/Water_Opaque.mdl'], 'Plastics': ['http://localhost:8080/omniverse://127.0.0.1/NVIDIA/Materials/Base/Plastics/Plastic.mdl', 'http://localhost:8080/omniverse://127.0.0.1/NVIDIA/Materials/Base/Plastics/Plastic_ABS.mdl', 'http://localhost:8080/omniverse://127.0.0.1/NVIDIA/Materials/Base/Plastics/Plastic_Acrylic.mdl', 'http://localhost:8080/omniverse://127.0.0.1/NVIDIA/Materials/Base/Plastics/Plastic_Clear.mdl', 'http://localhost:8080/omniverse://127.0.0.1/NVIDIA/Materials/Base/Plastics/Rubber_Smooth.mdl', 'http://localhost:8080/omniverse://127.0.0.1/NVIDIA/Materials/Base/Plastics/Rubber_Textured.mdl', 'http://localhost:8080/omniverse://127.0.0.1/NVIDIA/Materials/Base/Plastics/Veneer_OU_Walnut.mdl', 'http://localhost:8080/omniverse://127.0.0.1/NVIDIA/Materials/Base/Plastics/Veneer_UX_Walnut_Cherry.mdl', 'http://localhost:8080/omniverse://127.0.0.1/NVIDIA/Materials/Base/Plastics/Veneer_Z5_Maple.mdl', 'http://localhost:8080/omniverse://127.0.0.1/NVIDIA/Materials/Base/Plastics/Vinyl.mdl'], 'Stone': ['http://localhost:8080/omniverse://127.0.0.1/NVIDIA/Materials/Base/Stone/Adobe_Octagon_Dots.mdl', 'http://localhost:8080/omniverse://127.0.0.1/NVIDIA/Materials/Base/Stone/Ceramic_Smooth_Fired.mdl', 'http://localhost:8080/omniverse://127.0.0.1/NVIDIA/Materials/Base/Stone/Ceramic_Tile_12.mdl', 'http://localhost:8080/omniverse://127.0.0.1/NVIDIA/Materials/Base/Stone/Ceramic_Tile_18.mdl', 'http://localhost:8080/omniverse://127.0.0.1/NVIDIA/Materials/Base/Stone/Ceramic_Tile_6.mdl', 'http://localhost:8080/omniverse://127.0.0.1/NVIDIA/Materials/Base/Stone/Fieldstone.mdl', 'http://localhost:8080/omniverse://127.0.0.1/NVIDIA/Materials/Base/Stone/Granite_Dark.mdl', 'http://localhost:8080/omniverse://127.0.0.1/NVIDIA/Materials/Base/Stone/Granite_Light.mdl', 'http://localhost:8080/omniverse://127.0.0.1/NVIDIA/Materials/Base/Stone/Gravel.mdl', 'http://localhost:8080/omniverse://127.0.0.1/NVIDIA/Materials/Base/Stone/Gravel_River_Rock.mdl', 'http://localhost:8080/omniverse://127.0.0.1/NVIDIA/Materials/Base/Stone/Marble.mdl', 'http://localhost:8080/omniverse://127.0.0.1/NVIDIA/Materials/Base/Stone/Marble_Smooth.mdl', 'http://localhost:8080/omniverse://127.0.0.1/NVIDIA/Materials/Base/Stone/Marble_Tile_12.mdl', 'http://localhost:8080/omniverse://127.0.0.1/NVIDIA/Materials/Base/Stone/Marble_Tile_18.mdl', 'http://localhost:8080/omniverse://127.0.0.1/NVIDIA/Materials/Base/Stone/Pea_Gravel.mdl', 'http://localhost:8080/omniverse://127.0.0.1/NVIDIA/Materials/Base/Stone/Porcelain_Smooth.mdl', 'http://localhost:8080/omniverse://127.0.0.1/NVIDIA/Materials/Base/Stone/Porcelain_Tile_4.mdl', 'http://localhost:8080/omniverse://127.0.0.1/NVIDIA/Materials/Base/Stone/Porcelain_Tile_4_Linen.mdl', 'http://localhost:8080/omniverse://127.0.0.1/NVIDIA/Materials/Base/Stone/Porcelain_Tile_6.mdl', 'http://localhost:8080/omniverse://127.0.0.1/NVIDIA/Materials/Base/Stone/Porcelain_Tile_6_Linen.mdl', 'http://localhost:8080/omniverse://127.0.0.1/NVIDIA/Materials/Base/Stone/Retaining_Block.mdl', 'http://localhost:8080/omniverse://127.0.0.1/NVIDIA/Materials/Base/Stone/Slate.mdl', 'http://localhost:8080/omniverse://127.0.0.1/NVIDIA/Materials/Base/Stone/Stone_Wall.mdl', 'http://localhost:8080/omniverse://127.0.0.1/NVIDIA/Materials/Base/Stone/Terracotta.mdl', 'http://localhost:8080/omniverse://127.0.0.1/NVIDIA/Materials/Base/Stone/Terrazzo.mdl', 'http://localhost:8080/omniverse://127.0.0.1/NVIDIA/Materials/vMaterials_2/Stone/Cobblestone_Big_and_Loose.mdl', 'http://localhost:8080/omniverse://127.0.0.1/NVIDIA/Materials/vMaterials_2/Stone/Granite_Polished.mdl', 'http://localhost:8080/omniverse://127.0.0.1/NVIDIA/Materials/vMaterials_2/Stone/Stone_Mediterranean.mdl', 'http://localhost:8080/omniverse://127.0.0.1/NVIDIA/Materials/vMaterials_2/Stone/Stone_Natural_Black.mdl'], 'Styles': ['http://localhost:8080/omniverse://127.0.0.1/NVIDIA/Materials/Base/Styles/WhiteMode.mdl'], 'Templates': ['http://localhost:8080/omniverse://127.0.0.1/NVIDIA/Materials/Base/Templates/GlassUtils.mdl', 'http://localhost:8080/omniverse://127.0.0.1/NVIDIA/Materials/Base/Templates/GlassWithVolume.mdl'], 'Textiles': ['http://localhost:8080/omniverse://127.0.0.1/NVIDIA/Materials/Base/Textiles/Cloth_Black.mdl', 'http://localhost:8080/omniverse://127.0.0.1/NVIDIA/Materials/Base/Textiles/Cloth_Gray.mdl', 'http://localhost:8080/omniverse://127.0.0.1/NVIDIA/Materials/Base/Textiles/Leather_Black.mdl', 'http://localhost:8080/omniverse://127.0.0.1/NVIDIA/Materials/Base/Textiles/Leather_Brown.mdl', 'http://localhost:8080/omniverse://127.0.0.1/NVIDIA/Materials/Base/Textiles/Leather_Pumpkin.mdl', 'http://localhost:8080/omniverse://127.0.0.1/NVIDIA/Materials/Base/Textiles/Linen_Beige.mdl', 'http://localhost:8080/omniverse://127.0.0.1/NVIDIA/Materials/Base/Textiles/Linen_Blue.mdl', 'http://localhost:8080/omniverse://127.0.0.1/NVIDIA/Materials/Base/Textiles/Linen_White.mdl'], 'Wall_Board': ['http://localhost:8080/omniverse://127.0.0.1/NVIDIA/Materials/Base/Wall_Board/Cardboard.mdl', 'http://localhost:8080/omniverse://127.0.0.1/NVIDIA/Materials/Base/Wall_Board/Gypsum.mdl', 'http://localhost:8080/omniverse://127.0.0.1/NVIDIA/Materials/Base/Wall_Board/MDF.mdl', 'http://localhost:8080/omniverse://127.0.0.1/NVIDIA/Materials/Base/Wall_Board/Paper.mdl', 'http://localhost:8080/omniverse://127.0.0.1/NVIDIA/Materials/Base/Wall_Board/Plaster.mdl'], 'Wood': ['http://localhost:8080/omniverse://127.0.0.1/NVIDIA/Materials/Base/Wood/Ash.mdl', 'http://localhost:8080/omniverse://127.0.0.1/NVIDIA/Materials/Base/Wood/Ash_Planks.mdl', 'http://localhost:8080/omniverse://127.0.0.1/NVIDIA/Materials/Base/Wood/Bamboo.mdl', 'http://localhost:8080/omniverse://127.0.0.1/NVIDIA/Materials/Base/Wood/Bamboo_Planks.mdl', 'http://localhost:8080/omniverse://127.0.0.1/NVIDIA/Materials/Base/Wood/Beadboard.mdl', 'http://localhost:8080/omniverse://127.0.0.1/NVIDIA/Materials/Base/Wood/Birch.mdl', 'http://localhost:8080/omniverse://127.0.0.1/NVIDIA/Materials/Base/Wood/Birch_Planks.mdl', 'http://localhost:8080/omniverse://127.0.0.1/NVIDIA/Materials/Base/Wood/Cherry.mdl', 'http://localhost:8080/omniverse://127.0.0.1/NVIDIA/Materials/Base/Wood/Cherry_Planks.mdl', 'http://localhost:8080/omniverse://127.0.0.1/NVIDIA/Materials/Base/Wood/Cork.mdl', 'http://localhost:8080/omniverse://127.0.0.1/NVIDIA/Materials/Base/Wood/Mahogany.mdl', 'http://localhost:8080/omniverse://127.0.0.1/NVIDIA/Materials/Base/Wood/Mahogany_Planks.mdl', 'http://localhost:8080/omniverse://127.0.0.1/NVIDIA/Materials/Base/Wood/Oak.mdl', 'http://localhost:8080/omniverse://127.0.0.1/NVIDIA/Materials/Base/Wood/Oak_Planks.mdl', 'http://localhost:8080/omniverse://127.0.0.1/NVIDIA/Materials/Base/Wood/Parquet_Floor.mdl', 'http://localhost:8080/omniverse://127.0.0.1/NVIDIA/Materials/Base/Wood/Plywood.mdl', 'http://localhost:8080/omniverse://127.0.0.1/NVIDIA/Materials/Base/Wood/Timber.mdl', 'http://localhost:8080/omniverse://127.0.0.1/NVIDIA/Materials/Base/Wood/Timber_Cladding.mdl', 'http://localhost:8080/omniverse://127.0.0.1/NVIDIA/Materials/Base/Wood/Walnut.mdl', 'http://localhost:8080/omniverse://127.0.0.1/NVIDIA/Materials/Base/Wood/Walnut_Planks.mdl', 'http://localhost:8080/omniverse://127.0.0.1/NVIDIA/Materials/vMaterials_2/Wood/Laminate_Oak.mdl', 'http://localhost:8080/omniverse://127.0.0.1/NVIDIA/Materials/vMaterials_2/Wood/Wood_Bark.mdl', 'http://localhost:8080/omniverse://127.0.0.1/NVIDIA/Materials/vMaterials_2/Wood/Wood_Cork.mdl', 'http://localhost:8080/omniverse://127.0.0.1/NVIDIA/Materials/vMaterials_2/Wood/Wood_Tiles_Ash.mdl', 'http://localhost:8080/omniverse://127.0.0.1/NVIDIA/Materials/vMaterials_2/Wood/Wood_Tiles_Beech.mdl', 'http://localhost:8080/omniverse://127.0.0.1/NVIDIA/Materials/vMaterials_2/Wood/Wood_Tiles_Fineline.mdl', 'http://localhost:8080/omniverse://127.0.0.1/NVIDIA/Materials/vMaterials_2/Wood/Wood_Tiles_Oak_Mountain.mdl', 'http://localhost:8080/omniverse://127.0.0.1/NVIDIA/Materials/vMaterials_2/Wood/Wood_Tiles_Pine.mdl', 'http://localhost:8080/omniverse://127.0.0.1/NVIDIA/Materials/vMaterials_2/Wood/Wood_Tiles_Poplar.mdl', 'http://localhost:8080/omniverse://127.0.0.1/NVIDIA/Materials/vMaterials_2/Wood/Wood_Tiles_Walnut.mdl'], 'Ceramic': ['http://localhost:8080/omniverse://127.0.0.1/NVIDIA/Materials/vMaterials_2/Ceramic/Grog_Fired_Clay.mdl'], 'Concrete': ['http://localhost:8080/omniverse://127.0.0.1/NVIDIA/Materials/vMaterials_2/Concrete/Concrete_Precast.mdl', 'http://localhost:8080/omniverse://127.0.0.1/NVIDIA/Materials/vMaterials_2/Concrete/Spongy_Concrete_Weathered.mdl', 'http://localhost:8080/omniverse://127.0.0.1/NVIDIA/Materials/vMaterials_2/Concrete/Spongy_Concrete_Weathered_Mossy.mdl'], 'Fabric': ['http://localhost:8080/omniverse://127.0.0.1/NVIDIA/Materials/vMaterials_2/Fabric/Cotton_Roughly_Woven.mdl', 'http://localhost:8080/omniverse://127.0.0.1/NVIDIA/Materials/vMaterials_2/Fabric/Fabric_Cotton_Fine_Woven.mdl', 'http://localhost:8080/omniverse://127.0.0.1/NVIDIA/Materials/vMaterials_2/Fabric/Fabric_Cotton_Pique_Weave.mdl', 'http://localhost:8080/omniverse://127.0.0.1/NVIDIA/Materials/vMaterials_2/Fabric/Felt_Plain.mdl', 'http://localhost:8080/omniverse://127.0.0.1/NVIDIA/Materials/vMaterials_2/Fabric/Tweed_Herringbone.mdl'], 'Facade': ['http://localhost:8080/omniverse://127.0.0.1/NVIDIA/Materials/vMaterials_2/Facade/Facade_Brick_Grey.mdl', 'http://localhost:8080/omniverse://127.0.0.1/NVIDIA/Materials/vMaterials_2/Facade/Facade_Granular_Noise.mdl', 'http://localhost:8080/omniverse://127.0.0.1/NVIDIA/Materials/vMaterials_2/Facade/Facade_Plaster_Rough.mdl', 'http://localhost:8080/omniverse://127.0.0.1/NVIDIA/Materials/vMaterials_2/Facade/Plaster_Wall.mdl'], 'Ground': ['http://localhost:8080/omniverse://127.0.0.1/NVIDIA/Materials/vMaterials_2/Ground/Gravel_Track_Ballast.mdl', 'http://localhost:8080/omniverse://127.0.0.1/NVIDIA/Materials/vMaterials_2/Ground/Ground_Aggregate_Exposed.mdl', 'http://localhost:8080/omniverse://127.0.0.1/NVIDIA/Materials/vMaterials_2/Ground/Ground_Hard_Court.mdl', 'http://localhost:8080/omniverse://127.0.0.1/NVIDIA/Materials/vMaterials_2/Ground/Ground_Leaves.mdl', 'http://localhost:8080/omniverse://127.0.0.1/NVIDIA/Materials/vMaterials_2/Ground/Ground_Leaves_Oak.mdl', 'http://localhost:8080/omniverse://127.0.0.1/NVIDIA/Materials/vMaterials_2/Ground/Large_Granite_Paving.mdl', 'http://localhost:8080/omniverse://127.0.0.1/NVIDIA/Materials/vMaterials_2/Ground/Rough_Gravel.mdl'], 'Liquids': ['http://localhost:8080/omniverse://127.0.0.1/NVIDIA/Materials/vMaterials_2/Liquids/Water_Blue_Ocean_Perlinwaves.mdl', 'http://localhost:8080/omniverse://127.0.0.1/NVIDIA/Materials/vMaterials_2/Liquids/Water_Murky_Perlinwaves.mdl'], 'Metal': ['http://localhost:8080/omniverse://127.0.0.1/NVIDIA/Materials/vMaterials_2/Metal/Aluminum.mdl', 'http://localhost:8080/omniverse://127.0.0.1/NVIDIA/Materials/vMaterials_2/Metal/Aluminum_Brushed.mdl', 'http://localhost:8080/omniverse://127.0.0.1/NVIDIA/Materials/vMaterials_2/Metal/Aluminum_Foil.mdl', 'http://localhost:8080/omniverse://127.0.0.1/NVIDIA/Materials/vMaterials_2/Metal/Aluminum_Knurling.mdl', 'http://localhost:8080/omniverse://127.0.0.1/NVIDIA/Materials/vMaterials_2/Metal/Aluminum_Scratched.mdl', 'http://localhost:8080/omniverse://127.0.0.1/NVIDIA/Materials/vMaterials_2/Metal/Aluminum_Sheet.mdl', 'http://localhost:8080/omniverse://127.0.0.1/NVIDIA/Materials/vMaterials_2/Metal/Chromium.mdl', 'http://localhost:8080/omniverse://127.0.0.1/NVIDIA/Materials/vMaterials_2/Metal/Chromium_Brushed.mdl', 'http://localhost:8080/omniverse://127.0.0.1/NVIDIA/Materials/vMaterials_2/Metal/Chromium_Foil.mdl', 'http://localhost:8080/omniverse://127.0.0.1/NVIDIA/Materials/vMaterials_2/Metal/Chromium_Knurling.mdl', 'http://localhost:8080/omniverse://127.0.0.1/NVIDIA/Materials/vMaterials_2/Metal/Chromium_Scratched.mdl', 'http://localhost:8080/omniverse://127.0.0.1/NVIDIA/Materials/vMaterials_2/Metal/Chromium_Sheet.mdl', 'http://localhost:8080/omniverse://127.0.0.1/NVIDIA/Materials/vMaterials_2/Metal/Copper.mdl', 'http://localhost:8080/omniverse://127.0.0.1/NVIDIA/Materials/vMaterials_2/Metal/Copper_Antique_Brushed.mdl', 'http://localhost:8080/omniverse://127.0.0.1/NVIDIA/Materials/vMaterials_2/Metal/Copper_Antique_Brushed_Patinated.mdl', 'http://localhost:8080/omniverse://127.0.0.1/NVIDIA/Materials/vMaterials_2/Metal/Copper_Brushed.mdl', 'http://localhost:8080/omniverse://127.0.0.1/NVIDIA/Materials/vMaterials_2/Metal/Copper_Foil.mdl', 'http://localhost:8080/omniverse://127.0.0.1/NVIDIA/Materials/vMaterials_2/Metal/Copper_Knurling.mdl', 'http://localhost:8080/omniverse://127.0.0.1/NVIDIA/Materials/vMaterials_2/Metal/Copper_Scratched.mdl', 'http://localhost:8080/omniverse://127.0.0.1/NVIDIA/Materials/vMaterials_2/Metal/Copper_Sheet.mdl', 'http://localhost:8080/omniverse://127.0.0.1/NVIDIA/Materials/vMaterials_2/Metal/Gold.mdl', 'http://localhost:8080/omniverse://127.0.0.1/NVIDIA/Materials/vMaterials_2/Metal/Gold_Brushed.mdl', 'http://localhost:8080/omniverse://127.0.0.1/NVIDIA/Materials/vMaterials_2/Metal/Gold_Foil.mdl', 'http://localhost:8080/omniverse://127.0.0.1/NVIDIA/Materials/vMaterials_2/Metal/Gold_Knurling.mdl', 'http://localhost:8080/omniverse://127.0.0.1/NVIDIA/Materials/vMaterials_2/Metal/Gold_Scratched.mdl', 'http://localhost:8080/omniverse://127.0.0.1/NVIDIA/Materials/vMaterials_2/Metal/Gold_Sheet.mdl', 'http://localhost:8080/omniverse://127.0.0.1/NVIDIA/Materials/vMaterials_2/Metal/Iron.mdl', 'http://localhost:8080/omniverse://127.0.0.1/NVIDIA/Materials/vMaterials_2/Metal/Iron_Brushed.mdl', 'http://localhost:8080/omniverse://127.0.0.1/NVIDIA/Materials/vMaterials_2/Metal/Iron_Foil.mdl', 'http://localhost:8080/omniverse://127.0.0.1/NVIDIA/Materials/vMaterials_2/Metal/Iron_Knurling.mdl', 'http://localhost:8080/omniverse://127.0.0.1/NVIDIA/Materials/vMaterials_2/Metal/Iron_Pitted_Steel.mdl', 'http://localhost:8080/omniverse://127.0.0.1/NVIDIA/Materials/vMaterials_2/Metal/Iron_Scratched.mdl', 'http://localhost:8080/omniverse://127.0.0.1/NVIDIA/Materials/vMaterials_2/Metal/Iron_Sheet.mdl', 'http://localhost:8080/omniverse://127.0.0.1/NVIDIA/Materials/vMaterials_2/Metal/Mercury.mdl', 'http://localhost:8080/omniverse://127.0.0.1/NVIDIA/Materials/vMaterials_2/Metal/Nickel.mdl', 'http://localhost:8080/omniverse://127.0.0.1/NVIDIA/Materials/vMaterials_2/Metal/Nickel_Brushed.mdl', 'http://localhost:8080/omniverse://127.0.0.1/NVIDIA/Materials/vMaterials_2/Metal/Nickel_Foil.mdl', 'http://localhost:8080/omniverse://127.0.0.1/NVIDIA/Materials/vMaterials_2/Metal/Nickel_Knurling.mdl', 'http://localhost:8080/omniverse://127.0.0.1/NVIDIA/Materials/vMaterials_2/Metal/Nickel_Scratched.mdl', 'http://localhost:8080/omniverse://127.0.0.1/NVIDIA/Materials/vMaterials_2/Metal/Nickel_Sheet.mdl', 'http://localhost:8080/omniverse://127.0.0.1/NVIDIA/Materials/vMaterials_2/Metal/Platinum.mdl', 'http://localhost:8080/omniverse://127.0.0.1/NVIDIA/Materials/vMaterials_2/Metal/Platinum_Brushed.mdl', 'http://localhost:8080/omniverse://127.0.0.1/NVIDIA/Materials/vMaterials_2/Metal/Platinum_Foil.mdl', 'http://localhost:8080/omniverse://127.0.0.1/NVIDIA/Materials/vMaterials_2/Metal/Platinum_Knurling.mdl', 'http://localhost:8080/omniverse://127.0.0.1/NVIDIA/Materials/vMaterials_2/Metal/Platinum_Scratched.mdl', 'http://localhost:8080/omniverse://127.0.0.1/NVIDIA/Materials/vMaterials_2/Metal/Platinum_Sheet.mdl', 'http://localhost:8080/omniverse://127.0.0.1/NVIDIA/Materials/vMaterials_2/Metal/Silver.mdl', 'http://localhost:8080/omniverse://127.0.0.1/NVIDIA/Materials/vMaterials_2/Metal/Silver_Brushed.mdl', 'http://localhost:8080/omniverse://127.0.0.1/NVIDIA/Materials/vMaterials_2/Metal/Silver_Foil.mdl', 'http://localhost:8080/omniverse://127.0.0.1/NVIDIA/Materials/vMaterials_2/Metal/Silver_Knurling.mdl', 'http://localhost:8080/omniverse://127.0.0.1/NVIDIA/Materials/vMaterials_2/Metal/Silver_Scratched.mdl', 'http://localhost:8080/omniverse://127.0.0.1/NVIDIA/Materials/vMaterials_2/Metal/Silver_Sheet.mdl', 'http://localhost:8080/omniverse://127.0.0.1/NVIDIA/Materials/vMaterials_2/Metal/Titanium.mdl', 'http://localhost:8080/omniverse://127.0.0.1/NVIDIA/Materials/vMaterials_2/Metal/Titanium_Brushed.mdl', 'http://localhost:8080/omniverse://127.0.0.1/NVIDIA/Materials/vMaterials_2/Metal/Titanium_Foil.mdl', 'http://localhost:8080/omniverse://127.0.0.1/NVIDIA/Materials/vMaterials_2/Metal/Titanium_Knurling.mdl', 'http://localhost:8080/omniverse://127.0.0.1/NVIDIA/Materials/vMaterials_2/Metal/Titanium_Scratched.mdl', 'http://localhost:8080/omniverse://127.0.0.1/NVIDIA/Materials/vMaterials_2/Metal/Titanium_Sheet.mdl', 'http://localhost:8080/omniverse://127.0.0.1/NVIDIA/Materials/vMaterials_2/Metal/Tungsten.mdl', 'http://localhost:8080/omniverse://127.0.0.1/NVIDIA/Materials/vMaterials_2/Metal/Tungsten_Brushed.mdl', 'http://localhost:8080/omniverse://127.0.0.1/NVIDIA/Materials/vMaterials_2/Metal/Tungsten_Foil.mdl', 'http://localhost:8080/omniverse://127.0.0.1/NVIDIA/Materials/vMaterials_2/Metal/Tungsten_Knurling.mdl', 'http://localhost:8080/omniverse://127.0.0.1/NVIDIA/Materials/vMaterials_2/Metal/Tungsten_Scratched.mdl', 'http://localhost:8080/omniverse://127.0.0.1/NVIDIA/Materials/vMaterials_2/Metal/Tungsten_Sheet.mdl', 'http://localhost:8080/omniverse://127.0.0.1/NVIDIA/Materials/vMaterials_2/Metal/Zinc.mdl', 'http://localhost:8080/omniverse://127.0.0.1/NVIDIA/Materials/vMaterials_2/Metal/Zinc_Brushed.mdl', 'http://localhost:8080/omniverse://127.0.0.1/NVIDIA/Materials/vMaterials_2/Metal/Zinc_Foil.mdl', 'http://localhost:8080/omniverse://127.0.0.1/NVIDIA/Materials/vMaterials_2/Metal/Zinc_Knurling.mdl', 'http://localhost:8080/omniverse://127.0.0.1/NVIDIA/Materials/vMaterials_2/Metal/Zinc_Scratched.mdl', 'http://localhost:8080/omniverse://127.0.0.1/NVIDIA/Materials/vMaterials_2/Metal/Zinc_Sheet.mdl'], 'Paint': ['http://localhost:8080/omniverse://127.0.0.1/NVIDIA/Materials/vMaterials_2/Paint/Chalk_Paint.mdl', 'http://localhost:8080/omniverse://127.0.0.1/NVIDIA/Materials/vMaterials_2/Paint/Chalk_Paint_Pebbles.mdl', 'http://localhost:8080/omniverse://127.0.0.1/NVIDIA/Materials/vMaterials_2/Paint/Paint_Eggshell.mdl', 'http://localhost:8080/omniverse://127.0.0.1/NVIDIA/Materials/vMaterials_2/Paint/Paint_Gun_Metal.mdl'], 'Paper': ['http://localhost:8080/omniverse://127.0.0.1/NVIDIA/Materials/vMaterials_2/Paper/Cardboard.mdl'], 'Plastic': ['http://localhost:8080/omniverse://127.0.0.1/NVIDIA/Materials/vMaterials_2/Plastic/Plastic_Thick_Translucent.mdl', 'http://localhost:8080/omniverse://127.0.0.1/NVIDIA/Materials/vMaterials_2/Plastic/Plastic_Thick_Translucent_Flakes.mdl', 'http://localhost:8080/omniverse://127.0.0.1/NVIDIA/Materials/vMaterials_2/Plastic/Styrofoam.mdl']}
|
yizhouzhao/VRKitchen2.0-IndoorKit/exts/vrkitchen.indoor.kit/vrkitchen/indoor/kit/robot_setup/numpy_utils.py | import numpy as np
def orientation_error(desired, current):
cc = quat_conjugate(current)
q_r = quat_mul(desired, cc)
return q_r[:, 0:3] * np.sign(q_r[:, 3])[:, None]
def quat_mul(a, b):
assert a.shape == b.shape
shape = a.shape
a = a.reshape(-1, 4)
b = b.reshape(-1, 4)
x1, y1, z1, w1 = a[:, 0], a[:, 1], a[:, 2], a[:, 3]
x2, y2, z2, w2 = b[:, 0], b[:, 1], b[:, 2], b[:, 3]
ww = (z1 + x1) * (x2 + y2)
yy = (w1 - y1) * (w2 + z2)
zz = (w1 + y1) * (w2 - z2)
xx = ww + yy + zz
qq = 0.5 * (xx + (z1 - x1) * (x2 - y2))
w = qq - ww + (z1 - y1) * (y2 - z2)
x = qq - xx + (x1 + w1) * (x2 + w2)
y = qq - yy + (w1 - x1) * (y2 + z2)
z = qq - zz + (z1 + y1) * (w2 - x2)
quat = np.stack([x, y, z, w], axis=-1).reshape(shape)
return quat
def normalize(x, eps: float = 1e-9):
return x / np.clip(np.linalg.norm(x, axis=-1), a_min=eps, a_max=None)[:, None]
def quat_unit(a):
return normalize(a)
def quat_from_angle_axis(angle, axis):
theta = (angle / 2)[:, None]
xyz = normalize(axis) * np.sin(theta)
w = np.cos(theta)
return quat_unit(np.concatenate([xyz, w], axis=-1))
def quat_rotate(q, v):
shape = q.shape
q_w = q[:, -1]
q_vec = q[:, :3]
a = v * (2.0 * q_w ** 2 - 1.0)[:, None]
b = np.cross(q_vec, v) * q_w[:, None] * 2.0
c = q_vec * np.sum(q_vec * v, axis=1).reshape(shape[0], -1) * 2.0
return a + b + c
def quat_conjugate(a):
shape = a.shape
a = a.reshape(-1, 4)
return np.concatenate((-a[:, :3], a[:, -1:]), axis=-1).reshape(shape)
def quat_axis(q, axis=0):
basis_vec = np.zeros((q.shape[0], 3))
basis_vec[:, axis] = 1
return quat_rotate(q, basis_vec)
|
yizhouzhao/VRKitchen2.0-IndoorKit/exts/vrkitchen.indoor.kit/vrkitchen/indoor/kit/robot_setup/controller.py | # controller
import carb
class Controller():
w = False
s = False
a = False
d = False
q = False
e = False
up = False
down = False
left = False
right = False
# Controller.scale = 0.1
left_control = False
def __init__(self) -> None:
self.user_control = 0.25
self.network_control = 0.25
Controller.reset_movement()
@classmethod
def reset_movement(cls):
Controller.w = False
Controller.s = False
Controller.a = False
Controller.d = False
Controller.q = False
Controller.e = False
Controller.up = False
Controller.down = False
Controller.left = False
Controller.right = False
# Controller.left_control = False
def handle_keyboard_event(self, event):
if (
event.type == carb.input.KeyboardEventType.KEY_PRESS
or event.type == carb.input.KeyboardEventType.KEY_REPEAT
):
# print("event input", event.input)
if event.input == carb.input.KeyboardInput.W:
Controller.w = True
if event.input == carb.input.KeyboardInput.S:
Controller.s = True
if event.input == carb.input.KeyboardInput.A:
Controller.a = True
if event.input == carb.input.KeyboardInput.D:
Controller.d = True
if event.input == carb.input.KeyboardInput.Q:
Controller.q = True
if event.input == carb.input.KeyboardInput.E:
Controller.e = True
if event.input == carb.input.KeyboardInput.UP:
Controller.up = True
if event.input == carb.input.KeyboardInput.DOWN:
Controller.down = True
if event.input == carb.input.KeyboardInput.LEFT:
Controller.left = True
if event.input == carb.input.KeyboardInput.RIGHT:
Controller.right = True
if event.input == carb.input.KeyboardInput.LEFT_CONTROL:
Controller.left_control = True
if event.type == carb.input.KeyboardEventType.KEY_RELEASE:
# print("event release", event.input)
if event.input == carb.input.KeyboardInput.W:
Controller.w = False
if event.input == carb.input.KeyboardInput.S:
Controller.s = False
if event.input == carb.input.KeyboardInput.A:
Controller.a = False
if event.input == carb.input.KeyboardInput.D:
Controller.d = False
if event.input == carb.input.KeyboardInput.Q:
Controller.q = False
if event.input == carb.input.KeyboardInput.E:
Controller.e = False
if event.input == carb.input.KeyboardInput.UP:
Controller.up = False
if event.input == carb.input.KeyboardInput.DOWN:
Controller.down = False
if event.input == carb.input.KeyboardInput.LEFT:
Controller.left = False
if event.input == carb.input.KeyboardInput.RIGHT:
Controller.right = False
if event.input == carb.input.KeyboardInput.LEFT_CONTROL:
Controller.left_control = False
def PoolUserControl(self):
return self.user_control
def PoolNetworkControl(self):
return 0.1 if Controller.w else 0.25
def QueryMove(self):
move = [0, 0, 0]
if Controller.w:
move[0] += 1
if Controller.s:
move[0] -= 1
if Controller.a:
move[1] += 1
if Controller.d:
move[1] -= 1
if Controller.q:
move[2] -= 1
if Controller.e:
move[2] += 1
return move
def QueryRotation(self):
rotation = [0, 0]
if Controller.up:
rotation[0] += 1
if Controller.down:
rotation[0] -= 1
if Controller.left:
rotation[1] += 1
if Controller.right:
rotation[1] -= 1
return rotation
def QueryGripper(self):
if not Controller.left_control:
return 1 # open
else:
return -1 # close |
yizhouzhao/VRKitchen2.0-IndoorKit/exts/vrkitchen.indoor.kit/vrkitchen/indoor/kit/robot_setup/franka_tensor.py | from numpy.lib.index_tricks import fill_diagonal
import omni
import carb
import types
import numpy as np
import importlib
import os
import shutil
from ..param import IS_IN_CREAT, IS_IN_ISAAC_SIM, APP_VERION, SAVE_ROOT
from .controller import Controller
from .numpy_utils import orientation_error
from pxr import Usd, UsdGeom, Gf
class FrankaTensor():
def __init__(self, save_path, build_HUD = True):
"""
Franka tensor controller
::params:
save_path: path to save the recordings
build_HUD: build UI
"""
carb.log_info("Franks Tensor started (only in Create/Isaac-Sim >= 2022.1.0)")
self._is_stopped = True
self._tensor_started = False
self._tensor_api = None
self._flatcache_was_enabled = True
self._tensorapi_was_enabled = True
# stage
self.stage = omni.usd.get_context().get_stage()
self.franka_prim = self.stage.GetPrimAtPath("/World/game/franka")
# property
self.is_replay = False
self.is_record = False
# counting and index
self.count_down = 80
self.button_status = 0
self.npz_index = 0
self.is_start = True
# setup subscriptions:
self._setup_callbacks()
self._enable_tensor_api()
# task info
self.save_path = save_path
self.record_lines = []
# controller
self.controller = Controller()
def _enable_tensor_api(self):
manager = omni.kit.app.get_app().get_extension_manager()
self._tensorapi_was_enabled = manager.is_extension_enabled("omni.physx.tensors")
if not self._tensorapi_was_enabled:
manager.set_extension_enabled_immediate("omni.physx.tensors", True)
self._tensor_api = importlib.import_module("omni.physics.tensors")
# "PRIVATE" METHODS #
def _can_callback_physics_step(self) -> bool:
if self._is_stopped:
return False
if self._tensor_started or self._tensor_api is None:
return True
self._tensor_started = True
self.on_tensor_start(self._tensor_api)
return True
def on_tensor_start(self, tensorApi: types.ModuleType):
"""
This method is called when
1. the tensor API is enabled, and
2. when the simulation data is ready for the user to setup views using the tensor API.
"""
# if IS_IN_CREAT and APP_VERION >= "2022.1.1":
sim = tensorApi.create_simulation_view("numpy")
sim.set_subspace_roots("/World/game/*")
# franka view
self.frankas = sim.create_articulation_view("/World/game/franka")
self.franka_indices = np.arange(self.frankas.count, dtype=np.int32)
# !!!
# self.default_dof_pos = np.array([0.0, 0.0, 0.0, -0.95, 0.0, 1.12, 0.0, 0.02, 0.02])
self.default_dof_pos = np.array([1.2024134e-02, -5.6960440e-01, 7.3155526e-05, -2.8114836e+00,
-4.8544933e-03, 3.0270250e+00, 7.2893953e-01, 3.9919264e+00, 4.0000000e+00])
# set default dof pos:
init_dof_pos = np.stack(1 * [np.array(self.default_dof_pos, dtype=np.float32)])
self.frankas.set_dof_position_targets(init_dof_pos, self.franka_indices)
self.last_gripper_action = 1 # open as default
# end effector view
self.hands = sim.create_rigid_body_view("/World/game/franka/panda_hand")
# get initial hand transforms
# init_hand_transforms = self.hands.get_transforms().copy()
# self.hand_pos = init_hand_transforms[:, :3]
# self.hand_rot = init_hand_transforms[:, 3:]
# target
# self.target_pos = self.default_dof_pos[None, :]
# self.target_hand_transform = init_hand_transforms
def _setup_callbacks(self):
stream = omni.timeline.get_timeline_interface().get_timeline_event_stream()
self._timeline_sub = stream.create_subscription_to_pop(self._on_timeline_event)
# subscribe to Physics updates:
self._physics_update_sub = omni.physx.get_physx_interface().subscribe_physics_step_events(self._on_physics_step)
events = omni.physx.get_physx_interface().get_simulation_event_stream_v2()
self._simulation_event_subscription = events.create_subscription_to_pop(self.on_simulation_event)
# subscribute to keyboard
self._appwindow = omni.appwindow.get_default_app_window()
self._input = carb.input.acquire_input_interface()
self._keyboard = self._appwindow.get_keyboard()
self._sub_keyboard = self._input.subscribe_to_keyboard_events(self._keyboard, self._sub_keyboard_event)
def _sub_keyboard_event(self, event, *args, **kwargs):
self.controller.handle_keyboard_event(event)
def _on_timeline_event(self, e):
if e.type == int(omni.timeline.TimelineEventType.STOP):
self._is_stopped = True
self._tensor_started = False
# !!!
self._timeline_sub = None
self._simulation_event_subscription = None
self._physics_update_sub = None
self._input.unsubscribe_to_keyboard_events(self._keyboard, self._sub_keyboard)
if e.type == int(omni.timeline.TimelineEventType.PLAY):
self._is_stopped = False
# call user implementation
# self.on_timeline_event(e)
def _on_physics_step(self, dt):
if not self._can_callback_physics_step():
return
# call user implementation
self.on_physics_step(dt)
def on_simulation_event(self, e):
"""
This method is called on simulation events. See omni.physx.bindings._physx.SimulationEvent.
"""
pass
def on_physics_step(self, dt):
"""
This method is called on each physics step callback, and the first callback is issued
after the on_tensor_start method is called if the tensor API is enabled.
"""
self.count_down -= 1
# self.dof_pos = self.frankas.get_dof_positions()
# print("dof_pos", self.dof_pos)
# playing
if not self.is_replay:
if self.count_down == 0:
self.count_down = 6 # TODO: unify count_down is play and replay
if self.is_record:
current_dof_pos = self.frankas.get_dof_positions()
with open(os.path.join(self.save_path, 'record.csv'), 'a') as f:
f.write(",".join(list([str(e) for e in current_dof_pos[0]] + [str(self.last_gripper_action)])) + '\n')
# get movement from keyboard
move_vec = self.controller.QueryMove()
query_move = move_vec != [0, 0, 0]
# get rotation from keyboard
rotation_vec = self.controller.QueryRotation()
query_rotation = rotation_vec != [0, 0]
# get gripper
gripper_val = self.controller.QueryGripper()
query_gripper = self.last_gripper_action != gripper_val
# get end effector transforms
hand_transforms = self.hands.get_transforms().copy()
current_hand_pos, current_hand_rot = hand_transforms[:, :3], hand_transforms[:, 3:]
# update record
if query_move or query_rotation or query_gripper or self.is_start:
self.hand_pos = current_hand_pos
self.hand_rot = current_hand_rot
self.last_gripper_action = gripper_val
self.is_start = False
# print("current_dof_pos", self.frankas.get_dof_positions())
# # if no input
# if not query_move and not query_rotation and not query_gripper:
# return
# get franka xform mat # FIXME: time code?
mat = UsdGeom.Xformable(self.franka_prim).ComputeLocalToWorldTransform(Usd.TimeCode.Default())
move_vec_4d = Gf.Vec4d(move_vec[0], move_vec[1], move_vec[2], 0)
hand_move = move_vec_4d * mat
hand_move_np = np.array([[hand_move[0], hand_move[1], hand_move[2]]])
target_pos = self.hand_pos + hand_move_np
target_rot = self.hand_rot
dof_target = self.move_to_target(target_pos, target_rot)
if query_rotation:
dof_target[...,5] += rotation_vec[0] * 0.1 # slowly but surely
dof_target[...,6] += rotation_vec[1] * 0.2
# print("last_gripper_action", self.last_gripper_action)
dof_target[...,[-2, -1]] = 5 if self.last_gripper_action > 0 else -1
self.frankas.set_dof_position_targets(dof_target, np.arange(1))
# replaying
else: # self.is_replay:
if self.count_down == 0:
self.count_down = 4
# pause when record not exist
if len(self.record_lines) == 0:
omni.timeline.get_timeline_interface().pause()
return
# load joint
record_line = self.record_lines.pop(0)
self.target_pos = np.array([record_line[:-1]])
self.last_gripper_action = record_line[-1]
# load discreet gripper
self.target_pos[...,[-2, -1]] = 5 if self.last_gripper_action > 0 else -1
# print("target_pos", self.target_pos)
self.frankas.set_dof_position_targets(self.target_pos, self.franka_indices)
def load_record(self):
if not os.path.exists(os.path.join(self.save_path, 'record.csv')):
carb.log_error( "please start & record first")
return
with open(os.path.join(self.save_path, 'record.csv'), 'r') as f:
for line in f.readlines():
self.record_lines.append([float(e) for e in line.split(",")])
######################################### robot control #########################################
def move_to_target(self, goal_pos, goal_rot):
"""
Move hand to target points
"""
# get end effector transforms
hand_transforms = self.hands.get_transforms().copy()
hand_pos, hand_rot = hand_transforms[:, :3], hand_transforms[:, 3:]
#hand_rot = hand_rot[:,[1,2,3,0]] # WXYZ
# get franka DOF states
dof_pos = self.frankas.get_dof_positions()
# compute position and orientation error
pos_err = goal_pos - hand_pos
orn_err = orientation_error(goal_rot, hand_rot)
dpose = np.concatenate([pos_err, orn_err], -1)[:, None].transpose(0, 2, 1)
jacobians = self.frankas.get_jacobians()
# jacobian entries corresponding to franka hand
franka_hand_index = 8 # !!!
j_eef = jacobians[:, franka_hand_index - 1, :]
# solve damped least squares
j_eef_T = np.transpose(j_eef, (0, 2, 1))
d = 0.05 # damping term
lmbda = np.eye(6) * (d ** 2)
u = (j_eef_T @ np.linalg.inv(j_eef @ j_eef_T + lmbda) @ dpose).reshape(1, 9)
# update position targets
pos_targets = dof_pos + u # * 0.3
return pos_targets |
yizhouzhao/VRKitchen2.0-IndoorKit/exts/vrkitchen.indoor.kit/vrkitchen/indoor/kit/task_check/__init__.py | from .base_checker import BaseChecker
# from .grasp_checker import GraspChecker
# from .joint_checker import JointChecker
# from .orient_checker import OrientChecker
# from .container_checker import ContainerChecker
# from .water_checker import WaterChecker
# from .tap_water_checker import TapWaterChecker |
yizhouzhao/VRKitchen2.0-IndoorKit/exts/vrkitchen.indoor.kit/vrkitchen/indoor/kit/task_check/base_checker.py | from lib2to3.pgen2.token import BACKQUOTE
import os
import json
from pxr import PhysxSchema, UsdPhysics
# task completion checking
import pxr
import omni
import carb
from omni.physx.scripts import physicsUtils
from ..param import DATA_PATH_NEW
from ..layout.randomizer import Randomizer
class BaseChecker():
SUCCESS_UI = None
IS_REPLAY = False
def __init__(self, task_type, task_id, robot_id, mission_id, annotator="Steven", run_time = True) -> None:
"""
::params:
:run_time: is run-time task checker or not
"""
# property
self.task_type = task_type
self.task_id = str(task_id)
self.mission_id = str(mission_id)
self.robot_id = str(robot_id)
self.data_path = DATA_PATH_NEW
self.annotator = annotator
# keep the old mission identifier temporarily
self.old_mission_identifier = self.task_type + " " + self.task_id + " " + self.robot_id + " " + self.mission_id
self.mission_identifier_prefix = self.task_type + " " + self.task_id + " "#+ self.robot_id + " " + self.mission_id
self.mission_identifier_suffix = self.mission_id
# scene
self.stage = omni.usd.get_context().get_stage()
self.default_prim_path_str = self.stage.GetDefaultPrim().GetPath().pathString
self.timeline = omni.timeline.get_timeline_interface()
self.current_mission = self.register_mission()
self.success_steps = 0
self.success = False
self.time = 0
# tasks
if run_time:
self.create_task_callback()
# log
self.total_step = 0
self.print_every = 240
self.checking_interval = 15
# get time per second
physicsScenePath = "/World/physicsScene"
scene = UsdPhysics.Scene.Get(self.stage, physicsScenePath)
if not scene:
carb.log_warn("physics scene not found")
physxSceneAPI = PhysxSchema.PhysxSceneAPI.Apply(scene.GetPrim())
self.steps_per_second = physxSceneAPI.GetTimeStepsPerSecondAttr().Get()
def register_mission(self):
"""
Register mission
"""
task_folder = os.path.join(self.data_path, self.annotator, "task", self.task_type, str(self.task_id))
if not os.path.exists(task_folder):
raise carb.log_warn(f"Task folder not exist at {task_folder}")
self.mission_file_path = os.path.join(task_folder, "missions.json")
if os.path.exists(self.mission_file_path):
self.missions = json.load(open(self.mission_file_path))
carb.log_info(f"Loading missions.json at path {self.mission_file_path}")
else:
self.missions = {}
with open(self.mission_file_path, "w") as f:
json.dump(self.missions, f, indent = 4)
carb.log_info(f"Saving missions.json at path {self.mission_file_path}")
for key, value in self.missions.items():
if key.startswith(self.mission_identifier_prefix) and key.endswith(self.mission_identifier_suffix):
return self.missions[key]
else:
return {}
def get_diff(self):
raise NotImplementedError
def create_task_callback(self):
stream = self.timeline.get_timeline_event_stream()
self._timeline_subscription = stream.create_subscription_to_pop(self._on_timeline_event)
# subscribe to Physics updates:
self._physics_update_subscription = omni.physx.get_physx_interface().subscribe_physics_step_events(
self._on_physics_step
)
def _on_timeline_event(self, e):
"""
set up timeline event
"""
if e.type == int(omni.timeline.TimelineEventType.STOP):
self.it = 0
self.time = 0
self.reset()
def reset(self):
"""
Reset event
"""
self._physics_update_subscription = None
self._timeline_subscription = None
# self._setup_callbacks()
def _on_success_hold(self):
try:
if (self.success_steps - 1) % 240 == 0:
carb.log_info("hold on")
BaseChecker.SUCCESS_UI.model.set_value("hold on")
except:
pass
def _on_success(self):
carb.log_info("task sucess")
self.success = True
try:
BaseChecker.SUCCESS_UI.model.set_value("task sucess")
if self.timeline.is_playing() and not BaseChecker.IS_REPLAY:
self.timeline.pause()
except:
pass
def _on_not_success(self):
# carb.log_info("task not sucess")
self.success_steps = 0
self.success = False
try:
BaseChecker.SUCCESS_UI.model.set_value("")
except:
pass
def _on_physics_step(self, dt):
"""
Physics event
"""
# print("timestep: ", self.time)
if self.time == 0:
stage = omni.usd.get_context().get_stage()
prim_list = list(stage.TraverseAll())
prim_list = [ item for item in prim_list if 'Isosurface' in item.GetPath().pathString and item.GetTypeName() == 'Mesh' ]
from pxr import Sdf
water_path = Randomizer(None, 1).get_water_material()
for iso2Prim in prim_list:
# omni.kit.commands.execute(
# "CreateAndBindMdlMaterialFromLibrary",
# mdl_name='/media/nikepupu/fast/omni_lib/lib_path/isaac_sim-2021.2.1/kit/mdl/core/Base/OmniSurfacePresets.mdl',
# mtl_name='OmniSurface_ClearWater',
# mtl_created_list=None,
# )
# water_path = '/World/Looks/OmniSurface_ClearWater'
rel = iso2Prim.CreateRelationship("material:binding", False)
rel.SetTargets([Sdf.Path(water_path)])
# Randomizer.get_water_material(iso2Prim)
self.time += 1
self.start_checking()
def start_checking(self):
if self.success_steps > self.steps_per_second * 2:
self._on_success()
def save_mission(self):
"""
save mission
"""
self.missions[self.old_mission_identifier] = self.current_mission
with open(self.mission_file_path, "w") as f:
json.dump(self.missions, f, indent = 4)
carb.log_info(f"Saving missions.json at path {self.mission_file_path}")
|
yizhouzhao/VRKitchen2.0-IndoorKit/exts/vrkitchen.indoor.kit/asset/Sapien/StorageFurniture/parsed_StorageFurniture_indexes.json | {"StorageFurniture": [45749, 47632, 35059, 45949, 45767, 46616, 45176, 46166, 45249, 45203, 46896, 45135, 46060, 45385, 46440, 45463, 48876, 47595, 47133, 46466, 45606, 47388, 46132, 45271, 47529, 45290, 47601, 46134, 40417, 45746, 48010, 46417, 45384, 47316, 46556, 46380, 40453, 46462, 45632, 46172, 45759, 49038, 45689, 48169, 45423, 48797, 48013, 45915, 45801, 47187, 46437, 47686, 46057, 45524, 48859, 45642, 48036, 45159, 47254, 45780, 45910, 41085, 47729, 45756, 45244, 46084, 46981, 45403, 45173, 44962, 45415, 46123, 45413, 45162, 45662, 41529, 45219, 45667, 45164, 46906, 45620, 46480, 46401, 46699, 45676, 45671, 48491, 44853, 45964, 46108, 46179, 47233, 45397, 45444, 45783, 48253, 45526, 47651, 46653, 48623, 45779, 45248, 46117, 48519, 47944, 45855, 47570, 45427, 47180, 45612, 47168, 47185, 45448, 47711, 41083, 47514, 41086, 45600, 41004, 47024, 46544, 45922, 45238, 46741, 47963, 45717, 47238, 45146, 45087, 46762, 49132, 47278, 45622, 46019, 48271, 46456, 46045, 44826, 44781, 46408, 45937, 47235, 47585, 47954, 46120, 45784, 47577, 45950, 46955, 46107, 45372, 48721, 45710, 48746, 46033, 47976, 48023, 46427, 45189, 46014, 45725, 46922, 46037, 48243, 45378, 46452, 47613, 46403, 45194, 45961, 47021, 48467, 47747, 46768, 45262, 46197, 45178, 47808, 46859, 45776, 46801, 45699, 45419, 46481, 45670, 47252, 46874, 47183, 45092, 49025, 45168, 44817, 47099, 47296, 46944, 46744, 48479]} |
yizhouzhao/VRKitchen2.0-IndoorKit/exts/vrkitchen.indoor.kit/asset/Sapien/Bottle/parsed_Bottle_indexes.json | {"Bottle": [3519, 4043, 4200, 6037, 6040, 3625, 3635, 6209, 4393, 4514, 3990, 3934, 3763, 8736, 5902, 3678, 3655, 4118, 6335, 5861, 4216, 4233, 4084, 3571, 3616, 3380, 3558, 6222, 4427, 4403, 8848, 6263, 3574, 6771, 3933, 3517, 4204, 3593, 3618, 3944, 3615, 4314, 3520, 5850, 3854, 3614, 3822, 6493, 3868, 6430, 5601, 3398, 5688, 3596, 3830, 4064, 4500]} |
yizhouzhao/VRKitchen2.0-IndoorKit/exts/vrkitchen.indoor.kit/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 = "Indoorkit"
description="The python extension with omniverse for robotic tasks"
# preview
preview_image = "icons/preview.png"
icon = "icons/logo_large.png"
# 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", "robotics", "machine learning"]
# Use omni.ui to build simple UI
[dependencies]
"omni.kit.uiapp" = {}
"omni.syntheticdata" = {}
# Main python module this extension provides, it will be publicly available as "import omni.hello.world".
[[python.module]]
name = "vrkitchen.indoor.kit"
|
yizhouzhao/VRKitchen2.0-IndoorKit/data/readme.md | # data folder |
isaac-orbit/orbit.ext_template/pyproject.toml | # This section defines the build system requirements
[build-system]
requires = ["setuptools >= 61.0"]
build-backend = "setuptools.build_meta"
# Project metadata
[project]
version = "0.1.0"
name = "ext_template" # TODO
description = "Extension Template for Orbit" # TODO
keywords = ["extension", "template", "orbit"] # TODO
readme = "README.md"
requires-python = ">=3.10"
license = {file = "LICENSE.txt"}
classifiers = [
"Programming Language :: Python :: 3",
]
authors = [
{name = "Nico Burger", email = "[email protected]"}, # TODO
]
maintainers = [
{name = "Nico Burger", email = "[email protected]"}, # TODO
]
# Tool dependent subtables
[tool.setuptools]
py-modules = [
'orbit'
] # TODO, add modules required for your extension
|
isaac-orbit/orbit.ext_template/README.md | # Extension Template for Orbit
[](https://docs.omniverse.nvidia.com/isaacsim/latest/overview.html)
[](https://isaac-orbit.github.io/orbit/)
[](https://docs.python.org/3/whatsnew/3.10.html)
[](https://releases.ubuntu.com/20.04/)
[](https://pre-commit.com/)
## Overview
This repository serves as a template for building projects or extensions based on Orbit. It allows you to develop in an isolated environment, outside of the core Orbit repository. Furthermore, this template serves three use cases:
- **Python Package**
Can be installed into Isaac Sim's Python environment, making it suitable for users who want to integrate their extension to `Orbit` as a python package.
- **Project Template**
Ensures access to `Isaac Sim` and `Orbit` functionalities, which can be used as a project template.
- **Omniverse Extension**
Can be used as an Omniverse extension, ideal for projects that leverage the Omniverse platform's graphical user interface.
**Key Features:**
- `Isolation` Work outside the core Orbit repository, ensuring that your development efforts remain self-contained.
- `Flexibility` This template is set up to allow your code to be run as an extension in Omniverse.
**Keywords:** extension, template, orbit
### License
The source code is released under a [BSD 3-Clause license](https://opensource.org/licenses/BSD-3-Clause).
**Author: The ORBIT Project Developers<br />
Affiliation: [The AI Institute](https://theaiinstitute.com/)<br />
Maintainer: Nico Burger, [email protected]**
## Setup
Depending on the use case defined [above](#overview), follow the instructions to set up your extension template. Start with the [Basic Setup](#basic-setup), which is required for either use case.
### Basic Setup
#### Dependencies
This template depends on Isaac Sim and Orbit. For detailed instructions on how to install these dependencies, please refer to the [installation guide](https://isaac-orbit.github.io/orbit/source/setup/installation.html).
- [Isaac Sim](https://docs.omniverse.nvidia.com/isaacsim/latest/index.html)
- [Orbit](https://isaac-orbit.github.io/orbit/)
#### Configuration
Decide on a name for your project or extension. This guide will refer to this name as `<your_extension_name>`.
- Create a new repository based off this template [here](https://github.com/new?owner=isaac-orbit&template_name=orbit.ext_template&template_owner=isaac-orbit). Name your forked repository using the following convention: `"orbit.<your_extension_name>"`.
- Clone your forked repository to a location **outside** the orbit repository.
```bash
git clone <your_repository_url>
```
- Configure the template. Search for and replace **`TODO`**'s according to your extension's needs within the following files:
- `config/extension.toml`
- `pyproject.toml`
- Rename your source folder.
```bash
cd orbit.<your_extension_name>
mv orbit/ext_template orbit/<your_extension_name>
```
- Set up a symbolic link from Orbit to this directory.
This makes it convenient to index the python modules and look for extensions shipped with Isaac Sim and Orbit.
```bash
ln -s <your_orbit_path> _orbit
```
#### Environment (Optional)
For clarity, we will be using the `${ISAACSIM_PATH}/python.sh` command to call the Orbit specific python interpreter. However, you might be working from within a virtual environment, allowing you to use the `python` command directly, instead of `${ISAACSIM_PATH}/python.sh`. Information on setting up a virtual environment for Orbit can be found [here](https://isaac-orbit.github.io/orbit/source/setup/installation.html#setting-up-the-environment). The `ISAACSIM_PATH` should already be set from installing Orbit, see [here](https://isaac-orbit.github.io/orbit/source/setup/installation.html#configuring-the-environment-variables).
#### Configure Python Interpreter
In the provided configuration, we set the default Python interpreter to use the Python executable provided by Omniverse. This is specified in the `.vscode/settings.json` file:
```json
"python.defaultInterpreterPath": "${env:ISAACSIM_PATH}/python.sh"
```
This setup requires you to have set up the `ISAACSIM_PATH` environment variable. If you want to use a different Python interpreter, you need to change the Python interpreter used by selecting and activating the Python interpreter of your choice in the bottom left corner of VSCode, or opening the command palette (`Ctrl+Shift+P`) and selecting `Python: Select Interpreter`.
#### Set up IDE
To setup the IDE, please follow these instructions:
1. Open the `orbit.<your_extension_template>` directory on Visual Studio Code IDE
2. Run VSCode Tasks, by pressing Ctrl+Shift+P, selecting Tasks: Run Task and running the setup_python_env in the drop down menu.
If everything executes correctly, it should create a file .python.env in the .vscode directory. The file contains the python paths to all the extensions provided by Isaac Sim and Omniverse. This helps in indexing all the python modules for intelligent suggestions while writing code.
### Setup as Python Package / Project Template
From within this repository, install your extension as a Python package to the Isaac Sim Python executable.
```bash
${ISAACSIM_PATH}/python.sh -m pip install --upgrade pip
${ISAACSIM_PATH}/python.sh -m pip install -e .
```
### Setup as Omniverse Extension
To enable your extension, follow these steps:
1. **Add the search path of your repository** to the extension manager:
- Navigate to the extension manager using `Window` -> `Extensions`.
- Click on the **Hamburger Icon** (☰), then go to `Settings`.
- In the `Extension Search Paths`, enter the path that goes up to your repository's location without actually including the repository's own directory. For example, if your repository is located at `/home/code/orbit.ext_template`, you should add `/home/code` as the search path.
- If not already present, in the `Extension Search Paths`, enter the path that leads to your local Orbit directory. For example: `/home/orbit/source/extensions`
- Click on the **Hamburger Icon** (☰), then click `Refresh`.
2. **Search and enable your extension**:
- Find your extension under the `Third Party` category.
- Toggle it to enable your extension.
## Usage
### Python Package
Import your python package within `Isaac Sim` and `Orbit` using:
```python
import orbit.<your_extension_name>
```
### Project Template
We provide an example for training and playing a policy for ANYmal on flat terrain. Install [RSL_RL](https://github.com/leggedrobotics/rsl_rl) outside of the orbit repository, e.g. `home/code/rsl_rl`.
```bash
git clone https://github.com/leggedrobotics/rsl_rl.git
cd rsl_rl
${ISAACSIM_PATH}/python.sh -m pip install -e .
```
Train a policy.
```bash
cd <path_to_your_extension>
${ISAACSIM_PATH}/python.sh scripts/rsl_rl/train.py --task Isaac-Velocity-Flat-Anymal-D-Template-v0 --num_envs 4096 --headless
```
Play the trained policy.
```bash
${ISAACSIM_PATH}/python.sh scripts/rsl_rl/play.py --task Isaac-Velocity-Flat-Anymal-D-Template-Play-v0 --num_envs 16
```
### Omniverse Extension
We provide an example UI extension that will load upon enabling your extension defined in `orbit/ext_template/ui_extension_example.py`. For more information on UI extensions, enable and check out the source code of the `omni.isaac.ui_template` extension and refer to the introduction on [Isaac Sim Workflows 1.2.3. GUI](https://docs.omniverse.nvidia.com/isaacsim/latest/introductory_tutorials/tutorial_intro_workflows.html#gui).
## Pre-Commit
Pre-committing involves using a framework to automate the process of enforcing code quality standards before code is actually committed to a version control system, like Git. This process involves setting up hooks that run automated checks, such as code formatting, linting (checking for programming errors, bugs, stylistic errors, and suspicious constructs), and running tests. If these checks pass, the commit is allowed; if not, the commit is blocked until the issues are resolved. This ensures that all code committed to the repository adheres to the defined quality standards, leading to a cleaner, more maintainable codebase. To do so, we use the [pre-commit](https://pre-commit.com/) module. Install the module using:
```bash
pip install pre-commit
```
Run the pre-commit with:
```bash
pre-commit run --all-files
```
## Finalize
You are all set and no longer need the template instructions
- The `orbit/ext_template` and `scripts/rsl_rl` directories act as a reference template for your convenience. Delete them if no longer required.
- When ready, use this `README.md` as a template and customize where appropriate.
## Docker / Cluster
We are currently working on a docker and cluster setup for this template. In the meanwhile, please refer to the current setup provided in the Orbit [documentation](https://isaac-orbit.github.io/orbit/source/deployment/index.html).
## Troubleshooting
### Docker Container
When running within a docker container, the following error has been encountered: `ModuleNotFoundError: No module named 'orbit'`. To mitigate, please comment out the docker specific environment definitions in `.vscode/launch.json` and run the following:
```bash
echo -e "\nexport PYTHONPATH=\$PYTHONPATH:/workspace/orbit.<your_extension_name>" >> ~/.bashrc
source ~/.bashrc
```
## Bugs & Feature Requests
Please report bugs and request features using the [Issue Tracker](https://github.com/isaac-orbit/orbit.ext_template/issues).
|
isaac-orbit/orbit.ext_template/scripts/rsl_rl/play.py | # Copyright (c) 2022-2024, The ORBIT Project Developers.
# All rights reserved.
#
# SPDX-License-Identifier: BSD-3-Clause
"""Script to play a checkpoint if an RL agent from RSL-RL."""
from __future__ import annotations
"""Launch Isaac Sim Simulator first."""
import argparse
from omni.isaac.orbit.app import AppLauncher
# local imports
import cli_args # isort: skip
# add argparse arguments
parser = argparse.ArgumentParser(description="Train an RL agent with RSL-RL.")
parser.add_argument("--cpu", action="store_true", default=False, help="Use CPU pipeline.")
parser.add_argument("--num_envs", type=int, default=None, help="Number of environments to simulate.")
parser.add_argument("--task", type=str, default=None, help="Name of the task.")
parser.add_argument("--seed", type=int, default=None, help="Seed used for the environment")
# append RSL-RL cli arguments
cli_args.add_rsl_rl_args(parser)
# append AppLauncher cli args
AppLauncher.add_app_launcher_args(parser)
args_cli = parser.parse_args()
# launch omniverse app
app_launcher = AppLauncher(args_cli)
simulation_app = app_launcher.app
"""Rest everything follows."""
import os
import gymnasium as gym
import omni.isaac.contrib_tasks # noqa: F401
import omni.isaac.orbit_tasks # noqa: F401
import torch
from omni.isaac.orbit_tasks.utils import get_checkpoint_path, parse_env_cfg
from omni.isaac.orbit_tasks.utils.wrappers.rsl_rl import (
RslRlOnPolicyRunnerCfg,
RslRlVecEnvWrapper,
export_policy_as_onnx,
)
from rsl_rl.runners import OnPolicyRunner
# Import extensions to set up environment tasks
import orbit.ext_template.tasks # noqa: F401 TODO: import orbit.<your_extension_name>
def main():
"""Play with RSL-RL agent."""
# parse configuration
env_cfg = parse_env_cfg(args_cli.task, use_gpu=not args_cli.cpu, num_envs=args_cli.num_envs)
agent_cfg: RslRlOnPolicyRunnerCfg = cli_args.parse_rsl_rl_cfg(args_cli.task, args_cli)
# create isaac environment
env = gym.make(args_cli.task, cfg=env_cfg)
# wrap around environment for rsl-rl
env = RslRlVecEnvWrapper(env)
# specify directory for logging experiments
log_root_path = os.path.join("logs", "rsl_rl", agent_cfg.experiment_name)
log_root_path = os.path.abspath(log_root_path)
print(f"[INFO] Loading experiment from directory: {log_root_path}")
resume_path = get_checkpoint_path(log_root_path, agent_cfg.load_run, agent_cfg.load_checkpoint)
print(f"[INFO]: Loading model checkpoint from: {resume_path}")
# load previously trained model
ppo_runner = OnPolicyRunner(env, agent_cfg.to_dict(), log_dir=None, device=agent_cfg.device)
ppo_runner.load(resume_path)
print(f"[INFO]: Loading model checkpoint from: {resume_path}")
# obtain the trained policy for inference
policy = ppo_runner.get_inference_policy(device=env.unwrapped.device)
# export policy to onnx
export_model_dir = os.path.join(os.path.dirname(resume_path), "exported")
export_policy_as_onnx(ppo_runner.alg.actor_critic, export_model_dir, filename="policy.onnx")
# reset environment
obs, _ = env.get_observations()
# simulate environment
while simulation_app.is_running():
# run everything in inference mode
with torch.inference_mode():
# agent stepping
actions = policy(obs)
# env stepping
obs, _, _, _ = env.step(actions)
# close the simulator
env.close()
if __name__ == "__main__":
# run the main execution
main()
# close sim app
simulation_app.close()
|
isaac-orbit/orbit.ext_template/scripts/rsl_rl/cli_args.py | # Copyright (c) 2022-2024, The ORBIT Project Developers.
# All rights reserved.
#
# SPDX-License-Identifier: BSD-3-Clause
from __future__ import annotations
import argparse
from typing import TYPE_CHECKING
if TYPE_CHECKING:
from omni.isaac.orbit_tasks.utils.wrappers.rsl_rl import RslRlOnPolicyRunnerCfg
def add_rsl_rl_args(parser: argparse.ArgumentParser):
"""Add RSL-RL arguments to the parser.
Args:
parser: The parser to add the arguments to.
"""
# create a new argument group
arg_group = parser.add_argument_group("rsl_rl", description="Arguments for RSL-RL agent.")
# -- experiment arguments
arg_group.add_argument(
"--experiment_name", type=str, default=None, help="Name of the experiment folder where logs will be stored."
)
arg_group.add_argument("--run_name", type=str, default=None, help="Run name suffix to the log directory.")
# -- load arguments
arg_group.add_argument("--resume", type=bool, default=None, help="Whether to resume from a checkpoint.")
arg_group.add_argument("--load_run", type=str, default=None, help="Name of the run folder to resume from.")
arg_group.add_argument("--checkpoint", type=str, default=None, help="Checkpoint file to resume from.")
# -- logger arguments
arg_group.add_argument(
"--logger", type=str, default=None, choices={"wandb", "tensorboard", "neptune"}, help="Logger module to use."
)
arg_group.add_argument(
"--log_project_name", type=str, default=None, help="Name of the logging project when using wandb or neptune."
)
def parse_rsl_rl_cfg(task_name: str, args_cli: argparse.Namespace) -> RslRlOnPolicyRunnerCfg:
"""Parse configuration for RSL-RL agent based on inputs.
Args:
task_name: The name of the environment.
args_cli: The command line arguments.
Returns:
The parsed configuration for RSL-RL agent based on inputs.
"""
from omni.isaac.orbit_tasks.utils.parse_cfg import load_cfg_from_registry
# load the default configuration
rslrl_cfg: RslRlOnPolicyRunnerCfg = load_cfg_from_registry(task_name, "rsl_rl_cfg_entry_point")
# override the default configuration with CLI arguments
if args_cli.seed is not None:
rslrl_cfg.seed = args_cli.seed
if args_cli.resume is not None:
rslrl_cfg.resume = args_cli.resume
if args_cli.load_run is not None:
rslrl_cfg.load_run = args_cli.load_run
if args_cli.checkpoint is not None:
rslrl_cfg.load_checkpoint = args_cli.checkpoint
if args_cli.run_name is not None:
rslrl_cfg.run_name = args_cli.run_name
if args_cli.logger is not None:
rslrl_cfg.logger = args_cli.logger
# set the project name for wandb and neptune
if rslrl_cfg.logger in {"wandb", "neptune"} and args_cli.log_project_name:
rslrl_cfg.wandb_project = args_cli.log_project_name
rslrl_cfg.neptune_project = args_cli.log_project_name
return rslrl_cfg
|
isaac-orbit/orbit.ext_template/scripts/rsl_rl/train.py | # Copyright (c) 2022-2024, The ORBIT Project Developers.
# All rights reserved.
#
# SPDX-License-Identifier: BSD-3-Clause
"""Script to train RL agent with RSL-RL."""
from __future__ import annotations
"""Launch Isaac Sim Simulator first."""
import argparse
import os
from omni.isaac.orbit.app import AppLauncher
# local imports
import cli_args # isort: skip
# add argparse arguments
parser = argparse.ArgumentParser(description="Train an RL agent with RSL-RL.")
parser.add_argument("--video", action="store_true", default=False, help="Record videos during training.")
parser.add_argument("--video_length", type=int, default=200, help="Length of the recorded video (in steps).")
parser.add_argument("--video_interval", type=int, default=2000, help="Interval between video recordings (in steps).")
parser.add_argument("--cpu", action="store_true", default=False, help="Use CPU pipeline.")
parser.add_argument("--num_envs", type=int, default=None, help="Number of environments to simulate.")
parser.add_argument("--task", type=str, default=None, help="Name of the task.")
parser.add_argument("--seed", type=int, default=None, help="Seed used for the environment")
# append RSL-RL cli arguments
cli_args.add_rsl_rl_args(parser)
# append AppLauncher cli args
AppLauncher.add_app_launcher_args(parser)
args_cli = parser.parse_args()
# load cheaper kit config in headless
if args_cli.headless:
app_experience = f"{os.environ['EXP_PATH']}/omni.isaac.sim.python.gym.headless.kit"
else:
app_experience = f"{os.environ['EXP_PATH']}/omni.isaac.sim.python.kit"
# launch omniverse app
app_launcher = AppLauncher(args_cli, experience=app_experience)
simulation_app = app_launcher.app
"""Rest everything follows."""
import os
from datetime import datetime
import gymnasium as gym
import omni.isaac.orbit_tasks # noqa: F401
import torch
from omni.isaac.orbit.envs import RLTaskEnvCfg
from omni.isaac.orbit.utils.dict import print_dict
from omni.isaac.orbit.utils.io import dump_pickle, dump_yaml
from omni.isaac.orbit_tasks.utils import get_checkpoint_path, parse_env_cfg
from omni.isaac.orbit_tasks.utils.wrappers.rsl_rl import (
RslRlOnPolicyRunnerCfg,
RslRlVecEnvWrapper,
)
from rsl_rl.runners import OnPolicyRunner
# Import extensions to set up environment tasks
import orbit.ext_template.tasks # noqa: F401 TODO: import orbit.<your_extension_name>
torch.backends.cuda.matmul.allow_tf32 = True
torch.backends.cudnn.allow_tf32 = True
torch.backends.cudnn.deterministic = False
torch.backends.cudnn.benchmark = False
def main():
"""Train with RSL-RL agent."""
# parse configuration
env_cfg: RLTaskEnvCfg = parse_env_cfg(args_cli.task, use_gpu=not args_cli.cpu, num_envs=args_cli.num_envs)
agent_cfg: RslRlOnPolicyRunnerCfg = cli_args.parse_rsl_rl_cfg(args_cli.task, args_cli)
# specify directory for logging experiments
log_root_path = os.path.join("logs", "rsl_rl", agent_cfg.experiment_name)
log_root_path = os.path.abspath(log_root_path)
print(f"[INFO] Logging experiment in directory: {log_root_path}")
# specify directory for logging runs: {time-stamp}_{run_name}
log_dir = datetime.now().strftime("%Y-%m-%d_%H-%M-%S")
if agent_cfg.run_name:
log_dir += f"_{agent_cfg.run_name}"
log_dir = os.path.join(log_root_path, log_dir)
# create isaac environment
env = gym.make(args_cli.task, cfg=env_cfg, render_mode="rgb_array" if args_cli.video else None)
# wrap for video recording
if args_cli.video:
video_kwargs = {
"video_folder": os.path.join(log_dir, "videos"),
"step_trigger": lambda step: step % args_cli.video_interval == 0,
"video_length": args_cli.video_length,
"disable_logger": True,
}
print("[INFO] Recording videos during training.")
print_dict(video_kwargs, nesting=4)
env = gym.wrappers.RecordVideo(env, **video_kwargs)
# wrap around environment for rsl-rl
env = RslRlVecEnvWrapper(env)
# create runner from rsl-rl
runner = OnPolicyRunner(env, agent_cfg.to_dict(), log_dir=log_dir, device=agent_cfg.device)
# write git state to logs
runner.add_git_repo_to_log(__file__)
# save resume path before creating a new log_dir
if agent_cfg.resume:
# get path to previous checkpoint
resume_path = get_checkpoint_path(log_root_path, agent_cfg.load_run, agent_cfg.load_checkpoint)
print(f"[INFO]: Loading model checkpoint from: {resume_path}")
# load previously trained model
runner.load(resume_path)
# set seed of the environment
env.seed(agent_cfg.seed)
# dump the configuration into log-directory
dump_yaml(os.path.join(log_dir, "params", "env.yaml"), env_cfg)
dump_yaml(os.path.join(log_dir, "params", "agent.yaml"), agent_cfg)
dump_pickle(os.path.join(log_dir, "params", "env.pkl"), env_cfg)
dump_pickle(os.path.join(log_dir, "params", "agent.pkl"), agent_cfg)
# run training
runner.learn(num_learning_iterations=agent_cfg.max_iterations, init_at_random_ep_len=True)
# close the simulator
env.close()
if __name__ == "__main__":
# run the main execution
main()
# close sim app
simulation_app.close()
|
isaac-orbit/orbit.ext_template/config/extension.toml | [package]
# Semantic Versioning is used: https://semver.org/
version = "0.1.0"
# Description
title = "Extension Template" # TODO: Please adapt to your title.
description="Extension Template for Orbit" #TODO: Please adapt to your description.
repository = "https://github.com/isaac-orbit/orbit.ext_template.git" # TODO: Please adapt to your repository.
keywords = ["extension", "template", "orbit"] # TODO: Please adapt to your keywords.
category = "orbit"
readme = "README.md"
[dependencies]
"omni.kit.uiapp" = {}
"omni.isaac.orbit" = {}
"omni.isaac.orbit_assets" = {}
"omni.isaac.orbit_tasks" = {}
"omni.isaac.core" = {}
"omni.isaac.gym" = {}
"omni.replicator.isaac" = {}
# Note: You can add additional dependencies here for your extension.
# For example, if you want to use the omni.kit module, you can add it as a dependency:
# "omni.kit" = {}
[[python.module]]
name = "orbit.ext_template" # TODO: Please adapt to your package name.
|
isaac-orbit/orbit.ext_template/orbit/ext_template/__init__.py | # Copyright (c) 2022-2024, The ORBIT Project Developers.
# All rights reserved.
#
# SPDX-License-Identifier: BSD-3-Clause
"""
Python module serving as a project/extension template.
"""
# Register Gym environments.
from .tasks import *
# Register UI extensions.
from .ui_extension_example import *
|
isaac-orbit/orbit.ext_template/orbit/ext_template/ui_extension_example.py | # Copyright (c) 2022-2024, The ORBIT Project Developers.
# All rights reserved.
#
# SPDX-License-Identifier: BSD-3-Clause
import omni.ext
import omni.ui as ui
# Functions and vars are available to other extension as usual in python: `example.python_ext.some_public_function(x)`
def some_public_function(x: int):
print("[orbit.ext_template] some_public_function was called with x: ", x)
return x**x
# Any class derived from `omni.ext.IExt` in top level module (defined in `python.modules` of `extension.toml`) will be
# instantiated when extension gets enabled and `on_startup(ext_id)` will be called. Later when extension gets disabled
# on_shutdown() is called.
class ExampleExtension(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("[orbit.ext_template] startup")
self._count = 0
self._window = ui.Window("My Window", width=300, height=300)
with self._window.frame:
with ui.VStack():
label = ui.Label("")
def on_click():
self._count += 1
label.text = f"count: {self._count}"
def on_reset():
self._count = 0
label.text = "empty"
on_reset()
with ui.HStack():
ui.Button("Add", clicked_fn=on_click)
ui.Button("Reset", clicked_fn=on_reset)
def on_shutdown(self):
print("[orbit.ext_template] shutdown")
|
isaac-orbit/orbit.ext_template/orbit/ext_template/tasks/__init__.py | # Copyright (c) 2022-2024, The ORBIT Project Developers.
# All rights reserved.
#
# SPDX-License-Identifier: BSD-3-Clause
"""Package containing task implementations for various robotic environments."""
import os
import toml
# Conveniences to other module directories via relative paths
ORBIT_TASKS_EXT_DIR = os.path.abspath(os.path.join(os.path.dirname(__file__), "../../../"))
"""Path to the extension source directory."""
ORBIT_TASKS_METADATA = toml.load(os.path.join(ORBIT_TASKS_EXT_DIR, "config", "extension.toml"))
"""Extension metadata dictionary parsed from the extension.toml file."""
# Configure the module-level variables
__version__ = ORBIT_TASKS_METADATA["package"]["version"]
##
# Register Gym environments.
##
from omni.isaac.orbit_tasks.utils import import_packages
# The blacklist is used to prevent importing configs from sub-packages
_BLACKLIST_PKGS = ["utils"]
# Import all configs in this package
import_packages(__name__, _BLACKLIST_PKGS)
|
isaac-orbit/orbit.ext_template/orbit/ext_template/tasks/locomotion/__init__.py | # Copyright (c) 2022-2024, The ORBIT Project Developers.
# All rights reserved.
#
# SPDX-License-Identifier: BSD-3-Clause
"""Locomotion environments for legged robots."""
from .velocity import * # noqa
|
isaac-orbit/orbit.ext_template/orbit/ext_template/tasks/locomotion/velocity/velocity_env_cfg.py | # Copyright (c) 2022-2024, The ORBIT Project Developers.
# All rights reserved.
#
# SPDX-License-Identifier: BSD-3-Clause
from __future__ import annotations
import math
from dataclasses import MISSING
import omni.isaac.orbit.sim as sim_utils
from omni.isaac.orbit.assets import ArticulationCfg, AssetBaseCfg
from omni.isaac.orbit.envs import RLTaskEnvCfg
from omni.isaac.orbit.managers import CurriculumTermCfg as CurrTerm
from omni.isaac.orbit.managers import ObservationGroupCfg as ObsGroup
from omni.isaac.orbit.managers import ObservationTermCfg as ObsTerm
from omni.isaac.orbit.managers import RandomizationTermCfg as RandTerm
from omni.isaac.orbit.managers import RewardTermCfg as RewTerm
from omni.isaac.orbit.managers import SceneEntityCfg
from omni.isaac.orbit.managers import TerminationTermCfg as DoneTerm
from omni.isaac.orbit.scene import InteractiveSceneCfg
from omni.isaac.orbit.sensors import ContactSensorCfg, RayCasterCfg, patterns
from omni.isaac.orbit.terrains import TerrainImporterCfg
from omni.isaac.orbit.utils import configclass
from omni.isaac.orbit.utils.noise import AdditiveUniformNoiseCfg as Unoise
import orbit.ext_template.tasks.locomotion.velocity.mdp as mdp
##
# Pre-defined configs
##
from omni.isaac.orbit.terrains.config.rough import ROUGH_TERRAINS_CFG # isort: skip
##
# Scene definition
##
@configclass
class MySceneCfg(InteractiveSceneCfg):
"""Configuration for the terrain scene with a legged robot."""
# ground terrain
terrain = TerrainImporterCfg(
prim_path="/World/ground",
terrain_type="generator",
terrain_generator=ROUGH_TERRAINS_CFG,
max_init_terrain_level=5,
collision_group=-1,
physics_material=sim_utils.RigidBodyMaterialCfg(
friction_combine_mode="multiply",
restitution_combine_mode="multiply",
static_friction=1.0,
dynamic_friction=1.0,
),
visual_material=sim_utils.MdlFileCfg(
mdl_path="{NVIDIA_NUCLEUS_DIR}/Materials/Base/Architecture/Shingles_01.mdl",
project_uvw=True,
),
debug_vis=False,
)
# robots
robot: ArticulationCfg = MISSING
# sensors
height_scanner = RayCasterCfg(
prim_path="{ENV_REGEX_NS}/Robot/base",
offset=RayCasterCfg.OffsetCfg(pos=(0.0, 0.0, 20.0)),
attach_yaw_only=True,
pattern_cfg=patterns.GridPatternCfg(resolution=0.1, size=[1.6, 1.0]),
debug_vis=False,
mesh_prim_paths=["/World/ground"],
)
contact_forces = ContactSensorCfg(prim_path="{ENV_REGEX_NS}/Robot/.*", history_length=3, track_air_time=True)
# lights
light = AssetBaseCfg(
prim_path="/World/light",
spawn=sim_utils.DistantLightCfg(color=(0.75, 0.75, 0.75), intensity=3000.0),
)
sky_light = AssetBaseCfg(
prim_path="/World/skyLight",
spawn=sim_utils.DomeLightCfg(color=(0.13, 0.13, 0.13), intensity=1000.0),
)
##
# MDP settings
##
@configclass
class CommandsCfg:
"""Command specifications for the MDP."""
base_velocity = mdp.UniformVelocityCommandCfg(
asset_name="robot",
resampling_time_range=(10.0, 10.0),
rel_standing_envs=0.02,
rel_heading_envs=1.0,
heading_command=True,
heading_control_stiffness=0.5,
debug_vis=True,
ranges=mdp.UniformVelocityCommandCfg.Ranges(
lin_vel_x=(-1.0, 1.0), lin_vel_y=(-1.0, 1.0), ang_vel_z=(-1.0, 1.0), heading=(-math.pi, math.pi)
),
)
@configclass
class ActionsCfg:
"""Action specifications for the MDP."""
joint_pos = mdp.JointPositionActionCfg(asset_name="robot", joint_names=[".*"], scale=0.5, use_default_offset=True)
@configclass
class ObservationsCfg:
"""Observation specifications for the MDP."""
@configclass
class PolicyCfg(ObsGroup):
"""Observations for policy group."""
# observation terms (order preserved)
base_lin_vel = ObsTerm(func=mdp.base_lin_vel, noise=Unoise(n_min=-0.1, n_max=0.1))
base_ang_vel = ObsTerm(func=mdp.base_ang_vel, noise=Unoise(n_min=-0.2, n_max=0.2))
projected_gravity = ObsTerm(
func=mdp.projected_gravity,
noise=Unoise(n_min=-0.05, n_max=0.05),
)
velocity_commands = ObsTerm(func=mdp.generated_commands, params={"command_name": "base_velocity"})
joint_pos = ObsTerm(func=mdp.joint_pos_rel, noise=Unoise(n_min=-0.01, n_max=0.01))
joint_vel = ObsTerm(func=mdp.joint_vel_rel, noise=Unoise(n_min=-1.5, n_max=1.5))
actions = ObsTerm(func=mdp.last_action)
height_scan = ObsTerm(
func=mdp.height_scan,
params={"sensor_cfg": SceneEntityCfg("height_scanner")},
noise=Unoise(n_min=-0.1, n_max=0.1),
clip=(-1.0, 1.0),
)
def __post_init__(self):
self.enable_corruption = True
self.concatenate_terms = True
# observation groups
policy: PolicyCfg = PolicyCfg()
@configclass
class RandomizationCfg:
"""Configuration for randomization."""
# startup
physics_material = RandTerm(
func=mdp.randomize_rigid_body_material,
mode="startup",
params={
"asset_cfg": SceneEntityCfg("robot", body_names=".*"),
"static_friction_range": (0.8, 0.8),
"dynamic_friction_range": (0.6, 0.6),
"restitution_range": (0.0, 0.0),
"num_buckets": 64,
},
)
add_base_mass = RandTerm(
func=mdp.add_body_mass,
mode="startup",
params={"asset_cfg": SceneEntityCfg("robot", body_names="base"), "mass_range": (-5.0, 5.0)},
)
# reset
base_external_force_torque = RandTerm(
func=mdp.apply_external_force_torque,
mode="reset",
params={
"asset_cfg": SceneEntityCfg("robot", body_names="base"),
"force_range": (0.0, 0.0),
"torque_range": (-0.0, 0.0),
},
)
reset_base = RandTerm(
func=mdp.reset_root_state_uniform,
mode="reset",
params={
"pose_range": {"x": (-0.5, 0.5), "y": (-0.5, 0.5), "yaw": (-3.14, 3.14)},
"velocity_range": {
"x": (-0.5, 0.5),
"y": (-0.5, 0.5),
"z": (-0.5, 0.5),
"roll": (-0.5, 0.5),
"pitch": (-0.5, 0.5),
"yaw": (-0.5, 0.5),
},
},
)
reset_robot_joints = RandTerm(
func=mdp.reset_joints_by_scale,
mode="reset",
params={
"position_range": (0.5, 1.5),
"velocity_range": (0.0, 0.0),
},
)
# interval
push_robot = RandTerm(
func=mdp.push_by_setting_velocity,
mode="interval",
interval_range_s=(10.0, 15.0),
params={"velocity_range": {"x": (-0.5, 0.5), "y": (-0.5, 0.5)}},
)
@configclass
class RewardsCfg:
"""Reward terms for the MDP."""
# -- task
track_lin_vel_xy_exp = RewTerm(
func=mdp.track_lin_vel_xy_exp, weight=1.0, params={"command_name": "base_velocity", "std": math.sqrt(0.25)}
)
track_ang_vel_z_exp = RewTerm(
func=mdp.track_ang_vel_z_exp, weight=0.5, params={"command_name": "base_velocity", "std": math.sqrt(0.25)}
)
# -- penalties
lin_vel_z_l2 = RewTerm(func=mdp.lin_vel_z_l2, weight=-2.0)
ang_vel_xy_l2 = RewTerm(func=mdp.ang_vel_xy_l2, weight=-0.05)
dof_torques_l2 = RewTerm(func=mdp.joint_torques_l2, weight=-1.0e-5)
dof_acc_l2 = RewTerm(func=mdp.joint_acc_l2, weight=-2.5e-7)
action_rate_l2 = RewTerm(func=mdp.action_rate_l2, weight=-0.01)
feet_air_time = RewTerm(
func=mdp.feet_air_time,
weight=0.125,
params={
"sensor_cfg": SceneEntityCfg("contact_forces", body_names=".*FOOT"),
"command_name": "base_velocity",
"threshold": 0.5,
},
)
undesired_contacts = RewTerm(
func=mdp.undesired_contacts,
weight=-1.0,
params={"sensor_cfg": SceneEntityCfg("contact_forces", body_names=".*THIGH"), "threshold": 1.0},
)
# -- optional penalties
flat_orientation_l2 = RewTerm(func=mdp.flat_orientation_l2, weight=0.0)
dof_pos_limits = RewTerm(func=mdp.joint_pos_limits, weight=0.0)
@configclass
class TerminationsCfg:
"""Termination terms for the MDP."""
time_out = DoneTerm(func=mdp.time_out, time_out=True)
base_contact = DoneTerm(
func=mdp.illegal_contact,
params={"sensor_cfg": SceneEntityCfg("contact_forces", body_names="base"), "threshold": 1.0},
)
@configclass
class CurriculumCfg:
"""Curriculum terms for the MDP."""
terrain_levels = CurrTerm(func=mdp.terrain_levels_vel)
##
# Environment configuration
##
@configclass
class LocomotionVelocityRoughEnvCfg(RLTaskEnvCfg):
"""Configuration for the locomotion velocity-tracking environment."""
# Scene settings
scene: MySceneCfg = MySceneCfg(num_envs=4096, env_spacing=2.5)
# Basic settings
observations: ObservationsCfg = ObservationsCfg()
actions: ActionsCfg = ActionsCfg()
commands: CommandsCfg = CommandsCfg()
# MDP settings
rewards: RewardsCfg = RewardsCfg()
terminations: TerminationsCfg = TerminationsCfg()
randomization: RandomizationCfg = RandomizationCfg()
curriculum: CurriculumCfg = CurriculumCfg()
def __post_init__(self):
"""Post initialization."""
# general settings
self.decimation = 4
self.episode_length_s = 20.0
# simulation settings
self.sim.dt = 0.005
self.sim.disable_contact_processing = True
self.sim.physics_material = self.scene.terrain.physics_material
# update sensor update periods
# we tick all the sensors based on the smallest update period (physics update period)
if self.scene.height_scanner is not None:
self.scene.height_scanner.update_period = self.decimation * self.sim.dt
if self.scene.contact_forces is not None:
self.scene.contact_forces.update_period = self.sim.dt
# check if terrain levels curriculum is enabled - if so, enable curriculum for terrain generator
# this generates terrains with increasing difficulty and is useful for training
if getattr(self.curriculum, "terrain_levels", None) is not None:
if self.scene.terrain.terrain_generator is not None:
self.scene.terrain.terrain_generator.curriculum = True
else:
if self.scene.terrain.terrain_generator is not None:
self.scene.terrain.terrain_generator.curriculum = False
|
isaac-orbit/orbit.ext_template/orbit/ext_template/tasks/locomotion/velocity/__init__.py | # Copyright (c) 2022-2024, The ORBIT Project Developers.
# All rights reserved.
#
# SPDX-License-Identifier: BSD-3-Clause
"""Locomotion environments with velocity-tracking commands.
These environments are based on the `legged_gym` environments provided by Rudin et al.
Reference:
https://github.com/leggedrobotics/legged_gym
"""
|
isaac-orbit/orbit.ext_template/orbit/ext_template/tasks/locomotion/velocity/mdp/__init__.py | # Copyright (c) 2022-2024, The ORBIT Project Developers.
# All rights reserved.
#
# SPDX-License-Identifier: BSD-3-Clause
"""This sub-module contains the functions that are specific to the locomotion environments."""
from omni.isaac.orbit.envs.mdp import * # noqa: F401, F403
from .curriculums import * # noqa: F401, F403
from .rewards import * # noqa: F401, F403
|
isaac-orbit/orbit.ext_template/orbit/ext_template/tasks/locomotion/velocity/mdp/curriculums.py | # Copyright (c) 2022-2024, The ORBIT Project Developers.
# All rights reserved.
#
# SPDX-License-Identifier: BSD-3-Clause
"""Common functions that can be used to create curriculum for the learning environment.
The functions can be passed to the :class:`omni.isaac.orbit.managers.CurriculumTermCfg` object to enable
the curriculum introduced by the function.
"""
from __future__ import annotations
from collections.abc import Sequence
from typing import TYPE_CHECKING
import torch
from omni.isaac.orbit.assets import Articulation
from omni.isaac.orbit.managers import SceneEntityCfg
from omni.isaac.orbit.terrains import TerrainImporter
if TYPE_CHECKING:
from omni.isaac.orbit.envs import RLTaskEnv
def terrain_levels_vel(
env: RLTaskEnv, env_ids: Sequence[int], asset_cfg: SceneEntityCfg = SceneEntityCfg("robot")
) -> torch.Tensor:
"""Curriculum based on the distance the robot walked when commanded to move at a desired velocity.
This term is used to increase the difficulty of the terrain when the robot walks far enough and decrease the
difficulty when the robot walks less than half of the distance required by the commanded velocity.
.. note::
It is only possible to use this term with the terrain type ``generator``. For further information
on different terrain types, check the :class:`omni.isaac.orbit.terrains.TerrainImporter` class.
Returns:
The mean terrain level for the given environment ids.
"""
# extract the used quantities (to enable type-hinting)
asset: Articulation = env.scene[asset_cfg.name]
terrain: TerrainImporter = env.scene.terrain
command = env.command_manager.get_command("base_velocity")
# compute the distance the robot walked
distance = torch.norm(asset.data.root_pos_w[env_ids, :2] - env.scene.env_origins[env_ids, :2], dim=1)
# robots that walked far enough progress to harder terrains
move_up = distance > terrain.cfg.terrain_generator.size[0] / 2
# robots that walked less than half of their required distance go to simpler terrains
move_down = distance < torch.norm(command[env_ids, :2], dim=1) * env.max_episode_length_s * 0.5
move_down *= ~move_up
# update terrain levels
terrain.update_env_origins(env_ids, move_up, move_down)
# return the mean terrain level
return torch.mean(terrain.terrain_levels.float())
|
isaac-orbit/orbit.ext_template/orbit/ext_template/tasks/locomotion/velocity/mdp/rewards.py | # Copyright (c) 2022-2024, The ORBIT Project Developers.
# All rights reserved.
#
# SPDX-License-Identifier: BSD-3-Clause
from __future__ import annotations
from typing import TYPE_CHECKING
import torch
from omni.isaac.orbit.managers import SceneEntityCfg
from omni.isaac.orbit.sensors import ContactSensor
if TYPE_CHECKING:
from omni.isaac.orbit.envs import RLTaskEnv
def feet_air_time(env: RLTaskEnv, command_name: str, sensor_cfg: SceneEntityCfg, threshold: float) -> torch.Tensor:
"""Reward long steps taken by the feet using L2-kernel.
This function rewards the agent for taking steps that are longer than a threshold. This helps ensure
that the robot lifts its feet off the ground and takes steps. The reward is computed as the sum of
the time for which the feet are in the air.
If the commands are small (i.e. the agent is not supposed to take a step), then the reward is zero.
"""
# extract the used quantities (to enable type-hinting)
contact_sensor: ContactSensor = env.scene.sensors[sensor_cfg.name]
# compute the reward
first_contact = contact_sensor.compute_first_contact(env.step_dt)[:, sensor_cfg.body_ids]
last_air_time = contact_sensor.data.last_air_time[:, sensor_cfg.body_ids]
reward = torch.sum((last_air_time - threshold) * first_contact, dim=1)
# no reward for zero command
reward *= torch.norm(env.command_manager.get_command(command_name)[:, :2], dim=1) > 0.1
return reward
def feet_air_time_positive_biped(env, command_name: str, threshold: float, sensor_cfg: SceneEntityCfg) -> torch.Tensor:
"""Reward long steps taken by the feet for bipeds.
This function rewards the agent for taking steps up to a specified threshold and also keep one foot at
a time in the air.
If the commands are small (i.e. the agent is not supposed to take a step), then the reward is zero.
"""
contact_sensor: ContactSensor = env.scene.sensors[sensor_cfg.name]
# compute the reward
air_time = contact_sensor.data.current_air_time[:, sensor_cfg.body_ids]
contact_time = contact_sensor.data.current_contact_time[:, sensor_cfg.body_ids]
in_contact = contact_time > 0.0
in_mode_time = torch.where(in_contact, contact_time, air_time)
single_stance = torch.sum(in_contact.int(), dim=1) == 1
reward = torch.min(torch.where(single_stance.unsqueeze(-1), in_mode_time, 0.0), dim=1)[0]
reward = torch.clamp(reward, max=threshold)
# no reward for zero command
reward *= torch.norm(env.command_manager.get_command(command_name)[:, :2], dim=1) > 0.1
return reward
|
isaac-orbit/orbit.ext_template/orbit/ext_template/tasks/locomotion/velocity/config/__init__.py | # Copyright (c) 2022-2024, The ORBIT Project Developers.
# All rights reserved.
#
# SPDX-License-Identifier: BSD-3-Clause
"""Configurations for velocity-based locomotion environments."""
# We leave this file empty since we don't want to expose any configs in this package directly.
# We still need this file to import the "config" module in the parent package.
|
isaac-orbit/orbit.ext_template/orbit/ext_template/tasks/locomotion/velocity/config/anymal_d/rough_env_cfg.py | # Copyright (c) 2022-2024, The ORBIT Project Developers.
# All rights reserved.
#
# SPDX-License-Identifier: BSD-3-Clause
from omni.isaac.orbit.utils import configclass
from orbit.ext_template.tasks.locomotion.velocity.velocity_env_cfg import (
LocomotionVelocityRoughEnvCfg,
)
##
# Pre-defined configs
##
from omni.isaac.orbit_assets.anymal import ANYMAL_D_CFG # isort: skip
@configclass
class AnymalDRoughEnvCfg(LocomotionVelocityRoughEnvCfg):
def __post_init__(self):
# post init of parent
super().__post_init__()
# switch robot to anymal-d
self.scene.robot = ANYMAL_D_CFG.replace(prim_path="{ENV_REGEX_NS}/Robot")
@configclass
class AnymalDRoughEnvCfg_PLAY(AnymalDRoughEnvCfg):
def __post_init__(self):
# post init of parent
super().__post_init__()
# make a smaller scene for play
self.scene.num_envs = 50
self.scene.env_spacing = 2.5
# spawn the robot randomly in the grid (instead of their terrain levels)
self.scene.terrain.max_init_terrain_level = None
# reduce the number of terrains to save memory
if self.scene.terrain.terrain_generator is not None:
self.scene.terrain.terrain_generator.num_rows = 5
self.scene.terrain.terrain_generator.num_cols = 5
self.scene.terrain.terrain_generator.curriculum = False
# disable randomization for play
self.observations.policy.enable_corruption = False
# remove random pushing
self.randomization.base_external_force_torque = None
self.randomization.push_robot = None
|
isaac-orbit/orbit.ext_template/orbit/ext_template/tasks/locomotion/velocity/config/anymal_d/flat_env_cfg.py | # Copyright (c) 2022-2024, The ORBIT Project Developers.
# All rights reserved.
#
# SPDX-License-Identifier: BSD-3-Clause
from omni.isaac.orbit.utils import configclass
from .rough_env_cfg import AnymalDRoughEnvCfg
@configclass
class AnymalDFlatEnvCfg(AnymalDRoughEnvCfg):
def __post_init__(self):
# post init of parent
super().__post_init__()
# override rewards
self.rewards.flat_orientation_l2.weight = -5.0
self.rewards.dof_torques_l2.weight = -2.5e-5
self.rewards.feet_air_time.weight = 0.5
# change terrain to flat
self.scene.terrain.terrain_type = "plane"
self.scene.terrain.terrain_generator = None
# no height scan
self.scene.height_scanner = None
self.observations.policy.height_scan = None
# no terrain curriculum
self.curriculum.terrain_levels = None
class AnymalDFlatEnvCfg_PLAY(AnymalDFlatEnvCfg):
def __post_init__(self) -> None:
# post init of parent
super().__post_init__()
# make a smaller scene for play
self.scene.num_envs = 50
self.scene.env_spacing = 2.5
# disable randomization for play
self.observations.policy.enable_corruption = False
# remove random pushing
self.randomization.base_external_force_torque = None
self.randomization.push_robot = None
|
isaac-orbit/orbit.ext_template/orbit/ext_template/tasks/locomotion/velocity/config/anymal_d/__init__.py | # Copyright (c) 2022-2024, The ORBIT Project Developers.
# All rights reserved.
#
# SPDX-License-Identifier: BSD-3-Clause
import gymnasium as gym
from . import agents, flat_env_cfg, rough_env_cfg
##
# Register Gym environments.
##
gym.register(
id="Isaac-Velocity-Flat-Anymal-D-Template-v0",
entry_point="omni.isaac.orbit.envs:RLTaskEnv",
disable_env_checker=True,
kwargs={
"env_cfg_entry_point": flat_env_cfg.AnymalDFlatEnvCfg,
"rsl_rl_cfg_entry_point": agents.rsl_rl_cfg.AnymalDFlatPPORunnerCfg,
},
)
gym.register(
id="Isaac-Velocity-Flat-Anymal-D-Template-Play-v0",
entry_point="omni.isaac.orbit.envs:RLTaskEnv",
disable_env_checker=True,
kwargs={
"env_cfg_entry_point": flat_env_cfg.AnymalDFlatEnvCfg_PLAY,
"rsl_rl_cfg_entry_point": agents.rsl_rl_cfg.AnymalDFlatPPORunnerCfg,
},
)
gym.register(
id="Isaac-Velocity-Rough-Anymal-D-Template-v0",
entry_point="omni.isaac.orbit.envs:RLTaskEnv",
disable_env_checker=True,
kwargs={
"env_cfg_entry_point": rough_env_cfg.AnymalDRoughEnvCfg,
"rsl_rl_cfg_entry_point": agents.rsl_rl_cfg.AnymalDRoughPPORunnerCfg,
},
)
gym.register(
id="Isaac-Velocity-Rough-Anymal-D-Template-Play-v0",
entry_point="omni.isaac.orbit.envs:RLTaskEnv",
disable_env_checker=True,
kwargs={
"env_cfg_entry_point": rough_env_cfg.AnymalDRoughEnvCfg_PLAY,
"rsl_rl_cfg_entry_point": agents.rsl_rl_cfg.AnymalDRoughPPORunnerCfg,
},
)
|
isaac-orbit/orbit.ext_template/orbit/ext_template/tasks/locomotion/velocity/config/anymal_d/agents/rsl_rl_cfg.py | # Copyright (c) 2022-2024, The ORBIT Project Developers.
# All rights reserved.
#
# SPDX-License-Identifier: BSD-3-Clause
from omni.isaac.orbit.utils import configclass
from omni.isaac.orbit_tasks.utils.wrappers.rsl_rl import (
RslRlOnPolicyRunnerCfg,
RslRlPpoActorCriticCfg,
RslRlPpoAlgorithmCfg,
)
@configclass
class AnymalDRoughPPORunnerCfg(RslRlOnPolicyRunnerCfg):
num_steps_per_env = 24
max_iterations = 1500
save_interval = 50
experiment_name = "anymal_d_rough"
empirical_normalization = False
policy = RslRlPpoActorCriticCfg(
init_noise_std=1.0,
actor_hidden_dims=[512, 256, 128],
critic_hidden_dims=[512, 256, 128],
activation="elu",
)
algorithm = RslRlPpoAlgorithmCfg(
value_loss_coef=1.0,
use_clipped_value_loss=True,
clip_param=0.2,
entropy_coef=0.005,
num_learning_epochs=5,
num_mini_batches=4,
learning_rate=1.0e-3,
schedule="adaptive",
gamma=0.99,
lam=0.95,
desired_kl=0.01,
max_grad_norm=1.0,
)
@configclass
class AnymalDFlatPPORunnerCfg(AnymalDRoughPPORunnerCfg):
def __post_init__(self):
super().__post_init__()
self.max_iterations = 300
self.experiment_name = "anymal_d_flat"
self.policy.actor_hidden_dims = [128, 128, 128]
self.policy.critic_hidden_dims = [128, 128, 128]
|
isaac-orbit/orbit.ext_template/orbit/ext_template/tasks/locomotion/velocity/config/anymal_d/agents/__init__.py | # Copyright (c) 2022-2024, The ORBIT Project Developers.
# All rights reserved.
#
# SPDX-License-Identifier: BSD-3-Clause
from . import rsl_rl_cfg # noqa: F401, F403
|
isaac-orbit/orbit.ext_template/docs/CHANGELOG.rst | Changelog
---------
0.1.0 (2024-01-29)
~~~~~~~~~~~~~~~~~~
Added
^^^^^
* Created an initial template for building an extension or project based on Orbit
|
MomentFactory/Omniverse-NDI-extension/example.usda | #usda 1.0
(
customLayerData = {
dictionary cameraSettings = {
dictionary Front = {
double3 position = (0, 0, 50000)
double radius = 500
}
dictionary Perspective = {
double3 position = (83.17940401698989, 1044.3144444268976, 4144.469143212094)
double3 target = (54.131303730017166, 696.4520152756534, -1154.3624507711083)
}
dictionary Right = {
double3 position = (-50000, 0, 0)
double radius = 500
}
dictionary Top = {
double3 position = (0, 50000, 0)
double radius = 500
}
string boundCamera = "/OmniverseKit_Persp"
}
dictionary omni_layer = {
dictionary muteness = {
}
}
dictionary renderSettings = {
float3 "rtx:debugView:pixelDebug:textColor" = (0, 1e18, 0)
bool "rtx:ecoMode:enabled" = 0
float3 "rtx:fog:fogColor" = (0.75, 0.75, 0.75)
float3 "rtx:post:backgroundZeroAlpha:backgroundDefaultColor" = (0, 0, 0)
float3 "rtx:post:colorcorr:contrast" = (1, 1, 1)
float3 "rtx:post:colorcorr:gain" = (1, 1, 1)
float3 "rtx:post:colorcorr:gamma" = (1, 1, 1)
float3 "rtx:post:colorcorr:offset" = (0, 0, 0)
float3 "rtx:post:colorcorr:saturation" = (1, 1, 1)
float3 "rtx:post:colorgrad:blackpoint" = (0, 0, 0)
float3 "rtx:post:colorgrad:contrast" = (1, 1, 1)
float3 "rtx:post:colorgrad:gain" = (1, 1, 1)
float3 "rtx:post:colorgrad:gamma" = (1, 1, 1)
float3 "rtx:post:colorgrad:lift" = (0, 0, 0)
float3 "rtx:post:colorgrad:multiply" = (1, 1, 1)
float3 "rtx:post:colorgrad:offset" = (0, 0, 0)
float3 "rtx:post:colorgrad:whitepoint" = (1, 1, 1)
float3 "rtx:post:lensDistortion:lensFocalLengthArray" = (10, 30, 50)
float3 "rtx:post:lensFlares:anisoFlareFalloffX" = (450, 475, 500)
float3 "rtx:post:lensFlares:anisoFlareFalloffY" = (10, 10, 10)
float3 "rtx:post:lensFlares:cutoffPoint" = (2, 2, 2)
float3 "rtx:post:lensFlares:haloFlareFalloff" = (10, 10, 10)
float3 "rtx:post:lensFlares:haloFlareRadius" = (75, 75, 75)
float3 "rtx:post:lensFlares:isotropicFlareFalloff" = (50, 50, 50)
float3 "rtx:post:tonemap:whitepoint" = (1, 1, 1)
float3 "rtx:raytracing:inscattering:singleScatteringAlbedo" = (0.9, 0.9, 0.9)
float3 "rtx:raytracing:inscattering:transmittanceColor" = (0.5, 0.5, 0.5)
float3 "rtx:sceneDb:ambientLightColor" = (0.1, 0.1, 0.1)
}
}
defaultPrim = "World"
endTimeCode = 100
metersPerUnit = 0.01
startTimeCode = 0
timeCodesPerSecond = 24
upAxis = "Y"
)
def Xform "World"
{
def Scope "NDI_Looks"
{
def Material "left"
{
token outputs:surface.connect = </World/NDI_Looks/left/Shader.outputs:surface>
def Shader "Shader"
{
uniform token info:id = "OmniPBR"
uniform token info:implementationSource = "sourceAsset"
uniform asset info:mdl:sourceAsset = @OmniPBR.mdl@
uniform token info:mdl:sourceAsset:subIdentifier = "OmniPBR"
asset inputs:diffuse_texture = @dynamic://left@
custom string ndi:source = "MY-PC (Test Pattern)"
token outputs:surface
}
}
def Material "right"
{
token outputs:surface.connect = </World/NDI_Looks/right/Shader.outputs:surface>
def Shader "Shader"
{
uniform token info:id = "OmniPBR"
uniform token info:implementationSource = "sourceAsset"
uniform asset info:mdl:sourceAsset = @OmniPBR.mdl@
uniform token info:mdl:sourceAsset:subIdentifier = "OmniPBR"
asset inputs:diffuse_texture = @dynamic://right@
custom string ndi:source = "MY-PC (Test Pattern 2)"
token outputs:surface
}
}
}
def Mesh "left_billboard"
{
float3[] extent = [(-50, 0, -50), (50, 0, 50)]
int[] faceVertexCounts = [4]
int[] faceVertexIndices = [0, 2, 3, 1]
rel material:binding = </World/NDI_Looks/left> (
bindMaterialAs = "weakerThanDescendants"
)
normal3f[] normals = [(0, 1, 0), (0, 1, 0), (0, 1, 0), (0, 1, 0)] (
interpolation = "faceVarying"
)
point3f[] points = [(-50, 0, -50), (50, 0, -50), (-50, 0, 50), (50, 0, 50)]
float2[] primvars:st = [(0, 0), (0, 1), (1, 1), (1, 0)] (
interpolation = "faceVarying"
)
uniform token subdivisionScheme = "none"
double3 xformOp:rotateXYZ = (-90, 0, 0)
double3 xformOp:scale = (19.2, 1, 10.8)
double3 xformOp:translate = (-1100, 600, 0)
uniform token[] xformOpOrder = ["xformOp:translate", "xformOp:rotateXYZ", "xformOp:scale"]
}
def Mesh "right_billboard"
{
float3[] extent = [(-50, 0, -50), (50, 0, 50)]
int[] faceVertexCounts = [4]
int[] faceVertexIndices = [0, 2, 3, 1]
rel material:binding = </World/NDI_Looks/right> (
bindMaterialAs = "weakerThanDescendants"
)
normal3f[] normals = [(0, 1, 0), (0, 1, 0), (0, 1, 0), (0, 1, 0)] (
interpolation = "faceVarying"
)
point3f[] points = [(-50, 0, -50), (50, 0, -50), (-50, 0, 50), (50, 0, 50)]
float2[] primvars:st = [(0, 0), (0, 1), (1, 1), (1, 0)] (
interpolation = "faceVarying"
)
uniform token subdivisionScheme = "none"
double3 xformOp:rotateXYZ = (-90, 0, 0)
double3 xformOp:scale = (19.2, 1, 10.8)
double3 xformOp:translate = (1100, 600, 0)
uniform token[] xformOpOrder = ["xformOp:translate", "xformOp:rotateXYZ", "xformOp:scale"]
}
}
def Xform "Environment"
{
double3 xformOp:rotateXYZ = (0, 0, 0)
double3 xformOp:scale = (1, 1, 1)
double3 xformOp:translate = (0, 0, 0)
uniform token[] xformOpOrder = ["xformOp:translate", "xformOp:rotateXYZ", "xformOp:scale"]
def DistantLight "defaultLight" (
prepend apiSchemas = ["ShapingAPI"]
)
{
float angle = 1
float intensity = 3000
float shaping:cone:angle = 180
float shaping:cone:softness
float shaping:focus
color3f shaping:focusTint
asset shaping:ies:file
double3 xformOp:rotateXYZ = (315, 0, 0)
double3 xformOp:scale = (1, 1, 1)
double3 xformOp:translate = (0, 0, 0)
uniform token[] xformOpOrder = ["xformOp:translate", "xformOp:rotateXYZ", "xformOp:scale"]
}
}
|
MomentFactory/Omniverse-NDI-extension/link_app.sh | #!/bin/bash
set -e
SCRIPT_DIR=$(dirname ${BASH_SOURCE})
cd "$SCRIPT_DIR"
exec "tools/packman/python.sh" tools/scripts/link_app.py $@
|
MomentFactory/Omniverse-NDI-extension/link_app.bat | @echo off
call "%~dp0tools\packman\python.bat" %~dp0tools\scripts\link_app.py %*
if %errorlevel% neq 0 ( goto Error )
:Success
exit /b 0
:Error
exit /b %errorlevel%
|
MomentFactory/Omniverse-NDI-extension/README.md | # mf.ov.ndi
An extension to enable NDI® live video input in Omniverse.
## Getting started
- Requires Omniverse Kit >= 105
- Requires USD Composer > 2023.1.0
- Requires [NDI® 5.5.3 runtime for Windows](https://go.ndi.tv/tools-for-windows)
Previous releases should still be supported in USD composer 2022.x
This plugin leverages the `dynamic://` keyword which is currently a beta feature of Omniverse.
## Using the extension
⚠️You should disable Render Settings > Raytracing > Eco Mode for the extension to work properly.
### Enable the extension
In USD Composer :
- Windows > Extensions.
- Switch to THIRD PARY tab.
- Install and enable the extension.
You may want to use [example.usda](./example.usda) in Create for your first test.
### Extension window
If not opened automatically : Windows > NDI®.

### Window header
- ➕**Create Dynamic Texture**: Creates a new material and shader under /Looks with the associated configuration for dynamic texture rendering. The text field `myDynamicMaterial` allows to customize the identifier for the dynamic texture to register.
- 🔄**Discover Dynamic Textures** searches through the USD stage hierarchy for any material with a `dynamic://` asset source (like the one created by “Create Dynamic Material”). Will add a collapsible section for each unique id found
- ⏹️**Stop all streams** stops the reception of the video stream for every dynamic texture. A material with a dynamic texture source will still display the last frame it received.
### Dynamic material component
Each dynamic texture will be represented in a collapsible component.
The title is the name of your dynamic texture.
- ☑️ Indicates the health of the video feed.
- **NDI® feed combobox** Select which NDI® feed to use for this dynamic texture identifier. This value is saved in USD as a custom property in the shader under `ndi:source`
- ⏸️ Allows to start/stop the video feed.
- 🖼️ Allows to switch the feed to Low bandwidth mode, saving performance by decreasing resolution for a particular feed.
- 🗇 To copy to clipboard the identifiers of the dynamic texture Example `dynamic://myDynamicMaterial`
## Resources
- Inspired by : [kit-extension-template](https://github.com/NVIDIA-Omniverse/kit-extension-template)
- [kit-cv-video-example](https://github.com/jshrake-nvidia/kit-cv-video-example)
- [kit-dynamic-texture-example](https://github.com/jshrake-nvidia/kit-dynamic-texture-example)
- [ndi-python](https://github.com/buresu/ndi-python)
## Known issues
- Currently implemented with Python, performance could be greatly improved with C++ (but limited by DynamicTextureProvider implementation)
- You can ignore warnings in the form of `[Warning] [omni.hydra] Material parameter '...' was assigned to incompatible texture: '...'`
- You can ignore warnings in the form of `[Warning] [omni.ext._impl._internal] mf.ov.ndi-... -> <class 'mf.ov.ndi...'>: extension object is still alive, something holds a reference on it...`
- You can ignore the first istance of `[Warning] Could not get stage`, because the extension loads before the stage is initialized |
MomentFactory/Omniverse-NDI-extension/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!")
|
MomentFactory/Omniverse-NDI-extension/tools/packman/python.sh | #!/bin/bash
# Copyright 2019-2020 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.
set -e
PACKMAN_CMD="$(dirname "${BASH_SOURCE}")/packman"
if [ ! -f "$PACKMAN_CMD" ]; then
PACKMAN_CMD="${PACKMAN_CMD}.sh"
fi
source "$PACKMAN_CMD" init
export PYTHONPATH="${PM_MODULE_DIR}:${PYTHONPATH}"
export PYTHONNOUSERSITE=1
# workaround for our python not shipping with certs
if [[ -z ${SSL_CERT_DIR:-} ]]; then
export SSL_CERT_DIR=/etc/ssl/certs/
fi
"${PM_PYTHON}" -u "$@"
|
MomentFactory/Omniverse-NDI-extension/tools/packman/python.bat | :: Copyright 2019-2020 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.
@echo off
setlocal
call "%~dp0\packman" init
set "PYTHONPATH=%PM_MODULE_DIR%;%PYTHONPATH%"
set PYTHONNOUSERSITE=1
"%PM_PYTHON%" -u %*
|
MomentFactory/Omniverse-NDI-extension/tools/packman/packman.cmd | :: Reset errorlevel status (don't inherit from caller) [xxxxxxxxxxx]
@call :ECHO_AND_RESET_ERROR
:: You can remove the call below if you do your own manual configuration of the dev machines
call "%~dp0\bootstrap\configure.bat"
if %errorlevel% neq 0 ( exit /b %errorlevel% )
:: Everything below is mandatory
if not defined PM_PYTHON goto :PYTHON_ENV_ERROR
if not defined PM_MODULE goto :MODULE_ENV_ERROR
:: Generate temporary path for variable file
for /f "delims=" %%a in ('powershell -ExecutionPolicy ByPass -NoLogo -NoProfile ^
-File "%~dp0bootstrap\generate_temp_file_name.ps1"') do set PM_VAR_PATH=%%a
if %1.==. (
set PM_VAR_PATH_ARG=
) else (
set PM_VAR_PATH_ARG=--var-path="%PM_VAR_PATH%"
)
"%PM_PYTHON%" -S -s -u -E "%PM_MODULE%" %* %PM_VAR_PATH_ARG%
if %errorlevel% neq 0 ( exit /b %errorlevel% )
:: Marshall environment variables into the current environment if they have been generated and remove temporary file
if exist "%PM_VAR_PATH%" (
for /F "usebackq tokens=*" %%A in ("%PM_VAR_PATH%") do set "%%A"
)
if %errorlevel% neq 0 ( goto :VAR_ERROR )
if exist "%PM_VAR_PATH%" (
del /F "%PM_VAR_PATH%"
)
if %errorlevel% neq 0 ( goto :VAR_ERROR )
set PM_VAR_PATH=
goto :eof
:: Subroutines below
:PYTHON_ENV_ERROR
@echo User environment variable PM_PYTHON is not set! Please configure machine for packman or call configure.bat.
exit /b 1
:MODULE_ENV_ERROR
@echo User environment variable PM_MODULE is not set! Please configure machine for packman or call configure.bat.
exit /b 1
:VAR_ERROR
@echo Error while processing and setting environment variables!
exit /b 1
:ECHO_AND_RESET_ERROR
@echo off
if /I "%PM_VERBOSITY%"=="debug" (
@echo on
)
exit /b 0
|
MomentFactory/Omniverse-NDI-extension/tools/packman/config.packman.xml | <config remotes="cloudfront">
<remote2 name="cloudfront">
<transport actions="download" protocol="https" packageLocation="d4i3qtqj3r0z5.cloudfront.net/${name}@${version}" />
</remote2>
</config>
|
MomentFactory/Omniverse-NDI-extension/tools/packman/bootstrap/generate_temp_file_name.ps1 | <#
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.
#>
$out = [System.IO.Path]::GetTempFileName()
Write-Host $out
# SIG # Begin signature block
# MIIaVwYJKoZIhvcNAQcCoIIaSDCCGkQCAQExDzANBglghkgBZQMEAgEFADB5Bgor
# BgEEAYI3AgEEoGswaTA0BgorBgEEAYI3AgEeMCYCAwEAAAQQH8w7YFlLCE63JNLG
# KX7zUQIBAAIBAAIBAAIBAAIBADAxMA0GCWCGSAFlAwQCAQUABCAK+Ewup1N0/mdf
# 1l4R58rxyumHgZvTmEhrYTb2Zf0zd6CCCiIwggTTMIIDu6ADAgECAhBi50XpIWUh
# PJcfXEkK6hKlMA0GCSqGSIb3DQEBCwUAMIGEMQswCQYDVQQGEwJVUzEdMBsGA1UE
# ChMUU3ltYW50ZWMgQ29ycG9yYXRpb24xHzAdBgNVBAsTFlN5bWFudGVjIFRydXN0
# IE5ldHdvcmsxNTAzBgNVBAMTLFN5bWFudGVjIENsYXNzIDMgU0hBMjU2IENvZGUg
# U2lnbmluZyBDQSAtIEcyMB4XDTE4MDcwOTAwMDAwMFoXDTIxMDcwOTIzNTk1OVow
# gYMxCzAJBgNVBAYTAlVTMRMwEQYDVQQIDApDYWxpZm9ybmlhMRQwEgYDVQQHDAtT
# YW50YSBDbGFyYTEbMBkGA1UECgwSTlZJRElBIENvcnBvcmF0aW9uMQ8wDQYDVQQL
# DAZJVC1NSVMxGzAZBgNVBAMMEk5WSURJQSBDb3Jwb3JhdGlvbjCCASIwDQYJKoZI
# hvcNAQEBBQADggEPADCCAQoCggEBALEZN63dA47T4i90jZ84CJ/aWUwVtLff8AyP
# YspFfIZGdZYiMgdb8A5tBh7653y0G/LZL6CVUkgejcpvBU/Dl/52a+gSWy2qJ2bH
# jMFMKCyQDhdpCAKMOUKSC9rfzm4cFeA9ct91LQCAait4LhLlZt/HF7aG+r0FgCZa
# HJjJvE7KNY9G4AZXxjSt8CXS8/8NQMANqjLX1r+F+Hl8PzQ1fVx0mMsbdtaIV4Pj
# 5flAeTUnz6+dCTx3vTUo8MYtkS2UBaQv7t7H2B7iwJDakEQKk1XHswJdeqG0osDU
# z6+NVks7uWE1N8UIhvzbw0FEX/U2kpfyWaB/J3gMl8rVR8idPj8CAwEAAaOCAT4w
# ggE6MAkGA1UdEwQCMAAwDgYDVR0PAQH/BAQDAgeAMBMGA1UdJQQMMAoGCCsGAQUF
# BwMDMGEGA1UdIARaMFgwVgYGZ4EMAQQBMEwwIwYIKwYBBQUHAgEWF2h0dHBzOi8v
# ZC5zeW1jYi5jb20vY3BzMCUGCCsGAQUFBwICMBkMF2h0dHBzOi8vZC5zeW1jYi5j
# b20vcnBhMB8GA1UdIwQYMBaAFNTABiJJ6zlL3ZPiXKG4R3YJcgNYMCsGA1UdHwQk
# MCIwIKAeoByGGmh0dHA6Ly9yYi5zeW1jYi5jb20vcmIuY3JsMFcGCCsGAQUFBwEB
# BEswSTAfBggrBgEFBQcwAYYTaHR0cDovL3JiLnN5bWNkLmNvbTAmBggrBgEFBQcw
# AoYaaHR0cDovL3JiLnN5bWNiLmNvbS9yYi5jcnQwDQYJKoZIhvcNAQELBQADggEB
# AIJKh5vKJdhHJtMzATmc1BmXIQ3RaJONOZ5jMHn7HOkYU1JP0OIzb4pXXkH8Xwfr
# K6bnd72IhcteyksvKsGpSvK0PBBwzodERTAu1Os2N+EaakxQwV/xtqDm1E3IhjHk
# fRshyKKzmFk2Ci323J4lHtpWUj5Hz61b8gd72jH7xnihGi+LORJ2uRNZ3YuqMNC3
# SBC8tAyoJqEoTJirULUCXW6wX4XUm5P2sx+htPw7szGblVKbQ+PFinNGnsSEZeKz
# D8jUb++1cvgTKH59Y6lm43nsJjkZU77tNqyq4ABwgQRk6lt8cS2PPwjZvTmvdnla
# ZhR0K4of+pQaUQHXVIBdji8wggVHMIIEL6ADAgECAhB8GzU1SufbdOdBXxFpymuo
# MA0GCSqGSIb3DQEBCwUAMIG9MQswCQYDVQQGEwJVUzEXMBUGA1UEChMOVmVyaVNp
# Z24sIEluYy4xHzAdBgNVBAsTFlZlcmlTaWduIFRydXN0IE5ldHdvcmsxOjA4BgNV
# BAsTMShjKSAyMDA4IFZlcmlTaWduLCBJbmMuIC0gRm9yIGF1dGhvcml6ZWQgdXNl
# IG9ubHkxODA2BgNVBAMTL1ZlcmlTaWduIFVuaXZlcnNhbCBSb290IENlcnRpZmlj
# YXRpb24gQXV0aG9yaXR5MB4XDTE0MDcyMjAwMDAwMFoXDTI0MDcyMTIzNTk1OVow
# gYQxCzAJBgNVBAYTAlVTMR0wGwYDVQQKExRTeW1hbnRlYyBDb3Jwb3JhdGlvbjEf
# MB0GA1UECxMWU3ltYW50ZWMgVHJ1c3QgTmV0d29yazE1MDMGA1UEAxMsU3ltYW50
# ZWMgQ2xhc3MgMyBTSEEyNTYgQ29kZSBTaWduaW5nIENBIC0gRzIwggEiMA0GCSqG
# SIb3DQEBAQUAA4IBDwAwggEKAoIBAQDXlUPU3N9nrjn7UqS2JjEEcOm3jlsqujdp
# NZWPu8Aw54bYc7vf69F2P4pWjustS/BXGE6xjaUz0wt1I9VqeSfdo9P3Dodltd6t
# HPH1NbQiUa8iocFdS5B/wFlOq515qQLXHkmxO02H/sJ4q7/vUq6crwjZOeWaUT5p
# XzAQTnFjbFjh8CAzGw90vlvLEuHbjMSAlHK79kWansElC/ujHJ7YpglwcezAR0yP
# fcPeGc4+7gRyjhfT//CyBTIZTNOwHJ/+pXggQnBBsCaMbwDIOgARQXpBsKeKkQSg
# mXj0d7TzYCrmbFAEtxRg/w1R9KiLhP4h2lxeffUpeU+wRHRvbXL/AgMBAAGjggF4
# MIIBdDAuBggrBgEFBQcBAQQiMCAwHgYIKwYBBQUHMAGGEmh0dHA6Ly9zLnN5bWNk
# LmNvbTASBgNVHRMBAf8ECDAGAQH/AgEAMGYGA1UdIARfMF0wWwYLYIZIAYb4RQEH
# FwMwTDAjBggrBgEFBQcCARYXaHR0cHM6Ly9kLnN5bWNiLmNvbS9jcHMwJQYIKwYB
# BQUHAgIwGRoXaHR0cHM6Ly9kLnN5bWNiLmNvbS9ycGEwNgYDVR0fBC8wLTAroCmg
# J4YlaHR0cDovL3Muc3ltY2IuY29tL3VuaXZlcnNhbC1yb290LmNybDATBgNVHSUE
# DDAKBggrBgEFBQcDAzAOBgNVHQ8BAf8EBAMCAQYwKQYDVR0RBCIwIKQeMBwxGjAY
# BgNVBAMTEVN5bWFudGVjUEtJLTEtNzI0MB0GA1UdDgQWBBTUwAYiSes5S92T4lyh
# uEd2CXIDWDAfBgNVHSMEGDAWgBS2d/ppSEefUxLVwuoHMnYH0ZcHGTANBgkqhkiG
# 9w0BAQsFAAOCAQEAf+vKp+qLdkLrPo4gVDDjt7nc+kg+FscPRZUQzSeGo2bzAu1x
# +KrCVZeRcIP5Un5SaTzJ8eCURoAYu6HUpFam8x0AkdWG80iH4MvENGggXrTL+QXt
# nK9wUye56D5+UaBpcYvcUe2AOiUyn0SvbkMo0yF1u5fYi4uM/qkERgSF9xWcSxGN
# xCwX/tVuf5riVpLxlrOtLfn039qJmc6yOETA90d7yiW5+ipoM5tQct6on9TNLAs0
# vYsweEDgjY4nG5BvGr4IFYFd6y/iUedRHsl4KeceZb847wFKAQkkDhbEFHnBQTc0
# 0D2RUpSd4WjvCPDiaZxnbpALGpNx1CYCw8BaIzGCD4swgg+HAgEBMIGZMIGEMQsw
# CQYDVQQGEwJVUzEdMBsGA1UEChMUU3ltYW50ZWMgQ29ycG9yYXRpb24xHzAdBgNV
# BAsTFlN5bWFudGVjIFRydXN0IE5ldHdvcmsxNTAzBgNVBAMTLFN5bWFudGVjIENs
# YXNzIDMgU0hBMjU2IENvZGUgU2lnbmluZyBDQSAtIEcyAhBi50XpIWUhPJcfXEkK
# 6hKlMA0GCWCGSAFlAwQCAQUAoHwwEAYKKwYBBAGCNwIBDDECMAAwGQYJKoZIhvcN
# AQkDMQwGCisGAQQBgjcCAQQwHAYKKwYBBAGCNwIBCzEOMAwGCisGAQQBgjcCARUw
# LwYJKoZIhvcNAQkEMSIEIPW+EpFrZSdzrjFFo0UT+PzFeYn/GcWNyWFaU/JMrMfR
# MA0GCSqGSIb3DQEBAQUABIIBAA8fmU/RJcF9t60DZZAjf8FB3EZddOaHgI9z40nV
# CnfTGi0OEYU48Pe9jkQQV2fABpACfW74xmNv3QNgP2qP++mkpKBVv28EIAuINsFt
# YAITEljLN/VOVul8lvjxar5GSFFgpE5F6j4xcvI69LuCWbN8cteTVsBGg+eGmjfx
# QZxP252z3FqPN+mihtFegF2wx6Mg6/8jZjkO0xjBOwSdpTL4uyQfHvaPBKXuWxRx
# ioXw4ezGAwkuBoxWK8UG7Qu+7CSfQ3wMOjvyH2+qn30lWEsvRMdbGAp7kvfr3EGZ
# a3WN7zXZ+6KyZeLeEH7yCDzukAjptaY/+iLVjJsuzC6tCSqhgg1EMIINQAYKKwYB
# BAGCNwMDATGCDTAwgg0sBgkqhkiG9w0BBwKggg0dMIINGQIBAzEPMA0GCWCGSAFl
# AwQCAQUAMHcGCyqGSIb3DQEJEAEEoGgEZjBkAgEBBglghkgBhv1sBwEwMTANBglg
# hkgBZQMEAgEFAAQg14BnPazQkW9whhZu1d0bC3lqqScvxb3SSb1QT8e3Xg0CEFhw
# aMBZ2hExXhr79A9+bXEYDzIwMjEwNDA4MDkxMTA5WqCCCjcwggT+MIID5qADAgEC
# AhANQkrgvjqI/2BAIc4UAPDdMA0GCSqGSIb3DQEBCwUAMHIxCzAJBgNVBAYTAlVT
# MRUwEwYDVQQKEwxEaWdpQ2VydCBJbmMxGTAXBgNVBAsTEHd3dy5kaWdpY2VydC5j
# b20xMTAvBgNVBAMTKERpZ2lDZXJ0IFNIQTIgQXNzdXJlZCBJRCBUaW1lc3RhbXBp
# bmcgQ0EwHhcNMjEwMTAxMDAwMDAwWhcNMzEwMTA2MDAwMDAwWjBIMQswCQYDVQQG
# EwJVUzEXMBUGA1UEChMORGlnaUNlcnQsIEluYy4xIDAeBgNVBAMTF0RpZ2lDZXJ0
# IFRpbWVzdGFtcCAyMDIxMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA
# wuZhhGfFivUNCKRFymNrUdc6EUK9CnV1TZS0DFC1JhD+HchvkWsMlucaXEjvROW/
# m2HNFZFiWrj/ZwucY/02aoH6KfjdK3CF3gIY83htvH35x20JPb5qdofpir34hF0e
# dsnkxnZ2OlPR0dNaNo/Go+EvGzq3YdZz7E5tM4p8XUUtS7FQ5kE6N1aG3JMjjfdQ
# Jehk5t3Tjy9XtYcg6w6OLNUj2vRNeEbjA4MxKUpcDDGKSoyIxfcwWvkUrxVfbENJ
# Cf0mI1P2jWPoGqtbsR0wwptpgrTb/FZUvB+hh6u+elsKIC9LCcmVp42y+tZji06l
# chzun3oBc/gZ1v4NSYS9AQIDAQABo4IBuDCCAbQwDgYDVR0PAQH/BAQDAgeAMAwG
# A1UdEwEB/wQCMAAwFgYDVR0lAQH/BAwwCgYIKwYBBQUHAwgwQQYDVR0gBDowODA2
# BglghkgBhv1sBwEwKTAnBggrBgEFBQcCARYbaHR0cDovL3d3dy5kaWdpY2VydC5j
# b20vQ1BTMB8GA1UdIwQYMBaAFPS24SAd/imu0uRhpbKiJbLIFzVuMB0GA1UdDgQW
# BBQ2RIaOpLqwZr68KC0dRDbd42p6vDBxBgNVHR8EajBoMDKgMKAuhixodHRwOi8v
# Y3JsMy5kaWdpY2VydC5jb20vc2hhMi1hc3N1cmVkLXRzLmNybDAyoDCgLoYsaHR0
# cDovL2NybDQuZGlnaWNlcnQuY29tL3NoYTItYXNzdXJlZC10cy5jcmwwgYUGCCsG
# AQUFBwEBBHkwdzAkBggrBgEFBQcwAYYYaHR0cDovL29jc3AuZGlnaWNlcnQuY29t
# ME8GCCsGAQUFBzAChkNodHRwOi8vY2FjZXJ0cy5kaWdpY2VydC5jb20vRGlnaUNl
# cnRTSEEyQXNzdXJlZElEVGltZXN0YW1waW5nQ0EuY3J0MA0GCSqGSIb3DQEBCwUA
# A4IBAQBIHNy16ZojvOca5yAOjmdG/UJyUXQKI0ejq5LSJcRwWb4UoOUngaVNFBUZ
# B3nw0QTDhtk7vf5EAmZN7WmkD/a4cM9i6PVRSnh5Nnont/PnUp+Tp+1DnnvntN1B
# Ion7h6JGA0789P63ZHdjXyNSaYOC+hpT7ZDMjaEXcw3082U5cEvznNZ6e9oMvD0y
# 0BvL9WH8dQgAdryBDvjA4VzPxBFy5xtkSdgimnUVQvUtMjiB2vRgorq0Uvtc4GEk
# JU+y38kpqHNDUdq9Y9YfW5v3LhtPEx33Sg1xfpe39D+E68Hjo0mh+s6nv1bPull2
# YYlffqe0jmd4+TaY4cso2luHpoovMIIFMTCCBBmgAwIBAgIQCqEl1tYyG35B5AXa
# NpfCFTANBgkqhkiG9w0BAQsFADBlMQswCQYDVQQGEwJVUzEVMBMGA1UEChMMRGln
# aUNlcnQgSW5jMRkwFwYDVQQLExB3d3cuZGlnaWNlcnQuY29tMSQwIgYDVQQDExtE
# aWdpQ2VydCBBc3N1cmVkIElEIFJvb3QgQ0EwHhcNMTYwMTA3MTIwMDAwWhcNMzEw
# MTA3MTIwMDAwWjByMQswCQYDVQQGEwJVUzEVMBMGA1UEChMMRGlnaUNlcnQgSW5j
# MRkwFwYDVQQLExB3d3cuZGlnaWNlcnQuY29tMTEwLwYDVQQDEyhEaWdpQ2VydCBT
# SEEyIEFzc3VyZWQgSUQgVGltZXN0YW1waW5nIENBMIIBIjANBgkqhkiG9w0BAQEF
# AAOCAQ8AMIIBCgKCAQEAvdAy7kvNj3/dqbqCmcU5VChXtiNKxA4HRTNREH3Q+X1N
# aH7ntqD0jbOI5Je/YyGQmL8TvFfTw+F+CNZqFAA49y4eO+7MpvYyWf5fZT/gm+vj
# RkcGGlV+Cyd+wKL1oODeIj8O/36V+/OjuiI+GKwR5PCZA207hXwJ0+5dyJoLVOOo
# CXFr4M8iEA91z3FyTgqt30A6XLdR4aF5FMZNJCMwXbzsPGBqrC8HzP3w6kfZiFBe
# /WZuVmEnKYmEUeaC50ZQ/ZQqLKfkdT66mA+Ef58xFNat1fJky3seBdCEGXIX8RcG
# 7z3N1k3vBkL9olMqT4UdxB08r8/arBD13ays6Vb/kwIDAQABo4IBzjCCAcowHQYD
# VR0OBBYEFPS24SAd/imu0uRhpbKiJbLIFzVuMB8GA1UdIwQYMBaAFEXroq/0ksuC
# MS1Ri6enIZ3zbcgPMBIGA1UdEwEB/wQIMAYBAf8CAQAwDgYDVR0PAQH/BAQDAgGG
# MBMGA1UdJQQMMAoGCCsGAQUFBwMIMHkGCCsGAQUFBwEBBG0wazAkBggrBgEFBQcw
# AYYYaHR0cDovL29jc3AuZGlnaWNlcnQuY29tMEMGCCsGAQUFBzAChjdodHRwOi8v
# Y2FjZXJ0cy5kaWdpY2VydC5jb20vRGlnaUNlcnRBc3N1cmVkSURSb290Q0EuY3J0
# MIGBBgNVHR8EejB4MDqgOKA2hjRodHRwOi8vY3JsNC5kaWdpY2VydC5jb20vRGln
# aUNlcnRBc3N1cmVkSURSb290Q0EuY3JsMDqgOKA2hjRodHRwOi8vY3JsMy5kaWdp
# Y2VydC5jb20vRGlnaUNlcnRBc3N1cmVkSURSb290Q0EuY3JsMFAGA1UdIARJMEcw
# OAYKYIZIAYb9bAACBDAqMCgGCCsGAQUFBwIBFhxodHRwczovL3d3dy5kaWdpY2Vy
# dC5jb20vQ1BTMAsGCWCGSAGG/WwHATANBgkqhkiG9w0BAQsFAAOCAQEAcZUS6VGH
# VmnN793afKpjerN4zwY3QITvS4S/ys8DAv3Fp8MOIEIsr3fzKx8MIVoqtwU0HWqu
# mfgnoma/Capg33akOpMP+LLR2HwZYuhegiUexLoceywh4tZbLBQ1QwRostt1AuBy
# x5jWPGTlH0gQGF+JOGFNYkYkh2OMkVIsrymJ5Xgf1gsUpYDXEkdws3XVk4WTfraS
# Z/tTYYmo9WuWwPRYaQ18yAGxuSh1t5ljhSKMYcp5lH5Z/IwP42+1ASa2bKXuh1Eh
# 5Fhgm7oMLSttosR+u8QlK0cCCHxJrhO24XxCQijGGFbPQTS2Zl22dHv1VjMiLyI2
# skuiSpXY9aaOUjGCAk0wggJJAgEBMIGGMHIxCzAJBgNVBAYTAlVTMRUwEwYDVQQK
# EwxEaWdpQ2VydCBJbmMxGTAXBgNVBAsTEHd3dy5kaWdpY2VydC5jb20xMTAvBgNV
# BAMTKERpZ2lDZXJ0IFNIQTIgQXNzdXJlZCBJRCBUaW1lc3RhbXBpbmcgQ0ECEA1C
# SuC+Ooj/YEAhzhQA8N0wDQYJYIZIAWUDBAIBBQCggZgwGgYJKoZIhvcNAQkDMQ0G
# CyqGSIb3DQEJEAEEMBwGCSqGSIb3DQEJBTEPFw0yMTA0MDgwOTExMDlaMCsGCyqG
# SIb3DQEJEAIMMRwwGjAYMBYEFOHXgqjhkb7va8oWkbWqtJSmJJvzMC8GCSqGSIb3
# DQEJBDEiBCCHEAmNNj2zWjWYRfEi4FgzZvrI16kv/U2b9b3oHw6UVDANBgkqhkiG
# 9w0BAQEFAASCAQCdefEKh6Qmwx7xGCkrYi/A+/Cla6LdnYJp38eMs3fqTTvjhyDw
# HffXrwdqWy5/fgW3o3qJXqa5o7hLxYIoWSULOCpJRGdt+w7XKPAbZqHrN9elAhWJ
# vpBTCEaj7dVxr1Ka4NsoPSYe0eidDBmmvGvp02J4Z1j8+ImQPKN6Hv/L8Ixaxe7V
# mH4VtXIiBK8xXdi4wzO+A+qLtHEJXz3Gw8Bp3BNtlDGIUkIhVTM3Q1xcSEqhOLqo
# PGdwCw9acxdXNWWPjOJkNH656Bvmkml+0p6MTGIeG4JCeRh1Wpqm1ZGSoEcXNaof
# wOgj48YzI+dNqBD9i7RSWCqJr2ygYKRTxnuU
# SIG # End signature block
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.