file_path
stringlengths
32
153
content
stringlengths
0
3.14M
omniverse-code/kit/exts/omni.kit.capture.viewport/omni/kit/capture/viewport/extension.py
# Copyright (c) 2018-2020, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. # import os import math import time import datetime import asyncio import omni.ext import carb import omni.kit.app import omni.timeline import omni.usd import omni.ui from pxr import Gf, Sdf from .capture_options import * from .capture_progress import * from .video_generation import VideoGenerationHelper from .helper import ( get_num_pattern_file_path, check_render_product_ext_availability, is_valid_render_product_prim_path, RenderProductCaptureHelper, is_kit_104_and_above, # TODO: Remove this as it is no longer used, but kept only if transitively depended on get_vp_object_visibility, set_vp_object_visibility, ) from omni.kit.viewport.utility import get_active_viewport, capture_viewport_to_file import omni.appwindow PERSISTENT_SETTINGS_PREFIX = "/persistent" FILL_VIEWPORT_SETTING = PERSISTENT_SETTINGS_PREFIX + "/app/viewport/{viewport_api_id}/fillViewport" SEQUENCE_CAPTURE_WAIT = "/app/captureSequence/waitFrames" MP4_ENCODING_BITRATE_SETTING = "/exts/omni.videoencoding/bitrate" MP4_ENCODING_IFRAME_INTERVAL_SETTING = "/exts/omni.videoencoding/iframeinterval" MP4_ENCODING_PRESET_SETTING = "/exts/omni.videoencoding/preset" MP4_ENCODING_PROFILE_SETTING = "/exts/omni.videoencoding/profile" MP4_ENCODING_RC_MODE_SETTING = "/exts/omni.videoencoding/rcMode" MP4_ENCODING_RC_TARGET_QUALITY_SETTING = "/exts/omni.videoencoding/rcTargetQuality" MP4_ENCODING_VIDEO_FULL_RANGE_SETTING = "/exts/omni.videoencoding/videoFullRangeFlag" VIDEO_FRAMES_DIR_NAME = "frames" DEFAULT_IMAGE_FRAME_TYPE_FOR_VIDEO = ".png" capture_instance = None class RenderStatus(IntEnum): # Note render status values from rtx/hydra/HydraRenderResults.h # Rendering was successful. A path tracer might not have reached a stopping criterion though. eSuccess = 0 # Rendering was successful and the renderer has reached a stopping criterion on this iteration. eStopCriterionJustReached = 1 # Rendering was successful and the renderer has reached a stopping criterion. eStopCriterionReached = 2 # Rendering failed eFailed = 3 class CaptureExtension(omni.ext.IExt): def on_startup(self): global capture_instance capture_instance = self self._options = CaptureOptions() self._progress = CaptureProgress() self._progress_window = CaptureProgressWindow() import omni.renderer_capture self._renderer = omni.renderer_capture.acquire_renderer_capture_interface() self._viewport_api = None self._app = omni.kit.app.get_app_interface() self._timeline = omni.timeline.get_timeline_interface() self._usd_context = omni.usd.get_context() self._selection = self._usd_context.get_selection() self._settings = carb.settings.get_settings() self._show_default_progress_window = True self._progress_update_fn = None self._forward_one_frame_fn = None self._capture_finished_fn = None self._to_capture_render_product = False self._render_product_path_for_capture = "" self._is_adaptivesampling_stop_criterion_reached = False class ReshadeUpdateState(): PRE_CAPTURE = 0 POST_CAPTURE = 1 POST_CAPTURE_READY = 3 def on_shutdown(self): self._progress = None self._progress_window = None global capture_instance capture_instance = None @property def options(self): return self._options @options.setter def options(self, value): self._options = value @property def progress(self): return self._progress @property def show_default_progress_window(self): return self._show_default_progress_window @show_default_progress_window.setter def show_default_progress_window(self, value): self._show_default_progress_window = value @property def progress_update_fn(self): return self._progress_update_fn @progress_update_fn.setter def progress_update_fn(self, value): self._progress_update_fn = value @property def forward_one_frame_fn(self): return self._forward_one_frame_fn @forward_one_frame_fn.setter def forward_one_frame_fn(self, value): self._forward_one_frame_fn = value @property def capture_finished_fn(self): return self._capture_finished_fn @capture_finished_fn.setter def capture_finished_fn(self, value): self._capture_finished_fn = value def start(self): self._to_capture_render_product = self._check_if_to_capture_render_product() if self._to_capture_render_product: self._render_product_path_for_capture = RenderProductCaptureHelper.prepare_render_product_for_capture( self._options.render_product, self._options.camera, Gf.Vec2i(self._options.res_width, self._options.res_height) ) if len(self._render_product_path_for_capture) == 0: carb.log_warn(f"Capture will use render product {self._options.render_product}'s original camera and resolution because it failed to make a copy of it for processing.") self._render_product_path_for_capture = self._options.render_product # use usd time code for animation play during capture, caption option's fps setting for movie encoding if CaptureOptions.INVALID_ANIMATION_FPS == self._options.animation_fps: self._capture_fps = self._timeline.get_time_codes_per_seconds() else: self._capture_fps = self._options.animation_fps if not self._prepare_folder_and_counters(): if self._render_product_path_for_capture != self._options.render_product: RenderProductCaptureHelper.remove_render_product_for_capture(self._render_product_path_for_capture) self._render_product_path_for_capture = "" return if self._prepare_viewport(): self._start_internal() def pause(self): if self._progress.capture_status == CaptureStatus.CAPTURING and self._ui_pause_button.text == "Pause": self._progress.capture_status = CaptureStatus.PAUSED def resume(self): if self._progress.capture_status == CaptureStatus.PAUSED: self._progress.capture_status = CaptureStatus.CAPTURING def cancel(self): if ( self._progress.capture_status == CaptureStatus.CAPTURING or self._progress.capture_status == CaptureStatus.PAUSED ): self._progress.capture_status = CaptureStatus.CANCELLED def _update_progress_hook(self): if self._progress_update_fn is not None: self._progress_update_fn( self._progress.capture_status, self._progress.progress, self._progress.elapsed_time, self._progress.estimated_time_remaining, self._progress.current_frame_time, self._progress.average_frame_time, self._progress.encoding_time, self._frame_counter, self._total_frame_count, ) def _get_index_for_image(self, dir, file_name, image_suffix): def is_int(string_val): try: v = int(string_val) return True except: return False images = os.listdir(dir) name_len = len(file_name) suffix_len = len(image_suffix) max_index = 0 for item in images: if item.startswith(file_name) and item.endswith(image_suffix): num_part = item[name_len : (len(item) - suffix_len)] if is_int(num_part): num = int(num_part) if max_index < num: max_index = num return max_index + 1 def _float_to_time(self, ft): hour = int(ft) ft = (ft - hour) * 60 minute = int(ft) ft = (ft - minute) * 60 second = int(ft) ft = (ft - second) * 1000000 microsecond = int(ft) return datetime.time(hour, minute, second, microsecond) def _check_if_to_capture_render_product(self): if len(self._options.render_product) == 0: return False omnigraph_exts_available = check_render_product_ext_availability() if not omnigraph_exts_available: carb.log_warn(f"Viewport Capture: unable to capture with render product {self._options.render_product} as it needs both omni.graph.nodes and omni.graph.examples.cpp enabled to work.") return False viewport_api = get_active_viewport() render_product_name = viewport_api.render_product_path if viewport_api else None if not render_product_name: carb.log_warn(f"Viewport Capture: unable to capture with render product {self._options.render_product} as Kit SDK needs updating to support viewport window render product APIs: {e}") return False if is_valid_render_product_prim_path(self._options.render_product): return True else: carb.log_warn(f"Viewport Capture: unable to capture with render product {self._options.render_product} as it's not a valid Render Product prim path") return False def _is_environment_sunstudy_player(self): if self._options.sunstudy_player is not None: return type(self._options.sunstudy_player).__module__ == "omni.kit.environment.core.sunstudy_player.player" else: carb.log_warn("Sunstudy player type check is valid only when the player is available.") return False def _update_sunstudy_player_time(self): if self._is_environment_sunstudy_player(): self._options.sunstudy_player.current_time = self._sunstudy_current_time else: self._options.sunstudy_player.update_time(self._sunstudy_current_time) def _set_sunstudy_player_time(self, current_time): if self._is_environment_sunstudy_player(): self._options.sunstudy_player.current_time = current_time else: date_time = self._options.sunstudy_player.get_date_time() time_to_set = self._float_to_time(current_time) new_date_time = datetime.datetime( date_time.year, date_time.month, date_time.day, time_to_set.hour, time_to_set.minute, time_to_set.second ) self._options.sunstudy_player.set_date_time(new_date_time) def _prepare_sunstudy_counters(self): self._total_frame_count = self._options.fps * self._options.sunstudy_movie_length_in_seconds duration = self._options.sunstudy_end_time - self._options.sunstudy_start_time self._sunstudy_iterations_per_frame = self._options.ptmb_subframes_per_frame self._sunstudy_delta_time_per_iteration = duration / float(self._total_frame_count * self._sunstudy_iterations_per_frame) self._sunstudy_current_time = self._options.sunstudy_start_time self._set_sunstudy_player_time(self._sunstudy_current_time) def _prepare_folder_and_counters(self): self._workset_dir = self._options.output_folder if not self._make_sure_directory_writeable(self._workset_dir): carb.log_warn(f"Capture failed due to unable to create folder {self._workset_dir} or this folder is not writeable.") self._finish() return False if self._options.is_capturing_nth_frames(): if self._options.capture_every_Nth_frames == 1: frames_folder = self._options.file_name + "_frames" else: frames_folder = self._options.file_name + "_" + str(self._options.capture_every_Nth_frames) + "th_frames" self._nth_frames_dir = os.path.join(self._workset_dir, frames_folder) if not self._make_sure_directory_existed(self._nth_frames_dir): carb.log_warn(f"Capture failed due to unable to create folder {self._nth_frames_dir}") self._finish() return False if self._options.is_video(): self._frames_dir = os.path.join(self._workset_dir, self._options.file_name + "_" + VIDEO_FRAMES_DIR_NAME) if not self._make_sure_directory_existed(self._frames_dir): carb.log_warn( f"Capture failed due to unable to create folder {self._workset_dir} to save frames of the video." ) self._finish() return False self._video_name = self._options.get_full_path() self._frame_pattern_prefix = os.path.join(self._frames_dir, self._options.file_name) if self._options.is_capturing_frame(): self._start_time = float(self._options.start_frame) / self._capture_fps self._end_time = float(self._options.end_frame + 1) / self._capture_fps self._time = self._start_time self._frame = self._options.start_frame self._start_number = self._frame self._total_frame_count = round((self._end_time - self._start_time) * self._capture_fps) else: self._start_time = self._options.start_time self._end_time = self._options.end_time self._time = self._options.start_time self._frame = int(self._options.start_time * self._capture_fps) self._start_number = self._frame self._total_frame_count = math.ceil((self._end_time - self._start_time) * self._capture_fps) if self._options.movie_type == CaptureMovieType.SUNSTUDY: self._prepare_sunstudy_counters() else: if self._options.is_capturing_nth_frames(): self._frame_pattern_prefix = self._nth_frames_dir if self._options.is_capturing_frame(): self._start_time = float(self._options.start_frame) / self._capture_fps self._end_time = float(self._options.end_frame + 1) / self._capture_fps self._time = self._start_time self._frame = self._options.start_frame self._start_number = self._frame self._total_frame_count = round((self._end_time - self._start_time) * self._capture_fps) else: self._start_time = self._options.start_time self._end_time = self._options.end_time self._time = self._options.start_time self._frame = int(self._options.start_time * self._capture_fps) self._start_number = self._frame self._total_frame_count = math.ceil((self._end_time - self._start_time) * self._capture_fps) if self._options.movie_type == CaptureMovieType.SUNSTUDY: self._prepare_sunstudy_counters() else: index = self._get_index_for_image(self._workset_dir, self._options.file_name, self._options.file_type) self._frame_pattern_prefix = os.path.join(self._workset_dir, self._options.file_name + str(index)) self._start_time = self._timeline.get_current_time() self._end_time = self._timeline.get_current_time() self._time = self._timeline.get_current_time() self._frame = 1 self._start_number = self._frame self._total_frame_count = 1 self._subframe = 0 self._sample_count = 0 self._frame_counter = 0 self._real_time_settle_latency_frames_done = 0 self._settle_latency_frames = self._get_settle_latency_frames() self._last_skipped_frame_path = "" self._path_trace_iterations = 0 self._time_rate = 1.0 / self._capture_fps self._time_subframe_rate = ( self._time_rate * (self._options.ptmb_fsc - self._options.ptmb_fso) / self._options.ptmb_subframes_per_frame ) return True def _prepare_viewport(self): viewport_api = get_active_viewport() if viewport_api is None: return False self._is_legacy_vp = hasattr(viewport_api, 'legacy_window') self._record_current_window_status(viewport_api) capture_camera = Sdf.Path(self._options.camera) if capture_camera != self._saved_camera: viewport_api.camera_path = capture_camera if not self._is_legacy_vp: viewport_api.updates_enabled = True if self._saved_fill_viewport_option: fv_setting_path = FILL_VIEWPORT_SETTING.format(viewport_api_id=viewport_api.id) # for application level capture, we want it to fill the viewport to make the viewport resolution the same to application window resolution # while for viewport capture, we can get images with the correct resolution so doesn't need it to fill viewport self._settings.set(fv_setting_path, self._options.app_level_capture) capture_resolution = (self._options.res_width, self._options.res_height) if capture_resolution != (self._saved_resolution_width, self._saved_resolution_height): viewport_api.resolution = capture_resolution self._settings.set_bool("/persistent/app/captureFrame/viewport", True) self._settings.set_bool("/app/captureFrame/setAlphaTo1", not self._options.save_alpha) if self._options.file_type == ".exr": self._settings.set_bool("/app/captureFrame/hdr", self._options.hdr_output) else: self._settings.set_bool("/app/captureFrame/hdr", False) if self._options.save_alpha: self._settings.set_bool("/rtx/post/backgroundZeroAlpha/enabled", True) self._settings.set_bool("/rtx/post/backgroundZeroAlpha/backgroundComposite", False) if self._options.hdr_output: self._settings.set_bool("/rtx/post/backgroundZeroAlpha/ApplyAlphaZeroPassFirst", True) if self._to_capture_render_product: viewport_api.render_product_path = self._render_product_path_for_capture # we only clear selection for non application level capture, other we will lose the ui.scene elemets during capture if not self._options.app_level_capture: self._selection.clear_selected_prim_paths() if self._options.render_preset == CaptureRenderPreset.RAY_TRACE: self._switch_renderer = self._saved_hd_engine != "rtx" or self._saved_render_mode != "RaytracedLighting" if self._switch_renderer: viewport_api.set_hd_engine("rtx", "RaytracedLighting") carb.log_info("Switching to RayTracing Mode") elif self._options.render_preset == CaptureRenderPreset.PATH_TRACE: self._switch_renderer = self._saved_hd_engine != "rtx" or self._saved_render_mode != "PathTracing" if self._switch_renderer: viewport_api.set_hd_engine("rtx", "PathTracing") carb.log_info("Switching to PathTracing Mode") elif self._options.render_preset == CaptureRenderPreset.IRAY: self._switch_renderer = self._saved_hd_engine != "iray" or self._saved_render_mode != "iray" if self._switch_renderer: viewport_api.set_hd_engine("iray", "iray") carb.log_info("Switching to IRay Mode") # now that Iray is not loaded automatically until renderer gets switched # we have to save and set the Iray settings after the renderer switch self._record_and_set_iray_settings() else: self._switch_renderer = False carb.log_info("Keeping current Render Mode") if self._options.debug_material_type == CaptureDebugMaterialType.SHADED: self._settings.set_int("/rtx/debugMaterialType", -1) elif self._options.debug_material_type == CaptureDebugMaterialType.WHITE: self._settings.set_int("/rtx/debugMaterialType", 0) else: carb.log_info("Keeping current debug mateiral type") # tell timeline window to stop force checks of end time so that it won't affect capture range self._settings.set_bool("/exts/omni.anim.window.timeline/playinRange", False) # set it to 0 to ensure we accumulate as many samples as requested even across subframes (for motion blur) # for non-motion blur path trace capture, we now rely on adaptive sampling's return status to decide if it's still # need to do more samples if self._is_capturing_pt_mb(): self._settings.set_int("/rtx/pathtracing/totalSpp", 0) # don't show light and grid during capturing self._set_vp_object_settings(viewport_api) # disable async rendering for capture, otherwise it won't capture images correctly if self._saved_async_rendering: self._settings.set_bool("/app/asyncRendering", False) if self._saved_async_renderingLatency: self._settings.set_bool("/app/asyncRenderingLowLatency", False) # Rendering to some image buffers additionally require explicitly setting `set_capture_sync(True)`, on top of # disabling the `/app/asyncRendering` setting. This can otherwise cause images to hold corrupted buffer # information by erroneously assuming a complete image buffer is available when only a first partial subframe # has been renderer (as in the case of EXR): self._renderer.set_capture_sync( self._options.file_type == ".exr" ) # frames to wait for the async settings above to be ready, they will need to be detected by viewport, and # then viewport will notify the renderer not to do async rendering self._frames_to_disable_async_rendering = 2 # Normally avoid using a high /rtx/pathtracing/spp setting since it causes GPU # timeouts for large sample counts. But a value larger than 1 can be useful in Multi-GPU setups self._settings.set_int( "/rtx/pathtracing/spp", min(self._options.spp_per_iteration, self._options.path_trace_spp) ) # Setting resetPtAccumOnlyWhenExternalFrameCounterChanges ensures we control accumulation explicitly # by simpling changing the /rtx/externalFrameCounter value self._settings.set_bool("/rtx-transient/resetPtAccumOnlyWhenExternalFrameCounterChanges", True) # Enable syncLoads in materialDB and Hydra. This is needed to make sure texture updates finish before we start the rendering self._settings.set("/rtx/materialDb/syncLoads", True) self._settings.set("/rtx/hydra/materialSyncLoads", True) self._settings.set("/rtx-transient/resourcemanager/texturestreaming/async", False) self._settings.set("/rtx-transient/resourcemanager/texturestreaming/streamingBudgetMB", 0) self._settings.set("/rtx-transient/samplerFeedbackTileSize", 1) self._settings.set("/rtx-transient/resourcemanager/texturestreaming/evictionFrameLatency", 0) #for now, reshade needs to be turned off and on again to apply settings self._settings.set_bool("/rtx/reshade/enable", False) #need to skip several updates for reshade settings to apply: self._frames_to_apply_reshade = 2 # these settings need to be True to ensure XR Output Alpha in composited image is right if not self._saved_output_alpha_in_composite: self._settings.set("/rtx/post/backgroundZeroAlpha/outputAlphaInComposite", True) # do not show the minibar of timeline window self._settings.set("/exts/omni.kit.timeline.minibar/stay_on_playing", False) # enable sequencer camera self._settings.set("/persistent/exts/omni.kit.window.sequencer/useSequencerCamera", True) # set timeline animation fps if self._capture_fps != self._saved_timeline_fps: self._timeline.set_time_codes_per_second(self._capture_fps) # return success return True def _show_progress_window(self): return ( self._options.is_video() or self._options.is_capturing_nth_frames() or (self._options.show_single_frame_progress and self._options.is_capturing_pathtracing_single_frame()) ) and self.show_default_progress_window def _start_internal(self): # if we want preroll, then set timeline's current time back with the preroll frames' time, # and rely on timeline to do the preroll using the give timecode if self._options.preroll_frames > 0: self._timeline.set_current_time(self._start_time - self._options.preroll_frames / self._capture_fps) else: self._timeline.set_current_time(self._start_time) # initialize Reshade state for update loop self._reshade_switch_state = self.ReshadeUpdateState.PRE_CAPTURE # change timeline to be in play state self._timeline.play(start_timecode=self._start_time*self._capture_fps, end_timecode=self._end_time*self._capture_fps, looping=False) # disable automatic time update in timeline so that movie capture tool can control time step self._timeline.set_auto_update(False) self._update_sub = ( omni.kit.app.get_app().get_update_event_stream().create_subscription_to_pop(self._on_update, order=1000000) ) self._is_adaptivesampling_stop_criterion_reached = False self._progress.start_capturing(self._total_frame_count, self._options.preroll_frames) # always show single frame capture progress for PT mode self._options.show_single_frame_progress = True if self._show_progress_window(): self._progress_window.show( self._progress, self._options.is_capturing_pathtracing_single_frame(), show_pt_subframes=self._options.render_preset == CaptureRenderPreset.PATH_TRACE, show_pt_iterations=self._options.render_preset == CaptureRenderPreset.IRAY ) # prepare for application level capture if self._options.app_level_capture: # move the progress window to external window, and then hide application UI if self._show_progress_window(): self._progress_window.move_to_external_window() self._settings.set("/app/window/hideUi", True) def _record_and_set_iray_settings(self): if self._options.render_preset == CaptureRenderPreset.IRAY: self._saved_iray_sample_limit = self._settings.get_as_int("/rtx/iray/progressive_rendering_max_samples") self._settings.set("/rtx/iray/progressive_rendering_max_samples", self._options.path_trace_spp) self._saved_iray_render_sync_flag = self._settings.get_as_bool("/iray/render_synchronous") if not self._saved_iray_render_sync_flag: self._settings.set_bool("/iray/render_synchronous", True) def _restore_iray_settings(self): if self._options.render_preset == CaptureRenderPreset.IRAY: self._settings.set_bool("/iray/render_synchronous", self._saved_iray_render_sync_flag) self._settings.set("/rtx/iray/progressive_rendering_max_samples", self._saved_iray_sample_limit) def __save_mp4_encoding_settings(self): self._saved_mp4_encoding_bitrate = self._settings.get_as_int(MP4_ENCODING_BITRATE_SETTING) self._saved_mp4_encoding_iframe_interval = self._settings.get_as_int(MP4_ENCODING_IFRAME_INTERVAL_SETTING) self._saved_mp4_encoding_preset = self._settings.get(MP4_ENCODING_PRESET_SETTING) self._saved_mp4_encoding_profile = self._settings.get(MP4_ENCODING_PROFILE_SETTING) self._saved_mp4_encoding_rc_mode = self._settings.get(MP4_ENCODING_RC_MODE_SETTING) self._saved_mp4_encoding_rc_target_quality = self._settings.get(MP4_ENCODING_RC_TARGET_QUALITY_SETTING) self._saved_mp4_encoding_video_full_range_flag = self._settings.get(MP4_ENCODING_VIDEO_FULL_RANGE_SETTING) def __set_mp4_encoding_settings(self): self._settings.set(MP4_ENCODING_BITRATE_SETTING, self._options.mp4_encoding_bitrate) self._settings.set(MP4_ENCODING_IFRAME_INTERVAL_SETTING, self._options.mp4_encoding_iframe_interval) self._settings.set(MP4_ENCODING_PRESET_SETTING, self._options.mp4_encoding_preset) self._settings.set(MP4_ENCODING_PROFILE_SETTING, self._options.mp4_encoding_profile) self._settings.set(MP4_ENCODING_RC_MODE_SETTING, self._options.mp4_encoding_rc_mode) self._settings.set(MP4_ENCODING_RC_TARGET_QUALITY_SETTING, self._options.mp4_encoding_rc_target_quality) self._settings.set(MP4_ENCODING_VIDEO_FULL_RANGE_SETTING, self._options.mp4_encoding_video_full_range_flag) def _save_and_set_mp4_encoding_settings(self): if self._options.is_video(): self.__save_mp4_encoding_settings() self.__set_mp4_encoding_settings() def _restore_mp4_encoding_settings(self): if self._options.is_video(): self._settings.set(MP4_ENCODING_BITRATE_SETTING, self._saved_mp4_encoding_bitrate) self._settings.set(MP4_ENCODING_IFRAME_INTERVAL_SETTING, self._saved_mp4_encoding_iframe_interval) self._settings.set(MP4_ENCODING_PRESET_SETTING, self._saved_mp4_encoding_preset) self._settings.set(MP4_ENCODING_PROFILE_SETTING, self._saved_mp4_encoding_profile) self._settings.set(MP4_ENCODING_RC_MODE_SETTING, self._saved_mp4_encoding_rc_mode) self._settings.set(MP4_ENCODING_RC_TARGET_QUALITY_SETTING, self._saved_mp4_encoding_rc_target_quality) self._settings.set(MP4_ENCODING_VIDEO_FULL_RANGE_SETTING, self._saved_mp4_encoding_video_full_range_flag) def _save_and_set_application_capture_settings(self): # as in application capture mode, we actually capture the window size instead of the renderer output, thus we do this with two steps: # 1. set it to fill the viewport, and padding to (0, -1) to make viewport's size equals to application window size # 2. resize application window to the resolution that users set in movie capture, so that we can save the images with the desired resolution # this is not ideal because when we resize the application window, the size is actaully limited by the screen resolution so it's possible that # the resulting window size could be smaller than what we want. # also, it's more intuitive that padding should be (0, 0), but it has to be (0, -1) after tests as we still have 1 pixel left at top and bottom. if self._options.app_level_capture: vp_window = omni.ui.Workspace.get_window("Viewport") self._saved_viewport_padding_x = vp_window.padding_x self._saved_viewport_padding_y = vp_window.padding_y vp_window.padding_x = 0 vp_window.padding_y = -1 app_window_factory = omni.appwindow.acquire_app_window_factory_interface() app_window = app_window_factory.get_app_window() self._saved_app_window_size = app_window.get_size() app_window.resize(self._options.res_width, self._options._res_height) def _restore_application_capture_settings(self): if self._options.app_level_capture: vp_window = omni.ui.Workspace.get_window("Viewport") vp_window.padding_x = self._saved_viewport_padding_x vp_window.padding_y = self._saved_viewport_padding_y app_window_factory = omni.appwindow.acquire_app_window_factory_interface() app_window = app_window_factory.get_app_window() app_window.resize(self._saved_app_window_size[0], self._saved_app_window_size[1]) def _record_vp_object_settings(self, viewport_api) -> None: self._saved_display_outline = get_vp_object_visibility(viewport_api, "guide/selection") self._saved_display_lights = get_vp_object_visibility(viewport_api, "scene/lights") self._saved_display_audio = get_vp_object_visibility(viewport_api, "scene/audio") self._saved_display_camera = get_vp_object_visibility(viewport_api, "scene/cameras") self._saved_display_grid = get_vp_object_visibility(viewport_api, "guide/grid") def _set_vp_object_settings(self, viewport_api) -> None: set_vp_object_visibility(viewport_api, "guide/selection", False) set_vp_object_visibility(viewport_api, "scene/lights", False) set_vp_object_visibility(viewport_api, "scene/audio", False) set_vp_object_visibility(viewport_api, "scene/cameras", False) set_vp_object_visibility(viewport_api, "guide/grid", False) def _restore_vp_object_settings(self, viewport_api): set_vp_object_visibility(viewport_api, "guide/selection", self._saved_display_outline) set_vp_object_visibility(viewport_api, "scene/lights", self._saved_display_lights) set_vp_object_visibility(viewport_api, "scene/audio", self._saved_display_audio) set_vp_object_visibility(viewport_api, "scene/cameras", self._saved_display_camera) set_vp_object_visibility(viewport_api, "guide/grid", self._saved_display_grid) def _record_current_window_status(self, viewport_api): assert viewport_api is not None, "No viewport to record to" self._viewport_api = viewport_api self._saved_camera = viewport_api.camera_path self._saved_hydra_engine = viewport_api.hydra_engine if not self._is_legacy_vp: self._saved_vp_updates_enabled = self._viewport_api.updates_enabled fv_setting_path = FILL_VIEWPORT_SETTING.format(viewport_api_id=self._viewport_api.id) self._saved_fill_viewport_option = self._settings.get_as_bool(fv_setting_path) resolution = viewport_api.resolution self._saved_resolution_width = int(resolution[0]) self._saved_resolution_height = int(resolution[1]) self._saved_hd_engine = viewport_api.hydra_engine self._saved_render_mode = viewport_api.render_mode self._saved_capture_frame_viewport = self._settings.get("/persistent/app/captureFrame/viewport") self._saved_debug_material_type = self._settings.get_as_int("/rtx/debugMaterialType") self._saved_total_spp = self._settings.get_as_int("/rtx/pathtracing/totalSpp") self._saved_spp = self._settings.get_as_int("/rtx/pathtracing/spp") self._saved_reset_pt_accum_only = self._settings.get("/rtx-transient/resetPtAccumOnlyWhenExternalFrameCounterChanges") self._record_vp_object_settings(viewport_api) self._saved_async_rendering = self._settings.get("/app/asyncRendering") self._saved_async_renderingLatency = self._settings.get("/app/asyncRenderingLowLatency") self._saved_background_zero_alpha = self._settings.get("/rtx/post/backgroundZeroAlpha/enabled") self._saved_background_zero_alpha_comp = self._settings.get("/rtx/post/backgroundZeroAlpha/backgroundComposite") self._saved_background_zero_alpha_zp_first = self._settings.get( "/rtx/post/backgroundZeroAlpha/ApplyAlphaZeroPassFirst" ) if self._options.movie_type == CaptureMovieType.SUNSTUDY: self._saved_sunstudy_current_time = self._options.sunstudy_current_time self._saved_timeline_current_time = self._timeline.get_current_time() self._saved_timeline_fps = self._timeline.get_time_codes_per_seconds() self._saved_rtx_sync_load_setting = self._settings.get("/rtx/materialDb/syncLoads") if self._to_capture_render_product: self._saved_render_product = viewport_api.render_product_path omnigraph_use_legacy_sim_setting = self._settings.get_as_bool("/persistent/omnigraph/useLegacySimulationPipeline") if omnigraph_use_legacy_sim_setting is not None and omnigraph_use_legacy_sim_setting is True: carb.log_warn("/persistent/omnigraph/useLegacySimulationPipeline setting is True, which might affect render product capture and cause the capture to have no output.") self._saved_hydra_sync_load_setting = self._settings.get("/rtx/hydra/materialSyncLoads") self._saved_async_texture_streaming = self._settings.get("/rtx-transient/resourcemanager/texturestreaming/async") self._saved_texture_streaming_budget = self._settings.get("/rtx-transient/resourcemanager/texturestreaming/streamingBudgetMB") self._saved_sampler_feedback_tile_size = self._settings.get_as_int("/rtx-transient/samplerFeedbackTileSize") self._saved_texture_streaming_eviction_frame_latency = self._settings.get_as_int("/rtx-transient/resourcemanager/texturestreaming/evictionFrameLatency") # save Reshade state in post process settings self._saved_reshade_state = bool(self._settings.get("/rtx/reshade/enable")) self._saved_output_alpha_in_composite = self._settings.get_as_bool("/rtx/post/backgroundZeroAlpha/outputAlphaInComposite") # save the visibility status of timeline window's minibar added in OM-92643 self._saved_timeline_window_mimibar_visibility = self._settings.get_as_bool("/exts/omni.kit.timeline.minibar/stay_on_playing") # save the setting for sequencer camera, we want to enable it during capture self._saved_use_sequencer_camera = self._settings.get_as_bool("/persistent/exts/omni.kit.window.sequencer/useSequencerCamera") # if to capture mp4, save encoding settings self._save_and_set_mp4_encoding_settings() # if to capture in application mode, save viewport's padding values as we will reset it to make resolution of final image match what users set as possible as we can self._save_and_set_application_capture_settings() def _restore_window_status(self): viewport_api, self._viewport_api = self._viewport_api, None assert viewport_api is not None, "No viewport to restore to" if not self._is_legacy_vp and not self._saved_vp_updates_enabled: viewport_api.updates_enabled = self._saved_vp_updates_enabled if not self._is_legacy_vp and self._saved_fill_viewport_option: fv_setting_path = FILL_VIEWPORT_SETTING.format(viewport_api_id=viewport_api.id) self._settings.set(fv_setting_path, self._saved_fill_viewport_option) viewport_api.camera_path = self._saved_camera viewport_api.resolution = (self._saved_resolution_width, self._saved_resolution_height) if self._switch_renderer: viewport_api.set_hd_engine(self._saved_hydra_engine, self._saved_render_mode) self._settings.set_bool("/persistent/app/captureFrame/viewport", self._saved_capture_frame_viewport) self._settings.set_int("/rtx/debugMaterialType", self._saved_debug_material_type) self._settings.set_int("/rtx/pathtracing/totalSpp", self._saved_total_spp) self._settings.set_int("/rtx/pathtracing/spp", self._saved_spp) self._settings.set_bool("/rtx-transient/resetPtAccumOnlyWhenExternalFrameCounterChanges", self._saved_reset_pt_accum_only) self._restore_vp_object_settings(viewport_api) self._settings.set_bool("/app/asyncRendering", self._saved_async_rendering) self._settings.set_bool("/app/asyncRenderingLowLatency", self._saved_async_renderingLatency) self._renderer.set_capture_sync(not self._saved_async_rendering) self._settings.set_bool("/rtx/post/backgroundZeroAlpha/enabled", self._saved_background_zero_alpha) self._settings.set_bool( "/rtx/post/backgroundZeroAlpha/backgroundComposite", self._saved_background_zero_alpha_comp ) self._settings.set_bool( "/rtx/post/backgroundZeroAlpha/ApplyAlphaZeroPassFirst", self._saved_background_zero_alpha_zp_first ) self._restore_iray_settings() if self._options.movie_type == CaptureMovieType.SUNSTUDY: self._set_sunstudy_player_time(self._saved_sunstudy_current_time) self._settings.set("/rtx/materialDb/syncLoads", self._saved_rtx_sync_load_setting) self._settings.set("/rtx/hydra/materialSyncLoads", self._saved_hydra_sync_load_setting) self._settings.set("/rtx-transient/resourcemanager/texturestreaming/async", self._saved_async_texture_streaming) self._settings.set("/rtx-transient/resourcemanager/texturestreaming/streamingBudgetMB", self._saved_texture_streaming_budget) self._settings.set("/rtx-transient/samplerFeedbackTileSize", self._saved_sampler_feedback_tile_size) self._settings.set("/rtx-transient/resourcemanager/texturestreaming/evictionFrameLatency", self._saved_texture_streaming_eviction_frame_latency) self._settings.set("/app/captureFrame/hdr", False) # tell timeline window it can restart force checks of end time self._settings.set_bool("/exts/omni.anim.window.timeline/playinRange", True) if self._to_capture_render_product: viewport_api.render_product_path = self._saved_render_product # set Reshade to its initial value it had before te capture: self._settings.set("/rtx/reshade/enable", self._saved_reshade_state) # set Reshade update loop state to initial value, so we're ready for the next run of the update loop: self._reshade_switch_state = self.ReshadeUpdateState.PRE_CAPTURE self._settings.set("/rtx/post/backgroundZeroAlpha/outputAlphaInComposite", self._saved_output_alpha_in_composite) if self._saved_timeline_window_mimibar_visibility: self._setting.set("/exts/omni.kit.timeline.minibar/stay_on_playing", self._saved_timeline_window_mimibar_visibility) self._settings.set("/persistent/exts/omni.kit.window.sequencer/useSequencerCamera", self._saved_use_sequencer_camera) # if to capture mp4, restore encoding settings self._restore_mp4_encoding_settings() # if to capture in application mode, restore viewport's padding values self._restore_application_capture_settings() def _clean_pngs_in_directory(self, directory): self._clean_files_in_directory(directory, ".png") def _clean_files_in_directory(self, directory, suffix): images = os.listdir(directory) for item in images: if item.endswith(suffix): os.remove(os.path.join(directory, item)) def _make_sure_directory_existed(self, directory): if not os.path.exists(directory): try: os.makedirs(directory, exist_ok=True) except OSError as error: carb.log_warn(f"Directory cannot be created: {dir}") return False return True def _make_sure_directory_writeable(self, directory): if not self._make_sure_directory_existed(directory): return False # if the directory exists, try to create a test folder and then remove it to check if it's writeable # Normally this should be done using omni.client.stat api, unfortunately it won't work well if the # give folder is a read-only one mapped by O Drive. try: test_folder_name = "(@m#C$%^)((test^file$@@).testfile" full_test_path = os.path.join(directory, test_folder_name) f = open(full_test_path, "a") f.close() os.remove(full_test_path) except OSError as error: return False return True def _finish(self): if ( self._progress.capture_status == CaptureStatus.FINISHING or self._progress.capture_status == CaptureStatus.CANCELLED ): self._update_sub = None self._restore_window_status() self._sample_count = 0 self._start_number = 0 self._frame_counter = 0 self._path_trace_iterations = 0 self._progress.capture_status = CaptureStatus.NONE # restore timeline settings # stop timeline, but re-enable auto update timeline = self._timeline timeline.set_auto_update(True) timeline.stop() self._timeline.set_current_time(self._saved_timeline_current_time) if self._capture_fps != self._saved_timeline_fps: self._timeline.set_time_codes_per_second(self._saved_timeline_fps) if self._to_capture_render_product and (self._render_product_path_for_capture != self._options.render_product): RenderProductCaptureHelper.remove_render_product_for_capture(self._render_product_path_for_capture) # restore application ui if in application level capture mode if self._options.app_level_capture: self._settings.set("/app/window/hideUi", False) if self._show_progress_window(): self._progress_window.close() if self._capture_finished_fn is not None: self._capture_finished_fn() def _wait_for_image_writing(self, seconds_to_wait: float = 5, seconds_to_sleep: float = 0.1): # wait for the last frame is written to disk # my tests of scenes of different complexity show a range of 0.2 to 1 seconds wait time # so 5 second max time should be enough and we can early quit by checking the last # frame every 0.1 seconds. seconds_tried = 0.0 carb.log_info("Waiting for frames to be ready for encoding.") while seconds_tried < seconds_to_wait: if os.path.isfile(self._frame_path) and os.access(self._frame_path, os.R_OK): break else: time.sleep(seconds_to_sleep) seconds_tried += seconds_to_sleep if seconds_tried >= seconds_to_wait: carb.log_warn(f"Wait time out. To start encoding with images already have.") def _capture_image(self, frame_path: str): if self._options.app_level_capture: self._capture_application(frame_path) else: self._capture_viewport(frame_path) def _capture_application(self, frame_path: str): async def capture_frame(capture_filename: str): try: import omni.renderer_capture renderer_capture = omni.renderer_capture.acquire_renderer_capture_interface() renderer_capture.capture_next_frame_swapchain(capture_filename) carb.log_info(f"Capturing {capture_filename} in application level.") except ImportError: carb.log_error(f"Failed to capture {capture_filename} due to unable to import omni.renderer_capture.") await omni.kit.app.get_app().next_update_async() asyncio.ensure_future(capture_frame(frame_path)) def _capture_viewport(self, frame_path: str): is_hdr = self.options._hdr_output render_product_path = self.options._render_product if self._to_capture_render_product else None format_desc = None if self._options.file_type == ".exr": format_desc = {} format_desc["format"] = "exr" format_desc["compression"] = self._options.exr_compression_method capture_viewport_to_file( self._viewport_api, file_path=frame_path, is_hdr=is_hdr, render_product_path=render_product_path, format_desc=format_desc ) carb.log_info(f"Capturing {frame_path}") def _get_current_frame_output_path(self): frame_path = "" if self._options.is_video(): frame_path = get_num_pattern_file_path( self._frames_dir, self._options.file_name, self._options.file_name_num_pattern, self._frame, DEFAULT_IMAGE_FRAME_TYPE_FOR_VIDEO, self._options.renumber_negative_frame_number_from_0, abs(self._start_number) ) else: if self._options.is_capturing_nth_frames(): if self._frame_counter % self._options.capture_every_Nth_frames == 0: frame_path = get_num_pattern_file_path( self._frame_pattern_prefix, self._options.file_name, self._options.file_name_num_pattern, self._frame, self._options.file_type, self._options.renumber_negative_frame_number_from_0, abs(self._start_number) ) else: frame_path = self._frame_pattern_prefix + self._options.file_type return frame_path def _handle_skipping_frame(self, dt): if not self._options.overwrite_existing_frames: if os.path.exists(self._frame_path): carb.log_warn(f"Frame {self._frame_path} exists, skip it...") self._settings.set_int("/rtx/pathtracing/spp", 1) self._subframe = 0 self._sample_count = 0 self._path_trace_iterations = 0 can_continue = True if self._forward_one_frame_fn is not None: can_continue = self._forward_one_frame_fn(dt) elif self._options.movie_type == CaptureMovieType.SUNSTUDY and \ (self._options.is_video() or self._options.is_capturing_nth_frames()): self._sunstudy_current_time += self._sunstudy_delta_time_per_iteration * self._sunstudy_iterations_per_frame self._update_sunstudy_player_time() else: # movie type is SEQUENCE self._time = self._start_time + (self._frame - self._start_number) * self._time_rate self._timeline.set_current_time(self._time) self._frame += 1 self._frame_counter += 1 # check if capture ends if self._forward_one_frame_fn is not None: if can_continue is False: if self._options.is_video(): self._progress.capture_status = CaptureStatus.TO_START_ENCODING elif self._options.is_capturing_nth_frames(): self._progress.capture_status = CaptureStatus.FINISHING else: if self._time >= self._end_time or self._frame_counter >= self._total_frame_count: if self._options.is_video(): self._progress.capture_status = CaptureStatus.TO_START_ENCODING elif self._options.is_capturing_nth_frames(): self._progress.capture_status = CaptureStatus.FINISHING return True else: if os.path.exists(self._frame_path) and self._last_skipped_frame_path != self._frame_path: carb.log_warn(f"Frame {self._frame_path} will be overwritten.") self._last_skipped_frame_path = self._frame_path return False def _get_default_settle_lateny_frames(self): # to workaround OM-40632, and OM-50514 FRAMES_TO_DELAY_FOR_FRAME_SKIPPING_HACK = 5 if self._options.render_preset == CaptureRenderPreset.RAY_TRACE: return FRAMES_TO_DELAY_FOR_FRAME_SKIPPING_HACK elif ( self._options.render_preset == CaptureRenderPreset.PATH_TRACE or self._options.render_preset == CaptureRenderPreset.IRAY ): pt_frames = self._options.ptmb_subframes_per_frame * self._options.path_trace_spp if pt_frames >= FRAMES_TO_DELAY_FOR_FRAME_SKIPPING_HACK: return 0 else: return FRAMES_TO_DELAY_FOR_FRAME_SKIPPING_HACK - pt_frames else: return 0 def _is_using_default_settle_latency_frames(self): return self._options.real_time_settle_latency_frames == 0 and self._settings.get(SEQUENCE_CAPTURE_WAIT) is None def _get_settle_latency_frames(self): settle_latency_frames = self._options.real_time_settle_latency_frames # Force a delay when capturing a range of frames if settle_latency_frames == 0 and (self._options.is_video() or self._options.is_capturing_nth_frames()): # Allow an explicit default to delay in SEQUENCE_CAPTURE_WAIT, when unset use logic below settle_latency_frames = self._settings.get(SEQUENCE_CAPTURE_WAIT) if settle_latency_frames is None: # Force a 4 frame delay when no sub-frames, otherwise account for sub-frames contributing to that 4 settle_latency_frames = self._get_default_settle_lateny_frames() carb.log_info(f"Forcing {settle_latency_frames} frame delay per frame for sequence capture") return settle_latency_frames def _is_handling_settle_latency_frames(self): return ((self._options.is_video() or self._options.is_capturing_nth_frames()) and self._settle_latency_frames > 0 and self._real_time_settle_latency_frames_done < self._settle_latency_frames ) def _handle_real_time_capture_settle_latency(self): # settle latency only works with sequence capture if not (self._options.is_video() or self._options.is_capturing_nth_frames()): return False if self._settle_latency_frames > 0: self._real_time_settle_latency_frames_done += 1 if self._real_time_settle_latency_frames_done > self._settle_latency_frames: self._real_time_settle_latency_frames_done = 0 return False else: self._subframe = 0 self._sample_count = 0 return True return False def _is_capturing_pt_mb(self): return CaptureRenderPreset.PATH_TRACE == self._options.render_preset and self._options.ptmb_subframes_per_frame > 1 def _is_capturing_pt_no_mb(self): return CaptureRenderPreset.PATH_TRACE == self._options.render_preset and 1 == self._options.ptmb_subframes_per_frame def _is_pt_adaptivesampling_stop_criterion_reached(self): if self._viewport_api is None: return False else: render_status = self._viewport_api.frame_info.get('status') return (render_status is not None and RenderStatus.eStopCriterionReached == render_status and self._is_capturing_pt_no_mb() ) def _on_update(self, e): dt = e.payload["dt"] if self._progress.capture_status == CaptureStatus.FINISHING: # need to turn reshade off, update, and turn on again in _restore_window_status to apply pre-capture resolution if self._reshade_switch_state == self.ReshadeUpdateState.POST_CAPTURE: self._settings.set_bool("/rtx/reshade/enable", False) self._reshade_switch_state = self.ReshadeUpdateState.POST_CAPTURE_READY return self._finish() self._update_progress_hook() elif self._progress.capture_status == CaptureStatus.CANCELLED: # need to turn reshade off, update, and turn on again in _restore_window_status to apply pre-capture resolution if self._reshade_switch_state == self.ReshadeUpdateState.POST_CAPTURE: self._settings.set_bool("/rtx/reshade/enable", False) self._reshade_switch_state = self.ReshadeUpdateState.POST_CAPTURE_READY return carb.log_warn("video recording cancelled") self._update_progress_hook() self._finish() elif self._progress.capture_status == CaptureStatus.ENCODING: if VideoGenerationHelper().encoding_done: self._progress.capture_status = CaptureStatus.FINISHING self._update_progress_hook() self._progress.add_encoding_time(dt) elif self._progress.capture_status == CaptureStatus.TO_START_ENCODING: if VideoGenerationHelper().is_encoding is False: self._wait_for_image_writing() if self._options.renumber_negative_frame_number_from_0 is True and self._start_number < 0: video_frame_start_num = 0 else: video_frame_start_num = self._start_number started = VideoGenerationHelper().generating_video( self._video_name, self._frames_dir, self._options.file_name, self._options.file_name_num_pattern, video_frame_start_num, self._total_frame_count, self._options.fps, ) if started: self._progress.capture_status = CaptureStatus.ENCODING self._update_progress_hook() self._progress.add_encoding_time(dt) else: carb.log_warn("Movie capture failed to encode the capture images.") self._progress.capture_status = CaptureStatus.FINISHING elif self._progress.capture_status == CaptureStatus.CAPTURING: if self._frames_to_disable_async_rendering >= 0: self._frames_to_disable_async_rendering -= 1 return #apply Reshade and skip frames to to pick up capturing resolution if self._reshade_switch_state == self.ReshadeUpdateState.PRE_CAPTURE: self._settings.set_bool("/rtx/reshade/enable", self._saved_reshade_state) # need to skip a couple of updates for Reshade settings to apply: if self._frames_to_apply_reshade>=0: self._frames_to_apply_reshade=self._frames_to_apply_reshade-1 return self._reshade_switch_state = self.ReshadeUpdateState.POST_CAPTURE return if self._progress.is_prerolling(): self._progress.prerolled_frames += 1 self._settings.set_int("/rtx/pathtracing/spp", 1) left_preroll_frames = self._options.preroll_frames - self._progress.prerolled_frames self._timeline.set_current_time(self._start_time - left_preroll_frames / self._capture_fps) return self._frame_path = self._get_current_frame_output_path() if self._handle_skipping_frame(dt): self._progress.add_frame_time(self._frame, dt) self._update_progress_hook() return self._settings.set_int( "/rtx/pathtracing/spp", min(self._options.spp_per_iteration, self._options.path_trace_spp) ) if self._options.render_preset == CaptureRenderPreset.IRAY: iterations_done = int(self._settings.get("/iray/progression")) self._path_trace_iterations = iterations_done self._sample_count = iterations_done else: self._sample_count += self._options.spp_per_iteration self._path_trace_iterations = self._sample_count self._timeline.set_prerolling(False) self._settings.set_int("/rtx/externalFrameCounter", self._frame) # update progress timers if self._options.is_capturing_pathtracing_single_frame(): if self._options.render_preset == CaptureRenderPreset.PATH_TRACE: self._progress.add_single_frame_capture_time_for_pt(self._subframe, self._options.ptmb_subframes_per_frame, dt) elif self._options.render_preset == CaptureRenderPreset.IRAY: self._progress.add_single_frame_capture_time_for_iray( self._subframe, self._options.ptmb_subframes_per_frame, self._path_trace_iterations, self._options.path_trace_spp, dt ) else: carb.log_warn(f"Movie capture: we don't support progress for {self._options.render_preset} in single frame capture mode.") else: self._progress.add_frame_time(self._frame, dt, self._subframe + 1, self._options.ptmb_subframes_per_frame, self._path_trace_iterations, self._options.path_trace_spp, self._is_handling_settle_latency_frames() and not self._is_using_default_settle_latency_frames(), self._real_time_settle_latency_frames_done, self._settle_latency_frames ) self._update_progress_hook() # check if path trace and meet the samples per pixels stop criterion render_status = self._viewport_api.frame_info.get('status') if RenderStatus.eStopCriterionReached == render_status and self._is_adaptivesampling_stop_criterion_reached: carb.log_info("Got continuous path tracing adaptive sampling stop criterion reached event, skip this frame for it to finish.") return self._is_adaptivesampling_stop_criterion_reached = self._is_pt_adaptivesampling_stop_criterion_reached() # capture frame when we reach the sample count for this frame and are rendering the last subframe # Note _sample_count can go over _samples_per_pixel when 'spp_per_iteration > 1' # also handle the case when we have adaptive sampling enabled and it returns stop criterion reached if (self._sample_count >= self._options.path_trace_spp) and \ (self._subframe == self._options.ptmb_subframes_per_frame - 1) or \ self._is_adaptivesampling_stop_criterion_reached: if self._handle_real_time_capture_settle_latency(): return if self._options.is_video(): self._capture_image(self._frame_path) else: if self._options.is_capturing_nth_frames(): if self._frame_counter % self._options.capture_every_Nth_frames == 0: self._capture_image(self._frame_path) else: self._progress.capture_status = CaptureStatus.FINISHING self._capture_image(self._frame_path) # reset time the *next frame* (since otherwise we capture the first sample) if self._sample_count >= self._options.path_trace_spp or self._is_adaptivesampling_stop_criterion_reached: self._sample_count = 0 self._path_trace_iterations = 0 self._subframe += 1 if self._subframe == self._options.ptmb_subframes_per_frame: self._subframe = 0 self._frame += 1 self._frame_counter += 1 self._time = self._start_time + (self._frame - self._start_number) * self._time_rate can_continue = False if self._forward_one_frame_fn is not None: can_continue = self._forward_one_frame_fn(dt) elif self._options.movie_type == CaptureMovieType.SUNSTUDY and \ (self._options.is_video() or self._options.is_capturing_nth_frames()): self._sunstudy_current_time += self._sunstudy_delta_time_per_iteration self._update_sunstudy_player_time() else: if self._options.is_video() or self._options.is_capturing_nth_frames(): cur_time = ( self._time + (self._options.ptmb_fso * self._time_rate) + self._time_subframe_rate * self._subframe ) self._timeline.set_current_time(cur_time) if self._forward_one_frame_fn is not None: if can_continue == False: if self._options.is_video(): self._progress.capture_status = CaptureStatus.TO_START_ENCODING elif self._options.is_capturing_nth_frames(): self._progress.capture_status = CaptureStatus.FINISHING else: if self._time >= self._end_time or self._frame_counter >= self._total_frame_count: if self._options.is_video(): self._progress.capture_status = CaptureStatus.TO_START_ENCODING elif self._options.is_capturing_nth_frames(): self._progress.capture_status = CaptureStatus.FINISHING @staticmethod def get_instance(): global capture_instance return capture_instance
omniverse-code/kit/exts/omni.kit.capture.viewport/omni/kit/capture/viewport/video_generation.py
# Copyright (c) 2018-2020, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. # import os import threading import carb try: from video_encoding import get_video_encoding_interface except ImportError: get_video_encoding_interface = lambda: None from .singleton import Singleton from .helper import get_num_pattern_file_path g_video_encoding_api = get_video_encoding_interface() @Singleton class VideoGenerationHelper: def __init__(self): self._init_internal() @property def is_encoding(self): return self._is_encoding @property def encoding_done(self): return self._is_encoding == False and self._encoding_done == True def generating_video( self, video_name, frames_dir, filename_prefix, filename_num_pattern, start_number, total_frames, frame_rate, image_type=".png" ): carb.log_warn(f"Using videoencoding plugin to encode video ({video_name})") global g_video_encoding_api self._encoding_finished = False if g_video_encoding_api is None: carb.log_warn("Video encoding api not available; cannot encode video.") return False # acquire list of available frame image files, based on start_number and filename_pattern next_frame = start_number frame_count = 0 self._frame_filenames = [] while True: frame_path = get_num_pattern_file_path( frames_dir, filename_prefix, filename_num_pattern, next_frame, image_type ) if os.path.isfile(frame_path) and os.access(frame_path, os.R_OK): self._frame_filenames.append(frame_path) next_frame += 1 frame_count += 1 if frame_count == total_frames: break else: break carb.log_warn(f"Found {len(self._frame_filenames)} frames to encode.") if len(self._frame_filenames) == 0: carb.log_warn(f"No frames to encode.") return False if not g_video_encoding_api.start_encoding(video_name, frame_rate, len(self._frame_filenames), True): carb.log_warn(f"videoencoding plug failed to start encoding.") return False if self._encoding_thread == None: self._encoding_thread = threading.Thread(target=self._encode_image_file_sequence, args=()) self._is_encoding = True self._encoding_thread.start() return True def _init_internal(self): self._video_generation_done_fn = None self._frame_filenames = [] self._encoding_thread = None self._is_encoding = False self._encoding_done = False def _encode_image_file_sequence(self): global g_video_encoding_api try: for frame_filename in self._frame_filenames: g_video_encoding_api.encode_next_frame_from_file(frame_filename) except: import traceback carb.log_warn(traceback.format_exc()) finally: g_video_encoding_api.finalize_encoding() self._init_internal() self._encoding_done = True
omniverse-code/kit/exts/omni.kit.capture.viewport/omni/kit/capture/viewport/__init__.py
# Copyright (c) 2018-2020, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. # from .extension import CaptureExtension from .capture_options import * from .capture_progress import *
omniverse-code/kit/exts/omni.kit.capture.viewport/omni/kit/capture/viewport/capture_options.py
# Copyright (c) 2018-2020, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. # import os from enum import Enum, IntEnum import carb class CaptureMovieType(IntEnum): SEQUENCE = 0 SUNSTUDY = 1 PLAYLIST = 2 class CaptureRangeType(IntEnum): FRAMES = 0 SECONDS = 1 class CaptureRenderPreset(IntEnum): PATH_TRACE = 0 RAY_TRACE = 1 IRAY = 2 class CaptureDebugMaterialType(IntEnum): SHADED = 0 WHITE = 1 EXR_COMPRESSION_METHODS = {"zip", "zips", "dwaa", "dwab", "piz", "rle", "b44", "b44a"} MP4_ENCODING_PRESETS = { "PRESET_DEFAULT", "PRESET_HP", "PRESET_HQ", "PRESET_BD", "PRESET_LOW_LATENCY_DEFAULT", "PRESET_LOW_LATENCY_HQ", "PRESET_LOW_LATENCY_HP", "PRESET_LOSSLESS_DEFAULT", "PRESET_LOSSLESS_HP" } MP4_ENCODING_PROFILES = { "H264_PROFILE_BASELINE", "H264_PROFILE_MAIN", "H264_PROFILE_HIGH", "H264_PROFILE_HIGH_444", "H264_PROFILE_STEREO", "H264_PROFILE_SVC_TEMPORAL_SCALABILITY", "H264_PROFILE_PROGRESSIVE_HIGH", "H264_PROFILE_CONSTRAINED_HIGH", "HEVC_PROFILE_MAIN", "HEVC_PROFILE_MAIN10", "HEVC_PROFILE_FREXT" } MP4_ENCODING_RC_MODES = { "RC_CONSTQP", "RC_VBR", "RC_CBR", "RC_CBR_LOWDELAY_HQ", "RC_CBR_HQ", "RC_VBR_HQ" } class CaptureOptions: """ All Capture options that will be used when capturing. Note: When adding an attribute make sure it is exposed via the constructor. Not doing this will cause erorrs when serializing and deserializing this object. """ INVALID_ANIMATION_FPS = -1 def __init__( self, camera="camera", range_type=CaptureRangeType.FRAMES, capture_every_nth_frames=-1, fps=24, start_frame=1, end_frame=40, start_time=0, end_time=10, res_width=1920, res_height=1080, render_preset=CaptureRenderPreset.PATH_TRACE, debug_material_type=CaptureDebugMaterialType.SHADED, spp_per_iteration=1, path_trace_spp=1, ptmb_subframes_per_frame=1, ptmb_fso=0.0, ptmb_fsc=1.0, output_folder="", file_name="Capture", file_name_num_pattern=".####", file_type=".tga", save_alpha=False, hdr_output=False, show_pathtracing_single_frame_progress=False, preroll_frames=0, overwrite_existing_frames=False, movie_type=CaptureMovieType.SEQUENCE, sunstudy_start_time=0.0, sunstudy_current_time=0.0, sunstudy_end_time=0.0, sunstudy_movie_length_in_seconds=0, sunstudy_player=None, real_time_settle_latency_frames=0, renumber_negative_frame_number_from_0=False, render_product="", exr_compression_method="zips", mp4_encoding_bitrate=16777216, mp4_encoding_iframe_interval=60, mp4_encoding_preset="PRESET_DEFAULT", mp4_encoding_profile="H264_PROFILE_HIGH", mp4_encoding_rc_mode="RC_VBR", mp4_encoding_rc_target_quality=0, mp4_encoding_video_full_range_flag=False, app_level_capture=False, animation_fps=INVALID_ANIMATION_FPS ): self._camera = camera self._range_type = range_type self._capture_every_nth_frames = capture_every_nth_frames self._fps = fps self._start_frame = start_frame self._end_frame = end_frame self._start_time = start_time self._end_time = end_time self._res_width = res_width self._res_height = res_height self._render_preset = render_preset self._debug_material_type = debug_material_type self._spp_per_iteration = spp_per_iteration self._path_trace_spp = path_trace_spp self._ptmb_subframes_per_frame = ptmb_subframes_per_frame self._ptmb_fso = ptmb_fso self._ptmb_fsc = ptmb_fsc self._output_folder = output_folder self._file_name = file_name self._file_name_num_pattern = file_name_num_pattern self._file_type = file_type self._save_alpha = save_alpha self._hdr_output = hdr_output self._show_pathtracing_single_frame_progress = show_pathtracing_single_frame_progress self._preroll_frames = preroll_frames self._overwrite_existing_frames = overwrite_existing_frames self._movie_type = movie_type self._sunstudy_start_time = sunstudy_start_time self._sunstudy_current_time = sunstudy_current_time self._sunstudy_end_time = sunstudy_end_time self._sunstudy_movie_length_in_seconds = sunstudy_movie_length_in_seconds self._sunstudy_player = sunstudy_player self._real_time_settle_latency_frames = real_time_settle_latency_frames self._renumber_negative_frame_number_from_0 = renumber_negative_frame_number_from_0 self._render_product = render_product self.exr_compression_method = exr_compression_method self.mp4_encoding_bitrate = mp4_encoding_bitrate self.mp4_encoding_iframe_interval = mp4_encoding_iframe_interval self.mp4_encoding_preset = mp4_encoding_preset self.mp4_encoding_profile = mp4_encoding_profile self.mp4_encoding_rc_mode = mp4_encoding_rc_mode self.mp4_encoding_rc_target_quality = mp4_encoding_rc_target_quality self.mp4_encoding_video_full_range_flag = mp4_encoding_video_full_range_flag self._app_level_capture = app_level_capture self.animation_fps = animation_fps def to_dict(self): data = vars(self) return {key.lstrip("_"): value for key, value in data.items()} @classmethod def from_dict(cls, options): return cls(**options) @property def camera(self): return self._camera @camera.setter def camera(self, value): self._camera = value @property def range_type(self): return self._range_type @range_type.setter def range_type(self, value): self._range_type = value @property def capture_every_Nth_frames(self): return self._capture_every_nth_frames @capture_every_Nth_frames.setter def capture_every_Nth_frames(self, value): self._capture_every_nth_frames = value @property def fps(self): return self._fps @fps.setter def fps(self, value): self._fps = value @property def start_frame(self): return self._start_frame @start_frame.setter def start_frame(self, value): self._start_frame = value @property def end_frame(self): return self._end_frame @end_frame.setter def end_frame(self, value): self._end_frame = value @property def start_time(self): return self._start_time @start_time.setter def start_time(self, value): self._start_time = value @property def end_time(self): return self._end_time @end_time.setter def end_time(self, value): self._end_time = value @property def res_width(self): return self._res_width @res_width.setter def res_width(self, value): self._res_width = value @property def res_height(self): return self._res_height @res_height.setter def res_height(self, value): self._res_height = value @property def render_preset(self): return self._render_preset @render_preset.setter def render_preset(self, value): self._render_preset = value @property def debug_material_type(self): return self._debug_material_type @debug_material_type.setter def debug_material_type(self, value): self._debug_material_type = value @property def spp_per_iteration(self): return self._spp_per_iteration @spp_per_iteration.setter def spp_per_iteration(self, value): self._spp_per_iteration = value @property def path_trace_spp(self): return self._path_trace_spp @path_trace_spp.setter def path_trace_spp(self, value): self._path_trace_spp = value @property def ptmb_subframes_per_frame(self): return self._ptmb_subframes_per_frame @ptmb_subframes_per_frame.setter def ptmb_subframes_per_frame(self, value): self._ptmb_subframes_per_frame = value @property def ptmb_fso(self): return self._ptmb_fso @ptmb_fso.setter def ptmb_fso(self, value): self._ptmb_fso = value @property def ptmb_fsc(self): return self._ptmb_fsc @ptmb_fsc.setter def ptmb_fsc(self, value): self._ptmb_fsc = value @property def output_folder(self): return self._output_folder @output_folder.setter def output_folder(self, value): self._output_folder = value @property def file_name(self): return self._file_name @file_name.setter def file_name(self, value): self._file_name = value @property def file_name_num_pattern(self): return self._file_name_num_pattern @file_name_num_pattern.setter def file_name_num_pattern(self, value): self._file_name_num_pattern = value @property def file_type(self): return self._file_type @file_type.setter def file_type(self, value): self._file_type = value @property def save_alpha(self): return self._save_alpha @save_alpha.setter def save_alpha(self, value): self._save_alpha = value @property def hdr_output(self): return self._hdr_output @hdr_output.setter def hdr_output(self, value): self._hdr_output = value @property def show_pathtracing_single_frame_progress(self): return self._show_pathtracing_single_frame_progress @show_pathtracing_single_frame_progress.setter def show_pathtracing_single_frame_progress(self, value): self._show_pathtracing_single_frame_progress = value @property def preroll_frames(self): return self._preroll_frames @preroll_frames.setter def preroll_frames(self, value): self._preroll_frames = value @property def overwrite_existing_frames(self): return self._overwrite_existing_frames @overwrite_existing_frames.setter def overwrite_existing_frames(self, value): self._overwrite_existing_frames = value @property def movie_type(self): return self._movie_type @movie_type.setter def movie_type(self, value): self._movie_type = value @property def sunstudy_start_time(self): return self._sunstudy_start_time @sunstudy_start_time.setter def sunstudy_start_time(self, value): self._sunstudy_start_time = value @property def sunstudy_current_time(self): return self._sunstudy_current_time @sunstudy_current_time.setter def sunstudy_current_time(self, value): self._sunstudy_current_time = value @property def sunstudy_end_time(self): return self._sunstudy_end_time @sunstudy_end_time.setter def sunstudy_end_time(self, value): self._sunstudy_end_time = value @property def sunstudy_movie_length_in_seconds(self): return self._sunstudy_movie_length_in_seconds @sunstudy_movie_length_in_seconds.setter def sunstudy_movie_length_in_seconds(self, value): self._sunstudy_movie_length_in_seconds = value @property def sunstudy_player(self): return self._sunstudy_player @sunstudy_player.setter def sunstudy_player(self, value): self._sunstudy_player = value @property def real_time_settle_latency_frames(self): return self._real_time_settle_latency_frames @real_time_settle_latency_frames.setter def real_time_settle_latency_frames(self, value): self._real_time_settle_latency_frames = value @property def renumber_negative_frame_number_from_0(self): return self._renumber_negative_frame_number_from_0 @renumber_negative_frame_number_from_0.setter def renumber_negative_frame_number_from_0(self, value): self._renumber_negative_frame_number_from_0 = value @property def render_product(self): return self._render_product @render_product.setter def render_product(self, value): self._render_product = value @property def exr_compression_method(self): return self._exr_compression_method @exr_compression_method.setter def exr_compression_method(self, value): global EXR_COMPRESSION_METHODS if value in EXR_COMPRESSION_METHODS: self._exr_compression_method = value else: self._exr_compression_method = "zips" carb.log_warn(f"Can't set unsupported compression method {value} for exr format, set to default zip16. Supported values are: {EXR_COMPRESSION_METHODS}") @property def mp4_encoding_bitrate(self): return self._mp4_encoding_bitrate @mp4_encoding_bitrate.setter def mp4_encoding_bitrate(self, value): self._mp4_encoding_bitrate = value @property def mp4_encoding_iframe_interval(self): return self._mp4_encoding_iframe_interval @mp4_encoding_iframe_interval.setter def mp4_encoding_iframe_interval(self, value): self._mp4_encoding_iframe_interval = value @property def mp4_encoding_preset(self): return self._mp4_encoding_preset @mp4_encoding_preset.setter def mp4_encoding_preset(self, value): global MP4_ENCODING_PRESETS if value in MP4_ENCODING_PRESETS: self._mp4_encoding_preset = value else: self._mp4_encoding_preset = "PRESET_DEFAULT" carb.log_warn(f"Can't set unsupported mp4 encoding preset {value}, set to default {self._mp4_encoding_preset}. Supported values are: {MP4_ENCODING_PRESETS}") @property def mp4_encoding_profile(self): return self._mp4_encoding_profile @mp4_encoding_profile.setter def mp4_encoding_profile(self, value): global MP4_ENCODING_PROFILES if value in MP4_ENCODING_PROFILES: self._mp4_encoding_profile = value else: self._mp4_encoding_profile = "H264_PROFILE_HIGH" carb.log_warn(f"Can't set unsupported mp4 encoding profile {value}, set to default {self._mp4_encoding_profile}. Supported values are: {MP4_ENCODING_PROFILES}") @property def mp4_encoding_rc_mode(self): return self._mp4_encoding_rc_mode @mp4_encoding_rc_mode.setter def mp4_encoding_rc_mode(self, value): global MP4_ENCODING_RC_MODES if value in MP4_ENCODING_RC_MODES: self._mp4_encoding_rc_mode = value else: self._mp4_encoding_rc_mode = "RC_VBR" carb.log_warn(f"Can't set unsupported mp4 encoding rate control mode {value}, set to default {self._mp4_encoding_rc_mode}. Supported values are: {MP4_ENCODING_RC_MODES}") @property def mp4_encoding_rc_target_quality(self): return self._mp4_encoding_rc_target_quality @mp4_encoding_rc_target_quality.setter def mp4_encoding_rc_target_quality(self, value): if 0 <= value and value <= 51: self._mp4_encoding_rc_target_quality = value else: self._mp4_encoding_rc_target_quality = 0 carb.log_warn(f"Can't set unsupported mp4 encoding rate control target quality {value}, set to default {self._mp4_encoding_rc_target_quality}. Supported range is [0, 51]") @property def mp4_encoding_video_full_range_flag(self): return self._mp4_encoding_video_full_range_flag @mp4_encoding_video_full_range_flag.setter def mp4_encoding_video_full_range_flag(self, value): self._mp4_encoding_video_full_range_flag = value @property def app_level_capture(self): return self._app_level_capture @app_level_capture.setter def app_level_capture(self, value): self._app_level_capture = value @property def animation_fps(self): return self._animation_fps @animation_fps.setter def animation_fps(self, value): self._animation_fps = value def is_video(self): return self.file_type == ".mp4" def is_capturing_nth_frames(self): return self._capture_every_nth_frames > 0 def is_capturing_pathtracing_single_frame(self): return ( self.is_video() is False and self.is_capturing_nth_frames() is False and (self.render_preset == CaptureRenderPreset.PATH_TRACE or self.render_preset == CaptureRenderPreset.IRAY) ) def is_capturing_frame(self): return self._range_type == CaptureRangeType.FRAMES def get_full_path(self): return os.path.join(self._output_folder, self._file_name + self._file_type)
omniverse-code/kit/exts/omni.kit.capture.viewport/omni/kit/capture/viewport/helper.py
# Copyright (c) 2018-2020, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. # import os import carb import omni.kit.app import omni.usd from pxr import Sdf, UsdRender, Gf, Usd ViewportObjectsSettingDict = { "guide/selection": "/app/viewport/outline/enabled", "scene/lights": "/app/viewport/show/lights", "scene/audio": "/app/viewport/show/audio", "scene/cameras": "/app/viewport/show/camera", "guide/grid": "/app/viewport/grid/enabled" } def get_num_pattern_file_path(frames_dir, file_name, num_pattern, frame_num, file_type, renumber_frames=False, renumber_offset=0): if renumber_frames: renumbered_frames = frame_num + renumber_offset else: renumbered_frames = frame_num abs_frame_num = abs(renumbered_frames) padding_length = len(num_pattern.strip(".")[len(str(abs_frame_num)) :]) if renumbered_frames >= 0: padded_string = "0" * padding_length + str(renumbered_frames) else: padded_string = "-" + "0" * padding_length + str(abs_frame_num) filename = ".".join((file_name, padded_string, file_type.strip("."))) frame_path = os.path.join(frames_dir, filename) return frame_path def is_ext_enabled(ext_name): ext_manager = omni.kit.app.get_app().get_extension_manager() return ext_manager.is_extension_enabled(ext_name) # TODO: These version checks exists only in case down-stream movie-capture has imported them # They should be removed for 105.2 and above. # def check_kit_major_version(version_num: int) -> bool: kit_version = omni.kit.app.get_app().get_build_version().split(".") try: major_ver = int(kit_version[0]) return major_ver >= version_num except Exception as e: return False def is_kit_104_and_above() -> bool: return False def is_kit_105_and_above() -> bool: return True def get_vp_object_setting_path(viewport_api, setting_key: str) -> str: usd_context_name = viewport_api.usd_context_name if setting_key.startswith("scene"): setting_path = f"/app/viewport/usdcontext-{usd_context_name}/{setting_key}/visible" else: setting_path = f"/persistent/app/viewport/{viewport_api.id}/{setting_key}/visible" return setting_path def get_vp_object_visibility(viewport_api, setting_key: str) -> bool: settings = carb.settings.get_settings() setting_path = get_vp_object_setting_path(viewport_api, setting_key) return settings.get_as_bool(setting_path) def set_vp_object_visibility(viewport_api, setting_key: str, visible: bool) -> None: if get_vp_object_visibility(viewport_api, setting_key) == visible: return settings = carb.settings.get_settings() action_key = { "guide/selection": "toggle_selection_hilight_visibility", "scene/lights": "toggle_light_visibility", "scene/audio": "toggle_audio_visibility", "scene/cameras": "toggle_camera_visibility", "guide/grid": "toggle_grid_visibility" }.get(setting_key, None) if not action_key: carb.log_error(f"No mapping between {setting_key} and omni.kit.viewport.actions") return action_registry = omni.kit.actions.core.get_action_registry() action = action_registry.get_action("omni.kit.viewport.actions", action_key) if action: action.execute(viewport_api=viewport_api, visible=visible) else: carb.log_error(f"Did not find action omni.kit.viewport.actions.{action_key}") def check_render_product_ext_availability(): return is_ext_enabled("omni.graph.nodes") and is_ext_enabled("omni.graph.examples.cpp") def is_valid_render_product_prim_path(prim_path): try: import omni.usd from pxr import UsdRender usd_context = omni.usd.get_context() stage = usd_context.get_stage() prim = stage.GetPrimAtPath(prim_path) if prim: return prim.IsA(UsdRender.Product) else: return False except Exception as e: return False class RenderProductCaptureHelper: @staticmethod def prepare_render_product_for_capture(render_product_prim_path, new_camera, new_resolution): usd_context = omni.usd.get_context() stage = usd_context.get_stage() working_layer = stage.GetSessionLayer() prim = stage.GetPrimAtPath(render_product_prim_path) path_new = omni.usd.get_stage_next_free_path(stage, render_product_prim_path, False) if prim.IsA(UsdRender.Product): with Usd.EditContext(stage, working_layer): omni.kit.commands.execute("CopyPrim", path_from=render_product_prim_path, path_to=path_new, duplicate_layers=False, combine_layers=True,exclusive_select=True) prim_new = stage.GetPrimAtPath(path_new) if prim_new.IsA(UsdRender.Product): omni.usd.editor.set_no_delete(prim_new, False) prim_new.GetAttribute("resolution").Set(new_resolution) prim_new.GetRelationship("camera").SetTargets([new_camera]) else: path_new = "" else: path_new = "" return path_new @staticmethod def remove_render_product_for_capture(render_product_prim_path): usd_context = omni.usd.get_context() stage = usd_context.get_stage() working_layer = stage.GetSessionLayer() prim = working_layer.GetPrimAtPath(render_product_prim_path) if prim: if prim.nameParent: name_parent = prim.nameParent else: name_parent = working_layer.pseudoRoot if not name_parent: return name = prim.name if name in name_parent.nameChildren: del name_parent.nameChildren[name]
omniverse-code/kit/exts/omni.kit.capture.viewport/omni/kit/capture/viewport/singleton.py
# Copyright (c) 2018-2020, 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. # def Singleton(class_): """A singleton decorator""" instances = {} def getinstance(*args, **kwargs): if class_ not in instances: instances[class_] = class_(*args, **kwargs) return instances[class_] return getinstance
omniverse-code/kit/exts/omni.kit.capture.viewport/omni/kit/capture/viewport/tests/__init__.py
from .test_capture_options import TestCaptureOptions from .test_capture_hdr import TestCaptureHdr from .test_capture_png import TestCapturePng from .test_capture_render_product import TestCaptureRenderProduct
omniverse-code/kit/exts/omni.kit.capture.viewport/omni/kit/capture/viewport/tests/test_helper.py
import os import os.path import asyncio import carb import omni.kit.app def clean_files_in_directory(directory, suffix): if not os.path.exists(directory): return images = os.listdir(directory) for item in images: if item.endswith(suffix): os.remove(os.path.join(directory, item)) def make_sure_directory_existed(directory): if not os.path.exists(directory): try: os.makedirs(directory, exist_ok=True) except OSError as error: carb.log_warn(f"Directory cannot be created: {dir}") return False return True # TODO: Remove this as it is no longer used, but kept only if transitively depended on # def is_kit_104_and_above(): kit_version = omni.kit.app.get_app().get_build_version().split(".") try: major_ver = int(kit_version[0]) return major_ver >= 104 except Exception as e: return False async def wait_for_image_writing(image_path, seconds_to_wait: float = 30, seconds_to_sleep: float = 0.5): seconds_tried = 0.0 carb.log_info(f"Waiting for {image_path} to be written to disk.") while seconds_tried < seconds_to_wait: if os.path.isfile(image_path) and os.access(image_path, os.R_OK): carb.log_info(f"{image_path} is written to disk in {seconds_tried}s.") break else: await asyncio.sleep(seconds_to_sleep) seconds_tried += seconds_to_sleep if seconds_tried >= seconds_to_wait: carb.log_warn(f"Waiting for {image_path} timed out..")
omniverse-code/kit/exts/omni.kit.capture.viewport/omni/kit/capture/viewport/tests/test_capture_hdr.py
from typing import Type import os import os.path import omni.kit.test import carb import carb.settings import carb.tokens import pathlib import gc from omni.kit.capture.viewport import CaptureOptions, CaptureExtension from omni.kit.viewport.utility import get_active_viewport, create_viewport_window, capture_viewport_to_file from .test_helper import clean_files_in_directory, make_sure_directory_existed, wait_for_image_writing KIT_ROOT = pathlib.Path(carb.tokens.acquire_tokens_interface().resolve("${kit}")).parent.parent.parent OUTPUTS_DIR = KIT_ROOT.joinpath("_testoutput/omni.kit.capture.viewport.images") class TestCaptureHdr(omni.kit.test.AsyncTestCase): # Before running each test async def setUp(self): self._usd_context = '' settings = carb.settings.get_settings() self._frames_wait_for_capture_resource_ready = 6 await omni.usd.get_context(self._usd_context).new_stage_async() async def test_hdr_capture(self): viewport_api = get_active_viewport(self._usd_context) # Wait until the viewport has valid resources await viewport_api.wait_for_rendered_frames() capture_filename = "capture_hdr_test" filePath = pathlib.Path(OUTPUTS_DIR).joinpath(capture_filename) options = CaptureOptions() options.file_type = ".exr" options.output_folder = str(filePath) make_sure_directory_existed(options.output_folder) clean_files_in_directory(options.output_folder, ".exr") exr_path = os.path.join(options._output_folder, "Capture1.exr") carb.log_warn(f"Capture image path: {exr_path}") options.hdr_output = True options.camera = viewport_api.camera_path.pathString # to reduce memory consumption and save time options.res_width = 600 options.res_height = 337 capture_instance = CaptureExtension().get_instance() capture_instance.options = options capture_instance.start() await wait_for_image_writing(exr_path) options = None capture_instance = None gc.collect() assert os.path.isfile(exr_path) async def _test_exr_compression_method(self, compression_method): viewport_api = get_active_viewport(self._usd_context) # Wait until the viewport has valid resources await viewport_api.wait_for_rendered_frames() capture_filename = "capture_exr_compression_method_test_" + compression_method filePath = pathlib.Path(OUTPUTS_DIR).joinpath(capture_filename) options = CaptureOptions() options.file_type = ".exr" options.exr_compression_method = compression_method options.output_folder = str(filePath) make_sure_directory_existed(options.output_folder) clean_files_in_directory(options.output_folder, ".exr") exr_path = os.path.join(options._output_folder, "Capture1.exr") carb.log_warn(f"Capture image path: {exr_path}") options.hdr_output = True options.camera = viewport_api.camera_path.pathString # to reduce memory consumption and save time options.res_width = 600 options.res_height = 337 capture_instance = CaptureExtension().get_instance() capture_instance.options = options capture_instance.start() await wait_for_image_writing(exr_path) options = None capture_instance = None gc.collect() assert os.path.isfile(exr_path) async def test_exr_compression_method_rle(self): await self._test_exr_compression_method("rle") async def test_exr_compression_method_zip(self): await self._test_exr_compression_method("zip") async def test_exr_compression_method_dwaa(self): await self._test_exr_compression_method("dwaa") async def test_exr_compression_method_dwab(self): await self._test_exr_compression_method("dwab") async def test_exr_compression_method_piz(self): await self._test_exr_compression_method("piz") async def test_exr_compression_method_b44(self): await self._test_exr_compression_method("b44") async def test_exr_compression_method_b44a(self): await self._test_exr_compression_method("b44a") # Notes: The following multiple viewport tests will fail now and should be revisited after we confirm the # multiple viewport capture support in new SRD. # # Make sure we do not crash in the unsupported multi-view case # async def test_hdr_multiview_capture(self): # viewport_api = get_active_viewport(self._usd_context) # # Wait until the viewport has valid resources # await viewport_api.wait_for_rendered_frames() # new_viewport = create_viewport_window("Viewport 2") # capture_filename = "capture.hdr_test.multiview" # filePath = pathlib.Path(OUTPUTS_DIR).joinpath(capture_filename) # options = CaptureOptions() # options.file_type = ".exr" # options.output_folder = str(filePath) # self._make_sure_directory_existed(options.output_folder) # self._clean_files_in_directory(options.output_folder, ".exr") # exr_path = os.path.join(options._output_folder, "Capture1.exr") # carb.log_warn(f"Capture image path: {exr_path}") # options.hdr_output = True # options.camera = viewport_api.camera_path.pathString # capture_instance = CaptureExtension().get_instance() # capture_instance.options = options # capture_instance.start() # capture_viewport_to_file(new_viewport.viewport_api, file_path=exr_path) # i = self._frames_wait_for_capture_resource_ready # while i > 0: # await omni.kit.app.get_app().next_update_async() # i -= 1 # options = None # capture_instance = None # gc.collect() # assert os.path.isfile(exr_path) # if viewport_widget: # viewport_widget.destroy() # del viewport_widget # async def test_hdr_multiview_capture_legacy(self): # await self.do_test_hdr_multiview_capture(True) # async def test_hdr_multiview_capture(self): # await self.do_test_hdr_multiview_capture(False)
omniverse-code/kit/exts/omni.kit.capture.viewport/omni/kit/capture/viewport/tests/test_capture_options.py
from typing import Type import omni.kit.test import omni.kit.capture.viewport.capture_options as _capture_options class TestCaptureOptions(omni.kit.test.AsyncTestCase): async def test_capture_options_serialisation(self): options = _capture_options.CaptureOptions() data_dict = options.to_dict() self.assertIsInstance(data_dict, dict) async def test_capture_options_deserialisation(self): options = _capture_options.CaptureOptions() data_dict = options.to_dict() regenerated_options = _capture_options.CaptureOptions.from_dict(data_dict) self.assertIsInstance(regenerated_options, _capture_options.CaptureOptions) async def test_capture_options_values_persisted(self): options = _capture_options.CaptureOptions(camera="my_camera") data_dict = options.to_dict() regenerated_options = _capture_options.CaptureOptions.from_dict(data_dict) self.assertEqual(regenerated_options.camera, "my_camera") async def test_adding_random_attribute_fails(self): """ Test that adding new attributes without making them configurable via the __init__ will raise an exception """ options = _capture_options.CaptureOptions() options._my_new_value = "foo" data_dict = options.to_dict() with self.assertRaises(TypeError, msg="__init__() got an unexpected keyword argument 'my_new_value'"): regnerated = _capture_options.CaptureOptions.from_dict(data_dict) async def test_capture_options_unsupported_exr_compression_method(self): options = _capture_options.CaptureOptions(exr_compression_method="sth_wrong") self.assertEqual(options.exr_compression_method, "zips") async def test_capture_options_mp4_encoding_settings(self): options = _capture_options.CaptureOptions( mp4_encoding_bitrate=4194304, mp4_encoding_iframe_interval=10, mp4_encoding_preset="PRESET_LOSSLESS_HP", mp4_encoding_profile="H264_PROFILE_PROGRESSIVE_HIGH", mp4_encoding_rc_mode="RC_VBR_HQ", mp4_encoding_rc_target_quality=51, mp4_encoding_video_full_range_flag=True, ) self.assertEqual(options.mp4_encoding_bitrate, 4194304) self.assertEqual(options.mp4_encoding_iframe_interval, 10) self.assertEqual(options.mp4_encoding_preset, "PRESET_LOSSLESS_HP") self.assertEqual(options.mp4_encoding_profile, "H264_PROFILE_PROGRESSIVE_HIGH") self.assertEqual(options._mp4_encoding_rc_mode, "RC_VBR_HQ") self.assertEqual(options._mp4_encoding_rc_target_quality, 51) self.assertEqual(options.mp4_encoding_video_full_range_flag, True) async def test_capture_options_unsupported_mp4_encoding_settings(self): options = _capture_options.CaptureOptions( mp4_encoding_bitrate=4194304, mp4_encoding_iframe_interval=10, mp4_encoding_preset="PRESET_NOT_EXISTING", mp4_encoding_profile="PROFILE_NOT_EXISTING", mp4_encoding_rc_mode="RC_NOT_EXISTING", mp4_encoding_rc_target_quality=52, mp4_encoding_video_full_range_flag=True, ) self.assertEqual(options.mp4_encoding_bitrate, 4194304) self.assertEqual(options.mp4_encoding_iframe_interval, 10) self.assertEqual(options.mp4_encoding_preset, "PRESET_DEFAULT") self.assertEqual(options.mp4_encoding_profile, "H264_PROFILE_HIGH") self.assertEqual(options._mp4_encoding_rc_mode, "RC_VBR") self.assertEqual(options._mp4_encoding_rc_target_quality, 0) self.assertEqual(options.mp4_encoding_video_full_range_flag, True)
omniverse-code/kit/exts/omni.kit.capture.viewport/omni/kit/capture/viewport/tests/test_capture_render_product.py
import os import os.path import omni.kit.test import omni.usd import carb import carb.settings import carb.tokens import pathlib import gc import unittest from omni.kit.capture.viewport import CaptureOptions, CaptureExtension from omni.kit.viewport.utility import get_active_viewport from omni.kit.test_suite.helpers import wait_stage_loading from .test_helper import clean_files_in_directory, make_sure_directory_existed, wait_for_image_writing KIT_ROOT = pathlib.Path(carb.tokens.acquire_tokens_interface().resolve("${kit}")).parent.parent.parent OUTPUTS_DIR = KIT_ROOT.joinpath("_testoutput/omni.kit.capture.viewport.images") TEST_DIR = str(pathlib.Path(__file__).parent.parent.parent.parent.parent.parent) class TestCaptureRenderProduct(omni.kit.test.AsyncTestCase): # Before running each test async def setUp(self): self._usd_context = '' self._frames_per_sec_to_wait_for_capture_resource_ready = 60 test_usd = TEST_DIR + "/data/tests/usd/PTAccumulateTest.usd" carb.log_warn(f"testing capture with usd {test_usd}") self._capture_folder_1spp = "rp_1spp" self._capture_folder_32spp = "rp_32spp" self._capture_folder_sequence = "rp_seq" self._context = omni.usd.get_context() self._capture_instance = CaptureExtension().get_instance() await self._context.open_stage_async(test_usd) await wait_stage_loading() for _ in range(2): await omni.kit.app.get_app().next_update_async() async def tearDown(self) -> None: self._capture_instance = None async def _test_render_product_capture(self, image_folder, render_product_name, spp, enable_hdr=True, sequence_capture=False, start_frame=0, end_frame=10): viewport_api = get_active_viewport(self._usd_context) # Wait until the viewport has valid resources await viewport_api.wait_for_rendered_frames() # wait for PT to resolve after loading, otherwise it's easy to crash i = self._frames_per_sec_to_wait_for_capture_resource_ready * 50 while i > 0: await omni.kit.app.get_app().next_update_async() i -= 1 # assert True capture_folder_name = image_folder filePath = pathlib.Path(OUTPUTS_DIR).joinpath(capture_folder_name) options = CaptureOptions() options.file_type = ".exr" options.output_folder = str(filePath) make_sure_directory_existed(options.output_folder) clean_files_in_directory(options.output_folder, ".exr") options.hdr_output = enable_hdr options.camera = viewport_api.camera_path.pathString options.render_preset = omni.kit.capture.viewport.CaptureRenderPreset.PATH_TRACE options.render_product = render_product_name options.path_trace_spp = spp # to reduce memory consumption and save time options.res_width = 600 options.res_height = 337 if sequence_capture: options.capture_every_Nth_frames = 1 options.start_frame = start_frame options.end_frame = end_frame self._capture_instance.options = options self._capture_instance.start() options = None async def _verify_file_exist(self, capture_folder_name, aov_channel): exr_path = self._get_exr_path(capture_folder_name, aov_channel) carb.log_warn(f"Verifying image: {exr_path}") await wait_for_image_writing(exr_path, 40) assert os.path.isfile(exr_path) def _get_exr_path(self, capture_folder_name, aov_channel): image_folder = pathlib.Path(OUTPUTS_DIR).joinpath(capture_folder_name) exr_path = os.path.join(str(image_folder), "Capture1_" + aov_channel + ".exr") return exr_path def _get_captured_image_size(self, capture_folder_name, aov_channel): image_folder = pathlib.Path(OUTPUTS_DIR).joinpath(capture_folder_name) exr_path = os.path.join(str(image_folder), "Capture1_" + aov_channel + ".exr") if os.path.isfile(exr_path): return os.path.getsize(exr_path) else: return 0 async def test_capture_1_default_rp(self): if True: # skip the test for vp2 due to OM-77175: we know it will fail and have a bug for it so mark it true here # and re-enable it after the bug gets fixed image_folder_name = "vp2_default_rp" default_rp_name = "/Render/RenderProduct_omni_kit_widget_viewport_ViewportTexture_0" assert True for _ in range(self._frames_per_sec_to_wait_for_capture_resource_ready * 10): await omni.kit.app.get_app().next_update_async() return await self._test_render_product_capture(image_folder_name, default_rp_name, 16, enable_hdr=False) exr_path = self._get_exr_path(image_folder_name, "LdrColor") await wait_for_image_writing(exr_path) await self._test_render_product_capture(image_folder_name, default_rp_name, 16) await self._verify_file_exist(image_folder_name, "LdrColor") for _ in range(self._frames_per_sec_to_wait_for_capture_resource_ready * 10): await omni.kit.app.get_app().next_update_async() async def test_capture_2_user_created_rp(self): await self._test_render_product_capture(self._capture_folder_1spp, "/Render/RenderView", 1) for _ in range(self._frames_per_sec_to_wait_for_capture_resource_ready * 10): await omni.kit.app.get_app().next_update_async() await self._verify_file_exist(self._capture_folder_1spp, "LdrColor") await self._verify_file_exist(self._capture_folder_1spp, "HdrColor") await self._verify_file_exist(self._capture_folder_1spp, "PtGlobalIllumination") await self._verify_file_exist(self._capture_folder_1spp, "PtReflections") await self._verify_file_exist(self._capture_folder_1spp, "PtWorldNormal") # the render product capture process will write the image file multiple times during the capture # so give it more cycles to settle down to check file size for _ in range(self._frames_per_sec_to_wait_for_capture_resource_ready * 20): await omni.kit.app.get_app().next_update_async() async def test_capture_3_rp_accumulation(self): await self._test_render_product_capture(self._capture_folder_32spp, "/Render/RenderView", 32) for _ in range(self._frames_per_sec_to_wait_for_capture_resource_ready * 10): await omni.kit.app.get_app().next_update_async() await self._verify_file_exist(self._capture_folder_32spp, "LdrColor") # the render product capture process will write the image file multiple times during the capture # so give it more cycles to settle down to check file size for _ in range(self._frames_per_sec_to_wait_for_capture_resource_ready * 20): await omni.kit.app.get_app().next_update_async() # compare result of test_capture_2_user_created_rp images to check accumulation works or not # if it works, more spp will result in smaller file size file_size_1spp = self._get_captured_image_size(self._capture_folder_1spp, "LdrColor") file_size_32spp = self._get_captured_image_size(self._capture_folder_32spp, "LdrColor") carb.log_warn(f"File size of 1spp capture is {file_size_1spp} bytes, and file size of 64spp capture is {file_size_32spp}") expected_result = file_size_32spp != file_size_1spp assert expected_result async def test_capture_4_rp_sequence(self): image_folder = pathlib.Path(OUTPUTS_DIR).joinpath(self._capture_folder_sequence, "Capture_frames") clean_files_in_directory(image_folder, ".exr") await self._test_render_product_capture(self._capture_folder_sequence, "/Render/RenderView", 1, True, True, 0, 10) start_frame_exr_path_1 = os.path.join(str(image_folder), "Capture.0000_" + "LdrColor" + ".exr") start_frame_exr_path_2 = os.path.join(str(image_folder), "Capture.0000_" + "PtGlobalIllumination" + ".exr") end_frame_exr_path_1 = os.path.join(str(image_folder), "Capture.0010_" + "LdrColor" + ".exr") end_frame_exr_path_2 = os.path.join(str(image_folder), "Capture.0010_" + "PtGlobalIllumination" + ".exr") await wait_for_image_writing(end_frame_exr_path_2, 50) assert os.path.isfile(start_frame_exr_path_1) assert os.path.isfile(start_frame_exr_path_2) assert os.path.isfile(end_frame_exr_path_1) assert os.path.isfile(end_frame_exr_path_2)
omniverse-code/kit/exts/omni.kit.capture.viewport/omni/kit/capture/viewport/tests/test_capture_png.py
from typing import Type import os import os.path import omni.kit.test import carb import carb.settings import carb.tokens import pathlib import gc from omni.kit.capture.viewport import CaptureOptions, CaptureExtension from omni.kit.viewport.utility import get_active_viewport, create_viewport_window, capture_viewport_to_file from .test_helper import clean_files_in_directory, make_sure_directory_existed, wait_for_image_writing KIT_ROOT = pathlib.Path(carb.tokens.acquire_tokens_interface().resolve("${kit}")).parent.parent.parent OUTPUTS_DIR = KIT_ROOT.joinpath("_testoutput/omni.kit.capture.viewport.images") class TestCapturePng(omni.kit.test.AsyncTestCase): # Before running each test async def setUp(self): self._usd_context = '' settings = carb.settings.get_settings() self._frames_wait_for_capture_resource_ready = 6 await omni.usd.get_context(self._usd_context).new_stage_async() async def test_png_capture(self): viewport_api = get_active_viewport(self._usd_context) # Wait until the viewport has valid resources await viewport_api.wait_for_rendered_frames() capture_filename = "capture_png_test" filePath = pathlib.Path(OUTPUTS_DIR).joinpath(capture_filename) options = CaptureOptions() options.file_type = ".png" options.output_folder = str(filePath) make_sure_directory_existed(options.output_folder) clean_files_in_directory(options.output_folder, ".png") exr_path = os.path.join(options._output_folder, "Capture1.png") carb.log_warn(f"Capture image path: {exr_path}") options.hdr_output = False options.camera = viewport_api.camera_path.pathString capture_instance = CaptureExtension().get_instance() capture_instance.options = options capture_instance.start() await wait_for_image_writing(exr_path) options = None capture_instance = None gc.collect() assert os.path.isfile(exr_path)
omniverse-code/kit/exts/omni.kit.window.imguidebug/PACKAGE-LICENSES/omni.kit.window.imguidebug-LICENSE.md
Copyright (c) 2020, 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.
omniverse-code/kit/exts/omni.kit.window.imguidebug/config/extension.toml
[package] title = "ImguiDebugWindows" description = "Extension to enable low-level debug windows" authors = ["NVIDIA"] version = "1.0.0" changelog="docs/CHANGELOG.md" readme = "docs/README.md" repository = "" [dependencies] "omni.ui" = {} [[native.plugin]] path = "bin/*.plugin" recursive = false [[test]] args = [ "--/app/window/dpiScaleOverride=1.0", "--/app/window/scaleToMonitor=false", "--/rtx-transient/debugwindows/enable=true", "--/rtx-transient/debugwindows/TestWindow=true", "--/rtx-transient/debugwindows/test=true" ] dependencies = [ "omni.kit.renderer.capture", "omni.kit.ui_test", ]
omniverse-code/kit/exts/omni.kit.window.imguidebug/docs/CHANGELOG.md
# Changelog ## [1.0.0] - 2022-05-04 ### Added - Initial implementation.
omniverse-code/kit/exts/omni.kit.window.imguidebug/docs/README.md
# omni.kit.debug.windows ## Introduction Enables low-level Imgui debug windows
omniverse-code/kit/exts/omni.kit.window.imguidebug/docs/index.rst
omni.kit.debug.windows module ################################## .. toctree:: :maxdepth: 1 CHANGELOG
omniverse-code/kit/exts/omni.usd.schema.anim/pxr/OmniSkelSchema/__init__.py
# #==== # Copyright (c) 2018, NVIDIA CORPORATION #====== # # # Copyright 2016 Pixar # # Licensed under the Apache License, Version 2.0 (the "Apache License") # with the following modification; you may not use this file except in # compliance with the Apache License and the following modification to it: # Section 6. Trademarks. is deleted and replaced with: # # 6. Trademarks. This License does not grant permission to use the trade # names, trademarks, service marks, or product names of the Licensor # and its affiliates, except as required to comply with Section 4(c) of # the License and to reproduce the content of the NOTICE file. # # You may obtain a copy of the Apache License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the Apache License with the above modification is # distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the Apache License for the specific # language governing permissions and limitations under the Apache License. # import os import sys py38 = (3,8) current_version = sys.version_info if os.name == 'nt' and current_version >= py38: from pathlib import Path os.add_dll_directory(Path.joinpath(Path(os.path.dirname(__file__)), Path('..\\..\\')).__str__()) from . import _omniSkelSchema from pxr import Tf Tf.PrepareModule(_omniSkelSchema, locals()) del Tf try: import __DOC __DOC.Execute(locals()) del __DOC except Exception: try: import __tmpDoc __tmpDoc.Execute(locals()) del __tmpDoc except: pass
omniverse-code/kit/exts/omni.usd.schema.anim/pxr/OmniSkelSchema/_omniSkelSchema.pyi
from __future__ import annotations import pxr.OmniSkelSchema._omniSkelSchema import typing import Boost.Python import pxr.Usd import pxr.UsdGeom __all__ = [ "OmniJoint", "OmniJointBoxShapeAPI", "OmniJointCapsuleShapeAPI", "OmniJointLimitsAPI", "OmniJointShapeAPI", "OmniJointSphereShapeAPI", "OmniSkelBaseAPI", "OmniSkelBaseType", "OmniSkeletonAPI" ] class OmniJoint(pxr.UsdGeom.Xform, pxr.UsdGeom.Xformable, pxr.UsdGeom.Imageable, pxr.Usd.Typed, pxr.Usd.SchemaBase, Boost.Python.instance): @staticmethod def CreateBindRotationAttr(*args, **kwargs) -> None: ... @staticmethod def CreateBindScaleAttr(*args, **kwargs) -> None: ... @staticmethod def CreateBindTranslationAttr(*args, **kwargs) -> None: ... @staticmethod def CreateRestRotationAttr(*args, **kwargs) -> None: ... @staticmethod def CreateRestScaleAttr(*args, **kwargs) -> None: ... @staticmethod def CreateRestTranslationAttr(*args, **kwargs) -> None: ... @staticmethod def CreateRetargetRotationAttr(*args, **kwargs) -> None: ... @staticmethod def CreateRetargetScaleAttr(*args, **kwargs) -> None: ... @staticmethod def CreateRetargetTagAttr(*args, **kwargs) -> None: ... @staticmethod def CreateRetargetTranslationAttr(*args, **kwargs) -> None: ... @staticmethod def Define(*args, **kwargs) -> None: ... @staticmethod def Get(*args, **kwargs) -> None: ... @staticmethod def GetBindRotationAttr(*args, **kwargs) -> None: ... @staticmethod def GetBindScaleAttr(*args, **kwargs) -> None: ... @staticmethod def GetBindTranslationAttr(*args, **kwargs) -> None: ... @staticmethod def GetRestRotationAttr(*args, **kwargs) -> None: ... @staticmethod def GetRestScaleAttr(*args, **kwargs) -> None: ... @staticmethod def GetRestTranslationAttr(*args, **kwargs) -> None: ... @staticmethod def GetRetargetRotationAttr(*args, **kwargs) -> None: ... @staticmethod def GetRetargetScaleAttr(*args, **kwargs) -> None: ... @staticmethod def GetRetargetTagAttr(*args, **kwargs) -> None: ... @staticmethod def GetRetargetTranslationAttr(*args, **kwargs) -> None: ... @staticmethod def GetSchemaAttributeNames(*args, **kwargs) -> None: ... @staticmethod def GetSkeletonAndJointToken(*args, **kwargs) -> None: ... @staticmethod def _GetStaticTfType(*args, **kwargs) -> None: ... __instance_size__ = 40 pass class OmniJointBoxShapeAPI(pxr.Usd.APISchemaBase, pxr.Usd.SchemaBase, Boost.Python.instance): @staticmethod def Apply(*args, **kwargs) -> None: ... @staticmethod def CanApply(*args, **kwargs) -> None: ... @staticmethod def Get(*args, **kwargs) -> None: ... @staticmethod def GetSchemaAttributeNames(*args, **kwargs) -> None: ... @staticmethod def GetSize(*args, **kwargs) -> None: ... @staticmethod def SetSize(*args, **kwargs) -> None: ... @staticmethod def _GetStaticTfType(*args, **kwargs) -> None: ... __instance_size__ = 48 pass class OmniJointCapsuleShapeAPI(pxr.Usd.APISchemaBase, pxr.Usd.SchemaBase, Boost.Python.instance): @staticmethod def Apply(*args, **kwargs) -> None: ... @staticmethod def CanApply(*args, **kwargs) -> None: ... @staticmethod def Get(*args, **kwargs) -> None: ... @staticmethod def GetHeight(*args, **kwargs) -> None: ... @staticmethod def GetRadius(*args, **kwargs) -> None: ... @staticmethod def GetSchemaAttributeNames(*args, **kwargs) -> None: ... @staticmethod def SetHeight(*args, **kwargs) -> None: ... @staticmethod def SetRadius(*args, **kwargs) -> None: ... @staticmethod def _GetStaticTfType(*args, **kwargs) -> None: ... __instance_size__ = 48 pass class OmniJointLimitsAPI(pxr.Usd.APISchemaBase, pxr.Usd.SchemaBase, Boost.Python.instance): @staticmethod def Apply(*args, **kwargs) -> None: ... @staticmethod def CanApply(*args, **kwargs) -> None: ... @staticmethod def CreateEnabledAttr(*args, **kwargs) -> None: ... @staticmethod def CreateOffsetRotationAttr(*args, **kwargs) -> None: ... @staticmethod def CreateSwingHorizontalAngleAttr(*args, **kwargs) -> None: ... @staticmethod def CreateSwingVerticalAngleAttr(*args, **kwargs) -> None: ... @staticmethod def CreateTwistMaximumAngleAttr(*args, **kwargs) -> None: ... @staticmethod def CreateTwistMinimumAngleAttr(*args, **kwargs) -> None: ... @staticmethod def Get(*args, **kwargs) -> None: ... @staticmethod def GetEnabledAttr(*args, **kwargs) -> None: ... @staticmethod def GetLocalTransform(*args, **kwargs) -> None: ... @staticmethod def GetOffsetRotationAttr(*args, **kwargs) -> None: ... @staticmethod def GetSchemaAttributeNames(*args, **kwargs) -> None: ... @staticmethod def GetSwingHorizontalAngleAttr(*args, **kwargs) -> None: ... @staticmethod def GetSwingVerticalAngleAttr(*args, **kwargs) -> None: ... @staticmethod def GetTwistMaximumAngleAttr(*args, **kwargs) -> None: ... @staticmethod def GetTwistMinimumAngleAttr(*args, **kwargs) -> None: ... @staticmethod def _GetStaticTfType(*args, **kwargs) -> None: ... __instance_size__ = 48 pass class OmniJointShapeAPI(pxr.Usd.APISchemaBase, pxr.Usd.SchemaBase, Boost.Python.instance): @staticmethod def Apply(*args, **kwargs) -> None: ... @staticmethod def CanApply(*args, **kwargs) -> None: ... @staticmethod def CreateXformOpOrderAttr(*args, **kwargs) -> None: ... @staticmethod def CreateXformOpRotateXYZAttr(*args, **kwargs) -> None: ... @staticmethod def CreateXformOpScaleAttr(*args, **kwargs) -> None: ... @staticmethod def CreateXformOpTranslateAttr(*args, **kwargs) -> None: ... @staticmethod def Get(*args, **kwargs) -> None: ... @staticmethod def GetLocalTransform(*args, **kwargs) -> None: ... @staticmethod def GetSchemaAttributeNames(*args, **kwargs) -> None: ... @staticmethod def GetXformOpOrderAttr(*args, **kwargs) -> None: ... @staticmethod def GetXformOpRotateXYZAttr(*args, **kwargs) -> None: ... @staticmethod def GetXformOpScaleAttr(*args, **kwargs) -> None: ... @staticmethod def GetXformOpTranslateAttr(*args, **kwargs) -> None: ... @staticmethod def _GetStaticTfType(*args, **kwargs) -> None: ... __instance_size__ = 48 pass class OmniJointSphereShapeAPI(pxr.Usd.APISchemaBase, pxr.Usd.SchemaBase, Boost.Python.instance): @staticmethod def Apply(*args, **kwargs) -> None: ... @staticmethod def CanApply(*args, **kwargs) -> None: ... @staticmethod def Get(*args, **kwargs) -> None: ... @staticmethod def GetRadius(*args, **kwargs) -> None: ... @staticmethod def GetSchemaAttributeNames(*args, **kwargs) -> None: ... @staticmethod def SetRadius(*args, **kwargs) -> None: ... @staticmethod def _GetStaticTfType(*args, **kwargs) -> None: ... __instance_size__ = 48 pass class OmniSkelBaseAPI(pxr.Usd.APISchemaBase, pxr.Usd.SchemaBase, Boost.Python.instance): @staticmethod def Apply(*args, **kwargs) -> None: ... @staticmethod def CanApply(*args, **kwargs) -> None: ... @staticmethod def Get(*args, **kwargs) -> None: ... @staticmethod def GetSchemaAttributeNames(*args, **kwargs) -> None: ... @staticmethod def _GetStaticTfType(*args, **kwargs) -> None: ... __instance_size__ = 48 pass class OmniSkelBaseType(pxr.Usd.Typed, pxr.Usd.SchemaBase, Boost.Python.instance): @staticmethod def Define(*args, **kwargs) -> None: ... @staticmethod def Get(*args, **kwargs) -> None: ... @staticmethod def GetSchemaAttributeNames(*args, **kwargs) -> None: ... @staticmethod def _GetStaticTfType(*args, **kwargs) -> None: ... __instance_size__ = 40 pass class OmniSkeletonAPI(pxr.Usd.APISchemaBase, pxr.Usd.SchemaBase, Boost.Python.instance): @staticmethod def Apply(*args, **kwargs) -> None: ... @staticmethod def CanApply(*args, **kwargs) -> None: ... @staticmethod def CreateForwardAxisAttr(*args, **kwargs) -> None: ... @staticmethod def CreateUpAxisAttr(*args, **kwargs) -> None: ... @staticmethod def Get(*args, **kwargs) -> None: ... @staticmethod def GetForwardAxisAttr(*args, **kwargs) -> None: ... @staticmethod def GetSchemaAttributeNames(*args, **kwargs) -> None: ... @staticmethod def GetUpAxisAttr(*args, **kwargs) -> None: ... @staticmethod def _GetStaticTfType(*args, **kwargs) -> None: ... __instance_size__ = 48 pass class _CanApplyResult(Boost.Python.instance): @property def whyNot(self) -> None: """ :type: None """ __instance_size__ = 56 pass __MFB_FULL_PACKAGE_NAME = 'omniSkelSchema'
omniverse-code/kit/exts/omni.usd.schema.anim/pxr/AnimationSchemaTools/_animationSchemaTools.pyi
from __future__ import annotations import pxr.AnimationSchemaTools._animationSchemaTools import typing import Boost.Python __all__ = [ "AddAnimation", "AddCurve", "AddCurves", "AddKey", "AddKeys", "ComputeTangent", "CopyKey", "DeleteAnimation", "DeleteCurves", "DeleteInfinityType", "DeleteKey", "GetAllKeys", "GetCurves", "GetKey", "GetKeys", "GetTangentControlStrategy", "HasAnimation", "HasCurve", "HasInfinityType", "HasKey", "Key", "MoveKey", "RaiseTimeSamplesToEditTarget", "SetInfinityType", "SetKey", "SwitchEditTargetForSessionLayer", "TangentControlStrategy", "testSkelRoot", "verifySkelAnimation" ] class Key(Boost.Python.instance): @staticmethod def GetRelativeInTangentX(*args, **kwargs) -> None: ... @staticmethod def GetRelativeOutTangentX(*args, **kwargs) -> None: ... @property def broken(self) -> None: """ :type: None """ @property def inRawTangent(self) -> None: """ :type: None """ @property def inTangentType(self) -> None: """ :type: None """ @property def outRawTangent(self) -> None: """ :type: None """ @property def outTangentType(self) -> None: """ :type: None """ @property def time(self) -> None: """ :type: None """ @property def value(self) -> None: """ :type: None """ @property def weighted(self) -> None: """ :type: None """ __instance_size__ = 88 __safe_for_unpickling__ = True pass class TangentControlStrategy(Boost.Python.instance): @staticmethod def ValidateInControl(*args, **kwargs) -> None: ... @staticmethod def ValidateOutControl(*args, **kwargs) -> None: ... __instance_size__ = 32 pass def AddAnimation(*args, **kwargs) -> None: pass def AddCurve(*args, **kwargs) -> None: pass def AddCurves(*args, **kwargs) -> None: pass def AddKey(*args, **kwargs) -> None: pass def AddKeys(*args, **kwargs) -> None: pass def ComputeTangent(*args, **kwargs) -> None: pass def CopyKey(*args, **kwargs) -> None: pass def DeleteAnimation(*args, **kwargs) -> None: pass def DeleteCurves(*args, **kwargs) -> None: pass def DeleteInfinityType(*args, **kwargs) -> None: pass def DeleteKey(*args, **kwargs) -> None: pass def GetAllKeys(*args, **kwargs) -> None: pass def GetCurves(*args, **kwargs) -> None: pass def GetKey(*args, **kwargs) -> None: pass def GetKeys(*args, **kwargs) -> None: pass def GetTangentControlStrategy(*args, **kwargs) -> None: pass def HasAnimation(*args, **kwargs) -> None: pass def HasCurve(*args, **kwargs) -> None: pass def HasInfinityType(*args, **kwargs) -> None: pass def HasKey(*args, **kwargs) -> None: pass def MoveKey(*args, **kwargs) -> None: pass def RaiseTimeSamplesToEditTarget(*args, **kwargs) -> None: pass def SetInfinityType(*args, **kwargs) -> None: pass def SetKey(*args, **kwargs) -> None: pass def SwitchEditTargetForSessionLayer(*args, **kwargs) -> None: pass def testSkelRoot(*args, **kwargs) -> None: pass def verifySkelAnimation(*args, **kwargs) -> None: pass __MFB_FULL_PACKAGE_NAME = 'animationSchemaTools'
omniverse-code/kit/exts/omni.usd.schema.anim/pxr/AnimationSchemaTools/__init__.py
# #==== # Copyright (c) 2021, NVIDIA CORPORATION #====== # # # Copyright 2016 Pixar # # Licensed under the Apache License, Version 2.0 (the "Apache License") # with the following modification; you may not use this file except in # compliance with the Apache License and the following modification to it: # Section 6. Trademarks. is deleted and replaced with: # # 6. Trademarks. This License does not grant permission to use the trade # names, trademarks, service marks, or product names of the Licensor # and its affiliates, except as required to comply with Section 4(c) of # the License and to reproduce the content of the NOTICE file. # # You may obtain a copy of the Apache License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the Apache License with the above modification is # distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the Apache License for the specific # language governing permissions and limitations under the Apache License. # import os import sys py38 = (3,8) current_version = sys.version_info if os.name == 'nt' and current_version >= py38: from pathlib import Path os.add_dll_directory(Path.joinpath(Path(os.path.dirname(__file__)), Path('..\\..\\')).__str__()) from . import _animationSchemaTools from pxr import Tf Tf.PrepareModule(_animationSchemaTools, locals()) del Tf try: import __DOC __DOC.Execute(locals()) del __DOC except Exception: try: import __tmpDoc __tmpDoc.Execute(locals()) del __tmpDoc except: pass
omniverse-code/kit/exts/omni.usd.schema.anim/pxr/AnimationSchema/__init__.py
# #==== # Copyright (c) 2018, NVIDIA CORPORATION #====== # # # Copyright 2016 Pixar # # Licensed under the Apache License, Version 2.0 (the "Apache License") # with the following modification; you may not use this file except in # compliance with the Apache License and the following modification to it: # Section 6. Trademarks. is deleted and replaced with: # # 6. Trademarks. This License does not grant permission to use the trade # names, trademarks, service marks, or product names of the Licensor # and its affiliates, except as required to comply with Section 4(c) of # the License and to reproduce the content of the NOTICE file. # # You may obtain a copy of the Apache License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the Apache License with the above modification is # distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the Apache License for the specific # language governing permissions and limitations under the Apache License. # import os import sys py38 = (3,8) current_version = sys.version_info if os.name == 'nt' and current_version >= py38: from pathlib import Path os.add_dll_directory(Path.joinpath(Path(os.path.dirname(__file__)), Path('..\\..\\')).__str__()) from . import _animationSchema from pxr import Tf Tf.PrepareModule(_animationSchema, locals()) del Tf try: import __DOC __DOC.Execute(locals()) del __DOC except Exception: try: import __tmpDoc __tmpDoc.Execute(locals()) del __tmpDoc except: pass
omniverse-code/kit/exts/omni.usd.schema.anim/pxr/AnimationSchema/_animationSchema.pyi
from __future__ import annotations import pxr.AnimationSchema._animationSchema import typing import Boost.Python import pxr.AnimationSchema import pxr.Usd import pxr.UsdGeom __all__ = [ "AnimationCurveAPI", "AnimationData", "AnimationDataAPI", "GetTangentControlStrategy", "Infinity", "Key", "SkelAnimationAnnotation", "SkelJoint", "Tangent", "TangentControlStrategy", "Tokens" ] class AnimationCurveAPI(pxr.Usd.APISchemaBase, pxr.Usd.SchemaBase, Boost.Python.instance): @staticmethod def DeleteCurve(*args, **kwargs) -> None: ... @staticmethod def Get(*args, **kwargs) -> None: ... @staticmethod def GetCurves(*args, **kwargs) -> None: ... @staticmethod def GetDefaultTangentType(*args, **kwargs) -> None: ... @staticmethod def GetInfinityType(*args, **kwargs) -> None: ... @staticmethod def GetKeys(*args, **kwargs) -> None: ... @staticmethod def GetSchemaAttributeNames(*args, **kwargs) -> None: ... @staticmethod def GetTicksPerSecond(*args, **kwargs) -> None: ... @staticmethod def SetDefaultTangentType(*args, **kwargs) -> None: ... @staticmethod def SetInfinityType(*args, **kwargs) -> None: ... @staticmethod def SetKeys(*args, **kwargs) -> None: ... @staticmethod def ValidateKeys(*args, **kwargs) -> None: ... @staticmethod def _GetStaticTfType(*args, **kwargs) -> None: ... __instance_size__ = 48 pass class AnimationData(pxr.Usd.Typed, pxr.Usd.SchemaBase, Boost.Python.instance): @staticmethod def Define(*args, **kwargs) -> None: ... @staticmethod def Get(*args, **kwargs) -> None: ... @staticmethod def GetSchemaAttributeNames(*args, **kwargs) -> None: ... @staticmethod def _GetStaticTfType(*args, **kwargs) -> None: ... __instance_size__ = 40 pass class AnimationDataAPI(pxr.Usd.APISchemaBase, pxr.Usd.SchemaBase, Boost.Python.instance): @staticmethod def Apply(*args, **kwargs) -> None: ... @staticmethod def CanApply(*args, **kwargs) -> None: ... @staticmethod def CreateAnimationDataBindingRel(*args, **kwargs) -> None: ... @staticmethod def Get(*args, **kwargs) -> None: ... @staticmethod def GetAnimationDataBindingRel(*args, **kwargs) -> None: ... @staticmethod def GetSchemaAttributeNames(*args, **kwargs) -> None: ... @staticmethod def _GetStaticTfType(*args, **kwargs) -> None: ... __instance_size__ = 48 pass class Infinity(Boost.Python.enum, int): Post = pxr.AnimationSchema.Infinity.Post Pre = pxr.AnimationSchema.Infinity.Pre __slots__ = () names = {'Pre': pxr.AnimationSchema.Infinity.Pre, 'Post': pxr.AnimationSchema.Infinity.Post} values = {0: pxr.AnimationSchema.Infinity.Pre, 1: pxr.AnimationSchema.Infinity.Post} pass class Key(Boost.Python.instance): @property def inTangent(self) -> None: """ :type: None """ @property def outTangent(self) -> None: """ :type: None """ @property def tangentBroken(self) -> None: """ :type: None """ @property def tangentWeighted(self) -> None: """ :type: None """ @property def time(self) -> None: """ :type: None """ @property def value(self) -> None: """ :type: None """ __instance_size__ = 88 pass class SkelAnimationAnnotation(pxr.Usd.Typed, pxr.Usd.SchemaBase, Boost.Python.instance): @staticmethod def CreateEndAttr(*args, **kwargs) -> None: ... @staticmethod def CreateStartAttr(*args, **kwargs) -> None: ... @staticmethod def CreateTagAttr(*args, **kwargs) -> None: ... @staticmethod def Define(*args, **kwargs) -> None: ... @staticmethod def Get(*args, **kwargs) -> None: ... @staticmethod def GetEndAttr(*args, **kwargs) -> None: ... @staticmethod def GetSchemaAttributeNames(*args, **kwargs) -> None: ... @staticmethod def GetStartAttr(*args, **kwargs) -> None: ... @staticmethod def GetTagAttr(*args, **kwargs) -> None: ... @staticmethod def _GetStaticTfType(*args, **kwargs) -> None: ... __instance_size__ = 40 pass class SkelJoint(pxr.UsdGeom.Boundable, pxr.UsdGeom.Xformable, pxr.UsdGeom.Imageable, pxr.Usd.Typed, pxr.Usd.SchemaBase, Boost.Python.instance): @staticmethod def CreateHideAttr(*args, **kwargs) -> None: ... @staticmethod def Define(*args, **kwargs) -> None: ... @staticmethod def Get(*args, **kwargs) -> None: ... @staticmethod def GetHideAttr(*args, **kwargs) -> None: ... @staticmethod def GetJoint(*args, **kwargs) -> None: ... @staticmethod def GetSchemaAttributeNames(*args, **kwargs) -> None: ... @staticmethod def _GetStaticTfType(*args, **kwargs) -> None: ... __instance_size__ = 40 pass class Tangent(Boost.Python.instance): @property def time(self) -> None: """ :type: None """ @property def type(self) -> None: """ :type: None """ @property def value(self) -> None: """ :type: None """ __instance_size__ = 40 pass class TangentControlStrategy(Boost.Python.instance): @staticmethod def ValidateInControl(*args, **kwargs) -> None: ... @staticmethod def ValidateOutControl(*args, **kwargs) -> None: ... __instance_size__ = 32 pass class Tokens(Boost.Python.instance): animationDataBinding = 'animationData:binding' auto_ = 'auto' constant = 'constant' cycle = 'cycle' cycleRelative = 'cycleRelative' defaultTangentType = 'defaultTangentType' end = 'end' fixed = 'fixed' flat = 'flat' hide = 'hide' inTangentTimes = 'inTangentTimes' inTangentTypes = 'inTangentTypes' inTangentValues = 'inTangentValues' linear = 'linear' oscillate = 'oscillate' outTangentTimes = 'outTangentTimes' outTangentTypes = 'outTangentTypes' outTangentValues = 'outTangentValues' postInfinityType = 'postInfinityType' preInfinityType = 'preInfinityType' smooth = 'smooth' start = 'start' step = 'step' tag = 'tag' tangentBrokens = 'tangentBrokens' tangentWeighteds = 'tangentWeighteds' times = 'times' values = 'values' pass class _CanApplyResult(Boost.Python.instance): @property def whyNot(self) -> None: """ :type: None """ __instance_size__ = 56 pass def GetTangentControlStrategy(*args, **kwargs) -> None: pass __MFB_FULL_PACKAGE_NAME = 'animationSchema'
omniverse-code/kit/exts/omni.usd.schema.anim/pxr/RetargetingSchema/_retargetingSchema.pyi
from __future__ import annotations import pxr.RetargetingSchema._retargetingSchema import typing import Boost.Python import pxr.Usd __all__ = [ "AnimationSkelBindingAPI", "ControlRigAPI", "JointConstraint" ] class AnimationSkelBindingAPI(pxr.Usd.APISchemaBase, pxr.Usd.SchemaBase, Boost.Python.instance): @staticmethod def Apply(*args, **kwargs) -> None: ... @staticmethod def BakeRetargetedSkelAnimation(*args, **kwargs) -> None: ... @staticmethod def CanApply(*args, **kwargs) -> None: ... @staticmethod def ComputeRetargetedJointLocalTransforms(*args, **kwargs) -> None: ... @staticmethod def CreateSourceSkeletonRel(*args, **kwargs) -> None: ... @staticmethod def Get(*args, **kwargs) -> None: ... @staticmethod def GetSchemaAttributeNames(*args, **kwargs) -> None: ... @staticmethod def GetSourceSkeleton(*args, **kwargs) -> None: ... @staticmethod def GetSourceSkeletonRel(*args, **kwargs) -> None: ... @staticmethod def _GetStaticTfType(*args, **kwargs) -> None: ... __instance_size__ = 48 pass class ControlRigAPI(pxr.Usd.APISchemaBase, pxr.Usd.SchemaBase, Boost.Python.instance): @staticmethod def Apply(*args, **kwargs) -> None: ... @staticmethod def CanApply(*args, **kwargs) -> None: ... @staticmethod def CreateForwardAxisAttr(*args, **kwargs) -> None: ... @staticmethod def CreateIKTargetsAttr(*args, **kwargs) -> None: ... @staticmethod def CreateJointConstraintsRel(*args, **kwargs) -> None: ... @staticmethod def CreateJointTagsAttr(*args, **kwargs) -> None: ... @staticmethod def CreateRetargetTagsAttr(*args, **kwargs) -> None: ... @staticmethod def CreateRetargetTransformsAttr(*args, **kwargs) -> None: ... @staticmethod def CreateTypeAttr(*args, **kwargs) -> None: ... @staticmethod def CreateUpAxisAttr(*args, **kwargs) -> None: ... @staticmethod def Get(*args, **kwargs) -> None: ... @staticmethod def GetForwardAxisAttr(*args, **kwargs) -> None: ... @staticmethod def GetIKTargetsAttr(*args, **kwargs) -> None: ... @staticmethod def GetJointConstraintsRel(*args, **kwargs) -> None: ... @staticmethod def GetJointTagsAttr(*args, **kwargs) -> None: ... @staticmethod def GetRetargetTagsAttr(*args, **kwargs) -> None: ... @staticmethod def GetRetargetTransformsAttr(*args, **kwargs) -> None: ... @staticmethod def GetSchemaAttributeNames(*args, **kwargs) -> None: ... @staticmethod def GetTypeAttr(*args, **kwargs) -> None: ... @staticmethod def GetUpAxisAttr(*args, **kwargs) -> None: ... @staticmethod def _GetStaticTfType(*args, **kwargs) -> None: ... __instance_size__ = 48 pass class JointConstraint(pxr.Usd.Typed, pxr.Usd.SchemaBase, Boost.Python.instance): @staticmethod def CreateFrameAttr(*args, **kwargs) -> None: ... @staticmethod def CreateJointAttr(*args, **kwargs) -> None: ... @staticmethod def CreateSwingAttr(*args, **kwargs) -> None: ... @staticmethod def CreateTwistAttr(*args, **kwargs) -> None: ... @staticmethod def Define(*args, **kwargs) -> None: ... @staticmethod def Get(*args, **kwargs) -> None: ... @staticmethod def GetFrameAttr(*args, **kwargs) -> None: ... @staticmethod def GetJointAttr(*args, **kwargs) -> None: ... @staticmethod def GetSchemaAttributeNames(*args, **kwargs) -> None: ... @staticmethod def GetSwingAttr(*args, **kwargs) -> None: ... @staticmethod def GetTwistAttr(*args, **kwargs) -> None: ... @staticmethod def _GetStaticTfType(*args, **kwargs) -> None: ... __instance_size__ = 40 pass class _CanApplyResult(Boost.Python.instance): @property def whyNot(self) -> None: """ :type: None """ __instance_size__ = 56 pass __MFB_FULL_PACKAGE_NAME = 'retargetingSchema'
omniverse-code/kit/exts/omni.usd.schema.anim/pxr/RetargetingSchema/__init__.py
# #==== # Copyright (c) 2018, NVIDIA CORPORATION #====== # # # Copyright 2016 Pixar # # Licensed under the Apache License, Version 2.0 (the "Apache License") # with the following modification; you may not use this file except in # compliance with the Apache License and the following modification to it: # Section 6. Trademarks. is deleted and replaced with: # # 6. Trademarks. This License does not grant permission to use the trade # names, trademarks, service marks, or product names of the Licensor # and its affiliates, except as required to comply with Section 4(c) of # the License and to reproduce the content of the NOTICE file. # # You may obtain a copy of the Apache License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the Apache License with the above modification is # distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the Apache License for the specific # language governing permissions and limitations under the Apache License. # import os import sys py38 = (3,8) current_version = sys.version_info if os.name == 'nt' and current_version >= py38: from pathlib import Path os.add_dll_directory(Path.joinpath(Path(os.path.dirname(__file__)), Path('..\\..\\')).__str__()) from . import _retargetingSchema from pxr import Tf Tf.PrepareModule(_retargetingSchema, locals()) del Tf try: import __DOC __DOC.Execute(locals()) del __DOC except Exception: try: import __tmpDoc __tmpDoc.Execute(locals()) del __tmpDoc except: pass
omniverse-code/kit/exts/omni.usd.schema.anim/pxr/RetargetingSchemaTools/__init__.py
# #==== # Copyright (c) 2021, NVIDIA CORPORATION #====== # # # Copyright 2016 Pixar # # Licensed under the Apache License, Version 2.0 (the "Apache License") # with the following modification; you may not use this file except in # compliance with the Apache License and the following modification to it: # Section 6. Trademarks. is deleted and replaced with: # # 6. Trademarks. This License does not grant permission to use the trade # names, trademarks, service marks, or product names of the Licensor # and its affiliates, except as required to comply with Section 4(c) of # the License and to reproduce the content of the NOTICE file. # # You may obtain a copy of the Apache License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the Apache License with the above modification is # distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the Apache License for the specific # language governing permissions and limitations under the Apache License. # import os import sys py38 = (3,8) current_version = sys.version_info if os.name == 'nt' and current_version >= py38: from pathlib import Path os.add_dll_directory(Path.joinpath(Path(os.path.dirname(__file__)), Path('..\\..\\')).__str__()) from . import _retargetingSchemaTools from pxr import Tf Tf.PrepareModule(_retargetingSchemaTools, locals()) del Tf try: import __DOC __DOC.Execute(locals()) del __DOC except Exception: try: import __tmpDoc __tmpDoc.Execute(locals()) del __tmpDoc except: pass
omniverse-code/kit/exts/omni.usd.schema.anim/pxr/RetargetingSchemaTools/_retargetingSchemaTools.pyi
from __future__ import annotations import pxr.RetargetingSchemaTools._retargetingSchemaTools import typing __all__ = [ "testSkelRoot", "verifySkelAnimation" ] def testSkelRoot(*args, **kwargs) -> None: pass def verifySkelAnimation(*args, **kwargs) -> None: pass __MFB_FULL_PACKAGE_NAME = 'retargetingSchemaTools'
omniverse-code/kit/exts/omni.usd.schema.anim/plugins/OmniSkelSchema/resources/generatedSchema.usda
#usda 1.0 ( "WARNING: THIS FILE IS GENERATED BY usdGenSchema. DO NOT EDIT." ) class OmniSkelBaseType "OmniSkelBaseType" ( doc = "based class of omniskeltype" ) { } class "OmniSkelBaseAPI" ( doc = "based class of omniskelschemaAPI" ) { } class "OmniSkeletonAPI" ( apiSchemas = ["OmniSkelBaseAPI"] doc = "omniverse skeleton API" ) { uniform token forwardAxis ( allowedTokens = ["X", "Y", "Z", "MINUS X", "MINUS Y", "MINUS Z"] displayName = "Forward Axis" doc = "Skeleton's rigging forwardAxis." ) uniform token upAxis ( allowedTokens = ["X", "Y", "Z", "MINUS X", "MINUS Y", "MINUS Z"] displayName = "Up Axis" doc = "Skeleton's rigging upAxis." ) } class OmniJoint "OmniJoint" ( doc = "omniverse skelton joint" ) { uniform float3 bindRotation = (0, 0, 0) ( displayName = "Bind Rotation" doc = "Euler rotation of the joint's bindTransform in local space, XYZ order." ) uniform float3 bindScale = (1, 1, 1) ( displayName = "Bind Scale" doc = "Scale of the joint's bindTransform in local space." ) uniform float3 bindTranslation = (0, 0, 0) ( displayName = "Bind Translation" doc = "Translation of the joint's bindTransform in local space." ) rel proxyPrim ( doc = '''The proxyPrim relationship allows us to link a prim whose purpose is "render" to its (single target) purpose="proxy" prim. This is entirely optional, but can be useful in several scenarios: - In a pipeline that does pruning (for complexity management) by deactivating prims composed from asset references, when we deactivate a purpose="render" prim, we will be able to discover and additionally deactivate its associated purpose="proxy" prim, so that preview renders reflect the pruning accurately. - DCC importers may be able to make more aggressive optimizations for interactive processing and display if they can discover the proxy for a given render prim. - With a little more work, a Hydra-based application will be able to map a picked proxy prim back to its render geometry for selection. \\note It is only valid to author the proxyPrim relationship on prims whose purpose is "render".''' ) uniform token purpose = "default" ( allowedTokens = ["default", "render", "proxy", "guide"] doc = """Purpose is a classification of geometry into categories that can each be independently included or excluded from traversals of prims on a stage, such as rendering or bounding-box computation traversals. See for more detail about how purpose is computed and used.""" ) uniform float3 restRotation = (0, 0, 0) ( displayName = "Rest Rotation" doc = "Euler rotation of the joint's restTransform in local space, XYZ order." ) uniform float3 restScale = (1, 1, 1) ( displayName = "Rest Scale" doc = "Scale of the joint's restTransform in local space." ) uniform float3 restTranslation = (0, 0, 0) ( displayName = "Rest Translation" doc = "Translation of the joint's restTransform in local space." ) uniform float3 retargetRotation = (0, 0, 0) ( displayName = "Retarget Rotation" doc = "Euler rotation of the joint's retargetTransform in local space, XYZ order." ) uniform float3 retargetScale = (1, 1, 1) ( displayName = "Retarget Scale" doc = "Scale of the joint's retargetTransform in local space." ) uniform token retargetTag ( displayName = "Retarget Tag" doc = "Tag name of this joint, used for retargeting." ) uniform float3 retargetTranslation = (0, 0, 0) ( displayName = "Retarget Translation" doc = "Translation of the joint's retargetTransform in local space." ) token visibility = "inherited" ( allowedTokens = ["inherited", "invisible"] doc = '''Visibility is meant to be the simplest form of "pruning" visibility that is supported by most DCC apps. Visibility is animatable, allowing a sub-tree of geometry to be present for some segment of a shot, and absent from others; unlike the action of deactivating geometry prims, invisible geometry is still available for inspection, for positioning, for defining volumes, etc.''' ) uniform token[] xformOpOrder ( doc = """Encodes the sequence of transformation operations in the order in which they should be pushed onto a transform stack while visiting a UsdStage's prims in a graph traversal that will effect the desired positioning for this prim and its descendant prims. You should rarely, if ever, need to manipulate this attribute directly. It is managed by the AddXformOp(), SetResetXformStack(), and SetXformOpOrder(), and consulted by GetOrderedXformOps() and GetLocalTransformation().""" ) } class "OmniJointLimitsAPI" ( apiSchemas = ["OmniSkelBaseAPI"] doc = "omniverse skeleton joint limits" ) { uniform bool enabled = 1 ( displayName = "Enabled" doc = "joint limits enabled or not" ) uniform double3 offsetRotation = (0, 0, 0) ( displayName = "Offset Rotation" doc = "rotation represented with EulerXYZ in local space" ) uniform float swingHorizontalAngle = 0 ( displayName = "Swing Horizontal Angle" doc = "swing horizontal angle in degree." ) uniform float swingVerticalAngle = 0 ( displayName = "Swing Vertical Angle" doc = "swing swingHorizontalAngle angle in degree." ) uniform float twistMaximumAngle = 0 ( displayName = "Twist Maximum Angle" doc = "maximum twist angle in degree." ) uniform float twistMinimumAngle = 0 ( displayName = "Twist Mininum Angle" doc = "minimum twist angle in degree." ) } class "OmniJointShapeAPI" ( apiSchemas = ["OmniSkelBaseAPI"] doc = "base class of different kinds of omniverse skeleton joint shapes" ) { uniform double3 xformOp:rotateXYZ = (0, 0, 0) ( doc = "rotation represented with EulerXYZ in local space" ) uniform double3 xformOp:scale = (1, 1, 1) ( doc = "scale in local space." ) uniform double3 xformOp:translate = (0, 0, 0) ( doc = "ranslation in local space." ) uniform token[] xformOpOrder = ["xformOp:translate", "xformOp:rotateXYZ", "xformOp:scale"] ( doc = "Xform Order." ) } class "OmniJointBoxShapeAPI" ( apiSchemas = ["OmniSkelBaseAPI", "OmniJointShapeAPI"] doc = "omniverse skeleton joint box shape" ) { } class "OmniJointSphereShapeAPI" ( apiSchemas = ["OmniSkelBaseAPI", "OmniJointShapeAPI"] doc = "omniverse skeleton joint sphere shape" ) { } class "OmniJointCapsuleShapeAPI" ( apiSchemas = ["OmniSkelBaseAPI", "OmniJointShapeAPI"] doc = "omniverse skeleton joint capsule shape" ) { }
omniverse-code/kit/exts/omni.usd.schema.anim/plugins/OmniSkelSchema/resources/OmniSkelSchema/schema.usda
#usda 1.0 ( """ This file contains a schema for omniverse skeleton. """ subLayers = [ @usdGeom/schema.usda@, @usdSkel/schema.usda@, ] ) over "GLOBAL" ( customData = { string libraryName = "omniSkelSchema" string libraryPath = "./" string libraryPrefix = "OmniSkelSchema" } ) { } class OmniSkelBaseType "OmniSkelBaseType" ( doc = """based class of omniskeltype""" inherits = </Typed> ) { } class "OmniSkelBaseAPI" ( doc = """based class of omniskelschemaAPI""" inherits = </APISchemaBase> ) { } class "OmniSkeletonAPI" ( doc = """omniverse skeleton API""" inherits = </APISchemaBase> prepend apiSchemas = ["OmniSkelBaseAPI"] customData = { token apiSchemaType = "singleApply" } customData = { string extraIncludes = """ #include "pxr/usd/usdSkel/skeleton.h" """ } ) { uniform token upAxis( allowedTokens = ["X", "Y", "Z", "MINUS X", "MINUS Y", "MINUS Z"] customData = { string apiName = "upAxis" } doc = """Skeleton's rigging upAxis.""" displayName = "Up Axis" ) uniform token forwardAxis( allowedTokens = ["X", "Y", "Z", "MINUS X", "MINUS Y", "MINUS Z"] customData = { string apiName = "forwardAxis" } doc = """Skeleton's rigging forwardAxis.""" displayName = "Forward Axis" ) } class OmniJoint "OmniJoint" ( doc = """omniverse skelton joint""" inherits = </Xform> customData = { string extraIncludes = """ #include "pxr/usd/usdSkel/skeleton.h" """ } ) { uniform float3 bindTranslation = (0.0, 0.0, 0.0) ( doc = """Translation of the joint's bindTransform in local space.""" displayName = "Bind Translation" ) uniform float3 bindRotation = (0.0, 0.0, 0.0) ( doc = """Euler rotation of the joint's bindTransform in local space, XYZ order.""" displayName = "Bind Rotation" ) uniform float3 bindScale = (1.0, 1.0, 1.0) ( doc = """Scale of the joint's bindTransform in local space.""" displayName = "Bind Scale" ) uniform token retargetTag( doc = """Tag name of this joint, used for retargeting.""" displayName = "Retarget Tag" ) uniform float3 retargetTranslation = (0.0, 0.0, 0.0) ( doc = """Translation of the joint's retargetTransform in local space.""" displayName = "Retarget Translation" ) uniform float3 retargetRotation = (0.0, 0.0, 0.0) ( doc = """Euler rotation of the joint's retargetTransform in local space, XYZ order.""" displayName = "Retarget Rotation" ) uniform float3 retargetScale = (1.0, 1.0, 1.0) ( doc = """Scale of the joint's retargetTransform in local space.""" displayName = "Retarget Scale" ) uniform float3 restTranslation = (0.0, 0.0, 0.0) ( doc = """Translation of the joint's restTransform in local space.""" displayName = "Rest Translation" ) uniform float3 restRotation = (0.0, 0.0, 0.0) ( doc = """Euler rotation of the joint's restTransform in local space, XYZ order.""" displayName = "Rest Rotation" ) uniform float3 restScale = (1.0, 1.0, 1.0) ( doc = """Scale of the joint's restTransform in local space.""" displayName = "Rest Scale" ) } class "OmniJointLimitsAPI" ( doc = """omniverse skeleton joint limits""" inherits = </APISchemaBase> prepend apiSchemas = ["OmniSkelBaseAPI"] ) { uniform float swingHorizontalAngle = 0.0 ( doc = """swing horizontal angle in degree.""" displayName = "Swing Horizontal Angle" ) uniform float swingVerticalAngle = 0.0 ( doc = """swing swingHorizontalAngle angle in degree.""" displayName = "Swing Vertical Angle" ) uniform float twistMinimumAngle = 0.0 ( doc = """minimum twist angle in degree.""" displayName = "Twist Mininum Angle" ) uniform float twistMaximumAngle = 0.0 ( doc = """maximum twist angle in degree.""" displayName = "Twist Maximum Angle" ) uniform double3 offsetRotation = (0, 0, 0) ( doc = """rotation represented with EulerXYZ in local space""" displayName = "Offset Rotation" ) uniform bool enabled = true ( doc = """joint limits enabled or not""" displayName = "Enabled" ) } class "OmniJointShapeAPI" ( doc = """base class of different kinds of omniverse skeleton joint shapes""" inherits = </APISchemaBase> prepend apiSchemas = ["OmniSkelBaseAPI"] customData = { string extraIncludes = """ #include "pxr/usd/usdGeom/gprim.h" """ } ) { uniform double3 xformOp:translate = (0, 0, 0) ( doc = """ranslation in local space.""" ) uniform double3 xformOp:rotateXYZ = (0, 0, 0) ( doc = """rotation represented with EulerXYZ in local space""" ) uniform double3 xformOp:scale = (1, 1, 1) ( doc = """scale in local space.""" ) uniform token[] xformOpOrder = ["xformOp:translate", "xformOp:rotateXYZ", "xformOp:scale"] ( doc = """Xform Order.""" ) } class "OmniJointBoxShapeAPI" ( doc = """omniverse skeleton joint box shape""" inherits = </APISchemaBase> prepend apiSchemas = ["OmniSkelBaseAPI", "OmniJointShapeAPI"] customData = { token apiSchemaType = "singleApply" } customData = { string extraIncludes = """ #include "./omniJointShapeAPI.h" #include "pxr/usd/usdGeom/cube.h" #include "pxr/usd/usdGeom/xformCache.h" """ } ) { } class "OmniJointSphereShapeAPI" ( doc = """omniverse skeleton joint sphere shape""" inherits = </APISchemaBase> prepend apiSchemas = ["OmniSkelBaseAPI", "OmniJointShapeAPI"] customData = { token apiSchemaType = "singleApply" } customData = { string extraIncludes = """ #include "pxr/usd/usdGeom/sphere.h" #include "pxr/usd/usdGeom/xformCache.h" """ } ) { } class "OmniJointCapsuleShapeAPI" ( doc = """omniverse skeleton joint capsule shape""" inherits = </APISchemaBase> prepend apiSchemas = ["OmniSkelBaseAPI", "OmniJointShapeAPI"] customData = { token apiSchemaType = "singleApply" } customData = { string extraIncludes = """ #include "pxr/usd/usdGeom/capsule.h" #include "pxr/usd/usdGeom/xformCache.h" """ } ) { }
omniverse-code/kit/exts/omni.usd.schema.anim/plugins/AnimationSchema/resources/generatedSchema.usda
#usda 1.0 ( "WARNING: THIS FILE IS GENERATED BY usdGenSchema. DO NOT EDIT." ) class SkelJoint "SkelJoint" ( doc = "SkelJoint represents a skeleton joint" ) { float3[] extent ( doc = """Extent is a three dimensional range measuring the geometric extent of the authored gprim in its own local space (i.e. its own transform not applied), without accounting for any shader-induced displacement. If __any__ extent value has been authored for a given Boundable, then it should be authored at every timeSample at which geometry-affecting properties are authored, to ensure correct evaluation via ComputeExtent(). If __no__ extent value has been authored, then ComputeExtent() will call the Boundable's registered ComputeExtentFunction(), which may be expensive, which is why we strongly encourage proper authoring of extent. \\sa ComputeExtent() \\sa \\ref UsdGeom_Boundable_Extent. An authored extent on a prim which has children is expected to include the extent of all children, as they will be pruned from BBox computation during traversal.""" ) bool hide = 0 ( doc = "Additional visibility flag to hide individual joint prim." ) rel proxyPrim ( doc = '''The proxyPrim relationship allows us to link a prim whose purpose is "render" to its (single target) purpose="proxy" prim. This is entirely optional, but can be useful in several scenarios: - In a pipeline that does pruning (for complexity management) by deactivating prims composed from asset references, when we deactivate a purpose="render" prim, we will be able to discover and additionally deactivate its associated purpose="proxy" prim, so that preview renders reflect the pruning accurately. - DCC importers may be able to make more aggressive optimizations for interactive processing and display if they can discover the proxy for a given render prim. - With a little more work, a Hydra-based application will be able to map a picked proxy prim back to its render geometry for selection. \\note It is only valid to author the proxyPrim relationship on prims whose purpose is "render".''' ) uniform token purpose = "default" ( allowedTokens = ["default", "render", "proxy", "guide"] doc = """Purpose is a classification of geometry into categories that can each be independently included or excluded from traversals of prims on a stage, such as rendering or bounding-box computation traversals. See for more detail about how purpose is computed and used.""" ) token visibility = "inherited" ( allowedTokens = ["inherited", "invisible"] doc = '''Visibility is meant to be the simplest form of "pruning" visibility that is supported by most DCC apps. Visibility is animatable, allowing a sub-tree of geometry to be present for some segment of a shot, and absent from others; unlike the action of deactivating geometry prims, invisible geometry is still available for inspection, for positioning, for defining volumes, etc.''' ) uniform token[] xformOpOrder ( doc = """Encodes the sequence of transformation operations in the order in which they should be pushed onto a transform stack while visiting a UsdStage's prims in a graph traversal that will effect the desired positioning for this prim and its descendant prims. You should rarely, if ever, need to manipulate this attribute directly. It is managed by the AddXformOp(), SetResetXformStack(), and SetXformOpOrder(), and consulted by GetOrderedXformOps() and GetLocalTransformation().""" ) } class SkelAnimationAnnotation "SkelAnimationAnnotation" ( doc = "Creates an annotation for a parent SkelAnimation that contains annotation tag and start/end range." ) { int end = 0 ( displayName = "End" doc = "The end offset." ) int start = 0 ( displayName = "Start" doc = "The start offset." ) token tag ( displayName = "Tag" doc = "The tag name." ) } class "AnimationCurveAPI" ( doc = "An API accessing curves." ) { } class AnimationData "AnimationData" ( doc = "Curve-based Animation data prim" ) { } class "AnimationDataAPI" ( doc = "Applied API for any prim who wants to link to an AnimationData prim for curve-based animation " ) { rel animationData:binding ( doc = " Relationship to link the prim to an AnimationData prim " ) }
omniverse-code/kit/exts/omni.usd.schema.anim/plugins/AnimationSchema/resources/AnimationSchema/schema.usda
#usda 1.0 ( """ This file contains a schema for supporting skeletal animations in USD. """ subLayers = [ @usdGeom/schema.usda@, @usdSkel/schema.usda@, ] ) over "GLOBAL" ( customData = { string libraryName = "animationSchema" string libraryPath = "./" string libraryPrefix = "AnimationSchema" } ) { } class SkelJoint "SkelJoint" ( doc = """SkelJoint represents a skeleton joint""" inherits = </Boundable> customData = { string extraIncludes = """ #include "pxr/usd/usdSkel/skeleton.h" """ } ) { bool hide = false( doc = "Additional visibility flag to hide individual joint prim." ) } class SkelAnimationAnnotation "SkelAnimationAnnotation" ( doc = """Creates an annotation for a parent SkelAnimation that contains annotation tag and start/end range.""" inherits = </Typed> ) { token tag ( doc = """The tag name.""" displayName = "Tag" ) int start = 0 ( doc = """The start offset.""" displayName = "Start" ) int end = 0 ( doc = """The end offset.""" displayName = "End" ) } class "AnimationCurveAPI" ( doc = """An API accessing curves.""" inherits = </APISchemaBase> customData = { token apiSchemaType = "nonApplied" string extraIncludes = """ #include "animationCurveTypes.h" """ dictionary schemaTokens = { dictionary values = {} dictionary times = {} dictionary inTangentValues = {} dictionary inTangentTimes = {} dictionary inTangentTypes = {} dictionary outTangentValues = {} dictionary outTangentTimes = {} dictionary outTangentTypes = {} dictionary tangentBrokens = {} dictionary tangentWeighteds = {} dictionary defaultTangentType = {} dictionary preInfinityType = {} dictionary postInfinityType = {} dictionary auto = {} dictionary smooth = {} dictionary flat = {} dictionary fixed = {} dictionary linear = {} dictionary step = {} dictionary constant = {} dictionary cycle = {} dictionary linear = {} dictionary cycleRelative = {} dictionary oscillate = {} } } ) { } class AnimationData "AnimationData" ( doc = """Curve-based Animation data prim""" inherits = </Typed> ) { } class "AnimationDataAPI" ( doc = """Applied API for any prim who wants to link to an AnimationData prim for curve-based animation """ inherits = </APISchemaBase> ) { rel animationData:binding ( doc = """ Relationship to link the prim to an AnimationData prim """ ) }
omniverse-code/kit/exts/omni.usd.schema.anim/plugins/RetargetingSchema/resources/generatedSchema.usda
#usda 1.0 ( "WARNING: THIS FILE IS GENERATED BY usdGenSchema. DO NOT EDIT." ) class "AnimationSkelBindingAPI" ( doc = "Provides API for setting source skeleton and evaluating retrargeted pose or bake retargeted plain SkelAnimation." ) { rel animationSkelBinding:sourceSkeleton ( doc = "Skeleton to be bound to animation prims to tell the animation was authored based on this source skeleton" ) } class "ControlRigAPI" ( doc = "Provides API for seting control rig information for skeleton prim" ) { uniform token controlRig:forwardAxis ( allowedTokens = ["X", "Y", "Z", "MINUS X", "MINUS Y", "MINUS Z"] doc = "Skeleton's rigging forwardAxis. If not authored, it should be aligned with stage metrics" ) uniform token[] controlRig:IKTargets ( doc = "list of joints that can receive desired target transform for full body IK" ) rel controlRig:jointConstraints ( doc = "Ordered list of all joint constraints" ) uniform token[] controlRig:jointTags ( doc = "An array of tokens identifying rig joint tags for each joint of skeleton prim" ) uniform token[] controlRig:retargetTags ( doc = "An array of tokens identifying retarget tags for each joint of skeleton prim" ) uniform matrix4d[] controlRig:retargetTransforms ( doc = """Specifies the retarget pose transforms of each joint in\r **local space**, in the ordering imposed by *joints*. If this attribute\r \t\tdoes not have authoring value, restTransforms of the skeleton will be\r \t\tused as fallback,""" ) uniform token controlRig:type ( doc = "The skeleton control rig type. " ) uniform token controlRig:upAxis ( allowedTokens = ["X", "Y", "Z", "MINUS X", "MINUS Y", "MINUS Z"] doc = "Skeleton's rigging upAxis. If not authored, it should be aligned with stage metrics" ) } class JointConstraint "JointConstraint" ( doc = "SkelJoint represents a skeleton joint" ) { uniform quatf frame uniform token joint uniform float2 swing uniform float2 twist }
omniverse-code/kit/exts/omni.usd.schema.anim/plugins/RetargetingSchema/resources/RetargetingSchema/schema.usda
#usda 1.0 ( """ This file contains a schema for supporting skeletal animations in USD. """ subLayers = [ @usdGeom/schema.usda@, @usdSkel/schema.usda@, ] ) over "GLOBAL" ( customData = { string libraryName = "retargetingSchema" string libraryPath = "./" string libraryPrefix = "RetargetingSchema" } ) { } class "AnimationSkelBindingAPI" ( inherits = </APISchemaBase> doc = """Provides API for setting source skeleton and evaluating retrargeted pose or bake retargeted plain SkelAnimation.""" customData = { string extraIncludes = """ #include "pxr/usd/usdSkel/animation.h" #include "pxr/usd/usdSkel/skeleton.h" #include "pxr/usd/usdSkel/bindingAPI.h" """ } ) { rel animationSkelBinding:sourceSkeleton ( customData = { string apiName = "sourceSkeleton" } doc = """Skeleton to be bound to animation prims to tell the animation was authored based on this source skeleton""" ) } class "ControlRigAPI" ( inherits = </APISchemaBase> doc = """Provides API for seting control rig information for skeleton prim""" customData = { string extraIncludes = """ #include "pxr/usd/usdSkel/skeleton.h" """ } ) { uniform token controlRig:type( customData = { string apiName = "type" } doc = """The skeleton control rig type. """ ) uniform token controlRig:upAxis( allowedTokens = ["X", "Y", "Z", "MINUS X", "MINUS Y", "MINUS Z"] customData = { string apiName = "upAxis" } doc = """Skeleton's rigging upAxis. If not authored, it should be aligned with stage metrics""" ) uniform token controlRig:forwardAxis( allowedTokens = ["X", "Y", "Z", "MINUS X", "MINUS Y", "MINUS Z"] customData = { string apiName = "forwardAxis" } doc = """Skeleton's rigging forwardAxis. If not authored, it should be aligned with stage metrics""" ) uniform token[] controlRig:jointTags ( customData = { string apiName = "jointTags" } doc = """An array of tokens identifying rig joint tags for each joint of skeleton prim""" ) uniform token[] controlRig:retargetTags ( customData = { string apiName = "retargetTags" } doc = """An array of tokens identifying retarget tags for each joint of skeleton prim""" ) uniform matrix4d[] controlRig:retargetTransforms ( customData = { string apiName = "retargetTransforms" } doc = """Specifies the retarget pose transforms of each joint in **local space**, in the ordering imposed by *joints*. If this attribute does not have authoring value, restTransforms of the skeleton will be used as fallback,""" ) uniform token[] controlRig:IKTargets( customData = { string apiName = "IKTargets" } doc = """list of joints that can receive desired target transform for full body IK""" ) rel controlRig:jointConstraints( customData = { string apiName= "jointConstraints" } doc = """Ordered list of all joint constraints""" ) } class JointConstraint "JointConstraint" ( doc = """SkelJoint represents a skeleton joint""" inherits = </Typed> ) { uniform token joint uniform quatf frame uniform float2 swing uniform float2 twist }
omniverse-code/kit/exts/omni.hydra.ui/omni/hydra/ui/__init__.py
from .scripts.extension import *
omniverse-code/kit/exts/omni.hydra.ui/omni/hydra/ui/scripts/extension.py
import omni.ext from .settings import OmniHydraSettings class PublicExtension(omni.ext.IExt): def on_startup(self): self._settings = OmniHydraSettings() def on_shutdown(self): self._settings = None
omniverse-code/kit/exts/omni.hydra.ui/omni/hydra/ui/scripts/settings.py
import asyncio import omni.ui import omni.kit.app import omni.kit.commands import carb.settings ### Copied from omni.phyx; Kit team will coalesce into omni.ui.settings module class Model(omni.ui.AbstractValueModel): def __init__(self, path): super().__init__() self._path = path val = carb.settings.get_settings().get(path) if val is None: val = 0 self._value = val def on_change(item, event_type, path=path): self._value = carb.settings.get_settings().get(path) self._value_changed() self._sub = omni.kit.app.SettingChangeSubscription(path, on_change) def get_value_as_bool(self): return self._value def get_value_as_int(self): return self._value def get_value_as_float(self): return self._value def get_value_as_string(self): return self._value def set_value(self, value): omni.kit.commands.execute("ChangeSetting", path=self._path, value=value) self._value = value self._value_changed() def create_setting_widget(setting_path, cls, **kwargs): model = Model(setting_path) widget = cls(model, **kwargs) return (model, widget) ### end omni.physx boilerplate class OmniHydraSettings(omni.ui.Window): def __init__(self): self._title = "OmniHydra Developer Settings" super().__init__(self._title, omni.ui.DockPreference.LEFT_BOTTOM, width=800, height=600) self._widgets = [] with self.frame: self._build_ui() asyncio.ensure_future(self._dock_window(self._title, omni.ui.DockPosition.SAME)) async def _dock_window(self, window_title: str, position: omni.ui.DockPosition, ratio: float = 1.0): frames = 3 while frames > 0: if omni.ui.Workspace.get_window(window_title): break frames = frames - 1 await omni.kit.app.get_app().next_update_async() window = omni.ui.Workspace.get_window(window_title) dockspace = omni.ui.Workspace.get_window("Property") if window and dockspace: window.dock_in(dockspace, position, ratio=ratio) window.dock_tab_bar_visible = False def on_shutdown(self): self._widgets = [] def _add_setting_widget(self, name, path, cls, **kwargs): with omni.ui.VStack(): omni.ui.Spacer(height=2) with omni.ui.HStack(height=20): self._widgets.append(create_setting_widget(path, cls, **kwargs)) omni.ui.Label(name) def _build_settings_ui(self): self._add_setting_widget("Use fast scene delegate", "/persistent/omnihydra/useFastSceneDelegate", omni.ui.CheckBox) self._add_setting_widget("Use scene graph instancing", "/persistent/omnihydra/useSceneGraphInstancing", omni.ui.CheckBox) self._add_setting_widget("Use skel adapter", "/persistent/omnihydra/useSkelAdapter", omni.ui.CheckBox) self._add_setting_widget("Use skel adapter blendshape", "/persistent/omnihydra/useSkelAdapterBlendShape", omni.ui.CheckBox) self._add_setting_widget("Use skel adapter deform graph", "/persistent/omnihydra/useSkelAdapterDeformGraph", omni.ui.CheckBox) self._add_setting_widget("Use cached xform time samples", "/persistent/omnihydra/useCachedXformTimeSamples", omni.ui.CheckBox) self._add_setting_widget("Use async RenderGraph in _PullFromRingBuffer", "/persistent/omnihydra/useAsyncRenderGraph", omni.ui.CheckBox) self._add_setting_widget("Use fast xform path from Fabric to renderer", "/persistent/rtx/hydra/readTransformsFromFabricInRenderDelegate", omni.ui.CheckBox) def _build_usdrt_settings_ui(self): self._add_setting_widget("Use Fabric World Bounds", "/app/omni.usd/useFabricWorldBounds", omni.ui.CheckBox) self._add_setting_widget("Use camera-based priority sorting", "/app/usdrt/scene_delegate/useWorldInterestBasedSorting", omni.ui.CheckBox) self._add_setting_widget("GPU Memory Budget %", "/app/usdrt/scene_delegate/gpuMemoryBudgetPercent", omni.ui.FloatSlider, min=0., max=100.) with omni.ui.CollapsableFrame("Geometry Streaming"): with omni.ui.VStack(): self._add_setting_widget("Enable geometry streaming", "/app/usdrt/scene_delegate/geometryStreaming/enabled", omni.ui.CheckBox) self._add_setting_widget("Enable proxy cubes for unloaded prims", "/app/usdrt/scene_delegate/enableProxyCubes", omni.ui.CheckBox) self._add_setting_widget("Solid Angle Loading To Load in first batch", "/app/usdrt/scene_delegate/geometryStreaming/solidAngleToLoadInFirstChunk", omni.ui.FloatSlider, min=0, max=1, step=0.0001) self._add_setting_widget("Solid Angle Loading Limit", "/app/usdrt/scene_delegate/geometryStreaming/solidAngleLimit", omni.ui.FloatSlider, min=0, max=1, step=0.0001) self._add_setting_widget("Solid Angle Loading Limit Divider", "/app/usdrt/scene_delegate/geometryStreaming/solidAngleLimitDivider", omni.ui.FloatSlider, min=1, max=10000, step=100) self._add_setting_widget("Number of frames between batches", "/app/usdrt/scene_delegate/numFramesBetweenLoadBatches", omni.ui.IntSlider, min=1, max=50) self._add_setting_widget("Number of vertices to load per batch", "/app/usdrt/scene_delegate/geometryStreaming/numberOfVerticesToLoadPerChunk", omni.ui.IntSlider, min=1, max=5000000) self._add_setting_widget("Number of vertices to unload per batch", "/app/usdrt/scene_delegate/geometryStreaming/numberOfVerticesToUnloadPerChunk", omni.ui.IntSlider, min=1, max=5000000) self._add_setting_widget("Number of cubes proxy instances per instancer", "/app/usdrt/scene_delegate/proxyInstanceBucketSize", omni.ui.IntSlider, min=0, max=200000) with omni.ui.CollapsableFrame("Memory Budget Experimental Stability Values"): with omni.ui.VStack(): self._add_setting_widget("Update Delay in microseconds", "/app/usdrt/scene_delegate/updateDelayInMicroSeconds", omni.ui.IntSlider, min=0, max=1000000) self._add_setting_widget("GPU Memory Deadzone %", "/app/usdrt/scene_delegate/gpuMemoryBudgetDeadZone", omni.ui.FloatSlider, min=0., max=50.) self._add_setting_widget("GPU Memory Filter Damping", "/app/usdrt/scene_delegate/gpuMemoryFilterDamping", omni.ui.FloatSlider, min=0., max=2.) with omni.ui.CollapsableFrame("Memory Limit Testing (pretend values)"): with omni.ui.VStack(): self._add_setting_widget("Enable memory testing", "/app/usdrt/scene_delegate/testing/enableMemoryTesting", omni.ui.CheckBox) self._add_setting_widget("GPU Memory Available", "/app/usdrt/scene_delegate/testing/availableDeviceMemory", omni.ui.FloatSlider, min=0., max=float(1024*1024*1024*8)) self._add_setting_widget("GPU Memory Total", "/app/usdrt/scene_delegate/testing/totalDeviceMemory", omni.ui.FloatSlider, min=0., max=float(1024*1024*1024*8)) with omni.ui.CollapsableFrame("USD Population (reload scene to see effect)"): with omni.ui.VStack(): self._add_setting_widget("Read Curves", "/app/usdrt/population/utils/readCurves", omni.ui.CheckBox) self._add_setting_widget("Read Materials", "/app/usdrt/population/utils/readMaterials", omni.ui.CheckBox) self._add_setting_widget("Read Lights", "/app/usdrt/population/utils/readLights", omni.ui.CheckBox) self._add_setting_widget("Read Primvars", "/app/usdrt/population/utils/readPrimvars", omni.ui.CheckBox) self._add_setting_widget("Enable Subcomponent merging", "/app/usdrt/population/utils/mergeSubcomponents", omni.ui.CheckBox) self._add_setting_widget("Enable Instance merging", "/app/usdrt/population/utils/mergeInstances", omni.ui.CheckBox) self._add_setting_widget("Enable Material merging", "/app/usdrt/population/utils/mergeMaterials", omni.ui.CheckBox) self._add_setting_widget("Single-threaded population", "/app/usdrt/population/utils/singleThreaded", omni.ui.CheckBox) self._add_setting_widget("Disable Light Scaling (non-RTX delegates)", "/app/usdrt/scene_delegate/disableLightScaling", omni.ui.CheckBox) self._add_setting_widget("Use Fabric Scene Graph Instancing", "/app/usdrt/population/utils/handleSceneGraphInstances", omni.ui.CheckBox) self._add_setting_widget("Use Hydra BlendShape", "/app/usdrt/scene_delegate/useHydraBlendShape", omni.ui.CheckBox) self._add_setting_widget("Number of IO threads", "/app/usdrt/population/utils/ioBoundThreadCount", omni.ui.IntSlider, min=1, max=16) def _build_section(self, name, build_func): with omni.ui.CollapsableFrame(name, height=0): with omni.ui.HStack(): omni.ui.Spacer(width=20, height=5) with omni.ui.VStack(): build_func() def _build_ui(self): with omni.ui.ScrollingFrame(horizontal_scrollbar_policy=omni.ui.ScrollBarPolicy.SCROLLBAR_ALWAYS_OFF, vertical_scrollbar_policy=omni.ui.ScrollBarPolicy.SCROLLBAR_AS_NEEDED): with omni.ui.VStack(): self._build_section("Settings (requires stage reload)", self._build_settings_ui) self._build_section("USDRT Hydra Settings", self._build_usdrt_settings_ui)
omniverse-code/kit/exts/omni.kit.window.extensions/ext_template/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 $@
omniverse-code/kit/exts/omni.kit.window.extensions/ext_template/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%
omniverse-code/kit/exts/omni.kit.window.extensions/ext_template/README.md
# Extension Project Template This project was automatically generated. - `app` - It is a folder link to the location of your *Omniverse Kit* based app. - `exts` - It is a folder where you can add new extensions. It was automatically added to extension search path. (Extension Manager -> Gear Icon -> Extension Search Path). Open this folder using Visual Studio Code. It will suggest you to install few extensions that will make python experience better. Look for "${ext_id}" extension in extension manager and enable it. Try applying changes to any python files, it will hot-reload and you can observe results immediately. Alternatively, you can launch your app from console with this folder added to search path and your extension enabled, e.g.: ``` > app\omni.code.bat --ext-folder exts --enable company.hello.world ``` # App Link Setup If `app` folder link doesn't exist or broken it can be created again. For better developer experience it is recommended to create a folder link named `app` to the *Omniverse Kit* app installed from *Omniverse Launcher*. Convenience script to use is included. Run: ``` > link_app.bat ``` If successful you should see `app` folder link in the root of this repo. If multiple Omniverse apps is installed script will select recommended one. Or you can explicitly pass an app: ``` > link_app.bat --app create ``` You can also just pass a path to create link to: ``` > link_app.bat --path "C:/Users/bob/AppData/Local/ov/pkg/create-2021.3.4" ``` # Sharing Your Extensions This folder is ready to be pushed to any git repository. Once pushed direct link to a git repository can be added to *Omniverse Kit* extension search paths. Link might look like this: `git://github.com/[user]/[your_repo].git?branch=main&dir=exts` Notice `exts` is repo subfolder with extensions. More information can be found in "Git URL as Extension Search Paths" section of developers manual. To add a link to your *Omniverse Kit* based app go into: Extension Manager -> Gear Icon -> Extension Search Path
omniverse-code/kit/exts/omni.kit.window.extensions/ext_template/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!")
omniverse-code/kit/exts/omni.kit.window.extensions/ext_template/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 "$@"
omniverse-code/kit/exts/omni.kit.window.extensions/ext_template/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 %*
omniverse-code/kit/exts/omni.kit.window.extensions/ext_template/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
omniverse-code/kit/exts/omni.kit.window.extensions/ext_template/tools/packman/config.packman.xml
<config remotes="cloudfront"> <remote2 name="cloudfront"> <transport actions="download" protocol="https" packageLocation="d4i3qtqj3r0z5.cloudfront.net/${name}@${version}" /> </remote2> </config>
omniverse-code/kit/exts/omni.kit.window.extensions/ext_template/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
omniverse-code/kit/exts/omni.kit.window.extensions/ext_template/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
omniverse-code/kit/exts/omni.kit.window.extensions/ext_template/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
omniverse-code/kit/exts/omni.kit.window.extensions/ext_template/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)
omniverse-code/kit/exts/omni.kit.window.extensions/ext_template/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
omniverse-code/kit/exts/omni.kit.window.extensions/ext_template/tools/packman/bootstrap/install_package.py
# Copyright 2019 NVIDIA CORPORATION # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # http://www.apache.org/licenses/LICENSE-2.0 # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import logging import shutil import sys import tempfile import zipfile __author__ = "hfannar" logging.basicConfig(level=logging.WARNING, format="%(message)s") logger = logging.getLogger("install_package") class TemporaryDirectory: def __init__(self): self.path = None def __enter__(self): self.path = tempfile.mkdtemp() return self.path def __exit__(self, type, value, traceback): # Remove temporary data created shutil.rmtree(self.path) def install_package(package_src_path, package_dst_path): with zipfile.ZipFile(package_src_path, allowZip64=True) as zip_file, TemporaryDirectory() as temp_dir: zip_file.extractall(temp_dir) # Recursively copy (temp_dir will be automatically cleaned up on exit) try: # Recursive copy is needed because both package name and version folder could be missing in # target directory: shutil.copytree(temp_dir, package_dst_path) except OSError as exc: logger.warning("Directory %s already present, packaged installation aborted" % package_dst_path) else: logger.info("Package successfully installed to %s" % package_dst_path) install_package(sys.argv[1], sys.argv[2])
omniverse-code/kit/exts/omni.kit.window.extensions/ext_template/vscode/settings.json
{ "files.associations": { "*.kit": "toml", }, "editor.rulers": [120], // Python modules search paths: "python.analysis.extraPaths": [ "${workspaceFolder}/exts/${ext_id}", "${workspaceFolder}/app/${kit_subpath}extscore/omni.kit.pip_archive/pip_prebundle", "${workspaceFolder}/app/${kit_subpath}kernel/py", "${workspaceFolder}/app/${kit_subpath}plugins/bindings-python", ${ext_search_paths} ], // Python & Pylance Setup "python.languageServer": "Pylance", "python.pythonPath": "${workspaceFolder}/app/${kit_subpath}python/${python_exe}", "python.defaultInterpreterPath": "${workspaceFolder}/app/${kit_subpath}python/${python_exe}", // We use "black" as a formatter: "python.formatting.provider": "black", "python.formatting.blackArgs": ["--line-length", "120"], // Use flake8 for linting "python.linting.enabled": true, "python.linting.pylintEnabled": false, "python.linting.flake8Enabled": true, "python.linting.flake8Args": ["--max-line-length=120"] }
omniverse-code/kit/exts/omni.kit.window.extensions/ext_template/vscode/extensions.json
{ // See http://go.microsoft.com/fwlink/?LinkId=827846 // for the documentation about the extensions.json format "recommendations": [ "ms-vscode.cpptools", "ms-python.python", "ms-python.vscode-pylance", "bungcip.better-toml" ], }
omniverse-code/kit/exts/omni.kit.window.extensions/ext_template/vscode/launch.json
{ "version": "0.2.0", "configurations": [ { "name": "Python: Attach (windows-x86_64/linux-x86_64)", "type": "python", "request": "attach", "localRoot": "${workspaceFolder}", "remoteRoot": "${workspaceFolder}", "port": 3000, "host": "localhost", "subProcess": true, "runtimeArgs": [ "--preserve-symlinks", "--preserve-symlinks-main" ] } ] }
omniverse-code/kit/exts/omni.kit.window.extensions/ext_template/exts/[ext_id]/[python_module]/extension.py
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("[${ext_id}] 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 ${ext_name}Extension(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("[${ext_id}] ${ext_title} 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("[${ext_id}] ${ext_title} shutdown")
omniverse-code/kit/exts/omni.kit.window.extensions/ext_template/exts/[ext_id]/[python_module]/__init__.py
from .extension import *
omniverse-code/kit/exts/omni.kit.window.extensions/ext_template/exts/[ext_id]/[python_module]/tests/__init__.py
from .test_hello_world import *
omniverse-code/kit/exts/omni.kit.window.extensions/ext_template/exts/[ext_id]/[python_module]/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 ${python_module} # 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 = ${python_module}.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")
omniverse-code/kit/exts/omni.kit.window.extensions/ext_template/exts/[ext_id]/config/extension.toml
[package] # Semantic Versioning is used: https://semver.org/ version = "1.0.0" # Lists people or organizations that are considered the "authors" of the package. authors = ["NVIDIA"] # The title and description fields are primarily for displaying extension info in UI title = "${ext_title}" description="A simple python extension example to use as a starting point for your extensions." # Path (relative to the root) or content of readme markdown file for UI. readme = "docs/README.md" # URL of the extension source repository. repository = "" # One of categories for UI. category = "Example" # Keywords for the extension keywords = ["kit", "example"] # Location of change log file in target (final) folder of extension, relative to the root. # More info on writing changelog: https://keepachangelog.com/en/1.0.0/ changelog="docs/CHANGELOG.md" # Preview image and icon. Folder named "data" automatically goes in git lfs (see .gitattributes file). # Preview image is shown in "Overview" of Extensions window. Screenshot of an extension might be a good preview image. preview_image = "data/preview.png" # Icon is shown in Extensions window, it is recommended to be square, of size 256x256. icon = "data/icon.png" # Use omni.ui to build simple UI [dependencies] "omni.kit.uiapp" = {} # Main python module this extension provides, it will be publicly available as "import ${python_module}". [[python.module]] name = "${python_module}" [[test]] # Extra dependencies only to be used during test run dependencies = [ "omni.kit.ui_test" # UI testing extension ]
omniverse-code/kit/exts/omni.kit.window.extensions/ext_template/exts/[ext_id]/docs/CHANGELOG.md
# Changelog The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/). ## [1.0.0] - 2021-04-26 - Initial version of extension UI template with a window
omniverse-code/kit/exts/omni.kit.window.extensions/ext_template/exts/[ext_id]/docs/README.md
# Python Extension Example [${ext_id}] This is an example of pure python Kit extension. It is intended to be copied and serve as a template to create new extensions.
omniverse-code/kit/exts/omni.kit.window.extensions/ext_template/exts/[ext_id]/docs/index.rst
${ext_id} ############################# Example of Python only extension .. toctree:: :maxdepth: 1 README CHANGELOG .. automodule::"${python_module}" :platform: Windows-x86_64, Linux-x86_64 :members: :undoc-members: :show-inheritance: :imported-members: :exclude-members: contextmanager
omniverse-code/kit/exts/omni.kit.window.extensions/PACKAGE-LICENSES/omni.kit.window.extensions-LICENSE.md
Copyright (c) 2020, 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.
omniverse-code/kit/exts/omni.kit.window.extensions/config/extension.toml
[package] title = "Extensions" description = "Customize and personalize Kit with extensions" version = "1.1.1" category = "Internal" feature = true changelog = "docs/CHANGELOG.md" [dependencies] "omni.kit.async_engine" = {} "omni.kit.clipboard" = {} "omni.kit.commands" = {} "omni.kit.test" = {} "omni.kit.widget.graph" = {} "omni.ui" = {} "omni.client" = {} "omni.kit.menu.utils" = {} [[python.module]] name = "omni.kit.window.extensions" [settings] # Enable publish and unpublish from UI feature: persistent.exts."omni.kit.window.extensions".publishingEnabled = false # Open folders and files in VSCode instead of OS file explorer: persistent.exts."omni.kit.window.extensions".openInVSCode = false exts."omni.kit.window.extensions".docUrlInternal = "http://omniverse-docs.s3-website-us-east-1.amazonaws.com/${extName}/${version}" exts."omni.kit.window.extensions".docUrlExternal = "https://docs.omniverse.nvidia.com/kit/docs/${extName}/${version}" # Show Community extensions tab. Just always show or have an option to manually enable. exts."omni.kit.window.extensions".communityTabEnabled = true exts."omni.kit.window.extensions".communityTabOption = true # Links to create menu entries for under '+' exts."omni.kit.window.extensions".openExampleLinks = [ ["Open Extension Template On Github", "https://github.com/NVIDIA-Omniverse/kit-extension-template"] ] [[test]] args = ["--reset-user"] pythonTests.unreliable = [ "*UNRELIABLE*" ] #See https://nvidia-omniverse.atlassian.net/browse/OM-46331 stdoutFailPatterns.exclude = [ "*Failed to acquire interface*while unloading all plugins*" ] unreliable = true # OM-59453
omniverse-code/kit/exts/omni.kit.window.extensions/omni/kit/window/extensions/common.py
# Copyright (c) 2018-2020, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. # import asyncio import os import os.path from enum import Enum from functools import lru_cache from string import Template from typing import Callable, Dict, List, Tuple import carb.events import carb.settings import carb.tokens import omni.kit.app from . import ext_controller from .utils import get_ext_info_dict, get_extpath_git_ext, get_setting, set_default_and_get_setting, show_ok_popup # Extension root path. Set when extension starts. EXT_ROOT = None REGISTRIES_CHANGED_EVENT = carb.events.type_from_string("omni.kit.registry.nucleus.REGISTRIES_CHANGED_EVENT") REGISTRIES_SETTING = "/exts/omni.kit.registry.nucleus/registries" USER_REGISTRIES_SETTING = "/persistent/exts/omni.kit.registry.nucleus/userRegistries" EXTENSION_PULL_STARTED_EVENT = carb.events.type_from_string("omni.kit.window.extensions.EXTENSION_PULL_STARTED_EVENT") COMMUNITY_TAB_TOGGLE_EVENT = carb.events.type_from_string("omni.kit.window.extensions.COMMUNITY_TAB_TOGGLE_EVENT") REMOTE_IMAGE_SUPPORTED_EXTS = {".png"} def path_is_parent(parent_path, child_path): try: return os.path.commonpath([parent_path]) == os.path.commonpath([parent_path, child_path]) except ValueError: return False def is_in_omni_documents(path): return path_is_parent(get_omni_documents_path(), path) @lru_cache() def get_icons_path() -> str: assert EXT_ROOT is not None, "This function should be called only after EXT_ROOT is set" return f"{EXT_ROOT}/icons" @lru_cache() def get_omni_documents_path() -> str: return os.path.abspath(carb.tokens.get_tokens_interface().resolve("${omni_documents}")) @lru_cache() def get_kit_path() -> str: return os.path.abspath(carb.tokens.get_tokens_interface().resolve("${kit}")) @lru_cache() def get_categories() -> Dict: icons_path = get_icons_path() categories = { "animation": {"name": "Animation", "image": f"{icons_path}/data/category-animation.png"}, "graph": {"name": "Graph", "image": f"{icons_path}/data/category-graph.png"}, "rendering": {"name": "Lighting & Rendering", "image": f"{icons_path}/data/category-rendering.png"}, "audio": {"name": "Audio", "image": f"{icons_path}/data/category-audio.png"}, "simulation": {"name": "Simulation", "image": f"{icons_path}/data/category-simulation.png"}, "services": {"name": "Services", "image": f"{icons_path}/data/category-internal.png"}, "core": {"name": "Core", "image": f"{icons_path}/data/category-core.png"}, "example": {"name": "Example", "image": f"{icons_path}/data/category-example.png"}, "internal": {"name": "Internal", "image": f"{icons_path}/data/category-internal.png", "hidden": False}, "legacy": {"name": "Legacy", "image": f"{icons_path}/data/category-legacy.png"}, "other": {"name": "Other", "image": f"{icons_path}/data/category-internal.png"}, } return categories class ExtSource(Enum): NVIDIA = 0 THIRD_PARTY = 1 def get_ui_name(self): return "NVIDIA" if self == ExtSource.NVIDIA else "THIRD PARTY" class ExtAuthorGroup(Enum): NVIDIA = 0 PARTNER = 1 COMMUNITY_VERIFIED = 2 COMMUNITY_UNVERIFIED = 3 USER = 4 def get_ui_name(self): if self == ExtAuthorGroup.NVIDIA: return "NVIDIA" if self == ExtAuthorGroup.PARTNER: return "PARTNER" if self == ExtAuthorGroup.USER: return "USER" return "COMMUNITY" def get_registries(): settings = carb.settings.get_settings() settings_dict = settings.get_settings_dictionary("") for key, is_user in [(REGISTRIES_SETTING, False), (USER_REGISTRIES_SETTING, True)]: for r in settings_dict.get(key[1:], []): name = r.get("name", "") url = r.get("url", "") url = carb.tokens.get_tokens_interface().resolve(url) yield name, url, is_user @lru_cache() def get_registry_url(registry_name): version = get_setting("/app/extensions/registryVersion", "NOT_SET") for name, url, _ in get_registries(): if name == registry_name: return f"{url}/{version}" return None class ExtensionCommonInfo: def __init__(self, ext_id, ext_info, is_local): self.id = ext_id package_dict = ext_info.get("package", {}) self.fullname = package_dict["name"] self.title = package_dict.get("title", "").upper() or self.fullname self.name = self.title.lower() # used for sorting self.description = package_dict.get("description", "") or "No Description" self.version = package_dict.get("version", None) self.keywords = package_dict.get("keywords", []) self.toggleable = package_dict.get("toggleable", True) self.feature = package_dict.get("feature", False) self.authors = package_dict.get("authors", "") self.repository = package_dict.get("repository", "") self.package_id = package_dict.get("packageId", "") self.is_kit_file = ext_info.get("isKitFile", False) self.is_app = ("app" in self.keywords) or package_dict.get("app", self.is_kit_file) self.is_startup = ext_controller.is_startup_ext(self.fullname) self.is_startup_version = ext_controller.is_startup_ext(ext_id) self.is_featured = ext_controller.is_featured_ext(self.fullname) self.is_local = is_local state_dict = ext_info.get("state", {}) self.failed = state_dict.get("failed", False) self.enabled = state_dict.get("enabled", False) self.reloadable = state_dict.get("reloadable", False) self.is_pulled = state_dict.get("isPulled", False) self.is_toggle_blocked = (self.enabled and not self.reloadable) or (not self.toggleable) self.path = ext_info.get("path", "") self.provider_name = None # Only if solve_extensions is called self.non_toggleable_deps = [] self.solver_error = "" self.category = package_dict.get("category", "other").lower() # Ext sources if package_dict.get("exchange", False): if package_dict.get("partner", False): self.author_group = ExtAuthorGroup.PARTNER else: self.author_group = ExtAuthorGroup.COMMUNITY_VERIFIED elif not package_dict.get("trusted", True): self.author_group = ExtAuthorGroup.COMMUNITY_UNVERIFIED else: self.author_group = ExtAuthorGroup.NVIDIA # Extension location tag for UI and user extensions self.location_tag = "" if is_local: abs_path = os.path.abspath(self.path) if ext_info.get("isInCache", False): self.location_tag = "INSTALLED" elif self.author_group == ExtAuthorGroup.NVIDIA and ( ext_info.get("isUser", False) or is_in_omni_documents(abs_path) ): self.author_group = ExtAuthorGroup.USER else: git_ext = get_extpath_git_ext() if git_ext and path_is_parent(git_ext.get_cache_path(), abs_path): self.location_tag = "GIT" # Finalize source self.ext_source = ExtSource.NVIDIA if self.author_group == ExtAuthorGroup.NVIDIA else ExtSource.THIRD_PARTY self.is_untrusted = self.author_group == ExtAuthorGroup.COMMUNITY_UNVERIFIED # Remote exts if not is_local: self.location_tag = "REMOTE" self.provider_name = ext_info.get("registryProviderName", None) # If unknown category -> fallback to other categories = get_categories() if self.category not in categories: self.category = "other" # For icon by default use category icon, can be overriden with custom: self.icon_path = self._build_image_resource_path(package_dict, "icon", categories[self.category]["image"]) # For preview image there is no default self.preview_image_path = self._build_image_resource_path(package_dict, "preview_image") def _build_image_resource_path(self, package_dict, key, default_path=None): resource_path = default_path if self.is_local: path = package_dict.get(key, None) if path: icon_path = os.path.join(self.path, path) if os.path.exists(icon_path): resource_path = icon_path else: path = package_dict.get(key + "_remote", None) if path: if os.path.splitext(path)[1] not in REMOTE_IMAGE_SUPPORTED_EXTS: return default_path url = get_registry_url(self.provider_name) if url: resource_path = url + "/" + path return resource_path def solve_extensions(self): # This function is costly, so we don't run it for each item. Only on demand when UI shows selected extension. manager = omni.kit.app.get_app().get_extension_manager() result, exts, err = manager.solve_extensions([self.id], add_enabled=True, return_only_disabled=True) if not result: self.failed = True self.non_toggleable_deps = [] self.solver_error = err if result: for ext in exts: ext_dict, _ = get_ext_info_dict(manager, ext) if not ext_dict.get("package", {}).get("toggleable", True): self.non_toggleable_deps.append(ext["id"]) def build_ext_info(ext_id, package_id=None) -> Tuple[ExtensionCommonInfo, dict]: manager = omni.kit.app.get_app().get_extension_manager() package_id = package_id or ext_id ext_info_remote = manager.get_registry_extension_dict(package_id) ext_info_local = manager.get_extension_dict(ext_id) is_local = ext_info_local is not None ext_info = ext_info_local or ext_info_remote if not ext_info: return None, None ext_info = ext_info.get_dict() # convert to python dict to prolong lifetime return ExtensionCommonInfo(ext_id, ext_info, is_local), ext_info def check_can_be_toggled(ext_id: str, for_autoload=False): ext_item, _ = build_ext_info(ext_id) if ext_item: ext_item.solve_extensions() # Error to solve? if ext_item.solver_error: text = "Failed to solve all extension dependencies:" text += f"\n{ext_item.solver_error}" asyncio.ensure_future(show_ok_popup("Error", text)) return False if not for_autoload and ext_item.non_toggleable_deps: text = "This extension cannot be enabled at runtime.\n" text += "Some of dependencies require an app restart to be enabled (toggleable=false):\n\n" for ext in ext_item.non_toggleable_deps: text += f" * {ext}" text += "\n\n" text += "Set this extension to autoload and restart an app to enable it." asyncio.ensure_future(show_ok_popup("Warning", text)) return False return True def toggle_extension(ext_id: str, enable: bool): if enable and not check_can_be_toggled(ext_id): return False omni.kit.commands.execute("ToggleExtension", ext_id=ext_id, enable=enable) return True async def pull_extension_async(ext_item: ExtensionCommonInfo, on_pull_started_fn: Callable = None): if ext_item.is_untrusted: cancel = False def on_cancel(dialog): nonlocal cancel cancel = True dialog.hide() message = """ ATTENTION: UNVERIFIED COMMUNITY EXTENSION This extension will be installed directly from the repository (see "Repo Url"). It is not verified by NVIDIA and may contain bugs or malicious code. Do you want to proceed? """ await show_ok_popup( "Warning", message, ok_label="Install", cancel_label="Cancel", disable_cancel_button=False, cancel_handler=on_cancel, width=600, ) if cancel: return ext_manager = omni.kit.app.get_app().get_extension_manager() ext_manager.pull_extension_async(ext_item.id) omni.kit.app.get_app().get_message_bus_event_stream().push(EXTENSION_PULL_STARTED_EVENT) if on_pull_started_fn: on_pull_started_fn() class SettingBoolValue: def __init__(self, path: str, default: bool): self._path = path self._value = set_default_and_get_setting(path, default) def get(self) -> bool: return self._value def set_bool(self, value: bool): self._value = value carb.settings.get_settings().set(self._path, self._value) def __bool__(self): return self.get() def build_doc_urls(ext_item: ExtensionCommonInfo) -> List[str]: """Produce possible candiates for doc urls""" # Base url if omni.kit.app.get_app().is_app_external(): doc_url = get_setting("/exts/omni.kit.window.extensions/docUrlExternal", "") else: doc_url = get_setting("/exts/omni.kit.window.extensions/docUrlInternal", "") if not doc_url: return [] # Build candidates. Prefer exact version, fallback to just a link to latest candidates = [] for v in [ext_item.version, "latest", ""]: candidates.append(Template(doc_url).safe_substitute({"version": v, "extName": ext_item.fullname})) return candidates @lru_cache() def is_community_tab_always_enabled() -> bool: return get_setting("/exts/omni.kit.window.extensions/communityTabEnabled", True) def is_community_tab_enabled_as_option() -> bool: if is_community_tab_always_enabled(): return False return get_setting("/exts/omni.kit.window.extensions/communityTabOption", True) class ExtOptions: def __init__(self): self.community_tab = None if is_community_tab_enabled_as_option(): self.community_tab = SettingBoolValue( "/persistent/exts/omni.kit.window.extensions/communityTabEnabled", default=False ) self.publishing = SettingBoolValue( "/persistent/exts/omni.kit.window.extensions/publishingEnabled", default=False ) @lru_cache() def get_options() -> ExtOptions: return ExtOptions() def is_community_tab_enabled() -> bool: # Can be either always enabled, or as a toggleable preference if is_community_tab_always_enabled(): return True return get_options().community_tab is not None and get_options().community_tab @lru_cache() def get_open_example_links(): return get_setting("/exts/omni.kit.window.extensions/openExampleLinks", [])
omniverse-code/kit/exts/omni.kit.window.extensions/omni/kit/window/extensions/exts_properties_paths.py
# Copyright (c) 2018-2020, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. # import omni.kit.app import omni.ui as ui from .styles import get_style from .utils import cleanup_folder, copy_text, get_extpath_git_ext PATH_TYPE_TO_LABEL = { omni.ext.ExtensionPathType.COLLECTION: "[dir]", omni.ext.ExtensionPathType.COLLECTION_USER: "[user dir]", omni.ext.ExtensionPathType.COLLECTION_CACHE: "[cache dir]", omni.ext.ExtensionPathType.DIRECT_PATH: "[ext]", omni.ext.ExtensionPathType.EXT_1_FOLDER: "[exts 1.0]", } PATH_TYPE_TO_COLOR = { omni.ext.ExtensionPathType.COLLECTION: 0xFF29A9A9, omni.ext.ExtensionPathType.COLLECTION_USER: 0xFF1989A9, omni.ext.ExtensionPathType.COLLECTION_CACHE: 0xFFA9A929, omni.ext.ExtensionPathType.DIRECT_PATH: 0xFF29A929, omni.ext.ExtensionPathType.EXT_1_FOLDER: 0xFF2929A9, } PATHS_COLUMNS = ["", "name", "type", "edit"] class PathItem(ui.AbstractItem): def __init__(self, path, path_type: omni.ext.ExtensionPathType, add_dummy=False): super().__init__() self.path_model = ui.SimpleStringModel(path) self.type = path_type self.is_user = path_type == omni.ext.ExtensionPathType.COLLECTION_USER self.is_cache = path_type == omni.ext.ExtensionPathType.COLLECTION_CACHE self.add_dummy = add_dummy git_ext = get_extpath_git_ext() if git_ext and git_ext.is_git_path(path): self.is_git = True self.local_path = git_ext.get_local_path(path) else: self.is_git = False self.local_path = path class PathsModel(ui.AbstractItemModel): def __init__(self): super().__init__() self._ext_manager = omni.kit.app.get_app().get_extension_manager() self._children = [] self._load() self._add_dummy = PathItem("", omni.ext.ExtensionPathType.COLLECTION_USER, add_dummy=True) def destroy(self): self._children = [] def get_item_children(self, item): """Returns all the children when the widget asks it.""" if item is not None: return [] return self._children + [self._add_dummy] def get_item_value_model_count(self, item): """The number of columns""" return 4 def get_item_value_model(self, item, column_id): if column_id == 1: return item.path_model return None def _load(self): self._children = [] folders = self._ext_manager.get_folders() for folder in folders: path = folder["path"] path_type = folder["type"] item = PathItem(path, path_type) self._children.append(item) self._item_changed(None) def add_empty(self): self._children.append(PathItem("", omni.ext.ExtensionPathType.COLLECTION_USER)) self._item_changed(None) def remove_item(self, item): self._children.remove(item) self.save() self._item_changed(None) def clean_cache(self, item): path = item.local_path print(f"Cleaning up cache: {path}") cleanup_folder(path) def update_git(self, item): path = item.path_model.as_string get_extpath_git_ext().update_git_path(path) def save(self): current = [ folder["path"] for folder in self._ext_manager.get_folders() if folder["type"] == omni.ext.ExtensionPathType.COLLECTION_USER ] paths = [c.path_model.as_string for c in self._children if c.is_user] if current != paths: # remove and add again. We can only apply diff here, but then it is impossible to preserve the order. for p in current: self._ext_manager.remove_path(p) for p in paths: self._ext_manager.add_path(p, omni.ext.ExtensionPathType.COLLECTION_USER) get_extpath_git_ext.cache_clear() class EditableDelegate(ui.AbstractItemDelegate): def __init__(self): super().__init__() self._subscription = None self._context_menu = ui.Menu("Context menu") def destroy(self): self._subscription = None self._context_menu = None def _show_copy_context_menu(self, x, y, button, modifier, text): if button != 1: return self._context_menu.clear() with self._context_menu: ui.MenuItem("Copy", triggered_fn=lambda: copy_text(text)) self._context_menu.show() def build_widget(self, model, item, column_id, level, expanded): """Create a widget per column per item""" with ui.HStack(width=20): if column_id == 0 and not item.add_dummy: def open_path(item_=item): # Import it here instead of on the file root because it has long import time. path = item_.local_path if path: import webbrowser webbrowser.open(path) ui.Button("open", width=0, clicked_fn=open_path, tooltip="Open path using OS file explorer.") elif column_id == 1 and not item.add_dummy: value_model = model.get_item_value_model(item, column_id) stack = ui.ZStack(height=20) with stack: label = ui.Label(value_model.as_string, width=500, name=("config" if item.is_user else "builtin")) field = ui.StringField(value_model, visible=False) # Start editing when double clicked stack.set_mouse_double_clicked_fn( lambda x, y, b, _, f=field, l=label, m=model, i=item: self.on_double_click(b, f, l, m, i) ) # Right click is copy menu stack.set_mouse_pressed_fn( lambda x, y, b, m, t=value_model.as_string: self._show_copy_context_menu(x, y, b, m, t) ) elif column_id == 2 and not item.add_dummy: ui.Label(PATH_TYPE_TO_LABEL[item.type], style={"color": PATH_TYPE_TO_COLOR[item.type]}) elif column_id == 3: if item.is_user: def on_click(item_=item): if item.add_dummy: model.add_empty() else: model.remove_item(item_) ui.Spacer(width=10) ui.Button( name=("add" if item.add_dummy else "remove"), style_type_name_override="ItemButton", width=20, height=20, clicked_fn=on_click, ) ui.Spacer(width=4) elif item.is_cache: def clean_cache(item_=item): model.clean_cache(item_) ui.Spacer(width=10) ui.Button( name="clean", style_type_name_override="ItemButton", width=20, height=20, clicked_fn=clean_cache, ) ui.Spacer(width=4) if item.is_git: def update_git(item_=item): model.update_git(item_) ui.Button( name="update", style_type_name_override="ItemButton", width=20, height=20, clicked_fn=update_git, ) ui.Spacer() def on_double_click(self, button, field, label, model, item): """Called when the user double-clicked the item in TreeView""" if button != 0: return if item.add_dummy: return if not item.is_user: copy_text(field.model.as_string) return # Make Field visible when double clicked field.visible = True field.focus_keyboard() # When editing is finished (enter pressed of mouse clicked outside of the viewport) self._subscription = field.model.subscribe_end_edit_fn( lambda m, f=field, l=label, md=model: self.on_end_edit(m.as_string, f, l, md) ) def on_end_edit(self, text, field, label, model): """Called when the user is editing the item and pressed Enter or clicked outside of the item""" field.visible = False label.text = text self._subscription = None if text: model.save() def build_header(self, column_id): with ui.HStack(): ui.Spacer(width=10) ui.Label(PATHS_COLUMNS[column_id], name="header") class ExtsPathsWidget: def __init__(self): self._model = PathsModel() self._delegate = EditableDelegate() with ui.VStack(style=get_style(self)): ui.Spacer(height=20) with ui.ScrollingFrame( height=400, horizontal_scrollbar_policy=ui.ScrollBarPolicy.SCROLLBAR_ALWAYS_OFF, vertical_scrollbar_policy=ui.ScrollBarPolicy.SCROLLBAR_ALWAYS_OFF, style_type_name_override="TreeView", ): tree_view = ui.TreeView( self._model, delegate=self._delegate, root_visible=False, header_visible=True, ) tree_view.column_widths = [ui.Pixel(46), ui.Fraction(1), ui.Pixel(70), ui.Pixel(60)] ui.Spacer(height=10) def destroy(self): self._model.destroy() self._model = None self._delegate.destroy() self._delegate = None
omniverse-code/kit/exts/omni.kit.window.extensions/omni/kit/window/extensions/styles.py
# Copyright (c) 2018-2020, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. # from functools import lru_cache from typing import Dict import omni.ui as ui from omni.ui import color as cl from .common import get_icons_path # Common size constants: EXT_ICON_SIZE = (70, 70) EXT_ICON_SIZE_LARGE = (100, 100) CATEGORY_ICON_SIZE = (70, 70) EXT_LIST_ITEM_H = 106 EXT_LIST_ITEMS_MARGIN_H = 3 EXT_ITEM_TITLE_BAR_H = 27 EXT_LIST_ITEM_ICON_ZONE_W = 87 @lru_cache() def get_styles() -> Dict: icons_path = get_icons_path() styles = { "ExtensionToggle": { "Image::Failed": {"image_url": f"{icons_path}/exclamation.svg", "color": 0xFF2222DD, "margin": 5}, "Button": {"margin": 0, "padding": 0, "background_color": 0x0}, "Button:checked": {"background_color": 0x0}, "Button.Image::nonclickable": {"color": 0x60FFFFFF, "image_url": f"{icons_path}/toggle-off.svg"}, "Button.Image::nonclickable:checked": {"color": 0x60FFFFFF, "image_url": f"{icons_path}/toggle-on.svg"}, "Button.Image::clickable": {"image_url": f"{icons_path}/toggle-off.svg", "color": 0xFFFFFFFF}, "Button.Image::clickable:checked": {"image_url": f"{icons_path}/toggle-on.svg"}, "Label::EnabledLabel": {"font_size": 16, "color": 0xFF71A376}, "Label::DisabledLabel": {"font_size": 16, "color": 0xFFB9B9B9}, "Button::InstallButton": {"background_color": 0xFF00B976, "border_radius": 4}, "Button::InstallButton:checked": {"background_color": 0xFF06A66B}, "Button.Label::InstallButton": {"color": 0xFF3E3E3E, "font_size": 14}, "Button::DownloadingButton": {"background_color": 0xFF008253, "border_radius": 4}, "Button.Label::DownloadingButton": {"color": 0xFF3E3E3E, "font_size": 8}, "Button::LaunchButton": {"background_color": 0xFF00B976, "border_radius": 4}, "Button.Label::LaunchButton": {"color": 0xFF3E3E3E, "font_size": 14}, }, "SimpleCheckBox": { "Button": {"margin": 0, "padding": 0, "background_color": 0x0}, "Button:hovered": {"background_color": 0x0}, "Button:checked": {"background_color": 0x0}, "Button:pressed": {"background_color": 0x0}, "Button.Image": {"image_url": f"{icons_path}/checkbox-off.svg", "color": 0xFFA8A8A8}, "Button.Image:hovered": {"color": 0xFF929292}, "Button.Image:pressed": {"color": 0xFFA4A4A4}, "Button.Image:checked": {"image_url": f"{icons_path}/checkbox-on.svg", "color": 0xFFA8A8A8}, "Image::disabled_checked": {"image_url": f"{icons_path}/checkbox-on.svg", "color": 0x3FA8A8A8}, "Image::disabled_unchecked": {"image_url": f"{icons_path}/checkbox-off.svg", "color": 0x3FA8A8A8}, "Label::disabled": {"font_size": 12, "color": 0xFF444444}, "Label": {"font_size": 16, "color": 0xFFC4C4C4}, }, "SearchWidget": { "SearchField": { "background_color": 0xFF212121, "color": 0xFFA2A2A2, "border_radius": 0, "font_size": 16, "margin": 0, "padding": 5, }, "Image::SearchIcon": {"image_url": f"{icons_path}/search.svg", "color": 0xFF646464}, "Label::Search": {"color": 0xFF646464}, "Button.Image::ClearSearch": { "image_url": f"{icons_path}/close.svg", "color": 0xFF646464, }, "Button.Image::ClearSearch:hovered": { "image_url": f"{icons_path}/close.svg", "color": 0xFF929292, }, "Button.Image::ClearSearch:pressed": { "image_url": f"{icons_path}/close.svg", "color": 0xFFC4C4C4, }, "Button::ClearSearch": { "margin": 0, "border_radius": 0, "border_width": 0, "padding": 3, "background_color": 0x00000000, }, "Button::ClearSearch:hovered": { "background_color": 0x00000000, }, "Button::ClearSearch:pressed": { "background_color": 0x00000000, }, }, "MarkdownText": { "Label": {"font_size": 16, "color": 0xFFCCCCCC}, "Label::text": {"font_size": 16, "color": 0xFFCCCCCC}, "Label::H1": {"font_size": 32, "color": 0xFFCCCCCC}, "Label::H2": {"font_size": 28, "color": 0xFFCCCCCC}, "Label::H3": {"font_size": 24, "color": 0xFFCCCCCC}, "Label::H4": {"font_size": 20, "color": 0xFFCCCCCC}, }, "ExtsWindow": { "ExtensionDescription.Button": {"background_color": 0xFF090969}, "ExtensionDescription.Title": {"font_size": 18, "color": 0xFFCCCCCC, "margin": 5}, "ExtensionDescription.Header": {"font_size": 20, "color": 0xFF409656}, "ExtensionDescription.Content": {"font_size": 16, "color": 0xFFCCCCCC, "margin": 5}, "ExtensionDescription.ContentError": {"font_size": 16, "color": 0xFF4056C6, "margin": 5}, "ExtensionDescription.ContentValue": {"font_size": 16, "color": 0xFF409656}, "ExtensionDescription.ContentLink": {"font_size": 16, "color": 0xFF82C994}, "ExtensionDescription.ContentLink:hovered": {"color": 0xFFB8E0C2}, "ExtensionList.Label::Description": {"font_size": 16}, "ExtensionList.Label::Name": {"font_size": 12}, "ExtensionDescription.Background": {"background_color": 0xFF363636, "border_radius": 4}, "ExtensionDescription.ContentBackground": {"background_color": 0xFF23211F}, "ExtensionList.Background": { "background_color": 0xFF212121, "border_radius": 0, "corner_flag": ui.CornerFlag.BOTTOM, }, "Rectangle::ExtensionListGroup": { "background_color": 0xFF303030, }, "Rectangle::ExtensionListGroup:hovered": { "background_color": 0xFF404040, }, "Rectangle::ExtensionListGroup:pressed": { "background_color": 0xFF303030, }, "ExtensionList.Group.Label": {"font_size": 16, "color": 0xFFC0C0C0}, "ExtensionList.Group.Icon::expanded": {"image_url": f"{icons_path}/expanded.svg"}, "ExtensionList.Group.Icon": {"image_url": f"{icons_path}/collapsed.svg"}, "ExtensionList.Separator": {"background_color": 0xFF000000}, # "ExtensionList.Background:hovered": {"background_color": 0xFF191919}, "ExtensionList.Background:selected": {"background_color": 0xFF8A8777}, "ExtensionList.Foreground": { "background_color": 0xFF2F2F2F, "border_width": 0, "border_radius": 0, "corner_flag": ui.CornerFlag.BOTTOM_RIGHT, }, "ExtensionList.Foreground:selected": {"background_color": 0xFF9F9B8A}, "ExtensionList.Label": {"font_size": 16, "color": 0xFF878787}, "ExtensionList.Label:selected": {"color": 0xFF212121}, "ExtensionList.Label::Title": {"font_size": 20, "margin_width": 10}, "ExtensionList.Label::Title:selected": {"color": 0xFFE0E0E0}, "ExtensionList.Label::Category": {"font_size": 16, "margin_width": 10}, "ExtensionList.Label::Id": {"font_size": 16, "margin_width": 10}, "ExtensionList.Label::Version": {"font_size": 16, "margin_width": 10, "margin_height": 5}, "TreeView": { "background_color": 0xFF23211F, "background_selected_color": 0xFF23211F, "secondary_color": 0xFF989898, # Scroll knob "alignment": ui.Alignment.RIGHT, }, "TreeView.ScrollingFrame": {"background_color": 0xFF4A4A4A}, "ComboBox": { "background_color": 0xFF212121, "border_radius": 0, "font_size": 16, "margin": 0, "color": 0xFF929292, "padding": 0, }, "ComboBox:hovered": {"background_color": 0xFF2F2F2F}, "ComboBox:selected": {"background_color": 0xFF2F2F2F}, "ExtensionDescription.Label": {"color": 0xFFC4C4C4, "margin": 2, "font_size": 16}, "ExtensionDescription.Id::Name": {"background_color": 0xFF000000, "color": 0xFFC4C4C4, "font_size": 14}, "ExtensionDescription.Rectangle::Name": {"background_color": 0xFF24211F, "border_radius": 2}, "ExtensionDescription.UpdateButton": {"background_color": 0xFF00B976, "border_radius": 4}, "ExtensionDescription.UpdateButton.Label": {"color": 0xFF3E3E3E, "font_size": 18}, "ExtensionDescription.RestartButton": {"background_color": 0xFF00B976, "border_radius": 4}, "ExtensionDescription.RestartButton.Label": {"color": 0xFF3E3E3E, "font_size": 18}, "ExtensionDescription.UpToDateButton": {"background_color": 0xFF747474, "border_radius": 4}, "ExtensionDescription.UpToDateButton.Label": {"color": 0xFF3E3E3E, "font_size": 18}, "ExtensionDescription.InstallButton": {"background_color": 0xFF00B976, "border_radius": 4}, "ExtensionDescription.InstallButton.Label": {"color": 0xFF3E3E3E, "font_size": 18}, "ExtensionDescription.DownloadingButton": {"background_color": 0xFF00754A, "border_radius": 4}, "ExtensionDescription.DownloadingButton.Label": {"color": 0xFF3E3E3E, "font_size": 18}, "ExtensionDescription.CommunityRectangle": {"background_color": 0xFF1F1F1F, "border_radius": 2}, "ExtensionDescription.CommunityImage": { "image_url": f"{icons_path}/community.svg", "color": cl(180, 180, 180), }, "ExtensionDescription.CommunityLabel": {"color": 0xFFA4A4A4, "font_size": 16}, "ExtensionDescription.UnverifiedRectangle": {"background_color": 0xFF000038, "border_radius": 2}, "ExtensionDescription.UnverifiedLabel": {"color": 0xFFC4C4C4, "margin_width": 30, "font_size": 16}, "Button::create": {"background_color": 0x0, "margin": 0}, "Button.Image::create": {"image_url": f"{icons_path}/plus.svg", "color": 0xFF00B976}, "Button.Image::create:hovered": {"color": 0xFF00D976}, "Button::options": {"background_color": 0x0, "margin": 0}, "Button.Image::options": {"image_url": f"{icons_path}/options.svg", "color": 0xFF989898}, "Button.Image::options:hovered": {"color": 0xFFC2C2C2}, "Button::filter": {"background_color": 0x0, "margin": 0}, "Button.Image::filter": {"image_url": f"{icons_path}/filter_grey.svg", "color": 0xFF989898}, "Button.Image::filter:hovered": {"color": 0xFFC2C2C2}, "Button::filter_on": {"background_color": 0x0, "margin": 0}, "Button.Image::filter_on": {"image_url": f"{icons_path}/filter.svg", "color": 0xFF989898}, "Button.Image::filter_on:hovered": {"color": 0xFFC2C2C2}, "Button::sortby": {"background_color": 0x0, "margin": 0}, "Button.Image::sortby": {"image_url": f"{icons_path}/sort_by_grey.svg", "color": 0xFF989898}, "Button.Image::sortby:hovered": {"color": 0xFFC2C2C2}, "Button::sortby_on": {"background_color": 0x0, "margin": 0}, "Button.Image::sortby_on": {"image_url": f"{icons_path}/sort_by.svg", "color": 0xFF989898}, "Button.Image::sortby_on:hovered": {"color": 0xFFC2C2C2}, "ExtensionDescription.Tab": {"background_color": 0x0}, "ExtensionDescription.Tab.Label": {"color": 0xFF8D8D8D, "font_size": 16}, "ExtensionDescription.Tab.Label:pressed": {"color": 0xFFF3F2EC}, "ExtensionDescription.Tab.Label:selected": {"color": 0xFFF3F2EC}, "ExtensionDescription.Tab.Label:hovered": {"color": 0xFFADADAD}, "ExtensionDescription.TabLine": {"color": 0xFF00B976, "border_width": 1}, "ExtensionDescription.TabLineFull": {"color": 0xFF707070}, "ExtensionVersionMenu.MenuItem": {"color": 0x0, "margin": 0}, "IconButton": {"margin": 0, "padding": 0, "background_color": 0x0}, "IconButton:hovered": {"background_color": 0x0}, "IconButton:checked": {"background_color": 0x0}, "IconButton:pressed": {"background_color": 0x0}, "IconButton.Image": {"color": 0xFFA8A8A8}, "IconButton.Image:hovered": {"color": 0xFF929292}, "IconButton.Image:pressed": {"color": 0xFFA4A4A4}, "IconButton.Image:checked": {"color": 0xFFFFFFFF}, "IconButton.Image::OpenDoc": {"image_url": f"{icons_path}/question.svg"}, "IconButton.Image::OpenFolder": {"image_url": f"{icons_path}/open-folder.svg"}, "IconButton.Image::OpenConfig": {"image_url": f"{icons_path}/open-config.svg"}, "IconButton.Image::OpenInVSCode": {"image_url": f"{icons_path}/vscode.svg"}, "IconButton.Image::Export": {"image_url": f"{icons_path}/export.svg"}, "Image::UpdateAvailable": { "image_url": f"{icons_path}/update-available.svg", "color": 0xFFFFFFFF, "spacing": 50, }, "Label::UpdateAvailable": {"color": 0xFF00B977, "margin": 10}, "Label::LocationTag": {"color": 0xFF00B977, "margin": 10, "font_size": 16}, "Image::Community": {"image_url": f"{icons_path}/community.svg", "color": cl(255, 255, 255)}, "Image::Community:selected": {"color": cl("#ddefff")}, "Label::Community": {"color": 0xFFA4A4A4, "margin": 10, "font_size": 16}, "Rectangle::Splitter": {"background_color": 0x0, "margin": 3, "border_radius": 2}, "Rectangle::Splitter:hovered": {"background_color": 0xFFB0703B}, "Rectangle::Splitter:pressed": {"background_color": 0xFFB0703B}, "Image::UNKNOWN": {"color": 0xFFFFFFFF, "image_url": f"{icons_path}/question.svg"}, "Image::RUNNING": {"color": 0xFFFF7D7D, "image_url": f"{icons_path}/spinner.svg"}, "Image::PASSED": {"color": 0xFF00FF00, "image_url": f"{icons_path}/check_solid.svg"}, "Image::FAILED": {"color": 0xFF0000FF, "image_url": f"{icons_path}/exclamation.svg"}, }, "ExtsPropertiesWidget": { "Properies.Background": {"background_color": 0xFF24211F, "border_radius": 4}, }, "ExtsRegistriesWidget": { "TreeView": { "background_color": 0xFF23211F, "background_selected_color": 0xFF444444, }, "TreeView.Item": {"margin": 14, "color": 0xFF000055}, "Field": {"background_color": 0xFF333322}, "Label::header": {"margin": 4}, "Label": {"margin": 5}, "Label::builtin": {"color": 0xFF909090}, "Label::config": {"color": 0xFFDDDDDD}, "ItemButton": {"padding": 2, "background_color": 0xFF444444, "border_radius": 4}, "ItemButton.Image::add": {"image_url": f"{icons_path}/plus.svg", "color": 0xFF06C66B}, "ItemButton.Image::remove": {"image_url": f"{icons_path}/trash.svg", "color": 0xFF1010C6}, "ItemButton:hovered": {"background_color": 0xFF333333}, "ItemButton:pressed": {"background_color": 0xFF222222}, }, "ExtsPathsWidget": { "TreeView": { "background_color": 0xFF23211F, "background_selected_color": 0xFF444444, }, "TreeView.Item": {"margin": 14, "color": 0xFF000055}, "Field": {"background_color": 0xFF333322}, "Label::header": {"margin": 4}, "Label": {"margin": 5}, "Label::builtin": {"color": 0xFF909090}, "Label::config": {"color": 0xFFDDDDDD}, "ItemButton": {"padding": 2, "background_color": 0xFF444444, "border_radius": 4}, "ItemButton.Image::add": {"image_url": f"{icons_path}/plus.svg", "color": 0xFF06C66B}, "ItemButton.Image::remove": {"image_url": f"{icons_path}/trash.svg", "color": 0xFF1010C6}, "ItemButton.Image::clean": {"image_url": f"{icons_path}/broom.svg", "color": 0xFF5EDAFA}, "ItemButton.Image::update": {"image_url": f"{icons_path}/refresh.svg", "color": 0xFF5EDAFA}, "ItemButton:hovered": {"background_color": 0xFF333333}, "ItemButton:pressed": {"background_color": 0xFF222222}, }, } return styles def get_style(instance): return get_styles()[instance.__class__.__name__]
omniverse-code/kit/exts/omni.kit.window.extensions/omni/kit/window/extensions/ext_test_tab.py
# Copyright (c) 2018-2020, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. # import carb.settings import omni.kit.app import omni.ui as ui from omni.kit.test import TestRunStatus from .ext_components import SimpleCheckBox DEFAULT_TEST_APP = "${kit}/apps/omni.app.test_ext.kit" class ExtTestTab: def __init__(self): self.test_status = {} # options self.info_log = False self.wait_for_debugger = False self.python_debugger = False self.wait_for_python_debugger = False self.ui_mode = False self.do_not_exit = False self.coverage = False self.tests_filter = "" self._test_filter_model = None self._app_combo = None self.apps = [f"{DEFAULT_TEST_APP} (empty)"] manager = omni.kit.app.get_app_interface().get_extension_manager() all_exts = [(manager.get_extension_dict(e["id"]), e["id"]) for e in manager.get_extensions()] self.apps += [ext_id for d, ext_id in all_exts if d.get("isKitFile", False)] def destroy(self): pass def build_cb(self, attr, name): SimpleCheckBox( getattr(self, attr), lambda v: setattr(self, attr, not getattr(self, attr)), name, ) def _update_test_args(self): args = [] if self.info_log: args += ["-v"] if self.wait_for_debugger: args += ["-d"] if self.wait_for_python_debugger: self.python_debugger = True args += ["--/exts/omni.kit.debug.python/break=1"] if self.python_debugger: args += ["--enable", "omni.kit.debug.python"] if self.do_not_exit: args += ["--/exts/omni.kit.test/doNotQuit=1"] self.tests_filter = self._test_filter_model.as_string args += [f"--/exts/omni.kit.test/runTestsFilter='{self.tests_filter}'"] settings = carb.settings.get_settings() selected_app = self._app_combo.model.get_item_value_model().as_int app = self.apps[selected_app] if selected_app > 0 else DEFAULT_TEST_APP settings.set("/exts/omni.kit.test/testExtApp", app) settings.set("/exts/omni.kit.test/testExtArgs", args) settings.set("/exts/omni.kit.test/testExtUIMode", self.ui_mode) settings.set("/exts/omni.kit.test/testExtGenerateCoverageReport", self.coverage) settings.set("/exts/omni.kit.test/testExtCleanOutputPath", self.coverage) # todo offer a way to pick reliable/unreliable/both # settings.set("/exts/omni.kit.test/testExtRunUnreliableTests", 2) def build(self, ext_info): ext_id = ext_info.get("package").get("id") with ui.VStack(height=0): ui.Spacer(height=20) ui.Label("Options:", height=0, width=50, style_type_name_override="ExtensionDescription.Label") ui.Spacer(height=10) self.build_cb("info_log", "info log") self.build_cb("ui_mode", "ui mode (test selection)") self.build_cb("coverage", "generate coverage report") self.build_cb("wait_for_debugger", "wait for native debugger") self.build_cb("python_debugger", "enable python debugger") self.build_cb("wait_for_python_debugger", "enable python debugger and wait") self.build_cb("do_not_exit", "do not exit after tests") ui.Spacer(height=10) with ui.HStack(): ui.Spacer(width=10) ui.Label( "filter (e.g.: *test_usd*):", height=0, width=50, style_type_name_override="ExtensionDescription.Label", ) self._test_filter_model = ui.StringField(width=250).model self._test_filter_model.as_string = self.tests_filter ui.Spacer(height=20) with ui.HStack(): ui.Spacer(width=10) ui.Label("app:", height=0, width=50, style_type_name_override="ExtensionDescription.Label") self._app_combo = ui.ComboBox(0, *self.apps, style={"padding": 4}, width=400) ui.Spacer(height=20) with ui.HStack(): status_image = None def _refresh_test_status(): status = self.test_status.get(ext_id, TestRunStatus.UNKNOWN) status_image.name = str(status.name) def on_status(test_id, status, **_): self.test_status[ext_id] = status _refresh_test_status() def on_finish(status, *_): if self.coverage: omni.kit.test.generate_report() def on_click(ext_id=ext_id): self._update_test_args() omni.kit.test.run_ext_tests([ext_id], on_finish, on_status) ui.Button( "RUN EXTENSION TESTS", style_type_name_override="ExtensionDescription.InstallButton", width=80, height=20, clicked_fn=on_click, ) ui.Spacer(width=20) ui.Label("Result:", width=0, style_type_name_override="ExtensionDescription.Label") status_image = ui.Image( name="TestStatus", width=20, height=20, alignment=ui.Alignment.RIGHT_CENTER, ) _refresh_test_status()
omniverse-code/kit/exts/omni.kit.window.extensions/omni/kit/window/extensions/ext_info_widget.py
# Copyright (c) 2018-2020, 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. # # pylint: disable=protected-access, access-member-before-definition import abc import asyncio import contextlib import os import weakref from datetime import datetime, timezone from typing import Callable import omni.kit.app import omni.kit.commands import omni.kit.test import omni.ui as ui from . import ext_controller from .common import ( ExtAuthorGroup, ExtensionCommonInfo, build_ext_info, check_can_be_toggled, get_categories, get_options, pull_extension_async, toggle_extension, ) from .ext_components import ExtensionToggle, SimpleCheckBox, add_doc_link_button from .ext_data_fetcher import get_ext_data_fetcher from .ext_export_import import export_ext from .ext_test_tab import ExtTestTab from .exts_graph_window import ExtsGraphWidget from .markdown_renderer import MarkdownText from .styles import CATEGORY_ICON_SIZE, EXT_ICON_SIZE_LARGE from .utils import clip_text, is_vscode_installed, open_in_vscode_if_enabled, version_to_str ICON_ZONE_WIDTH = 120 CATEGORY_ZONE_WIDTH = 120 def get_ext_text_content(key: str, ext_info, ext_item: ExtensionCommonInfo): """Get extension readme/changelog from either local dict or registry extra data""" content_str = "" # Get the data if ext_item.is_local: content_str = ext_info.get("package", {}).get(key, "") else: fetcher = get_ext_data_fetcher() ext_data = fetcher.get_ext_data(ext_item.package_id) if ext_data: content_str = ext_data.get("package", {}).get(key, "") # Figure out if it is a path to a file or actual data if content_str and "\n" not in content_str: ext_path = ext_info.get("path", "") # If it is a path -> load file content readme_file = os.path.join(ext_path, content_str) if os.path.exists(readme_file): with open(readme_file, "r", encoding="utf-8") as f: content_str = f.read() return content_str class PageBase: """ Interface for any classes adding Tabs to the Extension Manager UI """ @abc.abstractmethod def build_tab(self, ext_info: dict, ext_item: ExtensionCommonInfo) -> None: """Build the Tab.""" @abc.abstractmethod def destroy(self) -> None: """Teardown the Tab.""" @staticmethod @abc.abstractmethod def get_tab_name() -> str: """Get the name used for the tab name in the UI""" def build_package_info(ext_info): if ext_info is None: return package_dict = ext_info.get("package", {}) publish_dict = package_dict.get("publish", {}) def add_info(name, value): if not value: return if isinstance(value, (tuple, list)): value = ", ".join(value) if isinstance(value, dict): value = str(value) with ui.HStack(): ui.Label(name, width=100, style_type_name_override="ExtensionDescription.Content") if value.startswith("http://") or value.startswith("https://"): def open_link(): import webbrowser webbrowser.open(value) ui.Label( value, style_type_name_override="ExtensionDescription.ContentLink", mouse_pressed_fn=lambda x, y, b, a: b == 0 and open_link(), ) else: ui.Label(value, style_type_name_override="ExtensionDescription.ContentValue") def add_package_info(name, key): add_info(name, package_dict.get(key, None)) # Package info add_package_info("Authors", "authors") add_package_info("Keywords", "keywords") add_info("Repo Name", publish_dict.get("repoName", None)) add_package_info("Repo Url", "repository") add_package_info("Github Release", "githubRelease") # Publish info ts = publish_dict.get("date", None) if not ts: ts = package_dict.get("publishDate", None) # backward compatibility for deprecated key if ts: add_info("Publish Date", str(datetime.fromtimestamp(ts, tz=timezone.utc).astimezone())) add_info("Build Number", publish_dict.get("buildNumber", None)) add_info("Kit Version", publish_dict.get("kitVersion", None)) add_package_info("Target", "target") # Test info test = ext_info.get("test", None) if isinstance(test, (list, tuple)): for t in test: add_info("Test Waiver", t.get("waiver", None)) class OverviewPage(PageBase): """ Build a class with same interface and add it to ExtInfoWidget.pages below to have it show up as a tab """ def build_tab(self, ext_info, ext_item: ExtensionCommonInfo): def content_label(text): ui.Label(text, style_type_name_override="ExtensionDescription.Content") readme_str = get_ext_text_content("readme", ext_info, ext_item) with ui.ScrollingFrame( horizontal_scrollbar_policy=ui.ScrollBarPolicy.SCROLLBAR_AS_NEEDED, vertical_scrollbar_policy=ui.ScrollBarPolicy.SCROLLBAR_ALWAYS_ON, ): with ui.ZStack(): ui.Rectangle(style_type_name_override="ExtensionDescription.ContentBackground") with ui.HStack(): ui.Spacer(width=10) with ui.VStack(height=0): ui.Spacer(height=10) # All the meta info about the package (version, date, authors) build_package_info(ext_info) ui.Spacer(height=15) # Readme MarkdownText(readme_str) # Preview ? if ext_item.preview_image_path: ui.Image( ext_item.preview_image_path, alignment=ui.Alignment.H_CENTER, fill_policy=ui.FillPolicy.PRESERVE_ASPECT_FIT, width=700, height=700, ) else: content_label("Preview: 'package/preview_image' is not specified.") def destroy(self): pass @staticmethod def get_tab_name(): return "OVERVIEW" class ChangelogPage(PageBase): def build_tab(self, ext_info, ext_item: ExtensionCommonInfo): changelog_str = get_ext_text_content("changelog", ext_info, ext_item) if not changelog_str: changelog_str = "[no changelog]" # word_wrap is important here because changelog can # be Markdown, and if word_wrap is defalut, Label # ignores everything after double hash. word_wrap fixes it. with ui.ScrollingFrame( horizontal_scrollbar_policy=ui.ScrollBarPolicy.SCROLLBAR_ALWAYS_OFF, vertical_scrollbar_policy=ui.ScrollBarPolicy.SCROLLBAR_ALWAYS_ON, ): with ui.ZStack(): ui.Rectangle(style_type_name_override="ExtensionDescription.ContentBackground") with ui.HStack(): ui.Spacer(width=10) with ui.VStack(height=0): ui.Spacer(height=10) MarkdownText(changelog_str) def destroy(self): pass @staticmethod def get_tab_name(): return "CHANGELOG" class DependenciesPage(PageBase): def __init__(self): self._ext_graph = None def build_tab(self, ext_info, ext_item: ExtensionCommonInfo): # Graph available if extension is enabled: if ext_info.get("state", {}).get("enabled", False): self._ext_graph = ExtsGraphWidget(ext_info.get("package").get("id")) else: with ui.VStack(height=0): manager = omni.kit.app.get_app().get_extension_manager() # Enable result result, exts, err = manager.solve_extensions([ext_item.id], add_enabled=True, return_only_disabled=True) if not result: ui.Label( "Enabling this extension will fail with the following error:", style_type_name_override="ExtensionDescription.Header", ) ui.Label(err, style_type_name_override="ExtensionDescription.ContentError") else: ui.Label( "Enabling this extension will enable the following extensions in order:", style_type_name_override="ExtensionDescription.Header", ) ui.Label( "".join(f"\n - {ext['id']}" for ext in exts), style_type_name_override="ExtensionDescription.Content", ) ui.Spacer(height=30) # Dependencies ui.Label("Dependencies (in config):", style_type_name_override="ExtensionDescription.Header") ui.Spacer(height=4) for k, v in ext_info.get("dependencies", {}).items(): label_text = f"{k}" tag = v.get("tag", None) if tag: label_text += f"-{tag}" version = v.get("version", "*.*.*") if version: label_text += f" | v{version}" optional = v.get("optional", False) if optional: label_text += "(optional)" ui.Label(label_text, style_type_name_override="ExtensionDescription.Content") def destroy(self): pass @staticmethod def get_tab_name(): return "DEPENDENCIES" class PackagesPage(PageBase): def build_tab(self, ext_info, ext_item: ExtensionCommonInfo): manager = omni.kit.app.get_app().get_extension_manager() package_info = ext_info.get("package") packages = manager.fetch_extension_packages(package_info.get("id")) with ui.VStack(height=0): ui.Label( "All available packages for version {} :".format(package_info["version"]), style_type_name_override="ExtensionDescription.Title", ) for p in packages: package_id = p["package_id"] with ui.CollapsableFrame(package_id, collapsed=True): with ui.HStack(): ui.Spacer(width=20) with ui.VStack(): build_package_info(manager.get_registry_extension_dict(package_id)) def destroy(self): pass @staticmethod def get_tab_name(): return "PACKAGES" class ExtTestPage(PageBase): def __init__(self): self.tab = ExtTestTab() def build_tab(self, ext_info, ext_item: ExtensionCommonInfo): self.tab.build(ext_info) def destroy(self): self.tab.destroy() @staticmethod def get_tab_name(): return "TESTS" class ExtInfoWidget: pages = [OverviewPage, ChangelogPage, DependenciesPage, PackagesPage, ExtTestPage] current_page = 0 def __init__(self): # Widgets for tabs self.__tabs = [] self.__pages = [] # Put into frame to enable rebuilding of UI self._frame = ui.Frame() self._ext_manager = omni.kit.app.get_app().get_extension_manager() self._ext_change_sub = self._ext_manager.get_change_event_stream().create_subscription_to_pop( lambda *_: self._refresh_once_next_frame(), name="ExtInfoWidget" ) self._ext_graph = None self._version_menu = None self._selected_version = None self._selected_package_id = None # Refresh when new ext data fetched fetcher = get_ext_data_fetcher() def on_data_fetched(package_id): if self._selected_package_id == package_id: self._refresh_once_next_frame() fetcher.on_data_fetched_fn = on_data_fetched self.select_ext(None) self.page_tabs = [] self.update_tabs() self.set_show_graph_fn(None) def update_tabs(self): self.page_tabs = [] for page in self.pages: self.page_tabs.append(page()) def set_visible(self, visible): self._frame.visible = visible def select_ext(self, ext_summary): """Select extension to display info about. Can be None""" self._ext_summary = ext_summary self._selected_version = None self._selected_package_id = None self._refresh_once_next_frame() def _refresh(self): # Fetch all extensions for currently selected extension summary extensions = ( self._ext_manager.fetch_extension_versions(self._ext_summary.fullname) if self._ext_summary is not None else [] ) def _draw_empty_page(): with self._frame: ui.Label("Select an extension") if len(extensions) == 0: _draw_empty_page() return # If user hasn't yet changed the version to display summary advices which should be shown by default: if self._selected_version is None: self._selected_version = self._ext_summary.default_ext["version"] # Now actual extension is selected (including version). Get all the info for it selected_index = next( (i for i, v in enumerate(extensions) if v["version"][:4] == self._selected_version[:4]), None ) # If selected version is not available, select latest. That can happen if latest published is incompatible with # current target. In summaries it will show later version than the one you can select by default. if self._selected_version is not None and selected_index is None: selected_index = 0 self._selected_version = extensions[selected_index]["version"] if selected_index is None: _draw_empty_page() return selected_ext = extensions[selected_index] is_version_latest = selected_index == 0 ext_id = selected_ext["id"] package_id = selected_ext["package_id"] self._selected_package_id = package_id # If this extension is enabled or other version of this extension is enabled: any_version_enabled = any(ext["enabled"] for ext in extensions) ext_item, ext_info = build_ext_info(ext_id, package_id) # -> Tuple[ExtensionCommonInfo, dict]: # Get ext info either from local or remote index if not ext_info: _draw_empty_page() return # Gather more info by solving dependencies. When other version of this extension is already enabled solving is # known to fail because of conflict. It will always display a red icon then. # When we actually toggle it we will first turn off that version. So for that case do not solve extensions. # An alternative solution might be to manually build a list of all enabled extensions, but exclude current one. if not any_version_enabled: ext_item.solve_extensions() if not ext_item.is_local: fetcher = get_ext_data_fetcher() fetcher.fetch(ext_item) ext_path = ext_info.get("path", "") package_dict = ext_info.get("package", {}) docs_dict = ext_info.get("documentation", {}) if ext_item.is_local: # For local extensions add version to ext_id to make it more concrete (for later enabling etc.) name = package_dict.get("name") version = package_dict.get("version", None) ext_id = name + "-" + version if version else name name = package_dict.get("name", "") enabled = ext_item.enabled category = get_categories().get(ext_item.category) ################################################################################################################ # Build version selector menu def select_version(version): self._selected_version = version self._refresh_once_next_frame() self._version_menu = ui.Menu("Version") with self._version_menu: ui.MenuItem("Version(s)", enabled=False) ui.Separator() for i, e in enumerate(extensions): version = e["version"] version_str = version_to_str(version[:4]) color = 0xFF76B900 if selected_index == i else 0xFFC0C0C0 ui.MenuItem( version_str, checked=selected_index == i, checkable=True, style={"color": color, "margin": 0}, triggered_fn=lambda v=version: select_version(v), ) # Publish / Unpublish buttons if get_options().publishing: ui.Separator() ui.MenuItem("Publishing", enabled=False) ui.Separator() if ext_item.is_local: ui.MenuItem( "PUBLISH", triggered_fn=lambda ext_id=ext_id: self._ext_manager.publish_extension(ext_id) ) else: ui.MenuItem( "UNPUBLISH", triggered_fn=lambda ext_id=ext_id: self._ext_manager.unpublish_extension(ext_id) ) # Uninstall can_be_uninstalled = not ext_item.enabled and ext_item.location_tag == "INSTALLED" if can_be_uninstalled: ui.Separator() ui.MenuItem( "UNINSTALL", triggered_fn=lambda ext_id=ext_id: self._ext_manager.uninstall_extension(ext_id) ) ################################################################################################################ ################################################################################################################ def draw_icon_block(): # Icon with ui.HStack(width=ICON_ZONE_WIDTH): ui.Spacer() with ui.VStack(width=EXT_ICON_SIZE_LARGE[0]): ui.Spacer() ui.Image(ext_item.icon_path, height=EXT_ICON_SIZE_LARGE[1], style={"color": 0xFFFFFFFF}) ui.Spacer() ui.Spacer() ################################################################################################################ def draw_top_row_block(): with ui.HStack(): # Big button if not ext_item.is_local: if ext_info.get("state", {}).get("isPulled", False): ui.Button( "INSTALLING...", style_type_name_override="ExtensionDescription.DownloadingButton", width=100, height=30, ) else: def on_click(item=ext_item): asyncio.ensure_future(pull_extension_async(item, self._refresh_once_next_frame)) ui.Button( "INSTALL", style_type_name_override="ExtensionDescription.InstallButton", width=100, height=30, clicked_fn=on_click, ) else: can_update = not is_version_latest is_autoload_enabled = ext_controller.is_autoload_enabled(ext_item.id) if not ext_item.enabled and ext_item.is_toggle_blocked and is_autoload_enabled: def on_click(): omni.kit.app.get_app().restart() ui.Button( "RESTART APP", style_type_name_override="ExtensionDescription.RestartButton", clicked_fn=on_click, width=100, height=30, ) elif can_update: def on_click(ext_id=ext_id, switch_off_on=(enabled and not ext_item.is_toggle_blocked)): latest_ext = extensions[0] latest_ext_id = latest_ext["id"] latest_ext_version = latest_ext["version"] # If autoload for that one is enabled, move it to latest: if ext_controller.is_autoload_enabled(ext_id): ext_controller.toggle_autoload(ext_id, False) if check_can_be_toggled(latest_ext_id, for_autoload=True): ext_controller.toggle_autoload(latest_ext_id, True) # If extension is enabled, switch off to latest: if switch_off_on: toggle_extension(ext_id, False) toggle_extension(latest_ext_id, True) # Finally switch UI to show newest version select_version(latest_ext_version) ui.Button( "UPDATE", style_type_name_override="ExtensionDescription.UpdateButton", clicked_fn=on_click, width=100, height=30, ) else: ui.Button( "UP TO DATE", style_type_name_override="ExtensionDescription.UpToDateButton", width=100, height=30, ) # Version selector with ui.VStack(width=0): ui.Spacer() ui.Button(name="options", width=40, height=22, clicked_fn=self._version_menu.show) ui.Spacer() # Toggle ui.Spacer(width=15) ExtensionToggle(ext_item, with_label=True, show_install_button=False) # Autoload toggle with ui.HStack(): ui.Spacer(width=20) def toggle_autoload(value, ext_id=ext_id): if check_can_be_toggled(ext_id, for_autoload=True): ext_controller.toggle_autoload(ext_id, value) self._refresh_once_next_frame() SimpleCheckBox( ext_controller.is_autoload_enabled(ext_id), toggle_autoload, "AUTOLOAD", enabled=True ) ui.Spacer(width=20) def add_icon_button(name, on_click, tooltip=None): with ui.VStack(width=0): ui.Spacer() # cannot get style tooltip override to work, so force it here b = ui.Button( name=name, style_type_name_override="IconButton", width=23, height=18, clicked_fn=on_click, style={"Label": {"color": 0xFF444444}}, ) if tooltip: b.set_tooltip_fn(lambda *_: ui.Label(tooltip)) ui.Spacer() return b def add_open_button(url, name, prefer_vscode=False, tooltip=None): def on_click(url=url): open_in_vscode_if_enabled(url, prefer_vscode) b = add_icon_button(name, on_click) if not tooltip: tooltip = url b.set_tooltip_fn(lambda *_: ui.Label(tooltip)) # Doc button add_doc_link_button(ext_item, package_dict, docs_dict) ui.Spacer(width=8) if ext_item.is_local: # Extension "open folder" button ext_folder = os.path.dirname(ext_path) if os.path.isfile(ext_path) else ext_path add_open_button(ext_folder, name="OpenFolder") ui.Spacer(width=8) # Extension "open folder" button if is_vscode_installed(): add_open_button(ext_folder, name="OpenInVSCode", prefer_vscode=True, tooltip="Open in VSCode") ui.Spacer(width=8) # Extension "open config" button add_open_button(ext_info.get("configPath", ""), name="OpenConfig", prefer_vscode=True) ui.Spacer(width=8) # Extension export button def on_export(ext_id=ext_id): export_ext(ext_id) add_icon_button("Export", on_export, tooltip=f"Export {ext_info['package']['packageId']}") ################################################################################################################ def draw_extension_name_block(): with ui.HStack(): # Extension id ui.Label( ext_item.title, height=0, width=0, style_type_name_override="ExtensionDescription.Label", tooltip=ext_id, ) ui.Spacer() # Remove that separate rect block with ext_id? # with ui.ZStack(height=0, width=0): # ui.Rectangle(style_type_name_override="ExtensionDescription.Rectangle", name="Name") # ui.Label(ext_id, style_type_name_override="ExtensionDescription.Id", name="Name") ################################################################################################################ def draw_extension_description_block(): with ui.HStack(): ui.Label( clip_text(ext_item.description), height=0, width=50, style_type_name_override="ExtensionDescription.Label", ) ################################################################################################################ def draw_extension_version_block(): with ui.HStack(): if ext_item.version: ui.Label( "v" + ext_item.version, style_type_name_override="ExtensionDescription.Label", width=0, name="Version", ) def add_separator(): ui.Spacer(width=10) ui.Line(alignment=ui.Alignment.LEFT, style_type_name_override="ExtensionDescription.Label", width=0) ui.Spacer(width=10) add_separator() # Repository/Local text = f"Registry: {ext_item.provider_name}" if ext_item.provider_name else "Local" ui.Label(text, style_type_name_override="ExtensionDescription.Label", width=0) ui.Spacer() ################################################################################################################ def draw_category_block(): # Categoty Info and Icon with ui.HStack(width=CATEGORY_ZONE_WIDTH): ui.Spacer() with ui.VStack(width=CATEGORY_ICON_SIZE[0]): ui.Spacer() ui.Image(category["image"], width=CATEGORY_ICON_SIZE[0], height=CATEGORY_ICON_SIZE[1]) ui.Spacer(height=10) ui.Label(category["name"], alignment=ui.Alignment.CENTER) ui.Spacer() ui.Spacer() def draw_ext_source_block(): with ui.HStack(height=0): with ui.ZStack(height=32, width=0): ui.Image(style_type_name_override="ExtensionDescription.CommunityImage", width=148, height=32) with ui.HStack(width=0): ui.Spacer(width=52) name = ext_item.author_group.get_ui_name() ui.Label(name, style_type_name_override="ExtensionDescription.CommunityLabel") ui.Spacer(width=2) if ext_item.is_untrusted: with ui.ZStack(height=30): with ui.VStack(): ui.Spacer(height=2) ui.Rectangle(style_type_name_override="ExtensionDescription.UnverifiedRectangle") ui.Label( "UNVERIFIED", alignment=ui.Alignment.RIGHT_CENTER, style_type_name_override="ExtensionDescription.UnverifiedLabel", ) def draw_content_block(): def set_page(index): for i in self.__tabs: i.selected = False for i in self.__pages: i.visible = False self.__tabs[index].selected = True self.__pages[index].visible = True ExtInfoWidget.current_page = index ui.Spacer(height=10) with ui.HStack(height=20): tab_buttons = [] for index, page in enumerate(self.page_tabs): tab_btn = ui.Button( page.get_tab_name(), width=0, style_type_name_override="ExtensionDescription.Tab", clicked_fn=lambda i=index: set_page(i), ) tab_buttons.append(tab_btn) if index < len(self.page_tabs) - 1: ui.Line( style_type_name_override="ExtensionDescription.TabLine", alignment=ui.Alignment.H_CENTER, height=20, width=40, ) ui.Spacer() self.__tabs[:] = tab_buttons ui.Spacer(height=8) with ui.ZStack(): pages = [] for page_tab in self.page_tabs: page = ui.Frame(build_fn=lambda i=ext_info, e=ext_item, page_tab=page_tab: page_tab.build_tab(i, e)) pages.append(page) self.__pages[:] = pages set_page(ExtInfoWidget.current_page) # Default page ################################################################################################################ ################################################################################################################ # Build Actual UI Layout of all blocks with self._frame: with ui.ZStack(): ui.Rectangle(style_type_name_override="ExtensionDescription.Background") with ui.VStack(spacing=4): # Top Margin ui.Spacer(height=15) with ui.HStack(height=0, spacing=5): draw_icon_block() with ui.VStack(): draw_top_row_block() ui.Spacer(height=10) draw_extension_name_block() draw_extension_description_block() ui.Spacer(height=10) draw_extension_version_block() draw_category_block() # ui.Spacer(height=4) if ext_item.author_group != ExtAuthorGroup.NVIDIA: draw_ext_source_block() with ui.HStack(): ui.Spacer(width=10) # Content page with ui.VStack(): # Separator line ui.Line( height=0, alignment=ui.Alignment.BOTTOM, style_type_name_override="ExtensionDescription.TabLineFull", ) draw_content_block() ui.Spacer(width=10) ui.Spacer(height=5) def _refresh_once_next_frame(self): async def _delayed_refresh(weak_widget): await omni.kit.app.get_app().next_update_async() w = weak_widget() if w: w._refresh_task = None w._refresh() with contextlib.suppress(Exception): self._refresh_task.cancel() self._refresh_task = asyncio.ensure_future(_delayed_refresh(weakref.ref(self))) def set_show_graph_fn(self, fn: Callable): self._show_graph_fn = fn def _show_graph(self, ext_id): if self._show_graph_fn: self._show_graph_fn(ext_id) def destroy(self): self._ext_change_sub = None if self._ext_graph: self._ext_graph.destroy() self._ext_graph = None for page in self.page_tabs: page.destroy() # We want to None the instances also self._version_menu = None self.__tabs = [] self.__pages = []
omniverse-code/kit/exts/omni.kit.window.extensions/omni/kit/window/extensions/ext_export_import.py
import asyncio import os import carb import carb.tokens import omni.kit.app from .common import get_omni_documents_path from .utils import get_setting # Store last user choosen folder for convenience between sessions RECENT_EXPORT_PATH_KEY = "/persistent/exts/omni.kit.window.extensions/recentExportPath" def _print_and_log(message): carb.log_info(message) print(message) async def _ask_user_for_path(is_export: bool, apply_button_label="Choose", title=None): app = omni.kit.app.get_app() manager = app.get_extension_manager() if not manager.is_extension_enabled("omni.kit.window.filepicker"): manager.set_extension_enabled("omni.kit.window.filepicker", True) await app.next_update_async() await app.next_update_async() from omni.kit.widget.filebrowser import FileBrowserItem from omni.kit.window.filepicker import FilePickerDialog done = False choosen_path = None def on_click_cancel(f, d): nonlocal done done = True if is_export: def on_click_open(f, d): nonlocal done, choosen_path choosen_path = d done = True filepicker = FilePickerDialog( title or "Choose Folder", allow_multi_selection=False, apply_button_label=apply_button_label, click_apply_handler=on_click_open, click_cancel_handler=on_click_cancel, enable_filename_input=False, ) else: def on_click_open(f, d): nonlocal done, choosen_path choosen_path = os.path.join(d, f) done = True def on_filter_zip_files(item: FileBrowserItem) -> bool: if not item or item.is_folder: return True return os.path.splitext(item.path)[1] == ".zip" filepicker = FilePickerDialog( title or "Choose Extension Zip Archive", allow_multi_selection=False, apply_button_label="Import", click_apply_handler=on_click_open, click_cancel_handler=on_click_cancel, item_filter_options=[("*.zip", ".zip Archives (*.zip)")], item_filter_fn=on_filter_zip_files, ) recent_path = get_setting(RECENT_EXPORT_PATH_KEY, None) if not recent_path: recent_path = get_omni_documents_path() filepicker.show(path=recent_path) while not done: await app.next_update_async() filepicker.hide() filepicker.destroy() if choosen_path: recent_path = os.path.dirname(choosen_path) if os.path.isfile(choosen_path) else choosen_path carb.settings.get_settings().set(RECENT_EXPORT_PATH_KEY, recent_path) return choosen_path async def _export(ext_id: str): output = await _ask_user_for_path(is_export=True, apply_button_label="Export") if output: app = omni.kit.app.get_app() manager = app.get_extension_manager() archive_path = manager.pack_extension(ext_id, output) app.print_and_log(f"Extension: '{ext_id}' was exported to: '{archive_path}'") async def _import(): archive_path = await _ask_user_for_path(is_export=False, apply_button_label="Import") # Registry Local Cache Folder registry_cache = get_setting("/app/extensions/registryCacheFull", None) if not registry_cache: carb.log_error("Can't import extension, registry cache path is not set.") return if archive_path: omni.ext.unpack_extension(archive_path, registry_cache) omni.kit.app.get_app().print_and_log(f"Extension: '{archive_path}' was imported to: '{registry_cache}'") def export_ext(ext_id: str): asyncio.ensure_future(_export(ext_id)) def import_ext(): asyncio.ensure_future(_import())
omniverse-code/kit/exts/omni.kit.window.extensions/omni/kit/window/extensions/exts_graph_window.py
# Copyright (c) 2018-2020, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. # import os from collections import defaultdict from typing import List, Tuple import carb import omni.kit.app import omni.ui as ui from omni.kit.widget.graph import GraphNodeDescription, GraphPortDescription from omni.kit.widget.graph.abstract_graph_node_delegate import AbstractGraphNodeDelegate from omni.kit.widget.graph.graph_model import GraphModel from omni.kit.widget.graph.graph_view import GraphView from .utils import ext_id_to_fullname # pylint: disable=property-with-parameters # Colors & Style BACKGROUND_COLOR = 0xFF34302A BORDER_DEFAULT = 0xFF232323 CONNECTION = 0xFF80C280 NODE_BACKGROUND = 0xFF141414 PLUGINS_COLOR = 0xFFFFE3C4 LIBRARIES_COLOR = 0xAA44EBE7 MODULES_COLOR = 0xFFAAE3C4 GRAPH_STYLE = { "Graph": {"background_color": BACKGROUND_COLOR}, "Graph.Connection": {"color": CONNECTION, "background_color": CONNECTION, "border_width": 2.0}, # Node "Graph.Node.Background": {"background_color": NODE_BACKGROUND}, "Graph.Node.Border": {"background_color": BORDER_DEFAULT}, # Header "Graph.Node.Header.Label": {"color": 0xFFEEEEEE, "margin_height": 5.0, "font_size": 14.0}, } # Constants MARGIN_WIDTH = 7.5 MARGIN_TOP = 20.0 MARGIN_BOTTOM = 25.0 BORDER_THICKNESS = 3.0 HEADER_HEIGHT = 25.0 MIN_WIDTH = 180.0 CONNECTION_CURVE = 60 class GraphNodeDelegate(AbstractGraphNodeDelegate): """ The delegate with the Omniverse design. """ def __init__(self, scale_factor=1.0): self._manager = omni.kit.app.get_app_interface().get_extension_manager() self._scale_factor = scale_factor def __scale(self, value): """Return the value multiplied by global scale multiplier""" return value * self._scale_factor def set_scale_factor(self, scale_factor): """Replace scale factor""" self._scale_factor = scale_factor def node_background(self, model, node_desc: GraphNodeDescription): """Called to create widgets of the node background""" # Computed values left_right_offset = MARGIN_WIDTH - BORDER_THICKNESS * 0.5 # Draw a rectangle and a top line with ui.HStack(): # Left offset ui.Spacer(width=self.__scale(left_right_offset)) with ui.VStack(): ui.Spacer(height=self.__scale(MARGIN_TOP)) # The node body with ui.ZStack(): # This trick makes min width ui.Spacer(width=self.__scale(MIN_WIDTH)) # Build outer rectangle ui.Rectangle(style_type_name_override="Graph.Node.Border") # Build inner rectangle with ui.VStack(): ui.Spacer(height=self.__scale(HEADER_HEIGHT)) with ui.HStack(): ui.Spacer(width=self.__scale(BORDER_THICKNESS)) ui.Rectangle(style_type_name_override="Graph.Node.Background") ui.Spacer(width=self.__scale(BORDER_THICKNESS)) ui.Spacer(height=self.__scale(BORDER_THICKNESS)) ui.Spacer(height=self.__scale(MARGIN_BOTTOM)) # Right offset ui.Spacer(width=self.__scale(left_right_offset)) def node_header_input(self, model, node_desc: GraphNodeDescription): """Called to create the left part of the header that will be used as input when the node is collapsed""" with ui.ZStack(width=self.__scale(8)): if node_desc.connected_target: # Circle that shows that the port is a target for the connection ui.Circle( radius=self.__scale(4), size_policy=ui.CircleSizePolicy.FIXED, style_type_name_override="Graph.Connection", alignment=ui.Alignment.RIGHT_CENTER, ) def node_header_output(self, model, node_desc: GraphNodeDescription): """Called to create the right part of the header that will be used as output when the node is collapsed""" with ui.ZStack(width=self.__scale(8)): if node_desc.connected_source: # Circle that shows that the port is a source for the connection ui.Circle( radius=self.__scale(4), size_policy=ui.CircleSizePolicy.FIXED, style_type_name_override="Graph.Connection", alignment=ui.Alignment.LEFT_CENTER, ) def node_header(self, model, node_desc: GraphNodeDescription): """Called to create widgets of the top of the node""" item = model[node_desc.node].item def build_list(files, title, color): if len(files) > 0: style = {"CollapsableFrame": {"color": color, "background_color": NODE_BACKGROUND}} with ui.CollapsableFrame(title, collapsed=False, style=style): with ui.VStack(height=0): for p in files: ui.Label(" - " + os.path.basename(p), height=self.__scale(20)).set_tooltip(p) # Draw the node name and a bit of space with ui.VStack(height=0): ui.Spacer(height=self.__scale(18)) with ui.HStack(height=0): ui.Spacer(width=self.__scale(18)) title = item.id ui.Label(title, style_type_name_override="Graph.Node.Header.Label") build_list(item.plugins, "carb plugins", PLUGINS_COLOR) build_list(item.libraries, "shared libraries", LIBRARIES_COLOR) build_list(item.modules, "python modules", MODULES_COLOR) ui.Spacer(height=self.__scale(55)) def node_footer(self, model, node_desc: GraphNodeDescription): pass def port_input(self, model, node_desc: GraphNodeDescription, port_desc: GraphPortDescription): pass def port_output(self, model, node_desc: GraphNodeDescription, port_desc: GraphPortDescription): pass def port(self, model, node_desc: GraphNodeDescription, port_desc: GraphPortDescription): pass def connection(self, model, source, target): """Called to create the connection between ports""" # If the connection is reversed, we need to mirror tangents connection_direction_is_same_as_flow = source.level >= target.level reversed_tangent = -1.0 if connection_direction_is_same_as_flow else 1.0 ui.FreeBezierCurve( target.widget, source.widget, start_tangent_width=ui.Percent(CONNECTION_CURVE * reversed_tangent), end_tangent_width=ui.Percent(-CONNECTION_CURVE * reversed_tangent), style_type_name_override="Graph.Connection", ) class ExtGraphItem: def __init__(self, manager, ext_id): info = manager.get_extension_dict(ext_id) # Extension dependencies: self.deps = info.get("state/dependencies", []) self.port_deps = [d + "/out" for d in self.deps] # Extension useful info (id, version, plugins, modules etc) state_dict = info.get("state", {}) native_dict = state_dict.get("native", {}) self.id = ext_id self.plugins = native_dict.get("plugins", []) self.libraries = native_dict.get("libraries", []) self.modules = state_dict.get("python", {}).get("modules", []) def __lt__(self, other): return self.id < other.id class Model(GraphModel): def __init__(self, ext_id: str = None): super().__init__() # build graph out of enabled extensions manager = omni.kit.app.get_app_interface().get_extension_manager() exts = manager.get_extensions() enabled_exts = [e["id"] for e in exts if e["enabled"]] self._nodes = {ext_id: ExtGraphItem(manager, ext_id) for ext_id in enabled_exts} # If ext_id was passed filter out extension that are not reachable from this one. To show only its graph: self._root_ext_id = ext_id if self._root_ext_id: self._filter_out_unreachable_nodes(ext_id) def _filter_out_unreachable_nodes(self, ext_id): visited = set() q = [] root = self._nodes.get(ext_id, None) if not root: carb.log_error(f"Failure to filter dep graph, can't find ext node: {ext_id}") return q.append(root) visited.add(root) while len(q) > 0: node = q.pop() for d in node.deps: child = self._nodes[d] if child not in visited: visited.add(child) q.append(child) self._nodes = {ext_id: item for ext_id, item in self._nodes.items() if item in visited} @property def expansion_state(self, item=None): return self.ExpansionState.CLOSED @property def nodes(self, item=None): return {e.id for e in self._nodes.values()} @property def name(self, item=None): return self._nodes[item].id @property def item(self, item=None): return self._nodes[item] @property def ports(self, item=None): return [item + "/in", item + "/out"] @property def inputs(self, item): if item.endswith("/in"): item = self._nodes.get(item[:-3], None) return item.port_deps if item else [] return None @property def outputs(self, item): outputs = [] if item.endswith("/out") else None return outputs def copy_as_graphviz(self): output = "" output += """ digraph Extensions { graph [outputMode=nodesfirst rankdir=LR] node [shape=box style=filled] """ for _, node in self._nodes.items(): label = node.id + "\\n-------------------\\n" def gen(files, title): if len(files) == 0: return "" return f"{title}:\\l" + "".join([f" * {os.path.basename(f)}\\l" for f in files]) label += gen(node.plugins, "plugins") label += gen(node.libraries, "libraries") label += gen(node.modules, "modules") output += f'\t\t"{node.id}" [label="{label}"]\n' for d in node.deps: output += f'\t\t"{d}" -> "{node.id}"\n' output += "}\n" print(output) omni.kit.clipboard.copy(output) class ExtsListView: def __init__(self, model, ext_id): self._model = model self._ext_id = ext_id # gather reverse dependencies from both local extensions and registry extensions registry_exts = [] unique_registry_exts = set() manager = omni.kit.app.get_app_interface().get_extension_manager() for ext in manager.get_extensions(): ext_name = ext["name"] registry_exts.append(ext) unique_registry_exts.add(ext_name) for ext in manager.get_registry_extensions(): ext_id = ext["id"] ext_name = ext["name"] if ext_name not in unique_registry_exts: # grab latest version of each extension versions = manager.fetch_extension_versions(ext_name) if len(versions) > 0 and versions[0]["id"] == ext_id: registry_exts.append(ext) unique_registry_exts.add(ext_name) self._reverse_dep = self._get_reverse_dependencies(manager, registry_exts) with ui.ScrollingFrame( horizontal_scrollbar_policy=ui.ScrollBarPolicy.SCROLLBAR_ALWAYS_OFF, vertical_scrollbar_policy=ui.ScrollBarPolicy.SCROLLBAR_ALWAYS_ON, ): with ui.ZStack(): ui.Rectangle(style_type_name_override="ExtensionDescription.ContentBackground") with ui.HStack(): ui.Spacer(width=10) with ui.VStack(height=0): ui.Spacer(height=10) direct = self._model._nodes[self._ext_id].deps if self._ext_id else () ui.Label(f"- Direct Dependencies ({len(direct)}):", height=20) for ext in sorted(direct): ui.Label(ext) ui.Spacer(height=10) indirect = [ node for node in self._model._nodes.values() if node.id not in direct and node.id != self._ext_id ] ui.Label(f"- All Indirect Dependencies ({len(indirect)}):", height=20) for node in sorted(indirect): ui.Label(node.id) ui.Spacer(width=10) with ui.VStack(height=10): ui.Spacer(height=10) direct = self._reverse_dep[0] ui.Label(f"- Direct Reverse Dependencies ({len(direct)}):", height=20) for item in sorted(direct): ui.Label(item) ui.Spacer(height=10) indirect = [ ext for ext in self._reverse_dep[1] if ext not in direct and ext != ext_id_to_fullname(self._ext_id) ] ui.Label(f"- All Indirect Reverse Dependencies ({len(indirect)}):", height=20) for item in sorted(indirect): ui.Label(item) def _get_reverse_dependencies(self, manager, exts) -> Tuple[List, List]: dependents = defaultdict(set) unique_exts_first_order = set() unique_exts = set() max_depth = 40 for ext in exts: ext_id = ext["id"] ext_name = ext["name"] info = manager.get_extension_dict(ext_id) if not info: info = manager.get_registry_extension_dict(ext_id) if info: deps = info.get("dependencies", []) for dep_name in deps: dependents[dep_name].add(ext_name) def recurse(ext_name: str, cur_depth: int): if cur_depth < max_depth: if cur_depth == 1: unique_exts_first_order.add(ext_name) unique_exts.add(ext_name) for dep_name in dependents[ext_name]: recurse(dep_name, cur_depth + 1) if self._ext_id: info = manager.get_extension_dict(self._ext_id) ext_name = info.get("package/name", "") recurse(ext_name, 0) # returns a tuple, 1st order deps only and all reverse deps return list(unique_exts_first_order), list(unique_exts) class ExtsGraphWidget: """Extensions graph window""" def __init__(self, ext_id): self._ext_id = ext_id self._view_index = 0 with ui.ZStack(): self._delegate = GraphNodeDelegate() self._model = Model(self._ext_id) # TODO(anov): remove pan_x, pan_y hardcoded after graph auto align fixed. self._graph_frame = ui.Frame() raster_nodes = carb.settings.get_settings().get("/exts/omni.kit.window.extensions/raster_nodes") with self._graph_frame: self._graph_view = GraphView( delegate=self._delegate, model=self._model, style=GRAPH_STYLE, zoom=0.5, pan_x=1000, pan_y=400, raster_nodes=raster_nodes, ) self._list_frame = ui.Frame() with self._list_frame: self._list_view = ExtsListView(self._model, self._ext_id) self._list_frame.visible = False with ui.VStack(): ui.Spacer() with ui.HStack(height=0): ui.Spacer() with ui.VStack(width=200, height=0, content_clipping=True): ui.Button( "Toggle View", width=200, height=20, mouse_pressed_fn=lambda *_: self._toggle_view(), ) ui.Button( "Copy as Graphviz .dot", width=200, height=20, mouse_pressed_fn=lambda *_: self._model.copy_as_graphviz(), ) ui.Spacer(width=10) ui.Spacer(height=10) def _toggle_view(self): self._view_index = (self._view_index + 1) % 2 self._list_frame.visible = self._view_index == 1 self._graph_frame.visible = self._view_index == 0 def destroy(self): self._delegate = None self._model = None self._list_frame = None self._list_view = None self._graph_frame = None self._graph_view = None class ExtsGraphWindow: """Extensions graph window""" def __init__(self): self._frame = ui.Frame() self._frame.visible = False self._graph_widget = None self.select_ext(None) manager = omni.kit.app.get_app_interface().get_extension_manager() change_stream = manager.get_change_event_stream() self._change_script_sub = change_stream.create_subscription_to_pop( lambda _: self._refresh(), name="ExtsGraphWindow watch for exts" ) def destroy(self): self._frame = None if self._graph_widget: self._graph_widget.destroy() self._change_script_sub = None def _refresh(self): self.set_visible(self._frame.visible) def select_ext(self, ext_id): self._ext_id = ext_id def set_visible(self, visible: bool): if self._frame.visible == visible: if visible: # recreate if already shown self.set_visible(False) else: # if not shown already -> do nothing. return if not visible: self._frame.visible = False else: self._build() self._frame.visible = True def _build(self): with self._frame: if self._graph_widget: self._graph_widget.destroy() self._graph_widget = ExtsGraphWidget(self._ext_id)
omniverse-code/kit/exts/omni.kit.window.extensions/omni/kit/window/extensions/extension.py
# Copyright (c) 2018-2020, 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. # # pylint: disable=attribute-defined-outside-init, protected-access import asyncio import contextlib import weakref from typing import Callable import omni.ext import omni.kit.app import omni.kit.ui import omni.ui as ui from . import common, ext_controller, ext_info_widget from .exts_list_widget import ExtsListWidget from .utils import get_setting from .window import ExtsWindow MENU_PATH = "Window/Extensions" _ext_instance = None def show_window(value: bool): """Show/Hide Extensions window""" if _ext_instance: _ext_instance.show_window(value) def get_instance() -> "weakref.ReferenceType[ExtsWindowExtension]": return weakref.ref(_ext_instance) class ExtsWindowExtension(omni.ext.IExt): """The entry point exts 2.0 window""" def on_startup(self, ext_id): global _ext_instance _ext_instance = self app = omni.kit.app.get_app() common.EXT_ROOT = app.get_extension_manager().get_extension_path(ext_id) self._window = None # # Add to menu - will fail if the editor is not loaded self._menu = None # Throwing is ok, but leaves self._menu undefined with contextlib.suppress(Exception): self._menu = omni.kit.ui.get_editor_menu().add_item( MENU_PATH, lambda _, v: self.show_window(v), toggle=True, value=False, priority=100 ) ui.Workspace.set_show_window_fn( "Extensions", lambda value: self.show_window(value), # pylint: disable=unnecessary-lambda ) # Start enabling autoloadable extensions: asyncio.ensure_future(ext_controller.autoload_extensions()) # Auto show window, for convenience show = get_setting("/exts/omni.kit.window.extensions/showWindow", False) if self._menu: omni.kit.ui.get_editor_menu().set_value(MENU_PATH, show) if show: self.show_window(True) # Some events trigger rebuild of a whole window bus = app.get_message_bus_event_stream() self._subs = [] def on_rebuild(_): if self._window: self.show_window(False) self.show_window(True) self._subs.append(bus.create_subscription_to_pop_by_type(common.COMMUNITY_TAB_TOGGLE_EVENT, on_rebuild)) def on_shutdown(self): global _ext_instance _ext_instance = None self.show_window(False) self._menu = None self._subs = None def show_window(self, value): if value: def on_visibility_changed(visible): omni.kit.ui.get_editor_menu().set_value(MENU_PATH, visible) self._window = ExtsWindow(on_visibility_changed if self._menu else None) else: if self._window: self._window.destroy() self._window = None # -------------------------------------------------------------------------------------------------------------- # API to add a new tab to the extension info pane @classmethod def refresh_extension_info_widget(cls): if _ext_instance._window and _ext_instance._window._ext_info_widget: _ext_instance._window._ext_info_widget.update_tabs() _ext_instance._window._ext_info_widget._refresh() @classmethod def add_tab_to_info_widget(cls, tab: ext_info_widget.PageBase): ext_info_widget.ExtInfoWidget.pages.append(tab) cls.refresh_extension_info_widget() @classmethod def remove_tab_from_info_widget(cls, tab: ext_info_widget.PageBase): if tab in ext_info_widget.ExtInfoWidget.pages: ext_info_widget.ExtInfoWidget.pages.remove(tab) ext_info_widget.ExtInfoWidget.current_page = 0 cls.refresh_extension_info_widget() # -------------------------------------------------------------------------------------------------------------- # API to add a searchable keyword @classmethod def refresh_search_items(cls): if _ext_instance._window and _ext_instance._window._exts_list_widget: _ext_instance._window._exts_list_widget.rebuild_filter_menu() _ext_instance._window._exts_list_widget._model.refresh_all() @classmethod def add_searchable_keyword(cls, keyword: str, description: str, filter_on_keyword: Callable, clear_cache: Callable): ExtsListWidget.searches[keyword] = (description, filter_on_keyword, clear_cache) cls.refresh_search_items() @classmethod def remove_searchable_keyword(cls, keyword_to_remove: str): if keyword_to_remove in ExtsListWidget.searches: del ExtsListWidget.searches[keyword_to_remove] cls.refresh_search_items()
omniverse-code/kit/exts/omni.kit.window.extensions/omni/kit/window/extensions/__init__.py
# flake8: noqa from .ext_commands import ToggleExtension from .ext_components import SimpleCheckBox from .extension import ExtsWindowExtension, get_instance
omniverse-code/kit/exts/omni.kit.window.extensions/omni/kit/window/extensions/ext_controller.py
# Copyright (c) 2018-2020, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. # from functools import lru_cache import carb import carb.settings import omni.kit.app from .utils import ext_id_to_fullname, set_default_and_get_setting DEFERRED_LOAD_SETTING_KEY = "/exts/omni.kit.window.extensions/deferredLoadExts" AUTOLOAD_SETTING_KEY = "/persistent/app/exts/enabled" FEATURED_EXT_SETTING_KEY = "/exts/omni.kit.window.extensions/featuredExts" WAIT_FRAMES_SETTING_KEY = "/exts/omni.kit.window.extensions/waitFramesBetweenEnable" _autoload_exts = None _startup_exts = set() _startup_ext_ids = set() def _get_autoload_exts(): global _autoload_exts if _autoload_exts is None: _autoload_exts = set(set_default_and_get_setting(AUTOLOAD_SETTING_KEY, [])) return _autoload_exts @lru_cache() def _get_featured_exts(): return set(set_default_and_get_setting(FEATURED_EXT_SETTING_KEY, [])) def _save(): exts = _get_autoload_exts() carb.settings.get_settings().set(AUTOLOAD_SETTING_KEY, list(exts)) def toggle_autoload(ext_id: str, toggle: bool): exts = _get_autoload_exts() if toggle: # Disable all other versions ext_manager = omni.kit.app.get_app().get_extension_manager() extensions = ext_manager.fetch_extension_versions(ext_id_to_fullname(ext_id)) for e in extensions: exts.discard(e["id"]) exts.add(ext_id) else: exts.discard(ext_id) _save() def is_autoload_enabled(ext_id: str) -> bool: exts = _get_autoload_exts() return ext_id in exts def is_startup_ext(ext_name: str) -> bool: return ext_name in _startup_exts def is_startup_ext_id(ext_id: str) -> bool: return ext_id in _startup_ext_ids def is_featured_ext(ext_name: str) -> bool: return ext_name in _get_featured_exts() def are_featured_exts_enabled() -> bool: return len(_get_featured_exts()) > 0 async def autoload_extensions(): # Delay for one update until everything else of a core app is loaded await omni.kit.app.get_app().next_update_async() ext_manager = omni.kit.app.get_app().get_extension_manager() wait_frames = set_default_and_get_setting(WAIT_FRAMES_SETTING_KEY, 1) # Enable all deferered extension, one by one. Wait for next frame inbetween each. for ext_id in set_default_and_get_setting(DEFERRED_LOAD_SETTING_KEY, []): ext_manager.set_extension_enabled_immediate(ext_id, True) for _ in range(wait_frames): await omni.kit.app.get_app().next_update_async() # Build list of startup extensions (those that were started by this point) _autoload_exts = _get_autoload_exts() for ext_info in ext_manager.get_extensions(): if ext_info["enabled"] and ext_info["id"] not in _autoload_exts: _startup_exts.add(ext_info["name"]) _startup_ext_ids.add(ext_info["id"])
omniverse-code/kit/exts/omni.kit.window.extensions/omni/kit/window/extensions/utils.py
# Copyright (c) 2018-2020, 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. # # pylint: disable=protected-access, access-member-before-definition import asyncio import contextlib import glob import os import platform import shutil import subprocess from functools import lru_cache from typing import Callable, Tuple import carb import carb.dictionary import carb.settings import omni.kit.commands def call_once_with_delay(fn: Callable, delay: float): """Call function once after `delay` seconds. If this function called again before `delay` is passed the timer gets reset.""" async def _delayed_refresh(): await asyncio.sleep(delay) fn() with contextlib.suppress(Exception): fn._delay_call_task.cancel() fn._delay_call_task = asyncio.ensure_future(_delayed_refresh()) @lru_cache() def is_windows(): return platform.system().lower() == "windows" def run_process(args): print(f"running process: {args}") kwargs = {"close_fds": False} if is_windows(): kwargs["creationflags"] = subprocess.CREATE_NEW_CONSOLE | subprocess.CREATE_NEW_PROCESS_GROUP subprocess.Popen(args, **kwargs) # pylint: disable=consider-using-with def version_to_str(version: Tuple[int, int, int, str, str]) -> str: """Generate string `0.0.0-tag+tag`""" delimiters = ("", ".", ".", "-", "+") return "".join(f"{d}{v}" for d, v in zip(delimiters, version) if str(v) and v is not None) def ext_id_to_fullname(ext_id: str) -> str: return omni.ext.get_extension_name(ext_id) def ext_id_to_name_version(ext_id: str) -> Tuple[str, str]: """Convert 'omni.foo-tag-1.2.3' to 'omni.foo-tag' and '1.2.3'""" a, b, *rest = ext_id.split("-") if b: if not b[0:1].isdigit(): return f"{a}-{b}", "-".join(rest) return a, "-".join([b] + rest) return a, "" def get_ext_info_dict(ext_manager, ext_info) -> Tuple[carb.dictionary.Item, bool]: ext_dict = ext_manager.get_extension_dict(ext_info["id"]) if ext_dict is not None: return (ext_dict, True) return (ext_manager.get_registry_extension_dict(ext_info["package_id"]), False) def get_setting(path, default=None): setting = carb.settings.get_settings().get(path) return setting if setting is not None else default def set_default_and_get_setting(path, default=None): settings = carb.settings.get_settings() settings.set_default(path, default) return settings.get(path) def clip_text(s, max_count=80): return s[:max_count] + ("..." if len(s) > max_count else "") def open_file_using_os_default(path: str): if platform.system() == "Darwin": # macOS subprocess.call(("open", path)) elif platform.system() == "Windows": # Windows os.startfile(path) # noqa: PLE1101 else: # linux variants subprocess.call(("xdg-open", path)) def open_url(url): import webbrowser webbrowser.open(url) def open_using_os_default(path: str): if os.path.isfile(path): open_file_using_os_default(path) else: # open dir import webbrowser webbrowser.open(path) def open_in_vscode(path: str): subprocess.call(["code", path], shell=is_windows()) @lru_cache() def is_vscode_installed(): try: cmd = ["code", "--version"] return subprocess.call(cmd, shell=is_windows(), stdout=subprocess.DEVNULL, stderr=subprocess.STDOUT) == 0 except FileNotFoundError: return False def _search_path_entry_up(path, entry, max_steps_up=3): for _ in range(0, max_steps_up + 1): if os.path.exists(os.path.join(path, entry)): return os.path.normpath(path) new_path = os.path.normpath(os.path.join(path, "..")) if new_path == path: break path = new_path return None def open_in_vscode_if_enabled(path: str, prefer_vscode: bool = True): if prefer_vscode and is_vscode_installed(): # Search for .vscode folder few folders up to open project instead of just extension # 5 steps is enough for '_build/window/release/exts/omni.foo' for instance if os.path.isdir(path): path = _search_path_entry_up(path, ".vscode", max_steps_up=5) or path open_in_vscode(path) else: open_using_os_default(path) def copy_text(text): omni.kit.clipboard.copy(text) def cleanup_folder(path): try: for p in glob.glob(f"{path}/*"): if os.path.isdir(p): if omni.ext.is_link(p): omni.ext.destroy_link(p) else: shutil.rmtree(p) else: os.remove(p) except Exception as exc: # pylint: disable=broad-except carb.log_warn(f"Unable to clean up files: {path}: {exc}") @lru_cache() def get_extpath_git_ext(): try: import omni.kit.extpath.git as git_ext return git_ext except ImportError: return None async def _load_popup_dialog_ext(): app = omni.kit.app.get_app() manager = app.get_extension_manager() if not manager.is_extension_enabled("omni.kit.window.popup_dialog"): manager.set_extension_enabled("omni.kit.window.popup_dialog", True) await app.next_update_async() await app.next_update_async() async def show_ok_popup(title, message, **dialog_kwargs): await _load_popup_dialog_ext() from omni.kit.window.popup_dialog import MessageDialog app = omni.kit.app.get_app() done = False def on_click(d): nonlocal done done = True dialog_kwargs.setdefault("disable_cancel_button", True) dialog = MessageDialog(title=title, message=message, ok_handler=on_click, **dialog_kwargs) dialog.show() while not done: await app.next_update_async() dialog.destroy() async def show_user_input_popup(title, label, default): await _load_popup_dialog_ext() from omni.kit.window.popup_dialog import InputDialog app = omni.kit.app.get_app() value = None def on_click(dialog: InputDialog): nonlocal value value = dialog.get_value() dialog = InputDialog( message=title, pre_label=label, post_label="", default_value=default, ok_handler=on_click, ok_label="Ok", ) dialog.show() while not value: await app.next_update_async() dialog.destroy() return value
omniverse-code/kit/exts/omni.kit.window.extensions/omni/kit/window/extensions/ext_components.py
# Copyright (c) 2018-2020, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. # import asyncio import sys from typing import Callable, Dict import omni.kit.app import omni.ui as ui from .common import ExtensionCommonInfo, ExtSource, build_doc_urls, pull_extension_async, toggle_extension from .styles import get_style from .utils import get_setting, open_url, run_process class ExtensionToggle: def __init__(self, item: ExtensionCommonInfo, with_label=False, show_install_button=True, refresh_cb=None): with ui.HStack(width=0, style=get_style(self)): if item.is_app: def on_click(is_local=item.is_local, ext_id=item.id): manager = omni.kit.app.get_app().get_extension_manager() if not is_local: manager.pull_extension(ext_id) args = [sys.argv[0]] ext_info = manager.get_extension_dict(ext_id) if ext_info.get("isKitFile", False): args.append(ext_info["path"]) else: args.extend(["--enable", ext_id]) # Pass all exts folders for folder in get_setting("/app/exts/folders", default=[]): args.extend(["--ext-folder", folder]) run_process(args) with ui.VStack(): ui.Spacer() ui.Button("LAUNCH", name="LaunchButton", width=60, height=20, clicked_fn=on_click) ui.Spacer() elif not item.is_local: if not show_install_button: return with ui.VStack(): ui.Spacer() if item.is_pulled: ui.Button("INSTALLING...", name="DownloadingButton", width=60, height=20) else: def on_click(item=item): asyncio.ensure_future(pull_extension_async(item)) ui.Button("INSTALL", name="InstallButton", width=60, height=20, clicked_fn=on_click) ui.Spacer() else: if item.failed: with ui.VStack(): ui.Spacer() # OM-90861: Add tooltip for extension depdency solve failure tooltip = "Failed to solve extension dependency." if item.solver_error: tooltip += f"\nError: {item.solver_error}" ui.Image(name="Failed", width=26, height=26, tooltip=tooltip) ui.Spacer() with ui.VStack(): ui.Spacer() name = "clickable" tb = ui.ToolButton(image_width=39, image_height=18, height=0, name=name) tb.model.as_bool = item.enabled def toggle(model, ext_id=item.id, fullname=item.fullname): enable = model.get_value_as_bool() # If we about to enable, toggle other versions if enabled if enable: manager = omni.kit.app.get_app().get_extension_manager() extensions = manager.fetch_extension_versions(fullname) for e in extensions: if e["enabled"] and e["id"] != ext_id: toggle_extension(e["id"], False) if not toggle_extension(ext_id, enable=enable): model.as_bool = not enable if item.is_toggle_blocked: tb.name = "nonclickable" # TODO(anov): how to make ToolButton disabled? def block_change(model, enabled=item.enabled): model.as_bool = enabled tb.model.add_value_changed_fn(block_change) else: tb.model.add_value_changed_fn(toggle) ui.Spacer() if with_label: ui.Spacer(width=8) if item.enabled: ui.Label("ENABLED", name="EnabledLabel") else: ui.Label("DISABLED", name="DisabledLabel") class SimpleCheckBox: def __init__(self, checked: bool, on_checked_fn: Callable, text: str = None, model=None, enabled=True): with ui.HStack(width=0, style=get_style(self)): with ui.VStack(width=0): ui.Spacer() if enabled: tb = ui.ToolButton(image_width=39, image_height=18, height=0, model=model) tb.model.as_bool = checked tb.model.add_value_changed_fn(lambda model: on_checked_fn(model.get_value_as_bool())) else: name = "disabled_checked" if checked else "disabled_unchecked" ui.Image(width=39, height=18, name=name) ui.Spacer() if text: ui.Label(text) class SearchWidget: """String field with a label overlay to type search string into.""" def __init__(self, on_search_fn: Callable[[str], None]): def clear_text(widget): widget.model.set_value("") widget.focus_keyboard() def field_changed(field_string): self._clear_button.visible = len(field_string) > 0 on_search_fn(field_string) self.clear_filters() with ui.ZStack(height=0, style=get_style(self)): # Search filed with ui.HStack(): field_widget = ui.StringField(style_type_name_override="SearchField") self._search = field_widget.model ui.Rectangle(width=20, style={"background_color": 0xFF212121, "border_radius": 0.0}) with ui.HStack(): ui.Spacer() self._clear_button = ui.Button( "", name="ClearSearch", width=16, alignment=ui.Alignment.CENTER, clicked_fn=lambda w=field_widget: clear_text(w), visible=False, ) # The label on the top of the search field with ui.HStack(): ui.Spacer(width=5) with ui.VStack(width=0): ui.Spacer() self._search_icon = ui.Image(name="SearchIcon", width=12, height=13) ui.Spacer() self._search_label = ui.Label("Search", style={"margin_width": 4}, name="Search") # The filtering logic self._begin_filter_sub = self._search.subscribe_begin_edit_fn(lambda _: self._toggle_visible(False)) self._edit_filter_sub = self._search.subscribe_value_changed_fn(lambda m: field_changed(m.as_string)) self._end_filter_sub = self._search.subscribe_end_edit_fn(lambda m: self._toggle_visible(not m.as_string)) def _toggle_visible(self, visible): self._search_label.visible = visible self._search_icon.visible = visible def set_text(self, text): self._search.as_string = text self._toggle_visible(False) def get_text(self): return self._search.as_string def get_filters(self): return self._filters def toggle_filter(self, filter_to_toggle): if filter_to_toggle in self._filters: self._filters.remove(filter_to_toggle) else: self._filters.append(filter_to_toggle) def clear_filters(self): self._filters = [] def destroy(self): self._begin_filter_sub = None self._edit_filter_sub = None self._end_filter_sub = None class ExtSourceSelector: def __init__(self, on_selected_fn): self._on_selected_fn = None self._buttons = {} with ui.HStack(height=20): for index, source in enumerate(ExtSource): ui.Spacer() tab_btn = ui.Button( source.get_ui_name(), width=0, style_type_name_override="ExtensionDescription.Tab", clicked_fn=lambda s=source: self.set_tab(s), ) self._buttons[source] = tab_btn if index < len(ExtSource) - 1: ui.Spacer() ui.Line( style_type_name_override="ExtensionDescription.TabLine", alignment=ui.Alignment.H_CENTER, height=20, width=40, ) ui.Spacer() self.set_tab(ExtSource.NVIDIA) self._on_selected_fn = on_selected_fn def set_badge_number(self, source, number): self._buttons[source].text = source.get_ui_name() + f" ({number})" def set_tab(self, source): for b in self._buttons.values(): b.selected = False self._buttons[source].selected = True if self._on_selected_fn: self._on_selected_fn(source) def add_icon_button(name, on_click): with ui.VStack(width=0): ui.Spacer() b = ui.Button(name=name, style_type_name_override="IconButton", width=23, height=18, clicked_fn=on_click) ui.Spacer() return b def add_doc_link_button(ext_item: ExtensionCommonInfo, package_dict: Dict, docs_dict: Dict): # Create a button, but hide. button = None with ui.VStack(width=0): ui.Spacer() button = ui.Button( name="OpenDoc", style_type_name_override="IconButton", width=23, height=18, style={"Label": {"color": 0xFF444444}}, ) ui.Spacer() button.visible = False def check_url_sync(url): import urllib try: return urllib.request.urlopen(url).getcode() == 200 except urllib.error.HTTPError: return False async def check_urls(doc_urls): for doc_url in doc_urls: # run sync code on other thread not to block if await asyncio.get_event_loop().run_in_executor(None, check_url_sync, doc_url): button.visible = True def on_click(url=doc_url): open_url(url) button.set_clicked_fn(on_click) button.set_tooltip_fn(lambda url=doc_url: ui.Label(url)) break # Async check for URLs and if valid show the button doc_urls = build_doc_urls(ext_item) if doc_urls: asyncio.ensure_future(check_urls(doc_urls))
omniverse-code/kit/exts/omni.kit.window.extensions/omni/kit/window/extensions/ext_data_fetcher.py
# Copyright (c) 2018-2020, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. # import asyncio import json import logging import os from functools import lru_cache from typing import Callable, List import omni.kit.app from .common import ExtensionCommonInfo, get_registry_url logger = logging.getLogger(__name__) class ExtDataFetcher: """Fetches json files near extension archives from the registry and caches them""" def __init__(self): # Notify when anything new fetched self.on_data_fetched_fn: Callable = None # Cached data self._data = {} def get_ext_data(self, package_id) -> dict: return self._data.get(package_id, None) def fetch(self, ext_item: ExtensionCommonInfo): if self.get_ext_data(ext_item.package_id): return json_data_urls = self._build_json_data_urls(ext_item) if json_data_urls: async def read_data(): for json_data_url in json_data_urls: result, _, content = await omni.client.read_file_async(json_data_url) if result == omni.client.Result.OK: try: content = memoryview(content).tobytes().decode("utf-8") self._data[ext_item.package_id] = json.loads(content) if self.on_data_fetched_fn: self.on_data_fetched_fn(ext_item.package_id) # noqa break except Exception as e: # noqa logger.error("Error reading extra registry data from: %s. Error: %s", json_data_url, e) asyncio.ensure_future(read_data()) def _build_json_data_urls(self, ext_item: ExtensionCommonInfo) -> List[str]: ext_manager = omni.kit.app.get_app().get_extension_manager() ext_remote_info = ext_manager.get_registry_extension_dict(ext_item.package_id) registry_url = get_registry_url(ext_item.provider_name) if not registry_url: return None # Same as archive path, but extension is `.json`: archive_path = ext_remote_info.get("package", {}).get("archivePath", None) if archive_path: # build url relative to the registry url archive_path = archive_path.replace("\\", "/") archive_path = omni.client.combine_urls(registry_url + "/index.zip", archive_path) archive_path = omni.client.normalize_url(archive_path) archive_path = os.path.splitext(archive_path)[0] + ".json" if omni.client.break_url(archive_path).host == omni.client.break_url(registry_url).host: return [archive_path] # that means archive path is on different host (like packman). Do the best guess using registry url. # Old format is one big folder, new format is a subfolder for each extension data_filename = os.path.basename(archive_path) return [ "{}/archives/{}".format(registry_url, data_filename), "{}/archives/{}/{}".format(registry_url, ext_item.fullname, data_filename), ] return None @lru_cache() def get_ext_data_fetcher(): return ExtDataFetcher()
omniverse-code/kit/exts/omni.kit.window.extensions/omni/kit/window/extensions/markdown_renderer.py
# Copyright (c) 2018-2020, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. # import omni.ui as ui from .styles import get_style class MarkdownText: def __init__(self, content): with ui.VStack(height=0, style=get_style(self)): def consume_heading(s): heading = 0 while s.startswith("#"): s = s[1:] heading += 1 return heading, s.lstrip() for line in content.splitlines(): line = line.lstrip() heading, line = consume_heading(line) style_name = "text" if heading > 0: style_name = f"H{heading}" ui.Label(line, name=style_name, height=0, word_wrap=True)
omniverse-code/kit/exts/omni.kit.window.extensions/omni/kit/window/extensions/exts_list_widget.py
# Copyright (c) 2018-2020, 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. # # pylint: disable=attribute-defined-outside-init, protected-access, # pylint: disable=access-member-before-definition, unnecessary-lambda-assignment import asyncio import contextlib import fnmatch from collections import OrderedDict, defaultdict from enum import IntFlag from functools import lru_cache from typing import Callable, List, Optional import carb import carb.events import carb.settings import omni.kit.app import omni.kit.commands import omni.ui as ui from omni.kit.widget.filter import FilterButton from omni.kit.widget.options_menu import OptionItem from omni.ui import color as cl from .common import ( EXTENSION_PULL_STARTED_EVENT, REGISTRIES_CHANGED_EVENT, ExtAuthorGroup, ExtensionCommonInfo, ExtSource, get_categories, get_open_example_links, is_community_tab_enabled, ) from .ext_components import ExtensionToggle, ExtSourceSelector, SearchWidget from .ext_controller import are_featured_exts_enabled from .ext_export_import import import_ext from .ext_template import create_new_extension_template from .styles import ( EXT_ICON_SIZE, EXT_ITEM_TITLE_BAR_H, EXT_LIST_ITEM_H, EXT_LIST_ITEM_ICON_ZONE_W, EXT_LIST_ITEMS_MARGIN_H, ) from .utils import get_ext_info_dict, get_extpath_git_ext ext_manager = None # Sync only once for now @lru_cache() def _sync_registry(): ext_manager.refresh_registry() class ExtGroupItem(ui.AbstractItem): def __init__(self, name): super().__init__() self.name = name self.total_count = 0 self.items = [] self.ext_source = ExtSource.NVIDIA def contains(self, ext_summary): return True def is_expanded_by_default(self): return True class ExtFeatureGroupItem(ExtGroupItem): def contains(self, ext_summary): return ext_summary.feature class ExtToggleableGroupItem(ExtGroupItem): def contains(self, ext_summary): return ext_summary.toggleable class ExtNonToggleableGroupItem(ExtGroupItem): def contains(self, ext_summary): return not ext_summary.toggleable def is_expanded_by_default(self): return False class ExtAuthorGroupItem(ExtGroupItem): def __init__(self, name, author_group: ExtAuthorGroup): super().__init__(name) self.author_group = author_group self.ext_source = ExtSource.THIRD_PARTY def contains(self, ext_summary): return ext_summary.author_group == self.author_group def is_expanded_by_default(self): return True class ExtSummaryItem(ui.AbstractItem): """An abstract item that represents an extension summary""" def refresh(self, ext_summary): self.fullname = ext_summary["fullname"] self.flags = ext_summary["flags"] self.enabled_ext = ext_summary["enabled_version"] self.latest_ext = ext_summary["latest_version"] self.default_ext = self.latest_ext self.enabled = bool(self.flags & omni.ext.EXTENSION_SUMMARY_FLAG_ANY_ENABLED) if self.enabled: self.default_ext = self.enabled_ext self.id = self.default_ext["id"] is_latest = self.enabled_ext["id"] == self.latest_ext["id"] self.can_update = self.enabled and not is_latest # Query more info ext_info, is_local = get_ext_info_dict(ext_manager, self.default_ext) # Take latest version (in terms of semver) and grab publish date from it if any, for sorting invert it. latest_info = ext_info if is_latest else get_ext_info_dict(ext_manager, self.latest_ext)[0] publish_date = latest_info.get("package", {}).get("publish", {}).get("date", 0) self.publish_date_rev = -publish_date # Move all attributes from ExtensionCommonInfo class to this class self.__dict__.update(ExtensionCommonInfo(self.id, ext_info, is_local).__dict__) class ExtSummariesModel(ui.AbstractItemModel): """Extension summary model that watches the changes in ext manager""" class SortDirection(IntFlag): NONE = 0 Ascending = 1 Descending = 2 def __init__(self, flat=None): super().__init__() global ext_manager app = omni.kit.app.get_app() ext_manager = app.get_extension_manager() self._ext_summaries = {} # Order matters here, because contains() matches first group self._groups = [ ExtAuthorGroupItem("User", ExtAuthorGroup.USER), ExtAuthorGroupItem("Partner", ExtAuthorGroup.PARTNER), ExtAuthorGroupItem("Community - Verified", ExtAuthorGroup.COMMUNITY_VERIFIED), ExtAuthorGroupItem("Community - Unverified", ExtAuthorGroup.COMMUNITY_UNVERIFIED), ExtFeatureGroupItem("Feature"), ExtToggleableGroupItem("General"), ExtNonToggleableGroupItem("Non-Toggleable"), ] # Attribute in ExtSummaryItem to sort by. For each attribute store order of sort in a dict (can be toggled) self._sort_attr = "name" self._sort_direction = ExtSummariesModel.SortDirection.Ascending # exscribe for ext manager changes and generic event def on_change(*_): self._resync_exts() self._subs = [] self._subs.append( ext_manager.get_change_event_stream().create_subscription_to_pop( on_change, name="ExtSummariesModel watch for exts" ) ) bus = app.get_message_bus_event_stream() self._subs.append(bus.create_subscription_to_pop_by_type(REGISTRIES_CHANGED_EVENT, on_change)) self._subs.append(bus.create_subscription_to_pop_by_type(EXTENSION_PULL_STARTED_EVENT, on_change)) # Current name filter self._filter_name_text = [] # Current category filter self._filter_category = "" # Current ext source self._filter_ext_source = ExtSource.NVIDIA # Hacky link back to tree view to be able to update expanded state self.tree_view = None # on refresh callback self.on_refresh_cb = None # Builds a list self._resync_exts() def resync_registry(self): ext_manager.refresh_registry() def refresh_all(self): self._resync_exts() def _resync_exts(self): get_extpath_git_ext.cache_clear() for (_, _, clear_cache) in ExtsListWidget.searches.values(): if clear_cache is not None: clear_cache() _sync_registry() ext_summaries = ext_manager.fetch_extension_summaries() # groups for g in self._groups: g.total_count = 0 self._ext_summaries = {} for ext_s in ext_summaries: item = ExtSummaryItem() item.refresh(ext_s) # assign group item.group = next(x for x in self._groups if x.contains(item)) item.group.total_count += 1 self._item_changed(item) self._ext_summaries[ext_s["fullname"]] = item self._item_changed(None) # Update expanded state after tree was built and rendered async def _delayed_expand(): await omni.kit.app.get_app().next_update_async() if self.tree_view: for g in self._groups: self.tree_view.set_expanded(g, g.is_expanded_by_default(), False) if self.tree_view: asyncio.ensure_future(_delayed_expand()) self._sorted_summaries = list(self._ext_summaries.values()) self._make_sure_sorted() def _refresh_item_group_lists(self): # Filtering logic here: matching_fns = [] # Split text in words and look for @keywords. Add matching functions and remove from the list. # To remove from list while iterating use backward iteration trick. parts = self._filter_name_text.copy() for i in range(len(parts) - 1, -1, -1): w = parts[i] if w.startswith("@"): # Predefined keywords or use default ones fn = ExtsListWidget.searches.get(w, [None, None, None])[1] if fn is None: fn = lambda item, w=w: w[1:] in item.keywords matching_fns.append(fn) del parts[i] # Whatever left just use as wildcard search: if len(parts) > 0: for part in parts: filter_str = f"*{part.lower()}*" matching_fns.append( lambda item, filter_str=filter_str: fnmatch.fnmatch(item.name.lower(), filter_str) or fnmatch.fnmatch(item.fullname.lower(), filter_str) ) # If category filter enabled, add matching function for it if len(self._filter_category) != 0: matching_fns.append(lambda item: self._filter_category == item.category) else: hidden_categories = [c for c, v in get_categories().items() if v.get("hidden", False)] matching_fns.append(lambda item: item.category not in hidden_categories) # Show item only if it matches all matching functions for group in self._groups: group.items = [v for v in self._sorted_summaries if v.group == group and all(f(v) for f in matching_fns)] self._item_changed(group) # callback if self.on_refresh_cb: self.on_refresh_cb() def get_item_children(self, item): """Reimplemented from AbstractItemModel""" if item is None: self._refresh_item_group_lists() return [g for g in self._groups if g.total_count and g.ext_source == self._filter_ext_source] if isinstance(item, ExtGroupItem): return item.items return [] def get_item_value_model_count(self, item): """Reimplemented from AbstractItemModel""" return 1 def get_item_value_model(self, item, column_id): """Reimplemented from AbstractItemModel""" return def filter_by_text(self, filter_name_text, filters): """Specify the filter string that is used to reduce the model""" new_list = filters + [filter_name_text] if self._filter_name_text == new_list and not new_list: return self._filter_name_text = new_list # Avoid refreshing on every key typed, as it can be slow. Add delay: self._refresh_once_with_delay(delay=0.3) def select_category(self, filter_category): # Special case for "All" => "" if self._filter_category == filter_category: return self._filter_category = filter_category self._refresh_once_with_delay(delay=0.1) def select_ext_source(self, ext_source): if self._filter_ext_source == ext_source: return False self._filter_ext_source = ext_source self._resync_exts() return True def _refresh_once_with_delay(self, delay: float): """Call refresh once after `delay` seconds. If called again before `delay` is passed the timer gets reset.""" async def _delayed_refresh(): await asyncio.sleep(delay) self._item_changed(None) with contextlib.suppress(Exception): self._refresh_task.cancel() self._refresh_task = asyncio.ensure_future(_delayed_refresh()) def sort_by_attr(self, attr: str): """Sort by item attribute.""" if attr is None: return if self._sort_attr != attr: self._sort_attr = attr self._make_sure_sorted() def sort_direction(self, direction: SortDirection): """Sort by direction.""" if direction is None: return self._sort_direction = direction self._make_sure_sorted() def _make_sure_sorted(self): # Sort order setting is global reverse = self._sort_direction == ExtSummariesModel.SortDirection.Descending # Attribute value getter key_fn = lambda x: getattr(x, self._sort_attr) cmp_fn = (lambda x, y: x >= y) if reverse else (lambda x, y: x <= y) # Check that it is already sorted to avoid list rebuild is_sorted_fn = lambda l: all(cmp_fn(key_fn(l[i]), key_fn(l[i + 1])) for i in range(len(l) - 1)) if not is_sorted_fn(self._sorted_summaries): self._sorted_summaries = sorted(self._sorted_summaries, key=key_fn, reverse=reverse) self._item_changed(None) def destroy(self): self._ext_summaries = {} self._sorted_summaries = [] self._subs = None self.tree_view = None self.on_refresh_cb = None class ExtsDelegate(ui.AbstractItemDelegate): def build_branch(self, model, item, column_id, level, expanded): """ui.AbstractItemDelegate API: Create a branch widget that opens or closes subtree""" return def build_widget(self, model, item, column_id, level, expanded): """ui.AbstractItemDelegate API: Create a widget per column""" if isinstance(item, ExtGroupItem): with ui.ZStack(): with ui.VStack(): ui.Spacer(height=1) ui.Rectangle(height=30, name="ExtensionListGroup") with ui.HStack(): image_name = "expanded" if expanded else "" ui.Image( style_type_name_override="ExtensionList.Group.Icon", name=image_name, width=31, height=31, alignment=ui.Alignment.LEFT_CENTER, ) ui.Label( "{} ({}/{})".format(item.name, len(item.items), item.total_count), style_type_name_override="ExtensionList.Group.Label", ) return h = EXT_LIST_ITEM_H - EXT_ITEM_TITLE_BAR_H with ui.VStack(height=EXT_LIST_ITEM_H + EXT_LIST_ITEMS_MARGIN_H): with ui.ZStack(): with ui.VStack(height=0): ui.Rectangle(height=EXT_LIST_ITEM_H, style_type_name_override="ExtensionList.Background") ui.Rectangle(height=EXT_LIST_ITEMS_MARGIN_H, style_type_name_override="ExtensionList.Separator") with ui.VStack(): # Top row with ui.HStack(height=EXT_ITEM_TITLE_BAR_H): # Title ui.Label( item.title, style_type_name_override="ExtensionList.Label", name="Title", elided_text=True ) # Toggle ExtensionToggle(item, show_install_button=not item.is_untrusted) ui.Spacer(width=5) with ui.HStack(): with ui.HStack(width=EXT_LIST_ITEM_ICON_ZONE_W): ui.Spacer() with ui.VStack(width=EXT_ICON_SIZE[0]): ui.Spacer() ui.Image(item.icon_path, height=EXT_ICON_SIZE[1], style={"color": 0xFFFFFFFF}) ui.Spacer() ui.Spacer() with ui.ZStack(): ui.Rectangle(height=h, style_type_name_override="ExtensionList.Foreground") with ui.VStack(): ui.Spacer(height=5) # Category name category = get_categories().get(item.category) ui.Label( category["name"], height=0, style_type_name_override="ExtensionList.Label", name="Category", ) # Extension id ui.Label( item.fullname, height=0, style_type_name_override="ExtensionList.Label", name="Id", elided_text=True, ) # Version if item.version and item.version[0:3] != (0, 0, 0): ui.Label( "v" + item.version, style_type_name_override="ExtensionList.Label", name="Version", alignment=ui.Alignment.BOTTOM, ) # Update available? # if item.can_update: with ui.VStack(): ui.Spacer(height=10) with ui.HStack(): ui.Spacer() if item.can_update: ui.Image( name="UpdateAvailable", width=28, height=31, alignment=ui.Alignment.RIGHT_CENTER, ) ui.Spacer(width=10) if item.can_update: ui.Label( "UPDATE AVAILABLE", alignment=ui.Alignment.RIGHT_CENTER, name="UpdateAvailable" ) elif item.author_group != ExtAuthorGroup.NVIDIA: with ui.HStack(): ui.Spacer() with ui.VStack(width=148, height=0): ui.Spacer() with ui.ZStack(): ui.Image( name="Community", width=148, height=32, alignment=ui.Alignment.RIGHT_BOTTOM, ) name = item.author_group.get_ui_name() ui.Label(name, alignment=ui.Alignment.RIGHT_CENTER, name="Community") elif item.location_tag: ui.Label(item.location_tag, alignment=ui.Alignment.RIGHT_CENTER, name="LocationTag") ui.Spacer() def build_header(self, column_id): pass class ExtsListWidget: # Search configuration information as SearchKey:(SearchUiName, FilterBySearchKey, ClearSearchCache) searches = OrderedDict( { "@startup": ("Startup", lambda item: item.is_startup, None), "@featured": ("Featured", lambda item: item.is_featured or item.ext_source == ExtSource.THIRD_PARTY, None), "@bundled": ("Bundled", lambda item: bool(item.flags & omni.ext.EXTENSION_SUMMARY_FLAG_BUILTIN), None), "@user": ("User", lambda item: item.author_group == ExtAuthorGroup.USER, None), "@app": ("App", lambda item: item.is_app, None), "@enabled": ("Enabled", lambda item: bool(item.flags & omni.ext.EXTENSION_SUMMARY_FLAG_ANY_ENABLED), None), "@update": ("Update Available", lambda item: item.can_update, None), "@installed": ( "Installed", lambda item: bool(item.flags & omni.ext.EXTENSION_SUMMARY_FLAG_INSTALLED), None, ), "@remote": ("Remote", lambda item: not bool(item.flags & omni.ext.EXTENSION_SUMMARY_FLAG_BUILTIN), None), } ) # remove "Featured" when not in use if not are_featured_exts_enabled(): del searches["@featured"] def __init__(self): # Extensions List Data Model self._model = ExtSummariesModel() self._model.on_refresh_cb = self._on_ext_list_refresh menu_style = { "padding": 2, "Menu.Item.CheckMark": {"color": cl.shade(cl("#34C7FF"))}, "Titlebar.Background": {"background_color": cl.shade(cl("#1F2123"))}, "Titlebar.Title": {"color": cl.shade(cl("#848484"))}, "Titlebar.Reset": {"background_color": 0}, "Titlebar.Reset.Label": {"color": cl.shade(cl("#2E86A9"))}, "Titlebar.Reset.Label:hovered": {"color": cl.shade(cl("#34C7FF"))}, } # Delegate to build list rows. self._delegate = ExtsDelegate() self.set_show_graph_fn(None) self.set_show_properties_fn(None) # Filter button self._filter_button: Optional[FilterButton] = None # Sort menu. One day it will be a hamburger. One can dream. self._sortby_menu = ui.Menu("Sort By", style=menu_style, menu_compatibility=False, tearable=False) self.rebuild_sortby_menu() self._options_menu = ui.Menu("Options", style=menu_style, menu_compatibility=False, tearable=False) self.rebuild_options_menu() # Extension creation menu self._create_menu = ui.Menu("Create", style=menu_style, menu_compatibility=False, tearable=False) self.rebuild_create_menu() def _menu_header(self, title, clicked_fn): with ui.ZStack(height=0): ui.Rectangle(style_type_name_override="Titlebar.Background") with ui.VStack(): ui.Spacer(height=3) with ui.HStack(): ui.Spacer(width=10) ui.Label(title, style_type_name_override="Titlebar.Title") ui.Spacer() ui.Button( "Reset all" if clicked_fn else " ", style_type_name_override="Titlebar.Reset", clicked_fn=clicked_fn, ) ui.Spacer(width=10) ui.Spacer(height=2) def rebuild_filter_menu(self): if self._filter_button: option_items = self._build_filter_items() self._filter_button.model.rebuild_items(option_items) def rebuild_sortby_menu(self): def reset_sort(): asyncio.ensure_future(update_sort("name", ExtSummariesModel.SortDirection.Ascending)) async def update_sort(sb: str, sd: ExtSummariesModel.SortDirection): if sb: await omni.kit.app.get_app().next_update_async() self._model.sort_by_attr(sb) if sd is not ExtSummariesModel.SortDirection.NONE: await omni.kit.app.get_app().next_update_async() self._model.sort_direction(sd) sort_by = self._model._sort_attr sort_direction = self._model._sort_direction # change button color self._sortby_button.name = ( "sortby" if sort_by == "name" and sort_direction == ExtSummariesModel.SortDirection.Ascending else "sortby_on" ) self._sortby_menu.clear() with self._sortby_menu: self._menu_header("Sort", reset_sort) ui.MenuItem( "Name", triggered_fn=lambda: asyncio.ensure_future( update_sort("name", ExtSummariesModel.SortDirection.NONE) ), checkable=True, checked=sort_by == "name", ) ui.MenuItem( "Enabled", triggered_fn=lambda: asyncio.ensure_future( update_sort("enabled", ExtSummariesModel.SortDirection.NONE) ), checkable=True, checked=sort_by == "enabled", ) ui.MenuItem( "Publish Date", triggered_fn=lambda: asyncio.ensure_future( update_sort("publish_date_rev", ExtSummariesModel.SortDirection.NONE) ), checkable=True, checked=sort_by == "publish_date_rev", ) ui.Separator() ui.MenuItem( "Ascending", triggered_fn=lambda: asyncio.ensure_future( update_sort(None, ExtSummariesModel.SortDirection.Ascending) ), checkable=True, checked=sort_direction == ExtSummariesModel.SortDirection.Ascending, ) ui.MenuItem( "Descending", triggered_fn=lambda: asyncio.ensure_future( update_sort(None, ExtSummariesModel.SortDirection.Descending) ), checkable=True, checked=sort_direction == ExtSummariesModel.SortDirection.Descending, ) asyncio.ensure_future(update_sort(None, ExtSummariesModel.SortDirection.NONE)) def rebuild_options_menu(self): self._options_menu.clear() with self._options_menu: self._menu_header("Options", None) ui.MenuItem("Settings", triggered_fn=self._show_properties) ui.MenuItem("Refresh", triggered_fn=self._model.refresh_all) ui.MenuItem("Resync Registry", triggered_fn=self._resync_registry) ui.MenuItem("Show Extension Graph", triggered_fn=self._show_graph) ui.MenuItem("Import Extension", triggered_fn=import_ext) def rebuild_create_menu(self): def open_url(url): import webbrowser webbrowser.open(url) self._create_menu.clear() with self._create_menu: self._menu_header("Create Extension", None) ui.MenuItem("New Extension Template Project", triggered_fn=create_new_extension_template) for name, url in get_open_example_links(): ui.MenuItem(name, triggered_fn=lambda u=url: open_url(u)) def _on_key_pressed(self, key, mod, pressed): """Allow up/down arrow to be used to select prev/next extension""" def _select_next(treeview: ui.TreeView, model: ui.AbstractItemModel, after=True): full_list = model.get_item_children(None) selection = treeview.selection if not selection: treeview.selection = [full_list[0]] else: index = full_list.index(selection[0]) index += 1 if after else -1 if index < 0 or index >= len(full_list): return treeview.selection = [full_list[index]] if not pressed: return if mod == 0 and key == int(carb.input.KeyboardInput.DOWN): _select_next(self.tree_view, self._model, after=True) elif mod == 0 and key == int(carb.input.KeyboardInput.UP): _select_next(self.tree_view, self._model, after=False) def _on_selection_changed(self, selection): item = selection[0] if len(selection) > 0 else None if item and isinstance(item, ExtGroupItem): self.tree_view.set_expanded(item, not self.tree_view.is_expanded(item), False) self.tree_view.clear_selection() else: self._ext_selected_fn(item) def _on_ext_list_refresh(self): cnt = defaultdict(int) for group in self._model._groups: cnt[group.ext_source] += len(group.items) for source, value in cnt.items(): self._ext_source_selector.set_badge_number(source, value) async def __update_filter(self, search_key: str) -> None: if search_key: self._search.toggle_filter(search_key) await omni.kit.app.get_app().next_update_async() self._filter_by_text(self._search.get_text(), self._search.get_filters()) def _build_filter_items(self) -> List[OptionItem]: option_items = [] filters = self._search.get_filters() for search_key, (search_description, _, _) in self.searches.items(): option_item = OptionItem( search_description, on_value_changed_fn=lambda m, sk=search_key: asyncio.ensure_future(self.__update_filter(sk)), ) option_item.model.set_value(search_key in filters) option_items.append(option_item) return option_items def _build_filter_button(self): option_items = self._build_filter_items() self._filter_button = FilterButton(option_items) def build(self): with ui.VStack(spacing=3): with ui.HStack(height=0): # Create button ui.Button(name="create", width=22, height=22, clicked_fn=self._create_menu.show) # Search field with ui.HStack(width=ui.Fraction(2)): self._search = SearchWidget( on_search_fn=lambda t: self._filter_by_text(t, self._search.get_filters()) ) if are_featured_exts_enabled(): self._search.toggle_filter("@featured") ui.Spacer(width=10) # Category selector category_list = [("All", "")] + [(v["name"], c) for c, v in get_categories().items()] self._category_combo = ui.ComboBox(0, *[c[0] for c in category_list], style={"padding": 4}) self._category_combo.model.add_item_changed_fn( lambda model, item: self._select_category(category_list[model.get_item_value_model(item).as_int][1]) ) ui.Spacer(width=5) # Filter button self._build_filter_button() # Sort-By button self._sortby_button = ui.Button(name="sortby", width=24, height=24, clicked_fn=self._sortby_menu.show) # Properies ui.Button(name="options", width=24, height=24, clicked_fn=self._options_menu.show) # Source selector (community tab) self._ext_source_selector = None if is_community_tab_enabled(): self._ext_source_selector = ExtSourceSelector(self._select_ext_source) frame = ui.ScrollingFrame( horizontal_scrollbar_policy=ui.ScrollBarPolicy.SCROLLBAR_ALWAYS_OFF, vertical_scrollbar_policy=ui.ScrollBarPolicy.SCROLLBAR_ALWAYS_ON, style_type_name_override="TreeView", ) with frame: with ui.ZStack(): self.tree_view = ui.TreeView( self._model, header_visible=False, delegate=self._delegate, column_widths=[ui.Fraction(1)], root_visible=False, keep_expanded=False, ) self._model.tree_view = self.tree_view self.tree_view.set_selection_changed_fn(self._on_selection_changed) # make that public self.clear_selection = self.tree_view.clear_selection frame.set_key_pressed_fn(self._on_key_pressed) def set_show_graph_fn(self, fn: Callable): self._show_graph_fn = fn def set_ext_selected_fn(self, fn: Callable): self._ext_selected_fn = fn def _resync_registry(self): self._model.resync_registry() def _show_graph(self): if self._show_graph_fn: self._show_graph_fn() def set_show_properties_fn(self, fn: Callable): self._show_properties_fn = fn def _show_properties(self): if self._show_properties_fn: self._show_properties_fn() def _filter_by_text(self, filter_text: str, filters: list): """Set the search filter string to the models and widgets""" self._model.filter_by_text(filter_text, filters) def _select_category(self, category: str): """Set the category to show""" self._model.select_category(category) def _select_ext_source(self, ext_source): self._model.select_ext_source(ext_source) def destroy(self): self._delegate = None if self._filter_button: self._filter_button.destroy() self._filter_button = None self._sortby_menu = None self._options_menu = None self._search.destroy() self._search = None self._category_combo = None self._model.destroy() self._model = None
omniverse-code/kit/exts/omni.kit.window.extensions/omni/kit/window/extensions/ext_commands.py
# Copyright (c) 2018-2020, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. # import omni.kit.app import omni.kit.commands class ToggleExtension(omni.kit.commands.Command): """ Toggle extension **Command**. Enables/disables an extension. Args: ext_id(str): Extension id. enable(bool): Enable or disable. """ def __init__(self, ext_id: str, enable: bool): self._ext_id = ext_id self._enable = enable self._ext_manager = omni.kit.app.get_app().get_extension_manager() def do(self): manager = omni.kit.app.get_app().get_extension_manager() manager.set_extension_enabled_immediate(self._ext_id, self._enable) omni.kit.app.send_telemetry_event( "omni.kit.window.extensions@enable_ext", data1=self._ext_id, value1=float(self._enable) )
omniverse-code/kit/exts/omni.kit.window.extensions/omni/kit/window/extensions/ext_template.py
# pylint: disable=protected-access import asyncio import glob import os import re import sys from datetime import datetime from itertools import chain from pathlib import Path from string import Template import carb.tokens import omni.ext import omni.kit.app from . import ext_controller from .ext_export_import import _ask_user_for_path from .utils import open_in_vscode_if_enabled, show_ok_popup, show_user_input_popup def substitute_tokens_in_file(path, tokens): try: with open(path, "r", encoding="utf-8") as f: content = Template(f.read()).safe_substitute(tokens) except UnicodeDecodeError: # Non-text file, ignore return with open(path, "w", encoding="utf-8") as f: f.write(content) def is_subpath(path, root): return root in path.parents def _copy_template(src, dst, ext_id, python_module_path): import shutil from distutils.dir_util import copy_tree # noqa: PLW0612, PLW4901 from os.path import join copy_tree(join(src, "tools"), join(dst, "tools")) copy_tree(join(src, "vscode"), join(dst, ".vscode")) shutil.copy(join(src, "README.md"), join(dst, "README.md")) shutil.copy(join(src, "gitignore"), join(dst, ".gitignore")) shutil.copy(join(src, "link_app.bat"), join(dst, "link_app.bat")) shutil.copy(join(src, "link_app.sh"), join(dst, "link_app.sh")) copy_tree(join(src, "exts", "[ext_id]", "[python_module]"), join(dst, "exts", ext_id, python_module_path)) copy_tree(join(src, "exts", "[ext_id]", "config"), join(dst, "exts", ext_id, "config")) copy_tree(join(src, "exts", "[ext_id]", "docs"), join(dst, "exts", ext_id, "docs")) copy_tree(join(src, "exts", "[ext_id]", "data"), join(dst, "exts", ext_id, "data")) async def _create_new_extension_template(): export_path = await _ask_user_for_path( is_export=True, apply_button_label="Select", title="Choose a location for your extension project" ) if not export_path: return project_folder = await show_user_input_popup( "Name the extension project. This is the root folder of the repository.", "Project Name: ", "kit-exts-project" ) export_path = os.path.join(export_path, project_folder) # Create folder os.makedirs(export_path, exist_ok=True) if len(os.listdir(export_path)) > 0: await show_ok_popup("Error", f"Folder already exist: {export_path}") return template_path = carb.tokens.get_tokens_interface().resolve("${omni.kit.window.extensions}/ext_template") if sys.platform == "win32": kit_exec = "kit.exe" python_exe = "python.exe" else: kit_exec = "kit" python_exe = "bin/python3" ext_id = await show_user_input_popup("Choose Extension Name:", "ext_id: ", "company.hello.world") ext_name = "".join([token.capitalize() for token in ext_id.split(".")]) ext_title = " ".join(ext_id.split(".")) ext_id_pattern = r"^[a-zA-Z0-9._]+$" if not re.match(ext_id_pattern, ext_id): await show_ok_popup("Error", f"Invalid extension name: {ext_id}. Supported chars: {ext_id_pattern}") return python_module = ext_id python_module_path = ext_id.replace(".", "/") # copy template folder _copy_template(template_path, export_path, ext_id, python_module_path) # Find app root def _look_for_app_root(path): path = Path(path) for p in chain([path], path.parents): for kit_subpath in ["", "kit"]: if p.joinpath(kit_subpath, kit_exec).is_file(): return str(p), str(kit_subpath) return None, None app_path = carb.tokens.get_tokens_interface().resolve("${app}") app_root_path, kit_subpath = _look_for_app_root(app_path) if not app_root_path: await show_ok_popup("Error", f"Can't find app root in {app_root_path}") return # build vscode exts search paths: ext_relative_paths = [] app = omni.kit.app.get_app() manager = app.get_extension_manager() for folder in manager.get_folders(): path_type = folder["type"] if path_type == omni.ext.ExtensionPathType.COLLECTION: path = Path(folder["path"]) if is_subpath(path, Path(app_root_path)): for p in glob.glob(f"{path}/*"): if os.path.isdir(p): s = ' "${{workspaceFolder}}/app/{}",'.format( Path(p).relative_to(app_root_path).as_posix() ) ext_relative_paths.append(s) export_exts_path = f"{export_path}/exts" export_app_path = f"{export_path}/app" # substitute all tokens tokens = { "ext_id": ext_id, "ext_name": ext_name, "ext_title": ext_title, "kit_subpath": kit_subpath + "/" if kit_subpath else "", "python_exe": python_exe, "python_module": python_module, "ext_search_paths": "\n".join(ext_relative_paths), "export_path": export_path, "export_exts_path": export_exts_path, "export_app_path": export_app_path, "author": os.environ.get("USERNAME", "please fill in author information"), "today": datetime.today().strftime("%Y-%m-%d"), } for folder, _, files in os.walk(export_path): for filename in files: substitute_tokens_in_file(os.path.join(folder, filename), tokens) # create link omni.ext.create_link(export_app_path, app_root_path) # try open in vscode: open_in_vscode_if_enabled(export_path, prefer_vscode=True) # add new search path (remove + add will trigger fs search for sure) manager.remove_path(export_exts_path) manager.add_path(export_exts_path, omni.ext.ExtensionPathType.COLLECTION_USER) await app.next_update_async() # Enable that one ext and make it autoload manager.set_extension_enabled(ext_id, True) ext_controller.toggle_autoload(f"{ext_id}-1.0.0", True) # Focus on it from .extension import get_instance instance = get_instance()() instance._window._ext_info_widget._refresh_once_next_frame() instance._window._exts_list_widget._search.set_text(ext_id) def create_new_extension_template(): asyncio.ensure_future(_create_new_extension_template())
omniverse-code/kit/exts/omni.kit.window.extensions/omni/kit/window/extensions/exts_properties_registries.py
# Copyright (c) 2018-2020, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. # import carb import carb.dictionary import carb.settings import omni.kit.app import omni.ui as ui from .common import REGISTRIES_CHANGED_EVENT, USER_REGISTRIES_SETTING, get_registries from .ext_components import SimpleCheckBox from .styles import get_style from .utils import copy_text, get_setting DEFAUT_PUBLISH_SETTING = "app/extensions/registryPublishDefault" EMPTY_REGISTRY_NAME = "[enter_name]" REGISTRIES_COLUMNS = ["name", "url", "default", "user"] class RegistryItem(ui.AbstractItem): def __init__(self, name, url, is_user=True, is_default=False, add_dummy=False): super().__init__() self.name_model = ui.SimpleStringModel(name) self.url_model = ui.SimpleStringModel(url) self.default_model = ui.SimpleBoolModel(is_default) self.is_user = is_user self.add_dummy = add_dummy class RegistriesModel(ui.AbstractItemModel): def __init__(self): super().__init__() self._children = [] self._load() self._add_dummy = RegistryItem("", "", add_dummy=True) self._default_changing = False def destroy(self): self._children = [] def get_item_children(self, item): """Returns all the children when the widget asks it.""" if item is not None: return [] return self._children + [self._add_dummy] def get_item_value_model_count(self, item): """The number of columns""" return 4 def get_item_value_model(self, item, column_id): if column_id == 0: return item.name_model if column_id == 1: return item.url_model return None def _load(self): self._children = [] default_registry = get_setting(DEFAUT_PUBLISH_SETTING, "") # Registries ui.Label("Registries:") for name, url, is_user in get_registries(): self._children.append(RegistryItem(name, url, is_user, is_default=(name == default_registry))) self._item_changed(None) def add_empty(self): self._children.append(RegistryItem(EMPTY_REGISTRY_NAME, "", is_user=True)) self._item_changed(None) def remove_item(self, item): self._children.remove(item) self._item_changed(None) self.save() def save(self): registries = [] for child in self._children: if child.is_user: name = child.name_model.as_string url = child.url_model.as_string if name and url: # Auto fill name? if name == EMPTY_REGISTRY_NAME: name = "/".join(url.split("/")[-2:]) # Take last 2 child.name_model.as_string = name registries.append({"name": name, "url": url}) settings_dict = carb.settings.get_settings().get_settings_dictionary("") settings_dict[USER_REGISTRIES_SETTING[1:]] = registries # Notify registry omni.kit.app.get_app().get_message_bus_event_stream().push(REGISTRIES_CHANGED_EVENT) def set_default(self, item, value): # to avoid recursion if self._default_changing: return self._default_changing = True for c in self._children: c.default_model.as_bool = False item.default_model.as_bool = value carb.settings.get_settings().set(DEFAUT_PUBLISH_SETTING, item.name_model.as_string if value else "") self._default_changing = False class EditableDelegate(ui.AbstractItemDelegate): def __init__(self): super().__init__() self._subscription = None self._context_menu = ui.Menu("Context menu") def destroy(self): self._subscription = None self._context_menu = None def _show_copy_context_menu(self, x, y, button, modifier, text): if button != 1: return self._context_menu.clear() with self._context_menu: ui.MenuItem("Copy", triggered_fn=lambda: copy_text(text)) self._context_menu.show() def build_widget(self, model, item, column_id, level, expanded): """Create a widget per column per item""" with ui.HStack(width=20): value_model = model.get_item_value_model(item, column_id) if column_id in (0, 1): stack = ui.ZStack(height=20) with stack: label = ui.Label(value_model.as_string, width=500, name=("config" if item.is_user else "builtin")) field = ui.StringField(value_model, visible=False) # Start editing when double clicked stack.set_mouse_double_clicked_fn( lambda x, y, b, _, f=field, l=label, m=model, i=item: self.on_double_click(b, f, l, m, i) ) # Right click is copy menu stack.set_mouse_pressed_fn( lambda x, y, b, m, t=value_model.as_string: self._show_copy_context_menu(x, y, b, m, t) ) elif column_id == 2: if not item.add_dummy: with ui.HStack(): ui.Spacer(width=10) SimpleCheckBox( item.default_model.as_bool, lambda value, item=item: model.set_default(item, value), model=item.default_model, text="", ) ui.Spacer(width=20) else: if item.is_user: def on_click(): if item.add_dummy: model.add_empty() else: model.remove_item(item) with ui.HStack(): ui.Spacer(width=10) ui.Button( name=("add" if item.add_dummy else "remove"), style_type_name_override="ItemButton", width=20, height=20, clicked_fn=on_click, ) ui.Spacer() def on_double_click(self, button, field, label, model, item): """Called when the user double-clicked the item in TreeView""" if button != 0: return if item.add_dummy: return if not item.is_user: copy_text(field.model.as_string) return # Make Field visible when double clicked field.visible = True field.focus_keyboard() # When editing is finished (enter pressed of mouse clicked outside of the viewport) self._subscription = field.model.subscribe_end_edit_fn( lambda m, f=field, l=label, md=model: self.on_end_edit(m.as_string, f, l, md) ) def on_end_edit(self, text, field, label, model): """Called when the user is editing the item and pressed Enter or clicked outside of the item""" field.visible = False label.text = text self._subscription = None if text: model.save() def build_header(self, column_id): with ui.HStack(): ui.Spacer(width=10) ui.Label(REGISTRIES_COLUMNS[column_id], name="header") class ExtsRegistriesWidget: def __init__(self): self._model = RegistriesModel() self._delegate = EditableDelegate() with ui.VStack(style=get_style(self)): ui.Spacer(height=20) with ui.ScrollingFrame( height=200, horizontal_scrollbar_policy=ui.ScrollBarPolicy.SCROLLBAR_ALWAYS_OFF, vertical_scrollbar_policy=ui.ScrollBarPolicy.SCROLLBAR_ALWAYS_OFF, style_type_name_override="TreeView", ): tree_view = ui.TreeView( self._model, delegate=self._delegate, root_visible=False, header_visible=True, ) tree_view.column_widths = [ui.Fraction(1), ui.Fraction(4), ui.Pixel(60), ui.Pixel(40)] ui.Spacer(height=10) def destroy(self): self._model.destroy() self._model = None self._delegate.destroy() self._delegate = None
omniverse-code/kit/exts/omni.kit.window.extensions/omni/kit/window/extensions/ext_status_bar.py
# Copyright (c) 2018-2020, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. # from datetime import datetime import omni.ext import omni.kit.app import omni.ui as ui from omni.ui import color as cl NEUTRAL = cl("#FFFFFF") SUCCESS = cl("#3794ff") FAILURE = cl("#CC0000") class ExtStatusBar: def __init__(self): self._label = ui.Label("", height=8) app = omni.kit.app.get_app() bus = app.get_message_bus_event_stream() self._subs = [] self._set_status("") def sub(e, message, color): self._subs.append(bus.create_subscription_to_pop_by_type(e, lambda e: self._set_status(message, color, e))) sub(omni.ext.EVENT_REGISTRY_REFRESH_BEGIN, "Syncing Registry...", NEUTRAL) sub( omni.ext.EVENT_REGISTRY_REFRESH_END_SUCCESS, "Registry Synced: " + datetime.now().strftime("%H:%M:%S"), SUCCESS, ) sub(omni.ext.EVENT_REGISTRY_REFRESH_END_FAILURE, "Registry Sync Failed.", FAILURE) sub(omni.ext.EVENT_EXTENSION_PULL_BEGIN, "Installing: {}...", NEUTRAL) sub(omni.ext.EVENT_EXTENSION_PULL_END_SUCCESS, "Installed successfully: {}", SUCCESS) sub(omni.ext.EVENT_EXTENSION_PULL_END_FAILURE, "Install failed: {}", FAILURE) def _set_status(self, status, color=NEUTRAL, evt=None): if evt and evt.payload["packageId"]: status = status.format(evt.payload["packageId"]) self._status = status self._status_color = color self._refresh_ui() def _refresh_ui(self): self._label.style = {"font_size": 14, "color": self._status_color} self._label.text = self._status
omniverse-code/kit/exts/omni.kit.window.extensions/omni/kit/window/extensions/exts_properties_widget.py
# Copyright (c) 2018-2020, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. # import carb import carb.dictionary import carb.settings import carb.tokens import omni.kit.app import omni.ui as ui from .common import COMMUNITY_TAB_TOGGLE_EVENT, SettingBoolValue, get_options from .exts_list_widget import ExtSummaryItem from .exts_properties_paths import ExtsPathsWidget from .exts_properties_registries import ExtsRegistriesWidget from .styles import get_style from .utils import cleanup_folder, copy_text, ext_id_to_name_version, get_setting, version_to_str class ExtsPropertiesWidget: def __init__(self): self._ext_manager = omni.kit.app.get_app().get_extension_manager() self._ext_change_sub = self._ext_manager.get_change_event_stream().create_subscription_to_pop( lambda *_: self._refresh(), name="ExtPropertiesWidget" ) self._registries_widget = None self._paths_widget = None self._frame = ui.Frame() def destroy(self): self._clean_widgets() self._ext_change_sub = None self._frame = None def set_visible(self, visible): self._frame.visible = visible self._refresh() def _clean_widgets(self): if self._registries_widget: self._registries_widget.destroy() self._registries_widget = None if self._paths_widget: self._paths_widget.destroy() self._paths_widget = None def _refresh(self): if not self._frame.visible: return self._clean_widgets() # Build UI with self._frame: with ui.ScrollingFrame( horizontal_scrollbar_policy=ui.ScrollBarPolicy.SCROLLBAR_ALWAYS_OFF, vertical_scrollbar_policy=ui.ScrollBarPolicy.SCROLLBAR_ALWAYS_ON, ): with ui.ZStack(style=get_style(self)): ui.Rectangle(style_type_name_override="Properies.Background") with ui.HStack(): ui.Spacer(width=20) with ui.VStack(spacing=4, height=0): def add_open_button(text, url): def open_url(url_=url): # Import it here instead of on the file root because it has long import time. import webbrowser webbrowser.open(url_) ui.Button(text, width=0, clicked_fn=open_url, tooltip=url) ui.Spacer(height=10) # Extension Search Paths with ui.CollapsableFrame("Extension Search Paths", collapsed=False): self._paths_widget = ExtsPathsWidget() # Registries with ui.CollapsableFrame("Extension Registries", collapsed=False): self._registries_widget = ExtsRegistriesWidget() with ui.CollapsableFrame("Extension System Cache", collapsed=True): with ui.VStack(): ui.Spacer(height=10) cache_path = get_setting("/exts/omni.kit.registry.nucleus/cachePath", None) if cache_path: cache_path = carb.tokens.get_tokens_interface().resolve(cache_path) with ui.HStack(): add_open_button("Open", cache_path) def clean(p_=cache_path): cleanup_folder(p_) ui.Button( "Clean", width=0, clicked_fn=clean, tooltip="Remove all downloaded extensions", ) ui.Label(f"Path: {cache_path}") ui.Spacer(height=10) with ui.CollapsableFrame("Options", collapsed=True): with ui.VStack(): ui.Spacer(height=10) def add_option(option: SettingBoolValue, name: str, evt: int = None): # Publishing enabled with ui.HStack(width=60): cb = ui.CheckBox() def on_change(model): option.set_bool(model.get_value_as_bool()) if evt: omni.kit.app.get_app().get_message_bus_event_stream().push(evt) cb.model.set_value(option.get()) cb.model.add_value_changed_fn(on_change) ui.Label(name) options = get_options() add_option(options.publishing, "Publishing Enabled") if options.community_tab is not None: ui.Spacer(height=10) add_option( options.community_tab, "Show Community Extensions", COMMUNITY_TAB_TOGGLE_EVENT, ) ui.Spacer(height=10) # Export all exts data with ui.CollapsableFrame("Miscellaneous", collapsed=True): with ui.VStack(): ui.Spacer(height=10) ext_summaries = self._ext_manager.fetch_extension_summaries() total_cnt = len(ext_summaries) builtin_cnt = sum( bool(e["flags"] & omni.ext.EXTENSION_SUMMARY_FLAG_BUILTIN) for e in ext_summaries ) installed_cnt = sum( bool(e["flags"] & omni.ext.EXTENSION_SUMMARY_FLAG_INSTALLED) for e in ext_summaries ) ui.Label(f"Total Extensions: {total_cnt}", height=20) ui.Label(f"Bultin Extensions: {builtin_cnt}", height=20) ui.Label(f"Installed Extensions: {installed_cnt}", height=20) registry_count = len(self._ext_manager.get_registry_extensions()) ui.Label(f"Registry Packages: {registry_count}", height=20) ui.Spacer(height=10) ui.Button( "Copy all exts as CSV", width=100, height=30, clicked_fn=lambda: self.export_all_exts(ext_summaries), ) # Export all exts data ui.Button( "Copy enabled exts as .kit file (top level)", width=100, height=30, clicked_fn=lambda: self.export_enabled_exts_as_kit_file(only_top_level=True), ) # Export all exts data ui.Button( "Copy enabled exts as .kit file (all)", width=100, height=30, clicked_fn=lambda: self.export_enabled_exts_as_kit_file(only_top_level=False), ) ui.Spacer() ui.Spacer(width=20) def export_all_exts(self, ext_summaries): """Export all exts in CSV format with some of config params. print and copy result.""" ext_sum_dict = {} for ext_s in ext_summaries: item = ExtSummaryItem() item.refresh(ext_s) ext_sum_dict[ext_s["fullname"]] = item fields_to_export = [ "package/name", "package/version", "can_update,latest_version", # special case "state/enabled", "isKitFile", "package/category", "package/title", "package/description", "package/authors", "package/repository", "package/keywords", "package/readme", "package/changelog", "package/preview_image", "package/icon", "core/reloadable", ] # Header output = ",".join(["id"] + fields_to_export) + "\n" # Per ext row data for ext in self._ext_manager.get_extensions(): d = self._ext_manager.get_extension_dict(ext["id"]) row = ext["id"] + "," for f in fields_to_export: if f.startswith("can_update"): # special case, do both rows at once item = ext_sum_dict.get(ext["name"], None) if item: latest_version = version_to_str(item.latest_ext["version"][:4]) row += f'"{item.can_update}",' row += f'"{latest_version}",' else: row += ",," else: row += f'"{str(d.get(f, ""))}",' row = row.replace("\n", r"\n") output += row + "\n" print(output) copy_text(output) def export_enabled_exts_as_kit_file(self, only_top_level=True): """Export all topmost exts in .kit format. print and copy result.""" excludes = {"omni.kit.registry.nucleus", "omni.kit.profile_python"} all_deps = set() all_exts = set() for ext in self._ext_manager.get_extensions(): if ext["enabled"]: ext_id = ext["id"] info = self._ext_manager.get_extension_dict(ext_id) deps = info.get("state/dependencies", []) all_exts.add(ext_id) all_deps.update(deps) output = "[dependencies]\n" exported_exts = (all_exts - all_deps) if only_top_level else all_exts for e in exported_exts: if "-" not in e: print(f"skipping ext 1.0: {e}") continue name, version = ext_id_to_name_version(e) if name in excludes: continue output += '"{0}" = {{ version = "{1}", exact = true }}\n'.format(name, version) print(output) copy_text(output)
omniverse-code/kit/exts/omni.kit.window.extensions/omni/kit/window/extensions/window.py
# Copyright (c) 2018-2020, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. # from typing import Callable import omni.ui as ui from .ext_info_widget import ExtInfoWidget from .ext_status_bar import ExtStatusBar from .exts_graph_window import ExtsGraphWindow from .exts_list_widget import ExtsListWidget from .exts_properties_widget import ExtsPropertiesWidget from .styles import get_style class PageSwitcher: def __init__(self): self._main_pages = {} self._selected_page = None def add_page(self, name, widget): widget.set_visible(False) self._main_pages[name] = widget def select_page(self, name, force=False): if self._selected_page == name and not force: return # Set previous inviisible selected_page = self._main_pages.get(self._selected_page, None) if selected_page: selected_page.set_visible(False) # Set new and make visible self._selected_page = name selected_page = self._main_pages.get(self._selected_page, None) if selected_page: selected_page.set_visible(True) def destroy(self): self._main_pages = {} PAGE_GRAPH = "graph" PAGE_INFO = "info" PAGE_PROPERTIES = "properties" class ExtsWindow: """Extensions window""" def __init__(self, on_visibility_changed_fn: Callable): self._window = ui.Window("Extensions", width=1300, height=800, flags=ui.WINDOW_FLAGS_NO_SCROLLBAR) self._window.set_visibility_changed_fn(on_visibility_changed_fn) # Tree view style self._exts_list_widget = ExtsListWidget() self._page_switcher = PageSwitcher() # Build UI with self._window.frame: with ui.HStack(style=get_style(self)): with ui.ZStack(width=0): # Draggable splitter with ui.Placer(offset_x=392, draggable=True, drag_axis=ui.Axis.X): ui.Rectangle(width=10, name="Splitter") with ui.HStack(): with ui.VStack(): # Extensions List Widget (on the left) self._exts_list_widget.build() # Status bar self._status_bar = ExtStatusBar() ui.Spacer(width=10) with ui.ScrollingFrame(vertical_scrollbar_policy=ui.ScrollBarPolicy.SCROLLBAR_ALWAYS_OFF): with ui.HStack(): # Selected Extension info self._ext_info_widget = ExtInfoWidget() self._page_switcher.add_page(PAGE_INFO, self._ext_info_widget) # Graph self._exts_graph = ExtsGraphWindow() self._page_switcher.add_page(PAGE_GRAPH, self._exts_graph) # Properties self._exts_properties = ExtsPropertiesWidget() self._page_switcher.add_page(PAGE_PROPERTIES, self._exts_properties) # Setup show graph callback self._exts_list_widget.set_show_graph_fn(lambda: self._show_graph(None)) self._exts_list_widget.set_show_properties_fn(self._show_properties) self._exts_list_widget.set_ext_selected_fn(self._select_ext) self._ext_info_widget.set_show_graph_fn(self._show_graph) self._select_ext(None) def _show_graph(self, ext_id: str): self._exts_list_widget.clear_selection() self._exts_graph.select_ext(ext_id) self._page_switcher.select_page(PAGE_GRAPH, force=True) def _show_properties(self): self._exts_list_widget.clear_selection() self._page_switcher.select_page(PAGE_PROPERTIES) def _select_ext(self, ext_summary): self._page_switcher.select_page(PAGE_INFO) self._ext_info_widget.select_ext(ext_summary) def destroy(self): """ Called by extension before destroying this object. It doesn't happen automatically. Without this hot reloading doesn't work. """ self._exts_graph.destroy() self._exts_graph = None self._ext_info_widget.destroy() self._ext_info_widget = None self._exts_list_widget.destroy() self._exts_list_widget = None self._exts_properties.destroy() self._exts_properties = None self._page_switcher.destroy() self._page_switcher = None self._window = None
omniverse-code/kit/exts/omni.kit.window.extensions/omni/kit/window/extensions/tests/test_properties_paths.py
import os import tempfile import omni.kit.app import omni.kit.test import omni.kit.window.extensions # pylint: disable=protected-access class TestPaths(omni.kit.test.AsyncTestCase): async def test_add_remove_user_path(self): manager = omni.kit.app.get_app().get_extension_manager() def get_paths(): return {p["path"] for p in manager.get_folders()} async def wait(): await omni.kit.app.get_app().next_update_async() await omni.kit.app.get_app().next_update_async() def get_model(): omni.kit.window.extensions.get_instance()() return instance._window._exts_properties._paths_widget._model instance = omni.kit.window.extensions.get_instance()() instance.show_window(True) instance._window._show_properties() await wait() paths_before = get_paths() with tempfile.TemporaryDirectory() as tmp_dir: p0 = f"{tmp_dir}/0" p1 = f"{tmp_dir}/1" # Add new path using model get_model().add_empty() last = get_model()._children[-1] last.path_model.as_string = p0 get_model().save() # Ext manager creates it automatically self.assertTrue(os.path.exists(p0)) self.assertEqual(len(get_paths()) - len(paths_before), 1) # Add new path using model get_model().add_empty() last = get_model()._children[-1] last.path_model.as_string = p1 get_model().save() await wait() # Ext manager creates it automatically self.assertTrue(os.path.exists(p1)) self.assertEqual(len(get_paths()) - len(paths_before), 2) # Remove! get_model().remove_item(get_model()._children[-1]) await wait() self.assertEqual(len(get_paths()) - len(paths_before), 1) # Remove! get_model().remove_item(get_model()._children[-1]) await wait() self.assertEqual(get_paths(), paths_before)
omniverse-code/kit/exts/omni.kit.window.extensions/omni/kit/window/extensions/tests/__init__.py
# flake8: noqa from .test_properties_paths import * from .test_properties_registries import *
omniverse-code/kit/exts/omni.kit.window.extensions/omni/kit/window/extensions/tests/test_properties_registries.py
import carb.settings import omni.kit.app import omni.kit.test import omni.kit.window.extensions # pylint: disable=protected-access class TestRegistries(omni.kit.test.AsyncTestCase): async def test_add_remove_registry_UNRELIABLE(self): # noqa manager = omni.kit.app.get_app().get_extension_manager() settings = carb.settings.get_settings() def get_default(): return settings.get("/app/extensions/registryPublishDefault") def get_providers(): return {p["name"] for p in manager.get_registry_providers()} instance = omni.kit.window.extensions.get_instance()() instance.show_window(True) instance._window._show_properties() await omni.kit.app.get_app().next_update_async() def get_model(): widget = instance._window._exts_properties._registries_widget return widget._model model = get_model() model.set_default(model._children[0], True) providers_before = get_providers() default_before = get_default() self.assertEqual(model._children[0].name_model.as_string, default_before) # Add new registry using model model.add_empty() last = model._children[-1] last.url_model.as_string = "omniverse://kit-extensions.ov.nvidia.com/exts/kit/debug" # name is set automatically model.save() model = None # Wait to propagate and check await omni.kit.app.get_app().next_update_async() await omni.kit.app.get_app().next_update_async() self.assertEqual(get_providers() - providers_before, {"kit/debug"}) # Make it default now get_model().set_default(get_model()._children[-1], True) await omni.kit.app.get_app().next_update_async() self.assertEqual(get_default(), "kit/debug") # Remove! get_model().remove_item(get_model()._children[-1]) await omni.kit.app.get_app().next_update_async() await omni.kit.app.get_app().next_update_async() self.assertEqual(get_providers(), providers_before) # get back default: get_model()._children[0].default_model.as_bool = True await omni.kit.app.get_app().next_update_async() self.assertEqual(get_default(), default_before)
omniverse-code/kit/exts/omni.kit.window.extensions/docs/CHANGELOG.md
# Changelog The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/). ## [1.1.1] - 2022-11-17 ### Updated - Switched out pyperclip for linux-friendly copy & paste ## [1.1.0] - 2022-05-06 ### Added - Added support for truncated words in extension search window ## [1.0.2] - 2020-12-07 ### Changed - Fix path_is_parent exception with different drive paths ## [1.0.1] - 2020-07-09 ### Changed - Don't produce symlink for icons in the extension folder ## [1.0.0] - 2020-07-08 ### Added - The initial release with minimal support of loading/unloading extensions and access to the external extension registry.
omniverse-code/kit/exts/omni.kit.window.extensions/docs/index.rst
omni.kit.window.extensions ########################### Extensions Window
omniverse-code/kit/exts/omni.kit.test_helpers_gfx/omni/kit/test_helpers_gfx/__init__.py
from .compare_utils import *
omniverse-code/kit/exts/omni.kit.test_helpers_gfx/omni/kit/test_helpers_gfx/compare_utils.py
## Copyright (c) 2018-2019, 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. ## """The utilities for image comparison""" import pathlib import sys import traceback import math from enum import Enum import numpy as np import carb import carb.tokens import omni.appwindow from omni.kit.test.teamcity import teamcity_publish_image_artifact class CompareError(Exception): pass class ComparisonMetric(Enum): MAX_DIFFERENCE = 0 # the maximum differrence between pixels. 0 is no difference. In the range [0-255]. PIXEL_COUNT = 1 # the total number of pixels that is not the same for two images MEAN_ERROR_SQUARED = 2 # Mean root square difference between pixels of two images PEAK_SIGNAL_TO_NOISE_RATIO = 3 def computeMSE(difference): components = len(difference.getpixel((0, 0))) errors = np.asarray(difference) / 255 return sum(np.mean(np.square(errors), axis = (0, 1))) / components def compare(image1: pathlib.Path, image2: pathlib.Path, image_diffmap: pathlib.Path, metric: ComparisonMetric = ComparisonMetric.MAX_DIFFERENCE): """ Compares two images and return a value that indicates the maximum differrence between pixels. 0 is no difference in the range [0-255]. It uses Pillow for image read. Args: image1, image2: images to compare image_diffmap: the difference map image will be saved if there is any difference between given images """ if not image1.exists(): raise CompareError(f"File image1 {image1} does not exist") if not image2.exists(): raise CompareError(f"File image2 {image2} does not exist") if "PIL" not in sys.modules.keys(): # Checking if we have Pillow imported try: from PIL import Image except ImportError: # Install Pillow if it's not installed import omni.kit.pipapi omni.kit.pipapi.install("Pillow", module="PIL") from PIL import Image from PIL import ImageChops original = Image.open(str(image1)) contrast = Image.open(str(image2)) if original.size != contrast.size: raise CompareError( f"[omni.ui.test] Can't compare different resolutions\n\n" f"{image1} {original.size[0]}x{original.size[1]}\n" f"{image2} {contrast.size[0]}x{contrast.size[1]}\n\n" f"It's possible that your monitor DPI is not 100%.\n\n" ) difference = ImageChops.difference(original, contrast) metric_value = 0.0 try: if metric is ComparisonMetric.MAX_DIFFERENCE: metric_value = sum([sum(i) for i in difference.convert("RGB").getextrema()]) if metric is ComparisonMetric.PIXEL_COUNT: metric_value = sum([sum( difference.getpixel((j, i))) > 0 for i in range(difference.height) for j in range(difference.width)]) if metric is ComparisonMetric.MEAN_ERROR_SQUARED: metric_value = computeMSE(difference) if metric is ComparisonMetric.PEAK_SIGNAL_TO_NOISE_RATIO: metric_value = computeMSE(difference) if metric_value < sys.float_info.epsilon: metric_value = math.inf metric_value = 10 * math.log10(1 / metric_value) except(): raise CompareError(f"[omni.ui.test] Can't compute metric {metric} \n\n") if metric_value > 0: # Images are different # Multiply image by 255 difference = difference.convert("RGB").point(lambda i: min(i * 255, 255)) difference.save(str(image_diffmap)) return metric_value def capture(image_name: str, output_img_dir: str, app_window: omni.appwindow.IAppWindow = None, use_log: bool = True): """ Captures frame. Args: image_name: the image name of the image and golden image. output_img_dir: the directory path that the capture will be saved to. golden_img_dir: the directory path that stores the golden image. Leave it to None to use default dir. """ image1 = pathlib.Path(output_img_dir).joinpath(image_name) if use_log: carb.log_info(f"[tests.compare] Capturing {image1}") import omni.renderer_capture capture_interface = omni.renderer_capture.acquire_renderer_capture_interface() capture_interface.capture_next_frame_swapchain(str(image1), app_window) def finalize_capture_and_compare(image_name: str, threshold: float, output_img_dir: str, golden_img_dir: str, app_window: omni.appwindow.IAppWindow = None, metric: ComparisonMetric = ComparisonMetric.MAX_DIFFERENCE): """ Finalizes capture and compares it with the golden image. Args: image_name: the image name of the image and golden image. threshold: the max threshold to collect TC artifacts. output_img_dir: the directory path that the capture will be saved to. golden_img_dir: the directory path that stores the golden image. Leave it to None to use default dir. app_window: IAppWindow instance for which the capture will happen, use None to capture default app window. Returns: A value that indicates the maximum difference between pixels. 0 is no difference in the range [0-255]. """ image1 = pathlib.Path(output_img_dir).joinpath(image_name) image2 = pathlib.Path(golden_img_dir).joinpath(image_name) image_diffmap = pathlib.Path(output_img_dir).joinpath(f"{pathlib.Path(image_name).stem}.diffmap.png") import omni.renderer_capture capture_interface = omni.renderer_capture.acquire_renderer_capture_interface() capture_interface.wait_async_capture(app_window) carb.log_info(f"[tests.compare] Comparing {image1} to {image2}") try: diff = compare(image1, image2, image_diffmap, metric) if diff >= threshold: teamcity_publish_image_artifact(image2, "golden", "Reference") teamcity_publish_image_artifact(image1, "results", "Generated") teamcity_publish_image_artifact(image_diffmap, "results", "Diff") return diff except CompareError as e: carb.log_error(f"[tests.compare] Failed to compare images for {image_name}. Error: {e}") exc = traceback.format_exc() carb.log_error(f"[tests.compare] Traceback:\n{exc}") async def capture_and_compare(image_name: str, threshold, output_img_dir: str, golden_img_dir: str, app_window: omni.appwindow.IAppWindow = None, use_log: bool = True, metric: ComparisonMetric = ComparisonMetric.MAX_DIFFERENCE): """ Captures frame and compares it with the golden image. Args: image_name: the image name of the image and golden image. threshold: the max threshold to collect TC artifacts. golden_img_dir: the directory path that stores the golden image. Leave it to None to use default dir. Returns: A value that indicates the maximum difference between pixels. 0 is no difference in the range [0-255]. """ capture(image_name, output_img_dir, app_window, use_log=use_log) await omni.kit.app.get_app().next_update_async() return finalize_capture_and_compare(image_name, threshold, output_img_dir, golden_img_dir, app_window, metric)
omniverse-code/kit/exts/omni.kit.test_helpers_gfx/docs/index.rst
omni.kit.test_helpers_gfx ########################### Testing system helpers for graphics. Module that provides helpers that simplify writing tests, e.g. capture and compare screenshots, create windows, etc. .. automodule:: omni.kit.test_helpers_gfx :platform: Windows-x86_64, Linux-x86_64 :members: :show-inheritance: :undoc-members: :imported-members: :noindex: enum
omniverse-code/kit/exts/omni.kit.window.usd_paths/PACKAGE-LICENSES/omni.kit.window.usd_paths-LICENSE.md
Copyright (c) 2020, 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.
omniverse-code/kit/exts/omni.kit.window.usd_paths/config/extension.toml
[package] # Semantic Versioning is used: https://semver.org/ version = "1.0.4" category = "Core" # Lists people or organizations that are considered the "authors" of the package. authors = ["NVIDIA"] # The title and description fields are primarly for displaying extension info in UI title = "USD Paths" description="Lists paths in USD file and allows editing" # URL of the extension source repository. repository = "" # Keywords for the extension keywords = ["kit", "usd", "paths"] # Location of change log file in target (final) folder of extension, relative to the root. # More info on writing changelog: https://keepachangelog.com/en/1.0.0/ changelog = "docs/CHANGELOG.md" [dependencies] "omni.kit.commands" = {} "omni.usd" = {} "omni.ui" = {} "omni.kit.menu.utils" = {} [[python.module]] name = "omni.kit.window.usd_paths" # That will make tests auto-discoverable by test_runner: [[python.module]] name = "omni.kit.window.usd_paths.tests" [[test]] stdoutFailPatterns.exclude = [ "*extension object is still alive*", # Ignore any leaks for startup tests to not block pipeline ]
omniverse-code/kit/exts/omni.kit.window.usd_paths/omni/kit/window/usd_paths/__init__.py
from .scripts import *
omniverse-code/kit/exts/omni.kit.window.usd_paths/omni/kit/window/usd_paths/scripts/__init__.py
from .usd_paths import *
omniverse-code/kit/exts/omni.kit.window.usd_paths/omni/kit/window/usd_paths/scripts/usd_paths.py
import re import os import asyncio import carb import omni.ext import omni.kit.ui import omni.ui as ui from pxr import Usd, UsdGeom, UsdShade, UsdUtils, Ar, Sdf _extension_instance = None _extension_path = None class UsdPathsExtension(omni.ext.IExt): def __init__(self): self.USD_PATHS_TOOL_MENU = "Window/USD Paths" self._use_regex = False self._regex_button = None self._regex_button_style = { "Button.Label":{"font_size": 12.0}, "Button":{"margin": 2, "padding": 2}, "Button:checked":{"background_color": 0xFF114411}, "Button:hovered":{"background_color": 0xFF444444}, "Button:pressed":{"background_color": 0xFF111111}, } self._action_button_style = { "Button.Label:disabled":{"color": 0xFF666666}, "Button:disabled": {"background_color": 0xFF222222} } super().__init__() def on_startup(self, ext_id): global _extension_instance _extension_instance = self global _extension_path _extension_path = omni.kit.app.get_app_interface().get_extension_manager().get_extension_path(ext_id) self._unique_paths = {} self._window = None editor_menu = omni.kit.ui.get_editor_menu() if editor_menu: self._menu = editor_menu.add_item(self.USD_PATHS_TOOL_MENU, self._show_ui, True, 10) editor_menu.set_value(self.USD_PATHS_TOOL_MENU, False) def on_shutdown(self): global _extension_instance global _template_list _extension_instance = None _template_list = None def _clean_up_paths_ui(self): if hasattr(self, "_scrollable") and self._scrollable is not None: self._window.layout.remove_child(self._scrollable) self._scrollable = None def _list_all_paths(self, path): if path not in self._scrollable_pending: self._scrollable_pending.append(path) return path def _modify_path(self, path): if path in self._unique_paths: return self._unique_paths[path].model.get_value_as_string() def _apply_path_edits(self, btn_widget=None): stage = omni.usd.get_context().get_stage() if not stage: carb.log_error("stage not found") return (all_layers, all_assets, unresolved_paths) = UsdUtils.ComputeAllDependencies(stage.GetRootLayer().identifier) if not all_layers: all_layers = stage.GetLayerStack() for layer in all_layers: UsdUtils.ModifyAssetPaths(layer, self._modify_path) self._traverse() self._btn_apply.enabled = False def _replace(self, btn_widget=None): if not self._unique_paths: self._traverse() for path in self._unique_paths: mdl_path = self._unique_paths[path].model.get_value_as_string() if self._use_regex: mdl_path = re.sub( self._txt_search.model.get_value_as_string(), self._txt_replace.model.get_value_as_string(), mdl_path, ) else: mdl_path = mdl_path.replace( self._txt_search.model.get_value_as_string(), self._txt_replace.model.get_value_as_string() ) self._unique_paths[path].model.set_value(mdl_path) self._btn_apply.enabled = True self._btn_replace.enabled = False def _toggle_block(self, is_enabled): self._txt_search.enabled = is_enabled self._txt_replace.enabled = is_enabled self._btn_replace.enabled = is_enabled if is_enabled: return self._btn_apply.enabled = False async def _wait_frame_finished(self, finish_fn): await omni.kit.app.get_app_interface().next_update_async() finish_fn() async def _preload_materials_from_stage(self, on_complete_fn): shaders = [] stage = omni.usd.get_context().get_stage() if not stage: carb.log_error("stage not found") return for p in stage.Traverse(): if p.IsA(UsdShade.Material): if not p.GetMetadata("ignore_material_updates"): material = UsdShade.Material(p) shader = material.ComputeSurfaceSource("mdl")[0] shaders.append(shader.GetPath().pathString) old_paths = omni.usd.get_context().get_selection().get_selected_prim_paths() omni.usd.get_context().get_selection().set_selected_prim_paths(shaders, True) await omni.kit.app.get_app_interface().next_update_async() await omni.kit.app.get_app_interface().next_update_async() def reload_old_paths(): omni.usd.get_context().get_selection().set_selected_prim_paths(old_paths, True) on_complete_fn() asyncio.ensure_future(self._wait_frame_finished(finish_fn=reload_old_paths)) def _traverse(self, btn_widget=None): self._unique_paths = {} self._scrollable.clear() self._scrollable_pending = [] self._toggle_block(False) def on_preload_complete(): with self._scrollable: with ui.VStack(spacing=2, height=0): self._scrollable_pending.sort() for path in self._scrollable_pending: text_box = ui.StringField(skip_draw_when_clipped=True) text_box.model.set_value(path) self._unique_paths[path] = text_box self._scrollable_pending = None if len(self._unique_paths) > 0: self._toggle_block(True) asyncio.ensure_future(self.get_asset_paths(on_preload_complete, self._list_all_paths)) def _build_ui(self): with self._window.frame: with ui.VStack(spacing=4): with ui.VStack(spacing=2, height=0): ui.Spacer(height=4) with ui.HStack(spacing=10, height=0): ui.Label("Search", width=60, alignment=ui.Alignment.RIGHT_CENTER) with ui.ZStack(height=0): self._txt_search = ui.StringField() with ui.HStack(): ui.Spacer(height=0) def toggle_regex(button): self._use_regex = not self._use_regex button.checked = self._use_regex def on_mouse_hover(hover_state): self._txt_search.enabled = not hover_state self._regex_button = ui.Button(width=0, text="Regex", style=self._regex_button_style) self._regex_button.set_clicked_fn(lambda b=self._regex_button: toggle_regex(b)) self._regex_button.set_mouse_hovered_fn(on_mouse_hover) ui.Spacer(width=10) ui.Spacer() with ui.HStack(spacing=10, height=0): ui.Label("Replace", width=60, alignment=ui.Alignment.RIGHT_CENTER) self._txt_replace = ui.StringField(height=0) ui.Spacer(width=10) ui.Spacer() with ui.HStack(spacing=10): ui.Spacer(width=56) ui.Button( width=0, style=self._action_button_style, clicked_fn=self._traverse, text=" Reload paths ") ui.Spacer() self._btn_replace = ui.Button( width=0, style=self._action_button_style, clicked_fn=self._replace, text=" Preview ", enabled=False) self._btn_apply = ui.Button( width=0, style=self._action_button_style, clicked_fn=self._apply_path_edits, text=" Apply ", enabled=False ) ui.Spacer() ui.Spacer(width=100) def on_text_changed(model): if self._btn_apply.enabled: self._btn_apply.enabled = False if not self._btn_replace.enabled: self._btn_replace.enabled = True self._txt_search.model.add_value_changed_fn(on_text_changed) self._txt_replace.model.add_value_changed_fn(on_text_changed) ui.Spacer(width=14) self._scrollable = ui.ScrollingFrame( text="ScrollingFrame", vertical_scrollbar_policy=omni.ui.ScrollBarPolicy.SCROLLBAR_ALWAYS_ON ) def _show_ui(self, menu, value): if self._window is None: window_flags = ui.WINDOW_FLAGS_NO_SCROLLBAR self._window = ui.Window( "USD Paths", width=400, height=400, flags=window_flags, dockPreference=omni.ui.DockPreference.LEFT_BOTTOM, ) self._window.set_visibility_changed_fn(self._on_visibility_changed) self._window.deferred_dock_in("Console", ui.DockPolicy.CURRENT_WINDOW_IS_ACTIVE) self._window.dock_order = 99 self._build_ui() if self._window: if value: self._window.visible = True else: self._window.visible = False def _on_visibility_changed(self, visible): omni.kit.ui.get_editor_menu().set_value(self.USD_PATHS_TOOL_MENU, visible) async def get_asset_paths(self, on_complete_fn, get_path_fn): stage = omni.usd.get_context().get_stage() if not stage: carb.log_error("stage not found") return def on_preload_complete(): (all_layers, all_assets, unresolved_paths) = UsdUtils.ComputeAllDependencies( stage.GetRootLayer().identifier ) if not all_layers: all_layers = stage.GetLayerStack() # all_layers doesn't include session layer, use that too session_layer = stage.GetSessionLayer() if not session_layer in all_layers: all_layers.append(session_layer) for layer in all_layers: UsdUtils.ModifyAssetPaths(layer, get_path_fn) on_complete_fn() await self._preload_materials_from_stage(on_preload_complete) def get_extension(): return Extension() def get_instance(): return _extension_instance def get_extension_path(sub_directory): global _extension_path path = _extension_path if sub_directory: path = os.path.normpath(os.path.join(path, sub_directory)) return path
omniverse-code/kit/exts/omni.kit.window.usd_paths/omni/kit/window/usd_paths/tests/create_prims.py
import os import carb import omni.kit.commands from pxr import Usd, Sdf, UsdGeom, Gf, Tf, UsdShade, UsdLux def create_test_stage(): settings = carb.settings.get_settings() default_prim_name = settings.get("/persistent/app/stage/defaultPrimName") rootname = f"/{default_prim_name}" stage = omni.usd.get_context().get_stage() kit_folder = carb.tokens.get_tokens_interface().resolve("${kit}") omni_pbr_mtl = os.path.normpath(kit_folder + "/mdl/core/Base/OmniPBR.mdl") sunflower_hdr = omni.kit.window.usd_paths.get_extension_path("data/sunflowers.hdr") lenna_dds = omni.kit.window.usd_paths.get_extension_path("textures/lenna.dds") lenna_gif = omni.kit.window.usd_paths.get_extension_path("textures/lenna.gif") lenna_jpg = omni.kit.window.usd_paths.get_extension_path("textures/lenna.jpg") lenna_png = omni.kit.window.usd_paths.get_extension_path("textures/lenna.png") lenna_tga = omni.kit.window.usd_paths.get_extension_path("textures/lenna.tga") # create Looks folder omni.kit.commands.execute( "CreatePrim", prim_path=omni.usd.get_stage_next_free_path(stage, "{}/Looks".format(rootname), False), prim_type="Scope", select_new_prim=False, ) # create GroundMat material mtl_name = "GroundMat" mtl_path = omni.usd.get_stage_next_free_path( stage, "{}/Looks/{}".format(rootname, Tf.MakeValidIdentifier(mtl_name)), False ) omni.kit.commands.execute( "CreateMdlMaterialPrim", mtl_url=omni_pbr_mtl, mtl_name=mtl_name, mtl_path=mtl_path ) ground_mat_prim = stage.GetPrimAtPath(mtl_path) shader = UsdShade.Material(ground_mat_prim).ComputeSurfaceSource("mdl")[0] shader.SetSourceAssetSubIdentifier("OmniPBR", "mdl") omni.usd.create_material_input(ground_mat_prim, "reflection_roughness_constant", 0.36, Sdf.ValueTypeNames.Float) omni.usd.create_material_input(ground_mat_prim, "specular_level", 0.25, Sdf.ValueTypeNames.Float) omni.usd.create_material_input( ground_mat_prim, "diffuse_color_constant", Gf.Vec3f(0.08, 0.08, 0.08), Sdf.ValueTypeNames.Color3f ) omni.usd.create_material_input(ground_mat_prim, "diffuse_tint", Gf.Vec3f(1, 1, 1), Sdf.ValueTypeNames.Color3f) omni.usd.create_material_input(ground_mat_prim, "diffuse_tint", Gf.Vec3f(1, 1, 1), Sdf.ValueTypeNames.Color3f) omni.usd.create_material_input(ground_mat_prim, "metallic_constant", 0.0, Sdf.ValueTypeNames.Float) omni.usd.create_material_input(ground_mat_prim, "reflection_roughness_constant", 0.36, Sdf.ValueTypeNames.Float) # add additional files to shader omni.usd.create_material_input( ground_mat_prim, "diffuse_texture", Sdf.AssetPath(lenna_dds), Sdf.ValueTypeNames.Asset ) omni.usd.create_material_input(ground_mat_prim, "ao_texture", Sdf.AssetPath(lenna_gif), Sdf.ValueTypeNames.Asset) omni.usd.create_material_input( ground_mat_prim, "normalmap_texture", Sdf.AssetPath(lenna_jpg), Sdf.ValueTypeNames.Asset ) omni.usd.create_material_input( ground_mat_prim, "reflectionroughness_texture", Sdf.AssetPath(lenna_png), Sdf.ValueTypeNames.Asset ) omni.usd.create_material_input( ground_mat_prim, "metallic_texture", Sdf.AssetPath(lenna_tga), Sdf.ValueTypeNames.Asset ) # create GroundCube ground_cube_path = omni.usd.get_stage_next_free_path(stage, "{}/GroundCube".format(rootname), False) omni.kit.commands.execute( "CreatePrim", prim_path=ground_cube_path, prim_type="Cube", select_new_prim=False, attributes={UsdGeom.Tokens.size: 100, UsdGeom.Tokens.extent: [(-50, -50, -50), (50, 50, 50)]}, ) ground_cube_prim = stage.GetPrimAtPath(ground_cube_path) # set transform ground_cube_prim.CreateAttribute("xformOp:translate", Sdf.ValueTypeNames.Double3, False).Set(Gf.Vec3d(0, -50, 0)) ground_cube_prim.CreateAttribute("xformOp:scale", Sdf.ValueTypeNames.Double3, False).Set(Gf.Vec3d(2000, 1, 2000)) ground_cube_prim.CreateAttribute("xformOpOrder", Sdf.ValueTypeNames.String, False).Set( ["xformOp:translate", "xformOp:scale"] ) # set doNotCastShadows primvars_api = UsdGeom.PrimvarsAPI(ground_cube_prim) primvars_api.CreatePrimvar("doNotCastShadows", Sdf.ValueTypeNames.Bool).Set(True) # set misc omni.kit.commands.execute( "BindMaterial", prim_path=ground_cube_path, material_path=mtl_path, strength=UsdShade.Tokens.strongerThanDescendants, ) # create DistantLight distant_light_path = omni.usd.get_stage_next_free_path(stage, "{}/DistantLight".format(rootname), False) omni.kit.commands.execute( "CreatePrim", prim_path=distant_light_path, prim_type="DistantLight", select_new_prim=False, # https://github.com/PixarAnimationStudios/USD/commit/b5d3809c943950cd3ff6be0467858a3297df0bb7 attributes={UsdLux.Tokens.inputsAngle: 1.0, UsdLux.Tokens.inputsColor: Gf.Vec3f(1, 1, 1), UsdLux.Tokens.inputsIntensity: 2000} if hasattr(UsdLux.Tokens, 'inputsIntensity') else \ {UsdLux.Tokens.angle: 1.0, UsdLux.Tokens.color: Gf.Vec3f(1, 1, 1), UsdLux.Tokens.intensity: 2000}, ) distant_light_prim = stage.GetPrimAtPath(distant_light_path) # set transform distant_light_prim.CreateAttribute("xformOp:scale", Sdf.ValueTypeNames.Double3, False).Set( Gf.Vec3d(1, 1.0000004, 1.0000004) ) distant_light_prim.CreateAttribute("xformOp:rotateZYX", Sdf.ValueTypeNames.Double3, False).Set( Gf.Vec3d(242.08, 327.06, 0) ) distant_light_prim.CreateAttribute("xformOp:translate", Sdf.ValueTypeNames.Double3, False).Set(Gf.Vec3d(0, 0, 0)) distant_light_prim.CreateAttribute("xformOpOrder", Sdf.ValueTypeNames.String, False).Set( ["xformOp:translate", "xformOp:rotateZYX", "xformOp:scale"] ) # create DomeLight dome_light_path = omni.usd.get_stage_next_free_path(stage, "{}/DomeLight".format(rootname), False) omni.kit.commands.execute( "CreatePrim", prim_path=dome_light_path, prim_type="DomeLight", select_new_prim=False, # https://github.com/PixarAnimationStudios/USD/commit/b5d3809c943950cd3ff6be0467858a3297df0bb7 attributes={ UsdLux.Tokens.inputsIntensity: 1000, UsdLux.Tokens.inputsSpecular: 1, UsdLux.Tokens.inputsTextureFile: sunflower_hdr, UsdLux.Tokens.inputsTextureFormat: UsdLux.Tokens.latlong, UsdGeom.Tokens.visibility: UsdGeom.Tokens.inherited, } if hasattr(UsdLux.Tokens, 'inputsIntensity') else \ { UsdLux.Tokens.intensity: 1000, UsdLux.Tokens.specular: 1, UsdLux.Tokens.textureFile: sunflower_hdr, UsdLux.Tokens.textureFormat: UsdLux.Tokens.latlong, UsdGeom.Tokens.visibility: UsdGeom.Tokens.inherited, }, ) dome_light_prim = stage.GetPrimAtPath(dome_light_path) # set misc # https://github.com/PixarAnimationStudios/USD/commit/3738719d72e60fb78d1cd18100768a7dda7340a4 if hasattr(UsdLux.Tokens, 'inputsShapingFocusTint'): dome_light_prim.GetAttribute(UsdLux.Tokens.inputsShapingFocusTint).Set(Gf.Vec3f(0, 0, 0)) dome_light_prim.GetAttribute(UsdLux.Tokens.inputsShapingFocus).Set(0) else: dome_light_prim.GetAttribute(UsdLux.Tokens.shapingFocusTint).Set(Gf.Vec3f(0, 0, 0)) dome_light_prim.GetAttribute(UsdLux.Tokens.shapingFocus).Set(0)
omniverse-code/kit/exts/omni.kit.window.usd_paths/omni/kit/window/usd_paths/tests/__init__.py
from .test_usd_paths import * from .create_prims import *
omniverse-code/kit/exts/omni.kit.window.usd_paths/omni/kit/window/usd_paths/tests/test_usd_paths.py
import os import unittest import carb import omni.kit.test class TestUsdPaths(omni.kit.test.AsyncTestCase): async def setUp(self): # Disable logging for the time of tests to avoid spewing errors await omni.usd.get_context().new_stage_async() omni.kit.window.usd_paths.tests.create_test_stage() async def tearDown(self): pass async def test_paths(self): found_paths = [] def get_all_paths(path): if path not in found_paths: found_paths.append(os.path.basename(path).lower()) return path def on_preload_complete(): paths = sorted( [ path for path in found_paths if path.endswith(".hdr") or path.endswith(".mdl") or path.find("lenna.") != -1 ] ) self.assertListEqual( paths, ["canary_wharf_4k.hdr", "lenna.dds", "lenna.gif", "lenna.jpg", "lenna.png", "lenna.tga", "omnipbr.mdl"], ) await omni.kit.window.usd_paths.get_instance().get_asset_paths(on_preload_complete, get_all_paths)