file_path
stringlengths
20
207
content
stringlengths
5
3.85M
size
int64
5
3.85M
lang
stringclasses
9 values
avg_line_length
float64
1.33
100
max_line_length
int64
4
993
alphanum_fraction
float64
0.26
0.93
omniverse-code/kit/include/omni/kit/ui/ColorScheme.h
// Copyright (c) 2019-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. // #pragma once #include <carb/Types.h> #include <carb/logging/Log.h> #include <unordered_map> namespace omni { namespace kit { namespace ui { // Generic const carb::Float4 kErrorMessageColor = { 1.f, 0.f, 0.f, 1.f }; // Asset Explorer const carb::Float4 kAssetExplorerFilterIconEnabledColor = { 126.f / 255.f, 187.f / 255.f, 199.f / 255.f, 1.f }; const carb::Float4 kAssetExplorerClearFilterColor = { 15.f / 255.f, 110.f / 255.f, 131.f / 255.f, 1.f }; const carb::Float4 kAssetExplorerAssetIconSelectedBgColorDark = { 0.2f, 0.2f, 0.2f, 0.6f }; const carb::Float4 kAssetExplorerAssetIconSelectedBgColorLight = { 0.84f, 0.84f, 0.84f, 1.0f }; const carb::Float4 kAssetExplorerAssetIconHoveredBgColorDark = { 0.2f, 0.2f, 0.2f, 0.8f }; const carb::Float4 kAssetExplorerAssetIconHoveredBgColorLight = { 0.749f, 0.8f, 0.812f, 1.0f }; const carb::Float4 kAssetExplorerPopulatedFolderColor = { 119.f / 255.f, 134 / 255.f, 137 / 255.f, 1.0f }; const carb::Float4 kAssetExplorerUnpopulatedFolderColor = { 0.39f, 0.39f, 0.39f, 1.0f }; // ECS Debug View const carb::Float4 kEcsDebugViewSelectedComponentColor = { 1.f, 1.f, 0.f, 1.f }; // IEditor Window const carb::Float4 kEditorWindowConnectionStateDisconnectedColor = { 1.f, 0.f, 0.f, 1.f }; const carb::Float4 kEditorWindowConnectionStateConnectedNoLiveColor = { 0.796f, 0.416f, 0.416f, 1.f }; const carb::Float4 kEditorWindowConnectionStateConnectedLiveColor = { 0.46f, 0.72f, 0.f, 1.f }; // Scene Hierarchy const carb::Float4 kSceneHierarchySearchMatchedColor = { 1.f, 1.f, 1.f, 1.f }; const carb::Float4 kSceneHierarchySearchUnmatchedColor = { 0.5f, 0.5f, 0.5f, 1.f }; // Status Bar const carb::Float4 kStatusBarProgressColor = { 79.f / 255.f, 125.f / 255.f, 160.f / 255.f, 1.f }; // Simple Tree View const carb::Float4 kTreeViewColor = { 0.3f, 0.3f, 0.3f, 1.0f }; // Viewport const carb::Float4 kViewportChildWindowBgColor = { 0.f, 0.f, 0.f, 0.f }; // Layers Window const carb::Float4 kLayerWarningColor = { 1.0f, 111.0f / 255.0f, 114.0f / 255.0f, 1.0f }; // Message using ColorMap = std::unordered_map<int32_t, carb::Float4>; const carb::Float4 kMessageTextColorLightDefault = { 0.30980f, 0.49020f, 0.62745f, 1.f }; const ColorMap kMessageTextColorLight = { // Other levels use default color { carb::logging::kLevelVerbose, carb::Float4{ 0.49020f, 0.49020f, 0.49020f, 1.f } }, { carb::logging::kLevelWarn, carb::Float4{ 0.89020f, 0.54118f, 0.14118f, 1.f } }, { carb::logging::kLevelError, carb::Float4{ 0.57255f, 0.25882f, 0.22745f, 1.f } }, { carb::logging::kLevelFatal, carb::Float4{ 0.57255f, 0.25882f, 0.22745f, 1.f } } }; const carb::Float4 kMessageTextColorDarkDefault = { 0.47451f, 0.72941f, 0.92157f, 1.f }; const ColorMap kMessageTextColorDark = { // Other levels use default color { carb::logging::kLevelVerbose, carb::Float4{ 0.72941f, 0.72941f, 0.72941f, 1.f } }, { carb::logging::kLevelWarn, carb::Float4{ 0.87451f, 0.79608f, 0.29020f, 1.f } }, { carb::logging::kLevelError, carb::Float4{ 0.96471f, 0.69412f, 0.66667f, 1.f } }, { carb::logging::kLevelFatal, carb::Float4{ 0.96471f, 0.69412f, 0.66667f, 1.f } } }; const carb::Float4 kMessageIconColorLightDefault = { 0.30980f, 0.49020f, 0.62745f, 1.f }; const ColorMap kMessageIconColorLight = { // Other levels use default color { carb::logging::kLevelVerbose, carb::Float4{ 0.49020f, 0.49020f, 0.49020f, 1.f } }, { carb::logging::kLevelWarn, carb::Float4{ 0.89020f, 0.54118f, 0.14118f, 1.f } }, { carb::logging::kLevelError, carb::Float4{ 0.973f, 0.541f, 0.49f, 1.f } }, { carb::logging::kLevelFatal, carb::Float4{ 0.973f, 0.541f, 0.49f, 1.f } } }; const carb::Float4 kMessageIconColorDarkDefault = { 0.47451f, 0.72941f, 0.92157f, 1.f }; const ColorMap kMessageIconColorDark = { // Other levels use default color { carb::logging::kLevelVerbose, carb::Float4{ 0.72941f, 0.72941f, 0.72941f, 1.f } }, { carb::logging::kLevelWarn, carb::Float4{ 0.87451f, 0.79608f, 0.29020f, 1.f } }, { carb::logging::kLevelError, carb::Float4{ 0.973f, 0.541f, 0.49f, 1.f } }, { carb::logging::kLevelFatal, carb::Float4{ 0.973f, 0.541f, 0.49f, 1.f } } }; inline carb::Float4 selectColor(bool darkUi, int32_t level, const ColorMap& darkMap, const ColorMap& lightMap, const carb::Float4& darkDefault, const carb::Float4& lightDefault) { const ColorMap& colorMap = darkUi ? darkMap : lightMap; carb::Float4 color = darkUi ? darkDefault : lightDefault; auto colorEntry = colorMap.find(level); if (colorEntry != colorMap.end()) { color = colorEntry->second; } return color; } } } }
5,198
C
42.689075
111
0.674298
omniverse-code/kit/include/omni/kit/ui/Image.h
// Copyright (c) 2019-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. // #pragma once #include "Widget.h" #include <carb/renderer/RendererTypes.h> #include <atomic> #include <mutex> namespace omni { namespace kit { namespace ui { /** * Defines a image. */ class OMNI_KIT_UI_CLASS_API Image : public Widget { public: static const WidgetType kType = CARB_HASH_TYPE(omni::kit::ui::Image); /** * Constructor. * ALWAYS create Image with make_shared so enable_shared_from_this works correctly. * * @param text The text for the label to use. */ OMNI_KIT_UI_API Image(const char* url, uint32_t width, uint32_t height); /** * Destructor. */ OMNI_KIT_UI_API ~Image() override; /** * Gets the url of the image. * * @return The url to be loaded. */ OMNI_KIT_UI_API const char* getUrl() const; /** * Sets the url of the image * * @param url The url to load. */ OMNI_KIT_UI_API virtual void setUrl(const char* url); /** * @see Widget::getType */ OMNI_KIT_UI_API WidgetType getType() override; /** * @see Widget::draw */ void draw(float elapsedTime) override; /** * draw image * * @param imgui imgui ptr * @param cursorPos position to draw image * @param width width of image to draw * @param height height of image to draw * @param color color of image to draw */ OMNI_KIT_UI_API virtual void drawImage(carb::imgui::ImGui* imgui, const carb::Float2& cursorPos, float width, float height, uint32_t color = 0xffffffff, uint32_t defaultColor = 0xffffffff, bool hovered = false); protected: void loadUrl(); std::string m_url; std::mutex m_textureMutex; carb::renderer::Texture* m_texture = nullptr; carb::renderer::TextureHandle m_textureGpuHandle = {}; bool m_hasSetUrl = false; }; } } }
2,532
C
24.33
87
0.587678
omniverse-code/kit/include/omni/kit/ui/ProgressBar.h
// Copyright (c) 2019-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. // #pragma once #include "ColorScheme.h" #include "Widget.h" namespace omni { namespace kit { namespace ui { /** * Defines a progress bar. */ class OMNI_KIT_UI_CLASS_API ProgressBar : public Widget { public: static const WidgetType kType = CARB_HASH_TYPE(omni::kit::ui::ProgressBar); OMNI_KIT_UI_API ProgressBar(Length width, Length height = Pixel(0), const carb::Float4& color = kStatusBarProgressColor); OMNI_KIT_UI_API ProgressBar(float width, const carb::Float4& color = kStatusBarProgressColor); /** * Destructor. */ OMNI_KIT_UI_API virtual ~ProgressBar(); /** * @see Widget::getType */ OMNI_KIT_UI_API virtual WidgetType getType(); /** * @see Widget::draw */ OMNI_KIT_UI_API virtual void draw(float elapsedTime); /** * Set progress * * @param value The current value of progress bar (between 0-1). * @param text The overlay text for the progress bar. If nullptr, the automatic percentage text is displayed. */ OMNI_KIT_UI_API void setProgress(float value, const char* text = nullptr); /** * Get current progress * * @return The current value of progress bar (between 0-1). */ OMNI_KIT_UI_API float getProgress() const; /** * Get current overlay * * @return The current overlay of progress bar. */ OMNI_KIT_UI_API const char* getOverlay() const; /** * Set color of bar * * @param color Value in carb::Float4. */ OMNI_KIT_UI_API void setColor(carb::Float4 color); /** * Get color of bar * * @return color Value in carb::Float4. */ OMNI_KIT_UI_API carb::Float4 getColor() const; protected: float m_value; ///< The progress bar value (between 0-1). carb::Float4 m_color; // The color of progress bar. }; } } }
2,350
C
24.554348
115
0.638298
omniverse-code/kit/include/omni/kit/ui/TextBox.h
// Copyright (c) 2019-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. // #pragma once #include "ValueWidget.h" #include <string> #include <vector> namespace omni { namespace kit { namespace ui { /** * Defines a text field. */ class OMNI_KIT_UI_CLASS_API TextBox : public ValueWidget<std::string> { public: static const WidgetType kType = CARB_HASH_TYPE(omni::kit::ui::TextBox); static const size_t kMaxLength = 1024; OMNI_KIT_UI_API explicit TextBox(const char* defaultText, bool changeValueOnEnter = false); OMNI_KIT_UI_API TextBox(const char* defaultText, const char* hint, bool changeValueOnEnter = false); OMNI_KIT_UI_API ~TextBox() override; OMNI_KIT_UI_API void setValueChangedFn(const std::function<void(WidgetRef)>& fn); OMNI_KIT_UI_API void setValueFinalizedFn(const std::function<void(WidgetRef)>& fn); OMNI_KIT_UI_API void setListSuggestionsFn(const std::function<std::vector<std::string>(WidgetRef, const char*)>& fn); OMNI_KIT_UI_API bool getReadOnly() const; OMNI_KIT_UI_API void setReadOnly(bool readOnly); OMNI_KIT_UI_API bool getShowBackground() const; OMNI_KIT_UI_API void setShowBackground(bool showBackground); OMNI_KIT_UI_API float getTextWidth(); /** * Sets the color of the text. * * @param textColor */ OMNI_KIT_UI_API void setTextColor(const carb::ColorRgba& textColor); /** * Resets the color of the text. * * @param textColor */ OMNI_KIT_UI_API void resetTextColor(); /** * @see Widget::getType */ OMNI_KIT_UI_API WidgetType getType() override; /** * @see Widget::draw */ OMNI_KIT_UI_API void draw(float elapsedTime) override; OMNI_KIT_UI_API virtual std::vector<std::string> listSuggestions(const char* prefix); /* NOTE: only eEllipsisLeft & eEllipsisRight are supported when clipping is used, the TextBox will be readonly & disabled, but not greyed out */ ClippingType getClippingMode(ClippingType mode) const { return m_clippingMode; } void setClippingMode(ClippingType mode) { if (mode == ClippingType::eWrap) { CARB_LOG_ERROR("TextBox widget does not support ClippingType::eWrap"); return; } m_clippingMode = mode; } protected: void _onValueChange() override; private: void setText(const char* text); bool m_changeValueOnEnter; bool m_isReadOnly = false; bool m_wasActive = false; bool m_showBackground = true; char m_text[kMaxLength] = ""; char m_hint[kMaxLength] = ""; std::function<void(WidgetRef)> m_valueChangedFn; std::function<void(WidgetRef)> m_valueFinalizedFn; std::function<std::vector<std::string>(WidgetRef, const char*)> m_listSuggestionsFn; SubscriptionId m_valueSubId; float m_clippingWidth; ClippingType m_clippingMode; bool m_customColor = false; carb::ColorRgba m_textColor; }; } } }
3,354
C
25.626984
121
0.682171
omniverse-code/kit/include/omni/kit/ui/ScrollingFrame.h
// Copyright (c) 2019-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. // #pragma once #include "Container.h" namespace omni { namespace kit { namespace ui { /** * Defines a FixedSizeFrame layout. */ class OMNI_KIT_UI_CLASS_API ScrollingFrame : public Container { public: static const WidgetType kType = CARB_HASH_TYPE(omni::kit::ui::ScrollingFrame); OMNI_KIT_UI_API ScrollingFrame(const char* title, float width, float height); OMNI_KIT_UI_API ~ScrollingFrame(); OMNI_KIT_UI_API virtual void scrollTo(float scrollTo); OMNI_KIT_UI_API WidgetType getType() override; void draw(float elapsedTime) override; protected: float m_width; float m_height; bool m_needsScrolling = false; float m_scrollTo; std::string m_title; bool m_defaultOpen; }; } } }
1,171
C
22.918367
82
0.734415
omniverse-code/kit/include/omni/kit/ui/Popup.h
// Copyright (c) 2019-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. // #pragma once #include "ColumnLayout.h" #include <omni/ui/windowmanager/IWindowCallbackManager.h> #include <cstdint> #include <functional> #include <memory> #include <string> namespace omni { namespace kit { namespace ui { class Container; /** * Defines a popup. */ class OMNI_KIT_UI_CLASS_API Popup { public: /** * Constructor */ OMNI_KIT_UI_API explicit Popup( const std::string& title, bool modal = false, float width = 0, float height = 0, bool autoResize = false); /** * Destructor. */ OMNI_KIT_UI_API ~Popup(); OMNI_KIT_UI_API void show(); OMNI_KIT_UI_API void hide(); OMNI_KIT_UI_API bool isVisible() const; OMNI_KIT_UI_API void setVisible(bool visible); OMNI_KIT_UI_API const char* getTitle() const; OMNI_KIT_UI_API void setTitle(const char* title); OMNI_KIT_UI_API carb::Float2 getPos() const; OMNI_KIT_UI_API void setPos(const carb::Float2& pos); OMNI_KIT_UI_API float getWidth() const; OMNI_KIT_UI_API void setWidth(float width); OMNI_KIT_UI_API float getHeight() const; OMNI_KIT_UI_API void setHeight(float height); OMNI_KIT_UI_API std::shared_ptr<Container> getLayout() const; OMNI_KIT_UI_API void setLayout(std::shared_ptr<Container> layout); OMNI_KIT_UI_API void setUpdateFn(const std::function<void(float)>& fn); OMNI_KIT_UI_API void setCloseFn(const std::function<void()>& fn); private: void _draw(float dt); std::string m_popupId; bool m_modal; bool m_autoResize; std::string m_title; float m_width; float m_height; carb::Float2 m_pos; std::shared_ptr<Container> m_layout; omni::ui::windowmanager::IWindowCallbackPtr m_handle; omni::kit::SubscriptionId m_updateSubId; bool m_visible = false; bool m_pendingVisiblityUpdate = false; bool m_pendingPositionUpdate = false; std::function<void(float)> m_updateFn; std::function<void()> m_closeFn; }; } } }
2,407
C
22.841584
114
0.688409
omniverse-code/kit/include/omni/kit/ui/Model.h
// Copyright (c) 2019-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. // #pragma once #include "Api.h" #include "Common.h" #include <carb/events/IEvents.h> #include <memory> #include <string> #include <unordered_map> namespace omni { namespace kit { namespace ui { enum class ModelNodeType { eUnknown, eObject, eArray, eString, eBool, eNumber }; enum class ModelEventType { eNodeAdd, eNodeRemove, eNodeTypeChange, eNodeValueChange }; struct ModelChangeInfo { carb::events::SenderId sender = carb::events::kGlobalSenderId; bool transient = false; }; template <class T> struct ModelValue { T value; bool ambiguous; }; class OMNI_KIT_UI_CLASS_API Model { public: Model() = default; // PART 1: Get OMNI_KIT_UI_API virtual ModelNodeType getType(const char* path, const char* meta = "") = 0; OMNI_KIT_UI_API virtual ModelValue<std::string> getValueAsString( const char* path, const char* meta = "", size_t index = 0, bool isTimeSampled = false, double time = -1.0) = 0; OMNI_KIT_UI_API virtual ModelValue<bool> getValueAsBool( const char* path, const char* meta = "", size_t index = 0, bool isTimeSampled = false, double time = -1.0) = 0; OMNI_KIT_UI_API virtual ModelValue<double> getValueAsNumber( const char* path, const char* meta = "", size_t index = 0, bool isTimeSampled = false, double time = -1.0) = 0; virtual size_t getKeyCount(const char* path, const char* meta = "") { return 0; } virtual std::string getKey(const char* path, const char* meta, size_t index) { return ""; } virtual size_t getArraySize(const char* path, const char* meta = "") { return 0; } // PART 2: Set virtual void beginChangeGroup() { } virtual void endChangeGroup() { } virtual void setType(const char* path, const char* meta, ModelNodeType type, const ModelChangeInfo& info = {}) { } OMNI_KIT_UI_API virtual void setValueString(const char* path, const char* meta, std::string value, size_t index = 0, bool isTimeSampled = false, double time = -1.0, const ModelChangeInfo& info = {}) = 0; OMNI_KIT_UI_API virtual void setValueBool(const char* path, const char* meta, bool value, size_t index = 0, bool isTimeSampled = false, double time = -1.0, const ModelChangeInfo& info = {}) = 0; OMNI_KIT_UI_API virtual void setValueNumber(const char* path, const char* meta, double value, size_t index = 0, bool isTimeSampled = false, double time = -1.0, const ModelChangeInfo& info = {}) = 0; OMNI_KIT_UI_API virtual void setArraySize(const char* path, const char* meta, size_t size, bool isTimeSampled = false, double time = -1.0, const ModelChangeInfo& info = {}) { } // PART 3: signals OMNI_KIT_UI_API void signalChange(const char* path, const char* meta, ModelEventType type, const ModelChangeInfo& info); virtual void onSubscribeToChange(const char* path, const char* meta, carb::events::IEventStream*) { } virtual void onUnsubscribeToChange(const char* path, const char* meta, carb::events::IEventStream*) { } OMNI_KIT_UI_API void subscribeToChange(const char* path, const char* meta, carb::events::IEventStream*); OMNI_KIT_UI_API void unsubscribeToChange(const char* path, const char* meta, carb::events::IEventStream*); // HELPERS: template <class T> OMNI_KIT_UI_API ModelValue<T> getValue( const char* path, const char* meta, size_t index = 0, bool isTimeSampled = false, double time = -1.0); template <class T> OMNI_KIT_UI_API void setValue(const char* path, const char* meta, T value, size_t index = 00, bool isTimeSampled = false, double time = -1.0, const ModelChangeInfo& info = {}); template <class T> OMNI_KIT_UI_API static ModelNodeType getNodeTypeForT(); OMNI_KIT_UI_API virtual ~Model(){}; private: std::unordered_map<std::string, std::vector<carb::events::IEventStream*>> m_pathChangeListeners; }; template <> inline ModelValue<bool> Model::getValue(const char* path, const char* meta, size_t index, bool isTimeSampled, double time) { return getValueAsBool(path, meta, index, isTimeSampled, time); } template <> inline ModelValue<std::string> Model::getValue( const char* path, const char* meta, size_t index, bool isTimeSampled, double time) { return getValueAsString(path, meta, index, isTimeSampled, time); } template <> inline ModelValue<double> Model::getValue(const char* path, const char* meta, size_t index, bool isTimeSampled, double time) { return getValueAsNumber(path, meta, index, isTimeSampled, time); } template <> inline ModelValue<float> Model::getValue(const char* path, const char* meta, size_t index, bool isTimeSampled, double time) { auto v = getValue<double>(path, meta, index, isTimeSampled, time); return { static_cast<float>(v.value), v.ambiguous }; } template <> inline ModelValue<int32_t> Model::getValue(const char* path, const char* meta, size_t index, bool isTimeSampled, double time) { auto v = getValue<double>(path, meta, index, isTimeSampled, time); return { static_cast<int32_t>(v.value), v.ambiguous }; } template <> inline ModelValue<uint32_t> Model::getValue(const char* path, const char* meta, size_t index, bool isTimeSampled, double time) { auto v = getValue<double>(path, meta, index, isTimeSampled, time); return { static_cast<uint32_t>(v.value), v.ambiguous }; } template <> inline ModelValue<carb::Int2> Model::getValue(const char* path, const char* meta, size_t, bool isTimeSampled, double time) { auto v0 = getValue<int32_t>(path, meta, 0, isTimeSampled, time); auto v1 = getValue<int32_t>(path, meta, 1, isTimeSampled, time); return { carb::Int2{ v0.value, v1.value }, v0.ambiguous || v1.ambiguous }; } template <> inline ModelValue<carb::Double2> Model::getValue(const char* path, const char* meta, size_t, bool isTimeSampled, double time) { auto v0 = getValue<double>(path, meta, 0, isTimeSampled, time); auto v1 = getValue<double>(path, meta, 1, isTimeSampled, time); return { carb::Double2{ v0.value, v1.value }, v0.ambiguous || v1.ambiguous }; } template <> inline ModelValue<carb::Double3> Model::getValue(const char* path, const char* meta, size_t, bool isTimeSampled, double time) { auto v0 = getValue<double>(path, meta, 0, isTimeSampled, time); auto v1 = getValue<double>(path, meta, 1, isTimeSampled, time); auto v2 = getValue<double>(path, meta, 2, isTimeSampled, time); return { carb::Double3{ v0.value, v1.value, v2.value }, v0.ambiguous || v1.ambiguous || v2.ambiguous }; } template <> inline ModelValue<carb::Double4> Model::getValue(const char* path, const char* meta, size_t, bool isTimeSampled, double time) { auto v0 = getValue<double>(path, meta, 0, isTimeSampled, time); auto v1 = getValue<double>(path, meta, 1, isTimeSampled, time); auto v2 = getValue<double>(path, meta, 2, isTimeSampled, time); auto v3 = getValue<double>(path, meta, 3, isTimeSampled, time); return { carb::Double4{ v0.value, v1.value, v2.value, v3.value }, v0.ambiguous || v1.ambiguous || v2.ambiguous || v3.ambiguous }; } template <> inline ModelValue<carb::ColorRgb> Model::getValue(const char* path, const char* meta, size_t, bool isTimeSampled, double time) { auto v0 = getValue<float>(path, meta, 0, isTimeSampled, time); auto v1 = getValue<float>(path, meta, 1, isTimeSampled, time); auto v2 = getValue<float>(path, meta, 2, isTimeSampled, time); return { carb::ColorRgb{ v0.value, v1.value, v2.value }, v0.ambiguous || v1.ambiguous || v2.ambiguous }; } template <> inline ModelValue<carb::ColorRgba> Model::getValue(const char* path, const char* meta, size_t, bool isTimeSampled, double time) { auto v0 = getValue<float>(path, meta, 0, isTimeSampled, time); auto v1 = getValue<float>(path, meta, 1, isTimeSampled, time); auto v2 = getValue<float>(path, meta, 2, isTimeSampled, time); auto v3 = getValue<float>(path, meta, 3, isTimeSampled, time); return { carb::ColorRgba{ v0.value, v1.value, v2.value, v3.value }, v0.ambiguous || v1.ambiguous || v2.ambiguous || v3.ambiguous }; } template <> inline ModelValue<Mat44> Model::getValue(const char* path, const char* meta, size_t, bool isTimeSampled, double time) { ModelValue<Mat44> res; res.ambiguous = false; for (size_t i = 0; i < 16; i++) { auto v = getValue<double>(path, meta, i, isTimeSampled, time); *(&res.value.rows[0].x + i) = v.value; res.ambiguous |= v.ambiguous; } return res; } template <> inline void Model::setValue(const char* path, const char* meta, bool value, size_t index, bool isTimeSampled, double time, const ModelChangeInfo& info) { this->beginChangeGroup(); this->setValueBool(path, meta, value, index, isTimeSampled, time, info); this->endChangeGroup(); } template <> inline void Model::setValue(const char* path, const char* meta, std::string value, size_t index, bool isTimeSampled, double time, const ModelChangeInfo& info) { this->beginChangeGroup(); this->setValueString(path, meta, value, index, isTimeSampled, time, info); this->endChangeGroup(); } template <> inline void Model::setValue(const char* path, const char* meta, double value, size_t index, bool isTimeSampled, double time, const ModelChangeInfo& info) { this->beginChangeGroup(); this->setValueNumber(path, meta, value, index, isTimeSampled, time, info); this->endChangeGroup(); } template <> inline void Model::setValue(const char* path, const char* meta, float value, size_t index, bool isTimeSampled, double time, const ModelChangeInfo& info) { this->beginChangeGroup(); this->setValueNumber(path, meta, static_cast<double>(value), index, isTimeSampled, time, info); this->endChangeGroup(); } template <> inline void Model::setValue(const char* path, const char* meta, int32_t value, size_t index, bool isTimeSampled, double time, const ModelChangeInfo& info) { this->beginChangeGroup(); this->setValueNumber(path, meta, static_cast<double>(value), index, isTimeSampled, time, info); this->endChangeGroup(); } template <> inline void Model::setValue(const char* path, const char* meta, uint32_t value, size_t index, bool isTimeSampled, double time, const ModelChangeInfo& info) { this->beginChangeGroup(); this->setValueNumber(path, meta, static_cast<double>(value), index, isTimeSampled, time, info); this->endChangeGroup(); } template <> inline void Model::setValue(const char* path, const char* meta, carb::Int2 value, size_t, bool isTimeSampled, double time, const ModelChangeInfo& info) { this->beginChangeGroup(); this->setArraySize(path, meta, 2); this->setValue(path, meta, value.x, 0, isTimeSampled, time, info); this->setValue(path, meta, value.y, 1, isTimeSampled, time, info); this->endChangeGroup(); } template <> inline void Model::setValue(const char* path, const char* meta, carb::Double2 value, size_t, bool isTimeSampled, double time, const ModelChangeInfo& info) { this->beginChangeGroup(); this->setArraySize(path, meta, 2, isTimeSampled, time); this->setValue(path, meta, value.x, 0, isTimeSampled, time, info); this->setValue(path, meta, value.y, 1, isTimeSampled, time, info); this->endChangeGroup(); } template <> inline void Model::setValue(const char* path, const char* meta, carb::Double3 value, size_t, bool isTimeSampled, double time, const ModelChangeInfo& info) { this->beginChangeGroup(); this->setArraySize(path, meta, 3, isTimeSampled, time); this->setValue(path, meta, value.x, 0, isTimeSampled, time, info); this->setValue(path, meta, value.y, 1, isTimeSampled, time, info); this->setValue(path, meta, value.z, 2, isTimeSampled, time, info); this->endChangeGroup(); } template <> inline void Model::setValue(const char* path, const char* meta, carb::Double4 value, size_t, bool isTimeSampled, double time, const ModelChangeInfo& info) { this->beginChangeGroup(); this->setArraySize(path, meta, 4, isTimeSampled, time); this->setValue(path, meta, value.x, 0, isTimeSampled, time, info); this->setValue(path, meta, value.y, 1, isTimeSampled, time, info); this->setValue(path, meta, value.z, 2, isTimeSampled, time, info); this->setValue(path, meta, value.w, 3, isTimeSampled, time, info); this->endChangeGroup(); } template <> inline void Model::setValue(const char* path, const char* meta, carb::ColorRgb value, size_t, bool isTimeSampled, double time, const ModelChangeInfo& info) { this->beginChangeGroup(); this->setArraySize(path, meta, 3, isTimeSampled, time); this->setValue(path, meta, value.r, 0, isTimeSampled, time, info); this->setValue(path, meta, value.g, 1, isTimeSampled, time, info); this->setValue(path, meta, value.b, 2, isTimeSampled, time, info); this->endChangeGroup(); } template <> inline void Model::setValue(const char* path, const char* meta, carb::ColorRgba value, size_t, bool isTimeSampled, double time, const ModelChangeInfo& info) { this->beginChangeGroup(); this->setArraySize(path, meta, 4, isTimeSampled, time); this->setValue(path, meta, value.r, 0, isTimeSampled, time, info); this->setValue(path, meta, value.g, 1, isTimeSampled, time, info); this->setValue(path, meta, value.b, 2, isTimeSampled, time, info); this->setValue(path, meta, value.a, 3, isTimeSampled, time, info); this->endChangeGroup(); } template <> inline void Model::setValue(const char* path, const char* meta, ui::Mat44 value, size_t, bool isTimeSampled, double time, const ModelChangeInfo& info) { this->beginChangeGroup(); this->setArraySize(path, meta, 16, isTimeSampled, time); for (size_t i = 0; i < 16; i++) this->setValue(path, meta, *(&value.rows[0].x + i), i, isTimeSampled, time, info); this->endChangeGroup(); } template <> inline ModelNodeType Model::getNodeTypeForT<std::string>() { return ModelNodeType::eString; } template <> inline ModelNodeType Model::getNodeTypeForT<bool>() { return ModelNodeType::eBool; } template <> inline ModelNodeType Model::getNodeTypeForT<double>() { return ModelNodeType::eNumber; } template <> inline ModelNodeType Model::getNodeTypeForT<float>() { return ModelNodeType::eNumber; } template <> inline ModelNodeType Model::getNodeTypeForT<int32_t>() { return ModelNodeType::eNumber; } template <> inline ModelNodeType Model::getNodeTypeForT<uint32_t>() { return ModelNodeType::eNumber; } template <> inline ModelNodeType Model::getNodeTypeForT<carb::Int2>() { return ModelNodeType::eArray; } template <> inline ModelNodeType Model::getNodeTypeForT<carb::Double2>() { return ModelNodeType::eArray; } template <> inline ModelNodeType Model::getNodeTypeForT<carb::Double3>() { return ModelNodeType::eArray; } template <> inline ModelNodeType Model::getNodeTypeForT<carb::Double4>() { return ModelNodeType::eArray; } template <> inline ModelNodeType Model::getNodeTypeForT<carb::ColorRgb>() { return ModelNodeType::eArray; } template <> inline ModelNodeType Model::getNodeTypeForT<carb::ColorRgba>() { return ModelNodeType::eArray; } template <> inline ModelNodeType Model::getNodeTypeForT<Mat44>() { return ModelNodeType::eArray; } // Default Value Model std::unique_ptr<Model> createSimpleValueModel(ModelNodeType valueType); } } }
19,326
C
32.966608
127
0.572441
omniverse-code/kit/include/omni/kit/ui/Menu.h
// Copyright (c) 2019-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. // #pragma once #include "Widget.h" #include <omni/kit/KitTypes.h> #include <functional> #include <memory> #include <string> #include <unordered_map> #include <vector> namespace carb { namespace imgui { struct ImGui; } } namespace omni { namespace kit { namespace ui { struct MenuItemImpl; enum class MenuEventType : uint32_t { eActivate, }; /** * Menu System allows to register menu items based on path like: "File/Preferences/Foo". * The item can be either a toggle (2 state, with a check) or just a command. * Menu items in the same sub menu a sorted based on priority value. If priority differs more than 10 inbetween items - * separator is added. */ class OMNI_KIT_UI_CLASS_API Menu : public Widget { public: OMNI_KIT_UI_API Menu(); OMNI_KIT_UI_API ~Menu() override; static const WidgetType kType = CARB_HASH_TYPE(omni::kit::ui::Menu); WidgetType getType() override { return kType; } /** * Checks if a menu item is already registered. * * @param menuPath The path to the menu (e.g. "File/Open"). * @return true if it's existed, or false otherwise. */ OMNI_KIT_UI_API bool hasItem(const char* menuPath); /** * Adds a menu item. * * @param menuPath The path to the menu (e.g. "File/Open"). * @param onMenuItemClicked The callback function called when menu item is clicked. * @param toggle If the menu item is a toggle (i.e. checkable). * @param priority Priority of the menu. Menu with smaller priority will be placed at top. If priority differs more * @param toggle value (if toggle). * @param enabled. * @param draw glyph char with origin color defined in svg. * then 10 in between items separator is added. */ OMNI_KIT_UI_API bool addItem(const char* menuPath, const std::function<void(const char* menuPath, bool value)>& onClick, bool toggle, int priority, bool value, bool enabled, bool originSvgColor = false); OMNI_KIT_UI_API void setOnClick(const char* menuPath, const std::function<void(const char* menuPath, bool value)>& onClick); OMNI_KIT_UI_API void setOnRightClick(const char* menuPath, const std::function<void(const char* menuPath, bool value)>& onClick); /** * Removes a menu item. * * @param menuPath The path of the menu item to be removed. */ OMNI_KIT_UI_API void removeItem(const char* menuPath); OMNI_KIT_UI_API size_t getItemCount() const; OMNI_KIT_UI_API std::vector<std::string> getItems() const; /** * Sets the priority of a menu item. * * @param menuPath The path of the menu to set priority. * @param priority The priority to be set to. */ OMNI_KIT_UI_API void setPriority(const char* menuPath, int priority); /** * Sets the hotkey for a menu item. * * @param menuPath The path of the menu to set hotkey to. * @param mod The modifier key flags for the hotkey. * @param key The key for the hotkey. */ OMNI_KIT_UI_API void setHotkey(const char* menuPath, carb::input::KeyboardModifierFlags mod, carb::input::KeyboardInput key); /** * Sets the input action for a menu item. * * @param menuPath The path of the menu to set hotkey to. * @param actionName The action name. */ OMNI_KIT_UI_API void setActionName(const char* menuPath, const char* actionMappingSetPath, const char* actionPath); /** * Sets the toggle value for a menu item. The menu must be a "toggle" when being created. * * @param value The toggle value of the menu item. */ OMNI_KIT_UI_API void setValue(const char* menuPath, bool value); /** * Gets the toggle value for a menu item. The menu must be a "toggle" when being created. * * @return The toggle value of the menu item. */ OMNI_KIT_UI_API bool getValue(const char* menuPath) const; /** * Sets the enabled state of a menu item. * * @param menuPath The path of the menu to set enabled state to. * @param enabled true to enabled the menu. false to disable it. */ OMNI_KIT_UI_API void setEnabled(const char* menuPath, bool value); /** * For non "toggle" menu items, invoke the onClick function handler * * @param menuPath The path of the menu to activate. */ OMNI_KIT_UI_API void executeOnClick(const char* menuPath); void draw(float elapsedTime) override; private: void _update(float elapsedTime); std::unique_ptr<MenuItemImpl> m_root; std::unordered_map<std::string, MenuItemImpl*> m_pathToMenu; carb::events::ISubscriptionPtr m_updateEvtSub; bool m_needUpdate = false; carb::input::Keyboard* m_keyboard = nullptr; bool m_warning_silence = false; }; // Temporary hook up to the Editor main menu bar OMNI_KIT_UI_API std::shared_ptr<Menu> getEditorMainMenu(); // Temporary hook to enable scripting a menu item via python OMNI_KIT_UI_API void activateMenuItem(const char* menuPath); } } }
5,785
C
29.452631
119
0.638894
omniverse-code/kit/include/omni/kit/ui/UI.h
// Copyright (c) 2019-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. // #pragma once #include "BroadcastModel.h" #include "Button.h" #include "CheckBox.h" #include "CollapsingFrame.h" #include "Color.h" #include "ColumnLayout.h" #include "ComboBox.h" #include "ContentWindow.h" #include "Drag.h" #include "Field.h" #include "FilePicker.h" #include "Image.h" #include "Label.h" #include "Library.h" #include "ListBox.h" #include "Menu.h" #include "Model.h" #include "ModelMeta.h" #include "Popup.h" #include "ProgressBar.h" #include "RowColumnLayout.h" #include "RowLayout.h" #include "ScalarXYZ.h" #include "ScalarXYZW.h" #include "ScrollingFrame.h" #include "Separator.h" #include "SimpleTreeView.h" #include "Slider.h" #include "Spacer.h" #include "TextBox.h" #include "Transform.h" #include "ViewCollapsing.h" #include "Window.h"
1,202
C
26.340908
77
0.757072
omniverse-code/kit/include/omni/kit/ui/Widget.h
// Copyright (c) 2019-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. // #pragma once #include "Api.h" #include "Common.h" #include <carb/Defines.h> #include <omni/ui/Font.h> #include <omni/ui/IGlyphManager.h> #include <functional> #include <memory> #include <string> namespace omni { namespace kit { namespace ui { class Container; class Window; typedef uint64_t WidgetType; /** * Parent this class it to asscoiate your own data with a Widget. */ class WidgetUserData { public: virtual ~WidgetUserData() = default; }; /** * Defines a widget. */ class OMNI_KIT_UI_CLASS_API Widget : public std::enable_shared_from_this<Widget> { friend class Container; friend class Window; public: /** * Constructor. */ OMNI_KIT_UI_API Widget(); /** * Destructor. */ OMNI_KIT_UI_API virtual ~Widget(); /** * Determines if the widget is enabled. * * @return true if the widget is enabled, false if disabled. */ OMNI_KIT_UI_API bool isEnabled() const; /** * Set the widget to enabled. */ OMNI_KIT_UI_API void setEnabled(bool enable); /** * Gets the layout this widget is within. * * A nullptr indicates the widget is not in a layout but directly in window. * * @return The layout this widget is within. */ OMNI_KIT_UI_API Container* getLayout() const; /** * Gets the type of widget. * * @return The type of widget. */ OMNI_KIT_UI_API virtual WidgetType getType() = 0; /** * Draws the widget. * * @param elapsedTime The time elapsed (in seconds) */ OMNI_KIT_UI_API virtual void draw(float elapsedTime) = 0; /** * set the font * * @param font The font to use */ OMNI_KIT_UI_API void setFontStyle(omni::ui::FontStyle fontStyle); /** * get the font * * @return The font in use */ OMNI_KIT_UI_API omni::ui::FontStyle getFontStyle() const; /** * Get the font size (height in pixels) of the current font style with the current scaling applied. * * @return The font size. */ OMNI_KIT_UI_API float getFontSize() const; /** * Sets the callback function when the widget recieves a dragdrop payload * * @param fn The callback function when the widget recieves a dragdrop payload * @param payloadName the name of acceptable payload */ OMNI_KIT_UI_API void setDragDropFn(const std::function<void(WidgetRef, const char*)>& fn, const char* payloadName); /** * Sets the callback function when the widget is dragged. * * @param fn The callback function when the widget is dragged. */ void setDraggingFn(const std::function<void(WidgetRef, DraggingType)>& fn) { m_draggedFn = fn; } /** * A way to associate arbitrary user data with it. */ std::shared_ptr<WidgetUserData> userData; /** * Determines if the widget is visible. * * @return true if the widget is visible, false if hidden. */ OMNI_KIT_UI_API bool isVisible() const; /** * Set the widget visibility state. */ OMNI_KIT_UI_API void setVisible(bool visible); Length width = Pixel(0); Length height = Pixel(0); static constexpr size_t kUniqueIdSize = 4; protected: bool m_enabled = true; bool m_visible = true; bool m_isDragging; Container* m_layout = nullptr; char m_uniqueId[kUniqueIdSize + 1]; std::string m_label; omni::ui::FontStyle m_fontStyle; carb::imgui::Font* m_font; std::function<void(WidgetRef, const char*)> m_dragDropFn; std::function<void(WidgetRef, DraggingType)> m_draggedFn; std::string m_dragDropPayloadName; }; } } }
4,127
C
22.191011
119
0.642113
omniverse-code/kit/include/omni/kit/ui/ModelMeta.h
// Copyright (c) 2019-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. // #pragma once #include "Model.h" namespace omni { namespace kit { namespace ui { constexpr const char* const kModelMetaWidgetType = "widgetType"; constexpr const char* const kModelMetaSerializedContents = "serializedContents"; } } }
678
C
23.249999
80
0.783186
omniverse-code/kit/include/omni/kit/ui/NativeFileDialog.h
// Copyright (c) 2019-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. // #pragma once #include <carb/extras/Unicode.h> #include <carb/logging/Log.h> #include <string> #include <utility> #include <vector> #if CARB_PLATFORM_WINDOWS # ifndef NOMINMAX # define NOMINMAX # endif # include <ShObjIdl_core.h> #endif #ifdef _MSC_VER # pragma warning(disable : 4996) #endif namespace omni { namespace kit { namespace ui { /** * Defines an NativeFileDialog class that handles file/folder selection using OS specific implementation. */ class NativeFileDialog { public: enum class Mode { eOpen, ///! OpenFileDialog. eSave, ///! SaveFileDialog. }; enum class Type { eFile, ///! Select file. eDirectory, ///! Select directory. }; /** * Constructor. * * @param mode Open or Save dialog. * @param type Choose File or Directory. * @param title Title text. * @param multiSelction If supporting selecting more than one file/directory. */ NativeFileDialog(Mode mode, Type type, const std::string& title, bool multiSelection); /** * Add file type filter. * * @param name Name of the file type. * @param spec Specification of the file type. */ void addFilter(const std::string& name, const std::string& spec); /** * Shows the open file dialog. */ bool show(); /** * Gets the selected path(s). * * @param urls The vector to write selected path(s) to. * @return True if the result is valid. */ bool getFileUrls(std::vector<std::string>& urls) const; private: struct FileTypeFilter { std::string name; std::string spec; }; Mode m_mode; Type m_type; std::string m_title; std::vector<FileTypeFilter> m_filters; std::vector<std::string> m_fileUrls; bool m_multiSel; }; inline NativeFileDialog::NativeFileDialog(Mode mode, Type type, const std::string& title, bool multiSelection) : m_mode(mode), m_type(type), m_title(title), m_multiSel(multiSelection) { } inline void NativeFileDialog::addFilter(const std::string& name, const std::string& spec) { m_filters.emplace_back(FileTypeFilter{ name, spec }); } inline bool NativeFileDialog::show() { bool ret = false; #if CARB_PLATFORM_WINDOWS auto prepareDialogCommon = [this](::IFileDialog* fileDialog, std::vector<std::wstring>& wstrs) { // Set filters std::vector<COMDLG_FILTERSPEC> rgFilterSpec; rgFilterSpec.reserve(m_filters.size()); wstrs.reserve(m_filters.size() * 2); for (auto& filter : m_filters) { wstrs.push_back(carb::extras::convertUtf8ToWide(filter.name)); std::wstring& nameWstr = wstrs.back(); wstrs.push_back(carb::extras::convertUtf8ToWide(filter.spec)); std::wstring& specWstr = wstrs.back(); rgFilterSpec.emplace_back(COMDLG_FILTERSPEC{ nameWstr.c_str(), specWstr.c_str() }); } fileDialog->SetFileTypes(static_cast<UINT>(rgFilterSpec.size()), rgFilterSpec.data()); std::wstring title = carb::extras::convertUtf8ToWide(m_title); fileDialog->SetTitle(title.c_str()); }; switch (m_mode) { case Mode::eOpen: { IFileOpenDialog* fileDialog; auto hr = CoCreateInstance(CLSID_FileOpenDialog, nullptr, CLSCTX_INPROC_SERVER, IID_PPV_ARGS(&fileDialog)); if (SUCCEEDED(hr)) { DWORD options; fileDialog->GetOptions(&options); if (m_multiSel) { options |= OFN_ALLOWMULTISELECT; } if (m_type == Type::eDirectory) { options |= FOS_PICKFOLDERS; } fileDialog->SetOptions(options); std::vector<std::wstring> wstrs; // keep a reference of the converted string around prepareDialogCommon(fileDialog, wstrs); hr = fileDialog->Show(nullptr); if (SUCCEEDED(hr)) { IShellItemArray* pItemArray; hr = fileDialog->GetResults(&pItemArray); if (SUCCEEDED(hr)) { DWORD dwNumItems = 0; pItemArray->GetCount(&dwNumItems); for (DWORD i = 0; i < dwNumItems; i++) { IShellItem* pItem = nullptr; hr = pItemArray->GetItemAt(i, &pItem); if (SUCCEEDED(hr)) { PWSTR pszFilePath; hr = pItem->GetDisplayName(SIGDN_FILESYSPATH, &pszFilePath); if (SUCCEEDED(hr)) { std::string path = carb::extras::convertWideToUtf8(pszFilePath); m_fileUrls.emplace_back(std::move(path)); CoTaskMemFree(pszFilePath); } pItem->Release(); } } ret = true; pItemArray->Release(); } } fileDialog->Release(); } break; } case Mode::eSave: { IFileSaveDialog* fileDialog; auto hr = CoCreateInstance(CLSID_FileSaveDialog, nullptr, CLSCTX_INPROC_SERVER, IID_PPV_ARGS(&fileDialog)); if (SUCCEEDED(hr)) { std::vector<std::wstring> wstrs; // keep a reference of the converted string around prepareDialogCommon(fileDialog, wstrs); fileDialog->SetFileName(L"Untitled"); hr = fileDialog->Show(nullptr); if (SUCCEEDED(hr)) { IShellItem* pItem = nullptr; hr = fileDialog->GetResult(&pItem); if (SUCCEEDED(hr)) { PWSTR pszFilePath; hr = pItem->GetDisplayName(SIGDN_FILESYSPATH, &pszFilePath); if (SUCCEEDED(hr)) { std::string path = carb::extras::convertWideToUtf8(pszFilePath); UINT fileTypeIndex; hr = fileDialog->GetFileTypeIndex(&fileTypeIndex); fileTypeIndex--; // One based index. Convert it to zero based if (SUCCEEDED(hr)) { std::string& fileType = m_filters[fileTypeIndex].spec; size_t extPos = path.rfind(".stage.usd"); path = path.substr(0, extPos) + fileType.substr(1); m_fileUrls.emplace_back(std::move(path)); } CoTaskMemFree(pszFilePath); } pItem->Release(); ret = true; } } fileDialog->Release(); } break; } } #endif return ret; } inline bool NativeFileDialog::getFileUrls(std::vector<std::string>& urls) const { if (m_fileUrls.size()) { urls = m_fileUrls; return true; } return false; } } } }
7,695
C
29.0625
115
0.540481
omniverse-code/kit/include/omni/kit/ui/ComboBox.h
// Copyright (c) 2019-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. // #pragma once #include "ValueWidget.h" #include <string> #include <vector> namespace omni { namespace kit { namespace ui { /** * Defines a combo box. */ template <class T> class OMNI_KIT_UI_CLASS_API ComboBox : public SimpleValueWidget<T> { public: static const WidgetType kType = CARB_HASH_TYPE(omni::kit::ui::ComboBox<T>); OMNI_KIT_UI_API explicit ComboBox(const char* text, const std::vector<T>& items = {}, const std::vector<std::string>& displayNames = {}); OMNI_KIT_UI_API ~ComboBox() override; OMNI_KIT_UI_API size_t getItemCount() const; OMNI_KIT_UI_API const T& getItemAt(size_t index) const; OMNI_KIT_UI_API void addItem(const T& item, const std::string& displayName = ""); OMNI_KIT_UI_API void removeItem(size_t index); OMNI_KIT_UI_API void clearItems(); OMNI_KIT_UI_API void setItems(const std::vector<T>& items, const std::vector<std::string>& displayNames = {}); OMNI_KIT_UI_API int64_t getSelectedIndex() const; OMNI_KIT_UI_API void setSelectedIndex(int64_t index); OMNI_KIT_UI_API WidgetType getType() override; protected: virtual bool _isTransientChangeSupported() const override { return false; } bool _drawImGuiWidget(carb::imgui::ImGui* imgui, T& value) override; private: struct Element { T value; std::string displayName; }; std::vector<Element> m_items; int64_t m_selectedIndex = -1; }; using ComboBoxString = ComboBox<std::string>; using ComboBoxInt = ComboBox<int>; } } }
2,044
C
23.939024
114
0.674658
omniverse-code/kit/include/omni/kit/ui/Separator.h
// Copyright (c) 2019-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. // #pragma once #include "Widget.h" namespace omni { namespace kit { namespace ui { /** * Defines a separator element. */ class OMNI_KIT_UI_CLASS_API Separator : public Widget { public: static const WidgetType kType = CARB_HASH_TYPE(omni::kit::ui::Separator); OMNI_KIT_UI_API Separator(); /** * @see Widget::getType */ OMNI_KIT_UI_API WidgetType getType() override; /** * @see Widget::draw */ void draw(float elapsedTime) override; }; } } }
931
C
20.181818
77
0.706767
omniverse-code/kit/include/omni/kit/ui/FilterGroupWidget.h
// Copyright (c) 2019-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. // #include <omni/kit/FilterGroup.h> #include <omni/kit/ui/ColorScheme.h> #include <omni/ui/IGlyphManager.h> namespace omni { namespace kit { namespace ui { template <typename FilterGroupT> class FilterGroupWidget { public: explicit FilterGroupWidget(FilterGroupT& filterGroup) : m_filterGroup(filterGroup) { m_glyphManager = carb::getFramework()->acquireInterface<omni::ui::IGlyphManager>(); } void draw(carb::imgui::ImGui* imgui, float elapsedTime) { using namespace carb::imgui; const float kFontSize = imgui->getFontSize(); const carb::Float2 kItemSpacing = imgui->getStyle()->itemSpacing; bool filterEnabled = m_filterGroup.isFilterGroupEnabled(); if (filterEnabled) { imgui->pushStyleColor(StyleColor::eText, kAssetExplorerFilterIconEnabledColor); } auto filterGlyph = m_glyphManager->getGlyphInfo("${glyphs}/filter.svg"); bool filterIconClicked = imgui->selectable(filterGlyph.code, false, 0, { kFontSize, kFontSize }); if (filterEnabled) { imgui->popStyleColor(); } // (RMB / hold LMB / Click LMB & No filter is enabled) to open filter list bool showFilterList = imgui->isItemClicked(1) || (imgui->isItemClicked(0) && !m_filterGroup.isAnyFilterEnabled()); m_mouseHeldOnFilterIconTime += elapsedTime; if (!(imgui->isItemHovered(0) && imgui->isMouseDown(0))) { m_mouseHeldOnFilterIconTime = 0.f; } const float kMouseHoldTime = 0.3f; if (showFilterList || m_mouseHeldOnFilterIconTime >= kMouseHoldTime) { imgui->openPopup("FilterList"); } else { if (filterIconClicked) { m_filterGroup.setFilterGroupEnabled(!filterEnabled); } } if (imgui->beginPopup("FilterList", 0)) { imgui->text("Filter"); imgui->sameLineEx(0.f, kFontSize * 3); imgui->textColored(kAssetExplorerClearFilterColor, "Clear Filters"); bool clearFilters = imgui->isItemClicked(0); imgui->separator(); std::vector<std::string> filterNames; m_filterGroup.getFilterNames(filterNames); for (auto& name : filterNames) { if (clearFilters) { m_filterGroup.setFilterEnabled(name, false); } bool enabled = m_filterGroup.isFilterEnabled(name); imgui->pushIdString(name.c_str()); auto checkGlyph = enabled ? m_glyphManager->getGlyphInfo("${glyphs}/check_square.svg") : m_glyphManager->getGlyphInfo("${glyphs}/square.svg"); if (imgui->selectable((std::string(checkGlyph.code) + " ").c_str(), false, kSelectableFlagDontClosePopups, { 0.f, 0.f })) { m_filterGroup.setFilterEnabled(name, !enabled); } imgui->popId(); imgui->sameLine(); imgui->text(name.c_str()); } imgui->endPopup(); } // Draw the tiny triangle at corner of the filter icon { imgui->sameLine(); auto cursorPos = imgui->getCursorScreenPos(); auto drawList = imgui->getWindowDrawList(); carb::Float2 points[3]; points[0] = { cursorPos.x - kItemSpacing.x, cursorPos.y + kFontSize * 0.75f + kItemSpacing.y * 0.5f }; points[1] = { cursorPos.x - kItemSpacing.x, cursorPos.y + kFontSize + kItemSpacing.y * 0.5f }; points[2] = { cursorPos.x - kItemSpacing.x - kFontSize * 0.25f, cursorPos.y + kFontSize + kItemSpacing.y * 0.5f }; imgui->addTriangleFilled( drawList, points[0], points[1], points[2], imgui->getColorU32StyleColor(StyleColor::eText, 1.f)); imgui->newLine(); } } private: FilterGroupT& m_filterGroup; omni::ui::IGlyphManager* m_glyphManager = nullptr; float m_mouseHeldOnFilterIconTime = 0.f; }; } } }
4,671
C
34.938461
122
0.588739
omniverse-code/kit/include/omni/kit/ui/SimpleTreeView.h
// Copyright (c) 2019-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. // #pragma once #include "Widget.h" #include <functional> #include <memory> #include <string> namespace omni { namespace kit { namespace ui { /** * Defines a SimpleTreeView. */ class OMNI_KIT_UI_CLASS_API SimpleTreeView : public Widget { public: static const WidgetType kType = CARB_HASH_TYPE(omni::kit::ui::SimpleTreeView); /** * Constructor. * * @param treeData A list of strings to construct the data of the TreeView * @param separator */ OMNI_KIT_UI_API explicit SimpleTreeView(const std::vector<std::string>& treeData, char separator = '/'); /** * Destructor. */ OMNI_KIT_UI_API ~SimpleTreeView() override; /** * Gets the text of the treeNode. * * @return The text of the treeNode. */ OMNI_KIT_UI_API const std::string getSelectedItemName() const; /** * Clears the currently selected tree node */ OMNI_KIT_UI_API void clearSelection(); /** * Sets the text of the tree nodes. * * @param text The text of the tree nodes. */ OMNI_KIT_UI_API void setTreeData(const std::vector<std::string>& treeData); /** * Sets the callback function when any tree node is clicked. * * fn The callback function when any tree node is clicked. */ OMNI_KIT_UI_API void setClickedFn(const std::function<void(WidgetRef)>& fn); /** * @see Widget::getType */ OMNI_KIT_UI_API WidgetType getType() override; /** * @see Widget::draw */ void draw(float elapsedTime) override; protected: // Clicked Function callback std::function<void(WidgetRef)> m_clickedFn; protected: struct TreeDataNode; using TreeDataNodePtr = std::shared_ptr<TreeDataNode>; // An internal structure to accomodate the Hierachical tree data struct TreeDataNode : public std::enable_shared_from_this<TreeDataNode> { // The text of the current node std::string m_text; // Pointer to the parent node std::weak_ptr<TreeDataNode> m_parentNode; // List of child nodes std::vector<TreeDataNodePtr> m_children; // Single Node's constructor/destructor explicit TreeDataNode(const std::string& data); ~TreeDataNode(); // Helper functions // Add a child TreeDataNodePtr& addChild(TreeDataNodePtr& node); // Recursively delete all childrens(decendents) void deleteChildren(); // Stack up the node text to construct the full path from root to the current node const std::string getFullPath(const char& separator) const; }; // The root node of the entire tree TreeDataNodePtr m_rootNode; // Pointer to the currently selected Node, for the rendering purpose std::weak_ptr<TreeDataNode> m_selectedNode; // A customized separator, default as '/' char m_separator; protected: // Helper function to build the entire data tree, return false if build fail bool buildDataTree(const std::vector<std::string>& inputStrings); // Helper function to split the string into a list of string tokens // example, "root/parent/child" ==> ["root","parent","child"] std::vector<std::string> split(const std::string& s, char seperator); // A core function to hierachically, node as the root, visualize the tree data using into the SimpleTreeView void drawTreeNode(carb::imgui::ImGui* imgui, const std::shared_ptr<SimpleTreeView::TreeDataNode>& node); }; } } }
3,948
C
27.007092
112
0.6692
omniverse-code/kit/include/omni/kit/ui/ScalarXYZW.h
// Copyright (c) 2019-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. // #pragma once #include "Image.h" #include "ScalarXYZ.h" #include "ValueWidget.h" namespace omni { namespace kit { namespace ui { /** * Defines a ScalarXYZW widget. */ class OMNI_KIT_UI_CLASS_API ScalarXYZW : public ValueWidget<carb::Double4> { public: static const WidgetType kType = CARB_HASH_TYPE(omni::kit::ui::ScalarXYZW); /** * Constructor. * */ OMNI_KIT_UI_API ScalarXYZW( const char* displayFormat, float speed, float wrapValue, float minValue, float maxValue, carb::Double4 value = {}); /** * Destructor. */ OMNI_KIT_UI_API ~ScalarXYZW(); /** * @see Widget::getType */ OMNI_KIT_UI_API WidgetType getType() override; void draw(float elapsedTime) override; private: std::shared_ptr<ScalarXYZ> m_scalar; bool m_edited; bool m_init; }; } } }
1,282
C
21.508772
123
0.690328
omniverse-code/kit/include/omni/kit/ui/ListBox.h
// Copyright (c) 2019-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. // #pragma once #include "Label.h" #include <functional> #include <string> #include <utility> #include <vector> namespace omni { namespace kit { namespace ui { /** * Defines a list box. */ class OMNI_KIT_UI_CLASS_API ListBox : public Label { public: static const WidgetType kType = CARB_HASH_TYPE(omni::kit::ui::ListBox); OMNI_KIT_UI_API explicit ListBox(const char* text, bool multiSelect = true, int visibleItemCount = -1, const std::vector<std::string>& items = {}); OMNI_KIT_UI_API ~ListBox() override; OMNI_KIT_UI_API bool isMultiSelect() const; OMNI_KIT_UI_API void setMultiSelect(bool multiSelect); OMNI_KIT_UI_API int getItemHeightCount() const; OMNI_KIT_UI_API void setItemHeightCount(int itemHeightCount); OMNI_KIT_UI_API size_t getItemCount() const; OMNI_KIT_UI_API const char* getItemAt(size_t index) const; OMNI_KIT_UI_API void addItem(const char* item); OMNI_KIT_UI_API void removeItem(size_t index); OMNI_KIT_UI_API void clearItems(); OMNI_KIT_UI_API std::vector<int> getSelected() const; OMNI_KIT_UI_API void setSelected(int index, bool selected); OMNI_KIT_UI_API void clearSelection(); OMNI_KIT_UI_API void setSelectionChangedFn(const std::function<void(WidgetRef)>& fn); OMNI_KIT_UI_API WidgetType getType() override; void draw(float elapsedTime) override; private: int m_itemHeightCount = -1; bool m_multiSelect = false; int m_selectedIndex = -1; std::vector<std::pair<std::string, bool>> m_items; std::function<void(WidgetRef)> m_selectionChangedFn; }; } } }
2,144
C
25.481481
89
0.680504
omniverse-code/kit/include/omni/kit/ui/ScalarXYZ.h
// Copyright (c) 2019-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. // #pragma once #include "Image.h" #include "ValueWidget.h" namespace omni { namespace kit { namespace ui { /** * Defines a ScalarXYZ widget. */ class OMNI_KIT_UI_CLASS_API ScalarXYZ : public ValueWidget<carb::Double3> { public: static const WidgetType kType = CARB_HASH_TYPE(omni::kit::ui::ScalarXYZ); OMNI_KIT_UI_API ScalarXYZ(const char* displayFormat, float speed, double wrapValue, double minValue, double maxValue, double deadZone = 0.0, carb::Double3 value = {}); OMNI_KIT_UI_API ~ScalarXYZ(); /** * @see Widget::getType */ OMNI_KIT_UI_API WidgetType getType() override; /** * Draws the scalar, used for drawing when allocated by other classes * * @param v x,y,z to draw * @return true if dirty */ OMNI_KIT_UI_API bool drawScalar(carb::Double3& v, bool& afterEdit, bool hasX = true, bool hasY = true, bool hasZ = true); OMNI_KIT_UI_API double wrapScalar(double value) const; OMNI_KIT_UI_API double deadzoneScalar(double value) const; std::string displayFormat; float dragSpeed; double wrapValue; double deadZone; double minVal; double maxVal; void draw(float elapsedTime) override; void setSkipYposUpdate(bool skip) { m_skipYposUpdate = skip; } private: enum class Images { eX, eY, eZ, eCount }; std::shared_ptr<Image> m_images[static_cast<size_t>(Images::eCount)]; std::string m_labelY; std::string m_labelZ; bool m_skipYposUpdate = false; const char* m_filenames[static_cast<size_t>(Images::eCount)] = { "/resources/icons/transform_x.png", "/resources/icons/transform_y.png", "/resources/icons/transform_z.png" }; }; } } }
2,487
C
26.340659
125
0.593888
omniverse-code/kit/include/omni/kit/usd/layers/LayerTypes.h
// Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved. // // NVIDIA CORPORATION and its licensors retain all intellectual property // and proprietary rights in and to this software, related documentation // and any modifications thereto. Any use, reproduction, disclosure or // distribution of this software and related documentation without an express // license agreement from NVIDIA CORPORATION is strictly prohibited. // #pragma once #include <carb/Interface.h> #include <carb/dictionary/IDictionary.h> #include <carb/events/IEvents.h> namespace omni { namespace kit { namespace usd { namespace layers { /** * Regards of edit mode, it's extended by Kit to support customized workflow. * USD supports to switch edit target so that all authoring will take place in * that layer. When it's working with multiple sublayers, this kind of freedom * may cause experience issues. User has to be aware the changes he/she made are * not overrided in any stronger layer. We extend a new mode called "auto authoring" * is to improve this. In this mode, all changes will firstly go into a middle delegate * layer and it will distribute them into their corresponding layers where it has the strongest * opinions. So it cannot switch edit target freely, and user does not need to be * aware of existence of multi-sublayers and how USD will compose the changes. * Besides, there is one more extended mode called "spec linking", which is based on * auto authoring. In this mode, user can customize the target layer of specific specs. */ enum class LayerEditMode { eNormal, // Normal USD mode that user can freely switch edit target and creates deltas. eAutoAuthoring, // Auto authoring mode that user cannot switch authoring layer freely. And all // deltas will be merged to its original layer where the prim specs have strongest opinions. // @see IWorkflowAutoAuthoring for interfaces about auto authoring. eSpecsLinking, // Spec linking mode will support to link specified spec changes into specific layers, // including forwarding changes of whole prim, or specific group of attributes. }; enum class LayerEventType { eInfoChanged, // Layer info changed, which includes: // PXR_NS::UsdGeomTokens->upAxis PXR_NS::UsdGeomTokens->metersPerUnit // PXR_NS::SdfFieldKeys->StartTimeCode PXR_NS::SdfFieldKeys->EndTimeCode // PXR_NS::SdfFieldKeys->FramesPerSecond PXR_NS::SdfFieldKeys->TimeCodesPerSecond // PXR_NS::SdfFieldKeys->SubLayerOffsets PXR_NS::SdfFieldKeys->Comment // PXR_NS::SdfFieldKeys->Documentation eMutenessScopeChanged, // For vallina USD, muteness is only local and not persistent. Omniverse extends // it so it could be persistent and sharable with other users. The muteness scope // is a concept about this that supports to switch between local and global scope. // In local scope, muteness will not be persistent In contract, global scope will // save muteness across sessions. This event is to notify change of muteness scope. eMutenessStateChanged, // Change of muteness state. eLockStateChanged, // Change of lock state. Lock is a customized concept in Omniverse that supports to // lock a layer it's not editable and savable. eDirtyStateChanged, // Change of dirtiness state. eOutdateStateChanged, // Change of outdate state. This is only emitted for layer in Nucleus when layer content // is out of sync with server one. ePrimSpecsChanged, // Change of layer. It will be emitted along with changed paths of prim specs. eSublayersChanged, // Change of sublayers. eSpecsLockingChanged, // Change of lock states of specs. It will be emitted along with the changed paths. eSpecsLinkingChanged, // Change of linking states of specs. It will be emitted along with the changed paths. eEditTargetChanged, // Change of edit target. eEditModeChanged, // Change of edit mode. @see LayerEditMode for details. eDefaultLayerChanged, // Change default layer. Default layer is an extended concept that's only available in auto // authornig mode. It's to host all new created prims from auto authoring layer. eLiveSessionStateChanged, // Live session started or stopped eLiveSessionListChanged, // List of live sessions refreshed, which may because of a session is created or removed. eLiveSessionUserJoined, // User joined. eLiveSessionUserLeft, // User left. eLiveSessionMergeStarted, // Starting to merge live session. eLiveSessionMergeEnded, // Finished to merge live session. eUsedLayersChanged, // Used layers changed in stage. Used layers includes all sublayers, references, payloads or any external layers loaded into stage. // If eSublayersChanged is sent, this event will be sent also. eLiveSessionJoining, // The event will be sent before Live Session is joined. eLayerFilePermissionChanged, // The event will be sent when file write/read permission is changed. }; enum class LayerErrorType { eSuccess, eReadOnly, // Destination folder or file is read-only eNotFound, // File/folder/live session is not found, or layer is not in the local layer stack. eAlreadyExists, // File/folder/layer/live session already existes. eInvalidStage, // No stage is attached to the UsdContext. eInvalidParam, // Invalid param passed to API. eLiveSessionInvalid, // The live session does not match the base layer. Or The live session exists, // but it is broken on disk, for example, toml file is corrupted. eLiveSessionVersionMismatch, eLiveSessionBaseLayerMismatch, // The base layer of thie live session does not match the specified one. // It's normally because user wants to join session of layer B for layer A. eLiveSessionAlreadyJoined, eLiveSessionNoMergePermission, eLiveSessionNotSupported, // Live session is not supported for the layer if layer is not in Nucleus or already has .live as extension. // Or it's reported for joining a live session for a reference or payload prim if prim is invalid, or it has // no references or payloads. eLiveSessionNotJoined, eUnkonwn }; class ILayersInstance : public carb::IObject { public: virtual carb::events::IEventStream* getEventStream() const = 0; virtual LayerEditMode getEditMode() const = 0; virtual void setEditMode(LayerEditMode editMode) = 0; virtual LayerErrorType getLastErrorType() const = 0; virtual const char* getLastErrorString() const = 0; }; } } } }
7,077
C
45.565789
160
0.693232
omniverse-code/kit/include/omni/kit/usd/layers/IWorkflowSpecsLocking.h
// Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved. // // NVIDIA CORPORATION and its licensors retain all intellectual property // and proprietary rights in and to this software, related documentation // and any modifications thereto. Any use, reproduction, disclosure or // distribution of this software and related documentation without an express // license agreement from NVIDIA CORPORATION is strictly prohibited. // #pragma once #include "LayerTypes.h" #include <carb/Interface.h> #include <carb/dictionary/IDictionary.h> namespace omni { namespace kit { namespace usd { namespace layers { struct IWorkflowSpecsLocking { CARB_PLUGIN_INTERFACE("omni::kit::usd::layers::IWorkflowSpecsLocking", 1, 0) carb::dictionary::Item*(CARB_ABI* lockSpec)(ILayersInstance* layersIntance, const char* specPath, bool hierarchy); carb::dictionary::Item*(CARB_ABI* unlockSpec)(ILayersInstance* layersIntance, const char* specPath, bool hierarchy); void(CARB_ABI* unlockAllSpecs)(ILayersInstance* layersIntance); bool(CARB_ABI* isSpecLocked)(ILayersInstance* layersInstance, const char* specPath); carb::dictionary::Item*(CARB_ABI* getAllLockedSpecs)(ILayersInstance* layersIntance); }; } } } }
1,230
C
25.760869
120
0.765041
omniverse-code/kit/include/omni/kit/usd/layers/IWorkflowAutoAuthoring.h
// Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved. // // NVIDIA CORPORATION and its licensors retain all intellectual property // and proprietary rights in and to this software, related documentation // and any modifications thereto. Any use, reproduction, disclosure or // distribution of this software and related documentation without an express // license agreement from NVIDIA CORPORATION is strictly prohibited. // #pragma once #include "LayerTypes.h" #include <carb/Interface.h> #include <carb/dictionary/IDictionary.h> namespace omni { namespace kit { namespace usd { namespace layers { struct IWorkflowAutoAuthoring { CARB_PLUGIN_INTERFACE("omni::kit::usd::layers::IWorkflowAutoAuthoring", 1, 0) bool(CARB_ABI* isEnabled)(ILayersInstance* layersIntance); void(CARB_ABI* suspend)(ILayersInstance* layersIntance); void(CARB_ABI* resume)(ILayersInstance* layersIntance); void(CARB_ABI* setDefaultLayer)(ILayersInstance* layersIntance, const char* layerIdentifier); const char*(CARB_ABI* getDefaultLayer)(ILayersInstance* layersIntance); bool(CARB_ABI* isAutoAuthoringLayer)(ILayersInstance* layersIntance, const char* layerIdentifier); }; } } } }
1,207
C
24.166666
102
0.767191
omniverse-code/kit/include/omni/kit/usd/layers/LayersHelper.hpp
// Copyright (c) 2019-2021, 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. // #pragma once // clang-format off #include "UsdPCH.h" // clang-format on #include <omni/kit/usd/layers/ILayers.h> #include <omni/usd/UsdContext.h> #if defined(__GNUC__) # pragma GCC diagnostic push # pragma GCC diagnostic ignored "-Wunused-function" #endif namespace omni { namespace kit { namespace usd { namespace layers { namespace internal { static carb::dictionary::IDictionary* getDictInterface() { static auto staticInterface = carb::getCachedInterface<carb::dictionary::IDictionary>(); return staticInterface; } } static ILayers* getLayersInterface() { static auto staticInterface = carb::getCachedInterface<omni::kit::usd::layers::ILayers>(); return staticInterface; } static ILayersState* getLayersStateInterface() { static auto staticInterface = carb::getCachedInterface<omni::kit::usd::layers::ILayersState>(); return staticInterface; } static IWorkflowAutoAuthoring* getAutoAuthoringInterface() { static auto staticInterface = carb::getCachedInterface<omni::kit::usd::layers::IWorkflowAutoAuthoring>(); return staticInterface; } static IWorkflowLiveSyncing* getLiveSyncingInterface() { static auto staticInterface = carb::getCachedInterface<omni::kit::usd::layers::IWorkflowLiveSyncing>(); return staticInterface; } static IWorkflowSpecsLocking* getSpecsLockingInterface() { static auto staticInterface = carb::getCachedInterface<omni::kit::usd::layers::IWorkflowSpecsLocking>(); return staticInterface; } static ILayersInstance* getLayersInstanceByName(const std::string& name) { auto layers = getLayersInterface(); return layers->getLayersInstanceByName(name.c_str()); } static ILayersInstance* getLayersInstanceByUsdContext(omni::usd::UsdContext* usdContext) { auto layers = getLayersInterface(); return layers->getLayersInstanceByContext(usdContext); } static carb::events::IEventStream* getEventStream(omni::usd::UsdContext* usdContext) { auto layerInstance = getLayersInstanceByUsdContext(usdContext); return layerInstance->getEventStream(); } static LayerEditMode getEditMode(omni::usd::UsdContext* usdContext) { auto layerInstance = getLayersInstanceByUsdContext(usdContext); return layerInstance->getEditMode(); } static void setEditMode(omni::usd::UsdContext* usdContext, LayerEditMode editMode) { auto layerInstance = getLayersInstanceByUsdContext(usdContext); layerInstance->setEditMode(editMode); } static std::vector<std::string> getLocalLayerIdentifiers( omni::usd::UsdContext* usdContext, bool includeSessionLayer = true, bool includeAnonymous = true, bool includeInvalid = true) { std::vector<std::string> layerIdentifiers; auto layerInstance = getLayersInstanceByUsdContext(usdContext); auto layersState = getLayersStateInterface(); auto item = layersState->getLocalLayerIdentifiers(layerInstance, includeSessionLayer, includeAnonymous, includeInvalid); if (item) { auto dict = internal::getDictInterface(); size_t length = dict->getArrayLength(item); for (size_t i = 0; i < length; i++) { layerIdentifiers.push_back(dict->getStringBufferAt(item, i)); } dict->destroyItem(item); } return layerIdentifiers; } static std::vector<std::string> getDirtyLayerIdentifiers(omni::usd::UsdContext* usdContext) { std::vector<std::string> layerIdentifiers; auto layerInstance = getLayersInstanceByUsdContext(usdContext); auto layersState = getLayersStateInterface(); auto item = layersState->getDirtyLayerIdentifiers(layerInstance); if (item) { auto dict = internal::getDictInterface(); size_t length = dict->getArrayLength(item); for (size_t i = 0; i < length; i++) { layerIdentifiers.push_back(dict->getStringBufferAt(item, i)); } dict->destroyItem(item); } return layerIdentifiers; } static std::string getLayerName(omni::usd::UsdContext* usdContext, const std::string& layerIdentifier) { std::vector<std::string> layerIdentifiers; auto layerInstance = getLayersInstanceByUsdContext(usdContext); auto layersState = getLayersStateInterface(); const std::string& name = layersState->getLayerName(layerInstance, layerIdentifier.c_str()); if (name.empty()) { if (PXR_NS::SdfLayer::IsAnonymousLayerIdentifier(layerIdentifier)) { return layerIdentifier; } else { return PXR_NS::SdfLayer::GetDisplayNameFromIdentifier(layerIdentifier); } } else { return name; } } static void suspendAutoAuthoring(omni::usd::UsdContext* usdContext) { auto autoAuthoring = getAutoAuthoringInterface(); auto layerInstance = getLayersInstanceByUsdContext(usdContext); autoAuthoring->suspend(layerInstance); } static void resumeAutoAuthoring(omni::usd::UsdContext* usdContext) { auto autoAuthoring = getAutoAuthoringInterface(); auto layerInstance = getLayersInstanceByUsdContext(usdContext); autoAuthoring->resume(layerInstance); } static std::string getDefaultLayerIdentifier(omni::usd::UsdContext* usdContext) { auto autoAuthoring = getAutoAuthoringInterface(); auto layerInstance = getLayersInstanceByUsdContext(usdContext); return autoAuthoring->getDefaultLayer(layerInstance); } } } } } #if defined(__GNUC__) # pragma GCC diagnostic pop #endif
5,871
C++
26.568075
124
0.731903
omniverse-code/kit/include/omni/kit/usd/layers/ILayersState.h
// Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved. // // NVIDIA CORPORATION and its licensors retain all intellectual property // and proprietary rights in and to this software, related documentation // and any modifications thereto. Any use, reproduction, disclosure or // distribution of this software and related documentation without an express // license agreement from NVIDIA CORPORATION is strictly prohibited. // #pragma once #include "LayerTypes.h" #include <carb/Interface.h> #include <carb/dictionary/IDictionary.h> namespace omni { namespace kit { namespace usd { namespace layers { /** * ILayersState works for managing all layers states of the corresponding stage. Not all layer states can be queried through ILayersState, * but only those ones that are not easily accessed from USD APIs or extended in Omniverse. All the following interfaces work for the used * layers in the bound UsdContext. */ struct ILayersState { CARB_PLUGIN_INTERFACE("omni::kit::usd::layers::ILayersState", 1, 1) // Gets all sublayers rooted from root layer, or session layer if includeSessionLayer is true. It's sorted from // strongest to weakest. If includeAnonymous is false, it will exclude anonymous ones. If includeInvalid is true, it // will include invalid sublayers. Invalid sublayers are those ones that in the layers list but its layer handle // cannot be found. carb::dictionary::Item*(CARB_ABI* getLocalLayerIdentifiers)(ILayersInstance* layerInstance, bool includeSessionLayer, bool includeAnonymous, bool includeInvalid); // Gets all dirty used layers excluding anonymous ones. carb::dictionary::Item*(CARB_ABI* getDirtyLayerIdentifiers)(ILayersInstance* layerInstance); /** * Muteness scope is a concept extended by Omniverse. It includes two modes: global and local. When it's in global mode, * muteness will be serialized and will broadcasted during live session, while local mode means they are transient and will * not be broadcasted during live session. */ void(CARB_ABI* setMutenessScope)(ILayersInstance* layersInstance, bool global); bool(CARB_ABI* isMutenessGlobal)(ILayersInstance* layersInstance); bool(CARB_ABI* isLayerGloballyMuted)(ILayersInstance* layersInstance, const char* layerIdentifier); bool(CARB_ABI* isLayerLocallyMuted)(ILayersInstance* layersInstance, const char* layerIdentifier); // If layer is writable means it can be set as edit target, it should satisfy: // 1. It's not read-only on disk. // 2. It's not muted. // 3. It's not locked by setLayerLockState. // You can still set it as edit target forcely if it's not writable, while this is useful for guardrails. bool(CARB_ABI* isLayerWritable)(ILayersInstance* layersInstance, const char* layerIdentifier); // If layer is savable means it can be saved to disk, it should satisfy: // 1. It's writable checked by isLayerWritable. // 2. It's not anonymous. // You can still save the layer forcely even it's locally locked or muted, while this is useful for guardrails. bool(CARB_ABI* isLayerSavable)(ILayersInstance* layersInstance, const char* layerIdentifier); /** * Layer is a lock extended in Omniverse. It's not real ACL control to lock the layer for accessing, but a bool * flag that's checked by all applications to access it for UX purpose so it cannot be set as edit target. * Currently, only sublayers in the local layer stack can be locked. */ void(CARB_ABI* setLayerLockState)(ILayersInstance* layersInstance, const char* layerIdentifier, bool locked); bool(CARB_ABI* isLayerLocked)(ILayersInstance* layersInstance, const char* layerIdentifier); void(CARB_ABI* setLayerName)(ILayersInstance* layersInstance, const char* layerIdentifier, const char* name); const char*(CARB_ABI* getLayerName)(ILayersInstance* layersInstance, const char* layerIdentifier); /** * If layer is outdated, it means it has updates on-disk. Currently, only layers in Nucleus can be watched * for updates. */ bool(CARB_ABI* isLayerOutdated)(ILayersInstance* layersInstance, const char* layerIdentifier); // If layer is read-only on disk, this is used to check file permission only. // It's only useful when layer is not anonymous. bool(CARB_ABI* isLayerReadOnlyOnDisk)(ILayersInstance* layersInstance, const char* layerIdentifier); // Gets all outdated layers. carb::dictionary::Item*(CARB_ABI* getAllOutdatedLayerIdentifiers)(ILayersInstance* layerInstance); // Gets all outdated sublayers in the stage's local layer stack. carb::dictionary::Item*(CARB_ABI* getOutdatedSublayerIdentifiers)(ILayersInstance* layerInstance); // Gets all outdated layers except those ones in the sublayers list, like those reference or payload layers. // If a layer is both inserted as sublayer, or reference, it will be treated as sublayer only. carb::dictionary::Item*(CARB_ABI* getOutdatedNonSublayerIdentifiers)(ILayersInstance* layerInstance); // Reload all outdated layers. void(CARB_ABI* reloadAllOutdatedLayers)(ILayersInstance* layerInstance); // Reload all outdated sublayers. void(CARB_ABI* reloadOutdatedSublayers)(ILayersInstance* layerInstance); // Reload all outdated layers except sublayers. If a layer is both inserted as sublayer, or reference, it will // be treated as sublayer only. void(CARB_ABI* reloadOutdatedNonSublayers)(ILayersInstance* layerInstance); // Gets the file owner. It's empty if file system does not support it. const char* (CARB_ABI* getLayerOwner)(ILayersInstance* layersInstance, const char* layerIdentifier); }; } } } }
5,905
C
46.248
138
0.725826
omniverse-code/kit/include/omni/kit/usd/layers/IWorkflowSpecsLinking.h
// Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved. // // NVIDIA CORPORATION and its licensors retain all intellectual property // and proprietary rights in and to this software, related documentation // and any modifications thereto. Any use, reproduction, disclosure or // distribution of this software and related documentation without an express // license agreement from NVIDIA CORPORATION is strictly prohibited. // #pragma once #include "LayerTypes.h" #include <carb/Interface.h> #include <carb/dictionary/IDictionary.h> namespace omni { namespace kit { namespace usd { namespace layers { struct IWorkflowSpecsLinking { CARB_PLUGIN_INTERFACE("omni::kit::usd::layers::IWorkflowSpecsLinking", 1, 0) bool(CARB_ABI* isEnabled)(ILayersInstance* layersIntance); void(CARB_ABI* suspend)(ILayersInstance* layersIntance); void(CARB_ABI* resume)(ILayersInstance* layersIntance); /** * Links spec to specific layer. * * @param specPath The spec path to be linked to layer, which can be prim or property path. If it's prim path, * all of its properties will be linked also. * @param layerIdentifier The layer that the spec is linked to. * @param hierarchy If it's true, all descendants of this spec will be linked to the specified layer also. * * @return Array of specs that are successfully linked. */ carb::dictionary::Item*(CARB_ABI* linkSpec)(ILayersInstance* layersIntance, const char* specPath, const char* layerIdentifier, bool hierarchy); /** * Unlinks spec from layer. * * @param specPath The spec path to be unlinked. * @param layerIdentifier The layer that the spec is unlinked from. * @param hierarchy If it's true, it means all of its descendants will be unlinked also. False otherwise. * @return Array of specs that are successfully unlinked. */ carb::dictionary::Item*(CARB_ABI* unlinkSpec)(ILayersInstance* layersIntance, const char* specPath, const char* layerIdentifier, bool hierarchy); /** * Unlinks spec from all linked layers. * * @param specPath The spec path to be unlinked. * @param hierarchy If it's true, it means all of its descendants will be unlinked also. False otherwise. * * @return Array of specs that are successfully unlinked. */ carb::dictionary::Item*(CARB_ABI* unlinkSpecFromAllLayers)(ILayersInstance* layersIntance, const char* specPath, bool hierarchy); /** * Unlinks specs that are linked to specific layer. * * @param layerIdentifier The layer identifier to unlink all specs from. * * @return array of specs that are successfully unlinked. */ carb::dictionary::Item*(CARB_ABI* unlinkSpecsToLayer)(ILayersInstance* layersIntance, const char* layerIdentifier); /** * Clears all spec links. */ void(CARB_ABI* unlinkAllSpecs)(ILayersInstance* layersIntance); /** * Gets all layer identifiers that specs are linked to. * * @param hierarchy If it's true, it means all of its descendants will be unlinked also. False otherwise. * @return Map of specs that are linked, of which key is the spec path, and value is list of layers that spec is * linked to. */ carb::dictionary::Item*(CARB_ABI* getSpecLayerLinks)(ILayersInstance* layersIntance, const char* specPath, bool hierarchy); /** * Gets all spec paths that link to this layer. */ carb::dictionary::Item*(CARB_ABI* getSpecLinksForLayer)(ILayersInstance* layersIntance, const char* layerIdentifier); /** * Gets all spec links. * * @return Map of spec links, of which key is the spec path, and value is layers that spec is linked to. */ carb::dictionary::Item*(CARB_ABI* getAllSpecLinks)(ILayersInstance* layersIntance); /** * Checkes if spec is linked or not. * * @param specPath The spec path. * @param layerIdentifier Layer identifier. If it's empty or null, it will return true if it's linked to any layers. * If it's not null and not empty, it will return true only when spec is linked to the specific layer. */ bool(CARB_ABI* isSpecLinked)(ILayersInstance* layersIntance, const char* specPath, const char* layerIdentifier); }; } } } }
4,823
C
36.6875
121
0.623886
omniverse-code/kit/include/omni/kit/usd/layers/ILayers.h
// Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved. // // NVIDIA CORPORATION and its licensors retain all intellectual property // and proprietary rights in and to this software, related documentation // and any modifications thereto. Any use, reproduction, disclosure or // distribution of this software and related documentation without an express // license agreement from NVIDIA CORPORATION is strictly prohibited. // #pragma once #include "ILayersState.h" #include "IWorkflowAutoAuthoring.h" #include "IWorkflowLiveSyncing.h" #include "IWorkflowSpecsLinking.h" #include "IWorkflowSpecsLocking.h" namespace omni { namespace kit { namespace usd { namespace layers { struct ILayers { CARB_PLUGIN_INTERFACE("omni::kit::usd::layers::ILayers", 1, 0) ILayersInstance*(CARB_ABI* getLayersInstanceByName)(const char* usdContextName); ILayersInstance*(CARB_ABI* getLayersInstanceByContext)(void* usdContext); }; } } } }
947
C
22.121951
84
0.771911
omniverse-code/kit/include/omni/kit/usd/layers/IWorkflowLiveSyncing.h
// Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved. // // NVIDIA CORPORATION and its licensors retain all intellectual property // and proprietary rights in and to this software, related documentation // and any modifications thereto. Any use, reproduction, disclosure or // distribution of this software and related documentation without an express // license agreement from NVIDIA CORPORATION is strictly prohibited. // #pragma once #include "LayerTypes.h" #include <carb/Interface.h> #include <carb/dictionary/IDictionary.h> #define LIVE_SYNCING_MAJOR_VER 1 #define LIVE_SYNCING_MINOR_VER 0 namespace omni { namespace kit { namespace usd { namespace layers { typedef void(*OnStageResultFn)(bool result, const char* err, void* userData); /** * A Live Session is a concept that extends live workflow for USD layers. * Users who join the same Live Session can see live updates with each other. * A Live Session is physically defined as follows: * 1. It has an unique URL to identify the location. * 2. It has a toml file to include the session configuration. * 3. It includes a Live Session layer that has extension .live for users to cooperate together. * 4. It includes a channel for users to send instant messages. * 5. It's bound to a base layer. A base layer is a USD file that your Live Session will be based on. */ class LiveSession; /** * LiveSyncing interfaces work to create/stop/manage Live Sessions. It supports to join a Live Session * for sublayer, or prim with references or payloads. If a layer is in the local sublayer list, and it's * added as reference or payload also. The Live Session can only be joined for the sublayer or reference/payload, * but cannot be joined for both. For layer that is added to multiple prims as reference/payload, it supports to * join the same Live Session for multiple prims that references the same layer. */ struct IWorkflowLiveSyncing { CARB_PLUGIN_INTERFACE("omni::kit::usd::layers::IWorkflowLiveSyncing", 2, 2) /** * Gets the count of Live Sessions for a specific layer. The layer must be in the layer stack of current UsdContext * that layerInstance is bound to. It's possible that getTotalLiveSessions will return 0 even there are Live Sessions * on the server as Live Sessions' finding is asynchronous, and this function only returns the count that's discovered * currently. * * @param layerIdentifier The base layer of Live Sessions. */ size_t(CARB_ABI* getTotalLiveSessions)(ILayersInstance* layerInstance, const char* layerIdentifier); /** * Gets the Live Session at index. The index must be less than the total Live Sessions got from getTotalLiveSessions. * Also, the index is not promised to be valid always as it's possible the Live Session is removed. * @param layerIdentifier The base layer of Live Sessions. * @param index The index to access. REMINDER: The same index may be changed to different Live Session as * it does not promise the list of Live Sessions will not be changed or re-ordered. */ LiveSession*(CARB_ABI* getLiveSessionAtIndex)(ILayersInstance* layerInstance, const char* layerIdentifier, size_t index); /** * The name of this Live Session. It's possible that session is invalid and it will return empty. * * @param session The Live Session instance. */ const char*(CARB_ABI* getLiveSessionName)(ILayersInstance* layerInstance, LiveSession* session); /** * The unique URL of this Live Session. It's possible that session is invalid and it will return empty. */ const char*(CARB_ABI* getLiveSessionUrl)(ILayersInstance* layerInstance, LiveSession* session); /** * The owner name of this session. The owner of the session is the one that has the permission to merge session changes back to * base layers. It's possible that session is invalid and it will return empty. REMEMBER: You should not use this * function to check if the local instance is the session owner as it's possible multiple instances with the same user join * in the Live Session. But only one of them is the real session owner. This funciton is only to check the static ownership * that tells you whom the session belongs to. In order to tell the runtime ownership, you should see permissionToMergeSessionChanges. * * @param session The Live Session instance. */ const char*(CARB_ABI* getLiveSessionOwner)(ILayersInstance* layersInstance, LiveSession* session); /** * The communication channel of this session. Channel is a concept in Nucleus to pub/sub transient messages * so all clients connected to it can communicate with each other. It's possible that session is invalid and it will return empty. * * @param session The Live Session instance. */ const char*(CARB_ABI* getLiveSessionChannelUrl)(ILayersInstance* layerInstance, LiveSession* session); /** * A session consists a root layer that's suffixed with .live extension. All live edits are done inside that * .live layer during a Live Session. It's possible that session is invalid and it will return empty. * * @param session The Live Session instance. */ const char*(CARB_ABI* getLiveSessionRootIdentifier)(ILayersInstance* layerInstance, LiveSession* session); /** * The base layer identifier for this Live Session. It's possible that session is invalid and it will return empty. * * @param session The Live Session instance. */ const char*(CARB_ABI* getLiveSessionBaseLayerIdentifier)(ILayersInstance* layerInstance, LiveSession* session); /** * Whether the local user has the permission to merge the Live Session or not. It's possible that the local user is * the owner of the Live Session but it returns false as if there are multiple instances with the same user join * the same session, only one of them has the merge permission to satisfy the requirement of unique ownership. * If the session is not joined, it will return the static ownership based on the owner name. * * @param session The Live Session instance. */ bool(CARB_ABI* permissionToMergeSessionChanges)(ILayersInstance* layersInstance, LiveSession* session); /** * If the session is valid. A valid session means it's not removed from disk. It's possible that this session * is removed during runtime. This function can be used to check if it's still valid before accessing it. * * @param session The Live Session instance. */ bool(CARB_ABI* isValidLiveSession)(ILayersInstance* layersInstance, LiveSession* session); /** * Creates a Live Session for specific sublayer. * * @param layerIdentifier The base layer. * @param sessionName The name of the Live Session. Name can only be alphanumerical characters with hyphens and underscores, * and should be prefixed with letter. * @see ILayersInstance::get_last_error_type() for more error details if it returns nullptr. */ LiveSession*(CARB_ABI* createLiveSession)(ILayersInstance* layersInstance, const char* layerIdentifier, const char* sessionName); /** * Joins the Live Session. The base layer of the Live Session must be in the local layer stack of current stage. * * @param session The Live Session instance. * @see ILayersInstance::get_last_error_type() for more error details if it returns false. */ bool(CARB_ABI* joinLiveSession)(ILayersInstance* layersInstance, LiveSession* session); /** * Joins Live Session by url for specified sublayer. The url must point to a valid Live Session for this layer or it can be created if it does not exist. * * @param layerIdentifier The base layer identifier of a sublayer. * @param liveSessionUrl The Live Session URL to join. * @param createIfNotExisted If it's true, it will create the Live Session under the URL specified if no Live Session is found. * @see ILayersInstance::get_last_error_type() for more error details if it returns false. */ bool(CARB_ABI* joinLiveSessionByURL)(ILayersInstance* layersInstance, const char* layerIdentifier, const char* liveSessionUrl, bool createIfNotExisted); /** * Stops the Live Session of base layer if it's in Live Session already. If this layer is added as reference/payload to multiple prims, and some of * them are in the Live Session of this layer, it will stop the Live Session for all the prims that reference this layer and in the Live Session. * @see stopLiveSessionForPrim to stop Live Session for specific prim. * * @param layerIdentifier The base layer. */ void(CARB_ABI* stopLiveSession)(ILayersInstance* layersInstance, const char* layerIdentifier); /** * Stops all Live Sessions in this stage for all layers. */ void(CARB_ABI* stopAllLiveSessions)(ILayersInstance* layersInstance); /** * If the current stage has any active Live Sessions for all used layers. */ bool(CARB_ABI* isStageInLiveSession)(ILayersInstance* layersInstance); /** * If a base layer is in any Live Sessions. It includes both Live Sessions for sublayer or reference/payload prims. * @see isLayerInPrimLiveSession to check if a layer is in any Live Sessions that are bound to reference/payload prims. * * @param layerIdentifier The base layer. */ bool(CARB_ABI* isLayerInLiveSession)(ILayersInstance* layersInstance, const char* layerIdentifier); /** * Gets the current Live Session of the base layer. A layer can only have one Live Session enabled at a time. * * @param layerIdentifier The base layer. */ LiveSession*(CARB_ABI* getCurrentLiveSession)(ILayersInstance* layersInstance, const char* layerIdentifier); /** * Checkes if this layer is a Live Session layer. A Live Session layer must be managed by a session, and with extension .live. * * @param layerIdentifier The base layer. */ bool(CARB_ABI* isLiveSessionLayer)(ILayersInstance* layersInstance, const char* layerIdentifier); /** * Merge changes of the Live Session to base layer specified by layerIdentifier. If layer is not in the Live Session currently, * it will return false directly. Live Session for prim is not supported to be merged. * * @param layerIdentifier The base layer to merge. * @param stopSession If it needs to stop the Live Session after merging. * @see ILayersInstance::get_last_error_type() for more error details if it returns false. */ bool(CARB_ABI* mergeLiveSessionChanges)(ILayersInstance* layersInstance, const char* layerIdentifier, bool stopSession); /** * Merge changes of the Live Session to target layer specified by targetLayerIdentifier. If base layer is not in the Live Session currently, * it will return false directly. Live Session for prim is not supported to be merged. * * @param layersInstance Layer instance. * @param layerIdentifier The base layer of the Live Session. * @param targetLayerIdentifier Target layer identifier. * @param stopSession If it's to stop Live Session after merge. * @param clearTargetLayer If it's to clear target layer before merge. * @see ILayersInstance::get_last_error_type() for more error details if it returns false. */ bool(CARB_ABI* mergeLiveSessionChangesToSpecificLayer)(ILayersInstance* layersInstance, const char* layerIdentifier, const char* targetLayerIdentifier, bool stopSession, bool clearTargetLayer); /** * Given the layer identifier of a .live layer, it's to find its corresponding session. * * @param liveLayerIdentifier The live layer of the Live Session. */ LiveSession*(CARB_ABI* getLiveSessionForLiveLayer)(ILayersInstance* layersInstance, const char* liveLayerIdentifier); /** * Gets the Live Session by url. It can only find the Live Session that belongs to one of the sublayer in the current stage. * * @param liveSessionURL The URL of the Live Session. */ LiveSession*(CARB_ABI* getLiveSessionByURL)(ILayersInstance* layersInstance, const char* liveSessionURL); /** * Gets the logged-in user name for this layer. The layer must be in the used layers of current opened stage, from Nucleus, * and not a live layer. As client library supports multiple Nucleus servers, the logged-in user for each layer may be different. * * @param layerIdentifier The base layer. */ const char*(CARB_ABI* getLoggedInUserNameForLayer)(ILayersInstance* layersInstance, const char* layerIdentifier); /** * Gets the logged-in user id for this layer. The layer must be in the used layers of current opened stage, from Nucleus, * and not a live layer. As client library supports multiple Nucleus servers, the logged-in user for each layer may be different. * * @param layerIdentifier The base layer. */ const char*(CARB_ABI* getLoggedInUserIdForLayer)(ILayersInstance* layersInstance, const char* layerIdentifier); /** * Opens stage with specified Live Session asynchronously. * * @param stageUrl The stageUrl to open. * @param sessionName The session to open. * @param stageResultFn Callback of stage open. This function will call omni::usd::UsdContext::openStage * * @return false if no session name is provided or other open issues. */ bool(CARB_ABI* openStageWithLiveSession)( ILayersInstance* layersInstance, const char* stageUrl, const char* sessionName, OnStageResultFn stageResultFn, void* userData); /** * Joins the Live Session for prim. The prim must include references or payloads. If it includes multiple references or payloads, an index * is provided to decide which reference or payload layer to join the Live Session. * @param layersInstance Layer instance. * @param session The Live Session to join. It must be the Live Session of the references or payloads of the specified prim. * @param primPath The prim to join the Live Session. * @see ILayersInstance::get_last_error_type() for more error details if it returns false. */ bool(CARB_ABI* joinLiveSessionForPrim)(ILayersInstance* layersInstance, LiveSession* session, const char* primPath); /** * Finds the Live Session by name. It will return the first one that matches the name. * @param layerIdentifier The base layer to find the Live Session. * @param sessionName The name to search. */ LiveSession*(CARB_ABI* findLiveSessionByName)(ILayersInstance* layersInstance, const char* layerIdentifier, const char* sessionName); /** * Whether the prim is in any Live Sessions or not. * * @param primPath The prim path to check. * @param layerIdentifier The optional layer identifier to check. If it's not specified, it will return true if it's in any Live Sessions. * Otherwise, it will only return true if the prim is in the Live Session specified by the layer identifier. * @param fromReferenceOrPayloadOnly If it's true, it will check only references and payloads to see if the same * Live Session is enabled already in any references or payloads. Otherwise, it checkes both the prim specificed by primPath and its references * and payloads. This is normally used to check if the Live Session can be stopped as prim that is in a Live Session may not own the Live Session, * which is owned by its references or payloads, so it cannot stop the Live Session with the prim. */ bool(CARB_ABI* isPrimInLiveSession)(ILayersInstance* layersInstance, const char* primPath, const char* layerIdentifier, bool fromReferenceOrPayloadOnly); /** * Whether the layer is in the Live Session that's bound to any prims. */ bool(CARB_ABI* isLayerInPrimLiveSession)(ILayersInstance* layersInstance, const char* layerIdentifier); /** * Returns all prim paths that this Live Session is currently bound to, or nullptr if no prims are in this Live Session. * * @param session The session handle. */ carb::dictionary::Item*(CARB_ABI* getLiveSessionPrimPaths)(ILayersInstance* layersInstance, LiveSession* session); /** * Stops all the Live Sessions that the prim joins to, or the specified Live Session if layerIdentifier is provided. */ void(CARB_ABI* stopLiveSessionForPrim)(ILayersInstance* layersInstance, const char* primPath, const char* layerIdentifier); /** * It provides option to cancel joining to a Live Session if layer is in joining state. * This function only works when it's called during handling eLiveSessionJoining event as all interfaces * to join a Live Session is synchronous currently. * TODO: Supports asynchronous interface to join a session to avoid blocking main thread. */ LiveSession*(CARB_ABI* tryCancellingLiveSessionJoin)(ILayersInstance* layersInstance, const char* layerIdentifier); /** * Nanoseconds since the Unix epoch (1 January 1970) of the last time the file was modified. This time is not real time * in the filesystem. Joining a session will modify its modified time also. * * @param session The Live Session instance. */ uint64_t (CARB_ABI* getLiveSessionLastModifiedTimeNs)(ILayersInstance* layerInstance, LiveSession* session); }; } } } }
17,655
C
50.028902
157
0.721609
omniverse-code/kit/include/omni/kit/commands/ICommand.h
// Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved. // // NVIDIA CORPORATION and its licensors retain all intellectual property // and proprietary rights in and to this software, related documentation // and any modifications thereto. Any use, reproduction, disclosure or // distribution of this software and related documentation without an express // license agreement from NVIDIA CORPORATION is strictly prohibited. // #pragma once #include <carb/IObject.h> #include <carb/dictionary/IDictionary.h> namespace omni { namespace kit { namespace commands { /** * Pure virtual command interface. */ class ICommand : public carb::IObject { public: /** * Factory function prototype to create a new command instance. * * @param extensionId The id of the source extension registering the command. * @param commandName The command name, unique to the extension registering it. * @param kwargs Arbitrary keyword arguments the command will be executed with. * * @return The command object that was created. */ using CreateFunctionType = carb::ObjectPtr<ICommand> (*)(const char* /*extensionId*/, const char* /*commandName*/, const carb::dictionary::Item* /*kwargs*/); /** * Function prototype to populate keyword arguments expected by a command along with default values. * * @param defaultKwargs Dictionary item to fill with all keyword arguments that have default values. * @param optionalKwargs Dictionary item to fill with all other keyword arguments that are optional. * @param requiredKwargs Dictionary item to fill with all other keyword arguments that are required. */ using PopulateKeywordArgsFunctionType = void (*)(carb::dictionary::Item* /*defaultKwargs*/, carb::dictionary::Item* /*optionalKwargs*/, carb::dictionary::Item* /*requiredKwargs*/); /** * Get the id of the source extension which registered this command. * * @return Id of the source extension which registered this command. */ virtual const char* getExtensionId() const = 0; /** * Get the name of this command, unique to the extension that registered it. * * @return Name of this command, unique to the extension that registered it. */ virtual const char* getName() const = 0; /** * Called when this command object is being executed, * either originally or in response to a redo request. */ virtual void doCommand() = 0; /** * Called when this command object is being undone. */ virtual void undoCommand() = 0; }; using ICommandPtr = carb::ObjectPtr<ICommand>; } } }
2,870
C
34.012195
104
0.64878
omniverse-code/kit/include/omni/kit/commands/ICommandBridge.h
// Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved. // // NVIDIA CORPORATION and its licensors retain all intellectual property // and proprietary rights in and to this software, related documentation // and any modifications thereto. Any use, reproduction, disclosure or // distribution of this software and related documentation without an express // license agreement from NVIDIA CORPORATION is strictly prohibited. // #pragma once #include <omni/kit/commands/ICommand.h> #include <carb/dictionary/IDictionary.h> #include <carb/Interface.h> namespace omni { namespace kit { namespace commands { /** * Defines the interface for the CommandBridge. Commands were originally * written in (and only available to use from) Python, so this interface * acts as a bridge allowing them to be registered and executed from C++ */ class ICommandBridge { public: CARB_PLUGIN_INTERFACE("omni::kit::commands::ICommandBridge", 1, 0); using RegisterFunctionType = void (*)(const char*, const char*, const carb::dictionary::Item*, const carb::dictionary::Item*, const carb::dictionary::Item*); using DeregisterFunctionType = void (*)(const char*, const char*); using ExecuteFunctionType = bool (*)(const char*, const char*, const carb::dictionary::Item*); using UndoFunctionType = bool (*)(); using RedoFunctionType = bool (*)(); using RepeatFunctionType = bool (*)(); using VoidFunctionType = void (*)(); /** * Enable the command bridge so that new command types can be registered and deregistered from C++, * and so that existing command types can be executed in Python (where commands are held) from C++. * * @param registerFunction Function responsible for registering new C++ command types with Python. * @param deregisterFunction Function responsible for deregistering C++ command types from Python. * @param executeFunction Function responsible for executing existing commands in Python from C++. * @param undoFunction Function responsible for calling undo on past commands in Python from C++. * @param redoFunction Function responsible for calling redo on past commands in Python from C++. * @param repeatFunction Function responsible for calling repeat on past commands in Python from C++. * @param beginUndoGroupFunction Function responsible for opening an undo group in Python from C++. * @param endUndoGroupFunction Function responsible for closing an undo group in Python from C++. * @param beginUndoDisabledFunction Function responsible for disabling undo in Python from C++. * @param endUndoDisabledFunction Function responsible for re-enabling undo in Python from C++. */ virtual void enableBridge(RegisterFunctionType registerFunction, DeregisterFunctionType deregisterFunction, ExecuteFunctionType executeFunction, UndoFunctionType undoFunction, RedoFunctionType redoFunction, RepeatFunctionType repeatFunction, VoidFunctionType beginUndoGroupFunction, VoidFunctionType endUndoGroupFunction, VoidFunctionType beginUndoDisabledFunction, VoidFunctionType endUndoDisabledFunction) = 0; /** * Disable the command bridge so that new command types can no longer be registered and deregistered from C++, * and so that existing command types can no longer be executed in Python (where commands are held) from C++. * Calling this will also cause any remaining command types previously registered in C++ to be deregistered. */ virtual void disableBridge() = 0; /** * Bridge function to call from C++ to register a C++ command type with Python. * * @param extensionId The id of the source extension registering the command. * @param commandName The command name, unique to the registering extension. * @param factory Factory function used to create instances of the command. * @param populateKeywordArgs Function called to populate the keyword args. */ virtual void registerCommand(const char* extensionId, const char* commandName, ICommand::CreateFunctionType factory, ICommand::PopulateKeywordArgsFunctionType populateKeywordArgs) = 0; /** * Bridge function to call from C++ to deregister a C++ command type from Python. * * @param extensionId The id of the source extension that registered the command. * @param commandName Command name, unique to the extension that registered it. */ virtual void deregisterCommand(const char* extensionId, const char* commandName) = 0; /** * Deregister all C++ command types that were registered by the specified extension. * * @param extensionId The id of the source extension that registered the commands. */ virtual void deregisterAllCommandsForExtension(const char* extensionId) = 0; /** * Bridge function to call from C++ to execute any existing command type in Python. * * @param commandName Command name, unique to the extension that registered it. * @param kwargs Arbitrary keyword arguments the command will be executed with. * * @return True if the command object was created and executed, false otherwise. */ virtual bool executeCommand(const char* commandName, const carb::dictionary::Item* kwargs = nullptr) const = 0; /** * Bridge function to call from C++ to execute any existing command type in Python. * * @param extensionId The id of the source extension that registered the command. * @param commandName Command name, unique to the extension that registered it. * @param kwargs Arbitrary keyword arguments the command will be executed with. * * @return True if the command object was created and executed, false otherwise. */ virtual bool executeCommand(const char* extensionId, const char* commandName, const carb::dictionary::Item* kwargs = nullptr) const = 0; /** * Bridge function to call from Python to create a new instance of a C++ command. * * @param extensionId The id of the source extension that registered the command. * @param commandName The command name, unique to the extension that registered it. * @param kwargs Arbitrary keyword arguments that the command will be executed with. * * @return A command object if it was created, or an empty ObjectPtr otherwise. */ virtual carb::ObjectPtr<ICommand> createCommandObject(const char* extensionId, const char* commandName, const carb::dictionary::Item* kwargs = nullptr) const = 0; /** * Bridge function to call from C++ to undo the last command that was executed. * * @return True if the last command was successfully undone, false otherwise. */ virtual bool undoCommand() const = 0; /** * Bridge function to call from C++ to redo the last command that was undone. * * @return True if the last command was successfully redone, false otherwise. */ virtual bool redoCommand() const = 0; /** * Bridge function to call from C++ to repeat the last command that was executed or redone. * * @return True if the last command was successfully repeated, false otherwise. */ virtual bool repeatCommand() const = 0; /** * Bridge function to call from C++ to begin a new group of commands to be undone together. */ virtual void beginUndoGroup() const = 0; /** * Bridge function to call from C++ to end a new group of commands to be undone together. */ virtual void endUndoGroup() const = 0; /** * Bridge function to call from C++ to begin disabling undo for subsequent commands. */ virtual void beginUndoDisabled() const = 0; /** * Bridge function to call from C++ to end disabling undo for subsequent commands. */ virtual void endUndoDisabled() const = 0; /** * RAII class used to begin and end a new undo group within a specific scope. */ class ScopedUndoGroup { public: ScopedUndoGroup() { if (ICommandBridge* commandBridge = carb::getCachedInterface<ICommandBridge>()) { commandBridge->beginUndoGroup(); } } ~ScopedUndoGroup() { if (ICommandBridge* commandBridge = carb::getCachedInterface<ICommandBridge>()) { commandBridge->endUndoGroup(); } } }; /** * RAII class used to begin and end disabling undo within a specific scope. */ class ScopedUndoDisabled { public: ScopedUndoDisabled() { if (ICommandBridge* commandBridge = carb::getCachedInterface<ICommandBridge>()) { commandBridge->beginUndoDisabled(); } } ~ScopedUndoDisabled() { if (ICommandBridge* commandBridge = carb::getCachedInterface<ICommandBridge>()) { commandBridge->endUndoDisabled(); } } }; }; } } }
9,730
C
40.763948
116
0.643063
omniverse-code/kit/include/omni/kit/commands/Command.h
// Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved. // // NVIDIA CORPORATION and its licensors retain all intellectual property // and proprietary rights in and to this software, related documentation // and any modifications thereto. Any use, reproduction, disclosure or // distribution of this software and related documentation without an express // license agreement from NVIDIA CORPORATION is strictly prohibited. // #pragma once #include <omni/kit/commands/ICommand.h> #include <carb/ObjectUtils.h> #include <omni/String.h> namespace omni { namespace kit { namespace commands { /** * Abstract command base class providing the core functionaly common to all commands. */ class Command : public ICommand { public: /** * Constructor. * * @param extensionId The id of the source extension registering the command. * @param commandName The command name, unique to the registering extension. */ Command(const char* extensionId, const char* commandName) : m_extensionId(extensionId ? extensionId : ""), m_commandName(commandName ? commandName : "") { } /** * Destructor. */ ~Command() override = default; /** * @ref ICommand::getExtensionId */ const char* getExtensionId() const override { return m_extensionId.c_str(); } /** * @ref ICommand::getName */ const char* getName() const override { return m_commandName.c_str(); } protected: omni::string m_extensionId; //!< The id of the source extension that registered the command. omni::string m_commandName; //!< Name of the command, unique to the registering extension. private: CARB_IOBJECT_IMPL }; } } }
1,728
C
22.684931
102
0.680556
omniverse-code/kit/include/omni/str/IReadOnlyCString.gen.h
// Copyright (c) 2020-2022, NVIDIA CORPORATION. All rights reserved. // // NVIDIA CORPORATION and its licensors retain all intellectual property // and proprietary rights in and to this software, related documentation // and any modifications thereto. Any use, reproduction, disclosure or // distribution of this software and related documentation without an express // license agreement from NVIDIA CORPORATION is strictly prohibited. // // --------- Warning: This is a build system generated file. ---------- // //! @file //! //! @brief This file was generated by <i>omni.bind</i>. #include <omni/core/OmniAttr.h> #include <omni/core/Interface.h> #include <omni/core/ResultError.h> #include <functional> #include <utility> #include <type_traits> #ifndef OMNI_BIND_INCLUDE_INTERFACE_IMPL //! Reference counted read-only C-style (i.e. null-terminated) string. template <> class omni::core::Generated<omni::str::IReadOnlyCString_abi> : public omni::str::IReadOnlyCString_abi { public: OMNI_PLUGIN_INTERFACE("omni::str::IReadOnlyCString") //! Returns a pointer to the null-terminated string. //! //! The returned pointer is valid for the lifetime of this object. //! //! This method is thread safe. const char* getBuffer() noexcept; }; #endif #ifndef OMNI_BIND_INCLUDE_INTERFACE_DECL inline const char* omni::core::Generated<omni::str::IReadOnlyCString_abi>::getBuffer() noexcept { return getBuffer_abi(); } #endif #undef OMNI_BIND_INCLUDE_INTERFACE_DECL #undef OMNI_BIND_INCLUDE_INTERFACE_IMPL
1,537
C
26.963636
101
0.72674
omniverse-code/kit/include/omni/str/IReadOnlyCString.h
// Copyright (c) 2020-2023, 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. // //! @file //! @brief Interface to manage access to a read-only string. #pragma once #include "../core/IObject.h" #include "../../carb/Defines.h" namespace omni { //! Namespace for various string helper classes, interfaces, and functions. namespace str { //! Forward declaration of the IReadOnlyCString. OMNI_DECLARE_INTERFACE(IReadOnlyCString); //! Reference counted read-only C-style (i.e. null-terminated) string. class IReadOnlyCString_abi : public omni::core::Inherits<omni::core::IObject, OMNI_TYPE_ID("omni.str.IReadOnlyCString")> { protected: //! Returns a pointer to the null-terminated string. //! //! The returned pointer is valid for the lifetime of this object. //! //! This method is thread safe. virtual OMNI_ATTR("c_str, not_null") const char* getBuffer_abi() noexcept = 0; }; } // namespace str } // namespace omni #include "IReadOnlyCString.gen.h" namespace omni { namespace str { //! Concrete implementation of the IReadOnlyCString interface. class ReadOnlyCString : public omni::core::Implements<omni::str::IReadOnlyCString> { public: //! Creates a read-only string. The given string is copied and must not be nullptr. static omni::core::ObjectPtr<IReadOnlyCString> create(const char* str) { OMNI_ASSERT(str, "ReadOnlyCString: the given string must not be nullptr"); return { new ReadOnlyCString{ str }, omni::core::kSteal }; } private: ReadOnlyCString(const char* str) : m_buffer{ str } { } const char* getBuffer_abi() noexcept override { return m_buffer.c_str(); } CARB_PREVENT_COPY_AND_MOVE(ReadOnlyCString); std::string m_buffer; }; } // namespace str } // namespace omni
2,144
C
27.6
120
0.712687
omniverse-code/kit/include/omni/str/Wildcard.h
// Copyright (c) 2020-2021, 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. // /** @file * @brief Helper functions to handle matching wildcard patterns. */ #pragma once #include <stddef.h> #include <cstdint> namespace omni { /** Namespace for various string helper functions. */ namespace str { /** Checks if a string matches a wildcard pattern. * * @param[in] str The string to attempt to match to the pattern @p pattern. * This may not be `nullptr`. * @param[in] pattern The wildcard pattern to match against. This may not be * `nullptr`. The wildcard pattern may contain '?' to match * exactly one character (any character), or '*' to match * zero or more characters. * @returns `true` if the string @p str matches the pattern. Returns `false` if * the pattern does not match the pattern. */ inline bool matchWildcard(const char* str, const char* pattern) { const char* star = nullptr; const char* s0 = str; const char* s1 = s0; const char* p = pattern; while (*s0) { // Advance both pointers when both characters match or '?' found in pattern if ((*p == '?') || (*p == *s0)) { s0++; p++; continue; } // * found in pattern, save index of *, advance a pattern pointer if (*p == '*') { star = p++; s1 = s0; continue; } // Current characters didn't match, consume character in string and rewind to star pointer in the pattern if (star) { p = star + 1; s0 = ++s1; continue; } // Characters do not match and current pattern pointer is not star return false; } // Skip remaining stars in pattern while (*p == '*') { p++; } return !*p; // Was whole pattern matched? } /** Attempts to match a string to a set of wildcard patterns. * * @param[in] str The string to attempt to match to the pattern @p pattern. * This may not be `nullptr`. * @param[in] patterns An array of patterns to attempt to match the string @p str * to. Each pattern in this array has the same format as the * pattern in @ref matchWildcard(). This may not be `nullptr`. * @param[in] patternsCount The total number of wildcard patterns in @p patterns. * @returns The pattern that the test string @p str matched to if successful. Returns * `nullptr` if the test string did not match any of the patterns. */ inline const char* matchWildcards(const char* str, const char* const* patterns, size_t patternsCount) { for (size_t i = 0; i < patternsCount; ++i) { if (matchWildcard(str, patterns[i])) { return patterns[i]; } } return nullptr; } /** Tests whether a string is potentially a wildcard pattern. * * @param[in] pattern The pattern to test as a wildcard. This will be considered a wildcard * if it contains the special wildcard characters '*' or '?'. This may not * be nullptr. * @returns `true` if the pattern is likely a wildcard string. Returns `false` if the pattern * does not contain any of the special wildcard characters. */ inline bool isWildcardPattern(const char* pattern) { for (const char* p = pattern; p[0] != 0; p++) { if (*p == '*' || *p == '?') return true; } return false; } } // namespace str } // namespace omni
4,056
C
31.717742
113
0.589744
usnuni/isaac-sim/README.md
# isaac-sim ## 코드 실행 - 아나콘다(python==3.7.16) 환경에서 아래 코드 실행 후 동일 터미널에서 경로 변경 및 py 파일 실행해야 정상 작동(새 터미널창으로 하면 작동 안 됨) ``` cd ~/.local/share/ov/pkg/isaac_sim-2022.2.1 source setup_conda_env.sh #cd ~/{py_file_path} cd ~/isaac_sample ``` ## 환경 설정 ### 1 NVIDIA-SMI, Driver Version 535.54.03 / CUDA Version: 12.2 #### 1.1 Nvidia driver (version: 535-server) ``` sudo add-apt-repository ppa:graphics-drivers/ppa sudo apt update sudo apt-get install nvidia-driver-535-server sudo reboot nvidia-smi ``` #### 1.2 CUDA toolkit - E: Unable to locate package nvidia-docker2 (아래 코드로 해결) ``` wget https://developer.download.nvidia.com/compute/cuda/repos/ubuntu2204/x86_64/cuda-keyring_1.1-1_all.deb sudo dpkg -i cuda-keyring_1.1-1_all.deb sudo apt update sudo apt -y install cuda # install packages sudo apt install nvidia-docker2 sudo apt install nvidia-container-toolkit ``` ### 2 Anaconda python ver=3.10 <pre> <code> sudo apt install curl bzip2 -y curl --output anaconda.sh https://repo.anaconda.com/archive/Anaconda3-2023.03-0-Linux-x86_64.sh sha256sum anaconda.sh bash anaconda.sh </code> </pre> ### 3 Isaac Sim 2022.2.1 [link](https://www.nvidia.com/en-us/omniverse/download/#ov-download) - E: AppImages require FUSE to run. ``` apt install fuse libfuse2 ``` ### 4 ROS2 humble [link](https://docs.ros.org/en/humble/Installation/Ubuntu-Install-Debians.html) - have to run this code every time start ROS ``` source /opt/ros/humble/setup.bash ``` ### 5 Docker [link](https://docs.docker.com/engine/install/ubuntu) #### 5.1 Nvidia drivers for Docker ``` sudo apt install nvidia-container-toolkit ``` #### 5.2 Docker compose [link](https://docs.docker.com/compose/install/linux/#install-using-the-repository) ``` sudo apt install docker-compose-plugin # verify docker compose version > Docker Compose version v2.21.0 ``` ### 6 Moveit #### 6.1 Docker MoveIt2 설치 [link](https://moveit.picknik.ai/main/doc/how_to_guides/how_to_setup_docker_containers_in_ubuntu.html) ``` wget https://raw.githubusercontent.com/ros-planning/moveit2_tutorials/main/.docker/docker-compose.yml DOCKER_IMAGE=rolling-tutorial docker compose run --rm --name moveit2_container gpu ``` - E: Failed to initialize NVML: Driver/library version mismatch > reboot - enter the container through another terminal ``` docker exec -it moveit2_container /bin/bash ``` ##### 6.1.1 moveit tutorial [link](https://github.com/ros-planning/moveit2_tutorials) [getting started](https://moveit.picknik.ai/main/doc/tutorials/getting_started/getting_started.html) ``` source /opt/ros/humble/setup.bash # same as link ``` https://docs.omniverse.nvidia.com/isaacsim/latest/install_ros.html#isaac-sim-app-install-ros To start using the ROS2 packages built within this workspace, open a new terminal and source the workspace with the following commands: ``` source /opt/ros/foxy/setup.bash cd foxy_ws source install/local_setup.bash ``` # Errors 1. sudo apt update ``` W: https://nvidia.github.io/libnvidia-container/stable/ubuntu18.04/amd64/InRelease: Key is stored in legacy trusted.gpg keyring (/etc/apt/trusted.gpg), see the DEPRECATION section in apt-key(8) for details. ``` 2. colcon build --mixin release ``` ModuleNotFoundError: No module named 'catkin_pkg' CMake Error at /opt/ros/humble/share/ament_cmake_core/cmake/core/ament_package_xml.cmake:95 (message): execute_process(/home/ari/anaconda3/bin/python3.10 /opt/ros/humble/share/ament_cmake_core/cmake/core/package_xml_2_cmake.py /home/ari/ws_moveit/src/moveit2/moveit_common/package.xml /home/ari/ws_moveit/build/moveit_common/ament_cmake_core/package.cmake) returned error code 1 Call Stack (most recent call first): /opt/ros/humble/share/ament_cmake_core/cmake/core/ament_package_xml.cmake:49 (_ament_package_xml) /opt/ros/humble/share/ament_lint_auto/cmake/ament_lint_auto_find_test_dependencies.cmake:31 (ament_package_xml) CMakeLists.txt:8 (ament_lint_auto_find_test_dependencies) ``` ``` conda install -c auto catkin_pkg <failed ``` ``` sudo cp -r /home/ari/anaconda3/envs/isaac/lib/python2.7/site-packages/catkin_pkg /opt/ros/humble/lib/python3.10/site-packages/ < failed ``` 3. 1 package had stderr output: isaac_ros_navigation_goal > ignoreed.. 4. ros2 bridge connect error ``` unset LD_LIBRARY_PATH export FASTRTPS_DEFAULT_PROFILES_FILE=~/.ros/fastdds.xml ```
4,340
Markdown
28.732877
206
0.737097
usnuni/isaac-sim/pick-n-place/README.md
# isaac-sim-pick-place ## Environment Setup ### 1. Download Isaac Sim - Dependency check - Ubuntu - Recommanded: 20.04 / 22.04 - Tested on: 20.04 - NVIDIA Driver version - Recommanded: 525.60.11 - Minimum: 510.73.05 - Tested on: 510.108.03 / - [Download Omniverse](https://developer.nvidia.com/isaac-sim) - [Workstation Setup](https://docs.omniverse.nvidia.com/app_isaacsim/app_isaacsim/install_basic.html) - [Python Environment Installation](https://docs.omniverse.nvidia.com/app_isaacsim/app_isaacsim/install_python.html#advanced-running-with-anaconda) ### 2. Environment Setup ## 2-1. Conda Check [Python Environment Installation](https://docs.omniverse.nvidia.com/app_isaacsim/app_isaacsim/install_python.html#advanced-running-with-anaconda) - Create env create ``` conda env create -f environment.yml conda activate isaac-sim ``` - Setup environment variables so that Isaac Sim python packages are located correctly ``` source setup_conda_env.sh ``` - Install requirment pakages ``` pip install -r requirements.txt ``` ## 2-2. Docker (recommended) - Install Init file ``` wget https://raw.githubusercontent.com/gist-ailab/AILAB-isaac-sim-pick-place/main/dockers/init_script.sh zsh init_script.sh ```
1,312
Markdown
26.93617
152
0.696646
usnuni/isaac-sim/pick-n-place/dockers/extension.toml
[core] reloadable = true order = 0 [package] version = "1.5.1" category = "Simulation" title = "Isaac Sim Samples" description = "Sample extensions for Isaac Sim" authors = ["NVIDIA"] repository = "" keywords = ["isaac", "samples", "manipulation"] changelog = "docs/CHANGELOG.md" readme = "docs/README.md" preview_image = "data/preview.png" icon = "data/icon.png" writeTarget.kit = true [dependencies] "omni.kit.uiapp" = {} "omni.physx" = {} "omni.physx.vehicle" = {} "omni.isaac.dynamic_control" = {} "omni.isaac.motion_planning" = {} "omni.isaac.synthetic_utils" = {} "omni.isaac.ui" = {} "omni.isaac.core" = {} "omni.isaac.franka" = {} "omni.isaac.manipulators" = {} "omni.isaac.dofbot" = {} "omni.isaac.universal_robots" = {} "omni.isaac.motion_generation" = {} "omni.graph.action" = {} "omni.graph.nodes" = {} "omni.graph.core" = {} "omni.isaac.quadruped" = {} "omni.isaac.wheeled_robots" = {} [[python.module]] name = "omni.isaac.examples.tests" [[python.module]] name = "omni.isaac.examples.kaya_gamepad" [[python.module]] name = "omni.isaac.examples.omnigraph_keyboard" [[python.module]] name = "omni.isaac.examples.follow_target" [[python.module]] name = "omni.isaac.examples.path_planning" [[python.module]] name = "omni.isaac.examples.simple_stack" [[python.module]] name = "omni.isaac.examples.bin_filling" [[python.module]] name = "omni.isaac.examples.robo_factory" [[python.module]] name = "omni.isaac.examples.robo_party" [[python.module]] name = "omni.isaac.examples.hello_world" [[python.module]] name = "omni.isaac.examples.franka_nut_and_bolt" [[python.module]] name = "omni.isaac.examples.replay_follow_target" [[python.module]] name = "omni.isaac.examples.surface_gripper" [[python.module]] name = "omni.isaac.examples.unitree_quadruped" [[python.module]] name = "omni.isaac.examples.user_examples" [[python.module]] name = "omni.isaac.examples.ailab_examples" [[test]] timeout = 960
1,927
TOML
20.186813
49
0.693306
usnuni/isaac-sim/pick-n-place/dockers/BUILD.md
# Install Container ```bash docker login nvcr.io id : $oauthtoken pwd : Njc5dHR0b2QwZTh0dTFtNW5ydXI4Y3JtNm46MGVkM2VjODctZTk1Ni00NmNjLTkxNDEtYTdmMjNlNjllMjNj ``` # Build ```bash docker build --pull -t \ registry.ark.svc.ops.openark/library/isaac-sim:2022.2.1-ubuntu22.04_v3 \ --build-arg ISAACSIM_VERSION=2022.2.1 \ --build-arg BASE_DIST=ubuntu20.04 \ --build-arg CUDA_VERSION=11.4.2 \ --build-arg VULKAN_SDK_VERSION=1.3.224.1 \ --file Dockerfile.2022.2.1-ubuntu22.04 . ``` ```bash docker push --tls-verify=false registry.ark.svc.ops.openark/library/isaac-sim:2022.2.1-ubuntu22.04_v3 ``` # Container Usage ```bash docker pull --tls-verify=false registry.ark.svc.ops.openark/library/isaac-sim:2022.2.1-ubuntu22.04_v3 ``` ```bash podman run -it --entrypoint bash --name isaac-sim --device nvidia.com/gpu=all -e "ACCEPT_EULA=Y" --rm --network=host \ -v /tmp/.X11-unix:/tmp/.X11-unix \ -e DISPLAY \ -v /home:/home \ -v ~/docker/isaac-sim/cache/kit:/isaac-sim/kit/cache/Kit:rw \ -v ~/docker/isaac-sim/cache/ov:/root/.cache/ov:rw \ -v ~/docker/isaac-sim/cache/pip:/root/.cache/pip:rw \ -v ~/docker/isaac-sim/cache/glcache:/root/.cache/nvidia/GLCache:rw \ -v ~/docker/isaac-sim/cache/computecache:/root/.nv/ComputeCache:rw \ -v ~/docker/isaac-sim/logs:/root/.nvidia-omniverse/logs:rw \ -v ~/docker/isaac-sim/data:/root/.local/share/ov/data:rw \ -v ~/docker/isaac-sim/documents:/root/Documents:rw \ registry.ark.svc.ops.openark/library/isaac-sim:2022.2.1-ubuntu22.04_v3 ``` # In a docker container (Deprecated) ```bash alias code="code --no-sandbox --user-data-dir=/root" alias chrome="google-chrome --no-sandbox" ln -sf /usr/lib64/libcuda.so.1 /usr/lib64/libcuda.so export LD_LIBRARY_PATH=$LD_LIBRARY_PATH:/usr/lib64 ```
1,737
Markdown
29.491228
118
0.716753
usnuni/isaac-sim/pick-n-place/dockers/README.md
# Install Init file wget https://raw.githubusercontent.com/gist-ailab/AILAB-isaac-sim-pick-place/main/dockers/init_script.sh zsh init_script.sh # VScode
155
Markdown
21.285711
104
0.787097
usnuni/isaac-sim/pick-n-place/dockers/ailab_examples/ailab_extension.py
# Copyright (c) 2020-2021, 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 omni.isaac.examples.ailab_script import AILabExtension from omni.isaac.examples.ailab_examples import AILab class AILabExtension(AILabExtension): def on_startup(self, ext_id: str): super().on_startup(ext_id) super().start_extension( menu_name="", submenu_name="", name="AILab extension", title="AILab extension Example", doc_link="https://docs.omniverse.nvidia.com/app_isaacsim/app_isaacsim/tutorial_core_hello_world.html", overview="This Example introduces the user on how to do cool stuff with Isaac Sim through scripting in asynchronous mode.", file_path=os.path.abspath(__file__), sample=AILab(), ) return
1,191
Python
41.571427
135
0.702771
usnuni/isaac-sim/pick-n-place/dockers/ailab_examples/__init__.py
# Copyright (c) 2021, 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 omni.isaac.examples.ailab_examples.ailab import AILab from omni.isaac.examples.ailab_examples.ailab_extension import AILabExtension
566
Python
46.249996
77
0.819788
usnuni/isaac-sim/pick-n-place/dockers/ailab_examples/ailab.py
# Copyright (c) 2020-2021, 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 omni.isaac.examples.base_sample import BaseSample # Note: checkout the required tutorials at https://docs.omniverse.nvidia.com/app_isaacsim/app_isaacsim/overview.html class AILab(BaseSample): def __init__(self) -> None: super().__init__() return def setup_scene(self): world = self.get_world() world.scene.add_default_ground_plane() return async def setup_post_load(self): return async def setup_pre_reset(self): return async def setup_post_reset(self): return def world_cleanup(self): return
1,035
Python
27.777777
116
0.707246
usnuni/isaac-sim/pick-n-place/dockers/ailab_script/ailab_extension_old.py
# ailabktw # from abc import abstractmethod import omni.ext import omni.ui as ui from omni.kit.menu.utils import add_menu_items, remove_menu_items, MenuItemDescription import weakref from omni.isaac.ui.ui_utils import setup_ui_headers, get_style, btn_builder, scrolling_frame_builder import asyncio from omni.isaac.examples.ailab_script import AILab from omni.isaac.core import World import os # ---- # class AILabExtension(omni.ext.IExt): def __init__(self): super().__init__() self._ext_id= 'omni.isaac.examples-1.5.1' self.use_custom_updated = False pass def on_startup(self, ext_id: str='omni.isaac.examples-1.5.1'): self._menu_items = None self._buttons = None self._ext_id = ext_id self._sample = None self._extra_frames = [] return def on_custom_startup(self, ext_id: str): super().on_startup(ext_id) super().start_extension( menu_name="", submenu_name="", name="AILab extension", title="AILab extension Example", doc_link="https://docs.omniverse.nvidia.com/app_isaacsim/app_isaacsim/tutorial_core_hello_world.html", overview="This Example introduces the user on how to do cool stuff with Isaac Sim through scripting in asynchronous mode.", file_path=os.path.abspath(__file__), sample=AILab(), ) return def start_extension( self, menu_name: str, submenu_name: str, name: str, title: str, doc_link: str, overview: str, file_path: str, sample=None, number_of_extra_frames=1, window_width=420, keep_window_open=False, ): if sample is None: self._sample = AILab() else: self._sample = sample menu_items = [MenuItemDescription(name=name, onclick_fn=lambda a=weakref.proxy(self): a._menu_callback())] if menu_name == "" or menu_name is None: self._menu_items = menu_items elif submenu_name == "" or submenu_name is None: self._menu_items = [MenuItemDescription(name=menu_name, sub_menu=menu_items)] else: self._menu_items = [ MenuItemDescription( name=menu_name, sub_menu=[MenuItemDescription(name=submenu_name, sub_menu=menu_items)] ) ] add_menu_items(self._menu_items, "Isaac Examples") self._buttons = dict() self._build_ui( name=name, title=title, doc_link=doc_link, overview=overview, file_path=file_path, number_of_extra_frames=number_of_extra_frames, window_width=window_width, keep_window_open=keep_window_open, ) return @property def sample(self): return self._sample def get_frame(self, index): if index >= len(self._extra_frames): raise Exception("there were {} extra frames created only".format(len(self._extra_frames))) return self._extra_frames[index] def get_world(self): return World.instance() def get_buttons(self): return self._buttons def _build_ui( self, name, title, doc_link, overview, file_path, # number_of_extra_frames, window_width, keep_window_open, number_of_extra_frames=1, window_width=420, keep_window_open=False, # use_custom_update=False, **args ): self._window = omni.ui.Window( name, width=window_width, height=0, visible=keep_window_open, dockPreference=ui.DockPreference.LEFT_BOTTOM ) with self._window.frame: with ui.VStack(spacing=5, height=0): setup_ui_headers(self._ext_id, file_path, title, doc_link, overview) self._controls_frame = ui.CollapsableFrame( title="Object Picking", width=ui.Fraction(1), height=0, collapsed=False, style=get_style(), horizontal_scrollbar_policy=ui.ScrollBarPolicy.SCROLLBAR_AS_NEEDED, vertical_scrollbar_policy=ui.ScrollBarPolicy.SCROLLBAR_ALWAYS_ON, ) with ui.VStack(style=get_style(), spacing=5, height=0): for i in range(number_of_extra_frames): self._extra_frames.append( ui.CollapsableFrame( title="", width=ui.Fraction(0.33), height=0, visible=False, collapsed=False, style=get_style(), horizontal_scrollbar_policy=ui.ScrollBarPolicy.SCROLLBAR_AS_NEEDED, vertical_scrollbar_policy=ui.ScrollBarPolicy.SCROLLBAR_ALWAYS_ON, ) ) with self._controls_frame: # = ++ if use_custom_update: with ui.VStack(style=get_style(), spacing=5, height=0): dict = { "label": "Check Objects", "type": "button", "text": "Check", "tooltip": "Check object to pick", "on_clicked_fn": self._on_check, } self._buttons["Check Objects"] = btn_builder(**dict) self._buttons["Check Objects"].enabled = True dict = { "label": "Reset", "type": "button", "text": "Reset", "tooltip": "Reset robot and environment", "on_clicked_fn": self._on_reset, } self._buttons["Reset"] = btn_builder(**dict) self._buttons["Reset"].enabled = True dict = { "label": "Object No.0", "type": "button", "text": "000_unkown", "tooltip": "Pick object and move", "on_clicked_fn": self._on_selected_button, } self._buttons["Object No.0"] = btn_builder(**dict) self._buttons["Object No.0"].enabled = True dict = { "label": "Object No.1", "type": "button", "text": "001_unkown", "tooltip": "Pick object and move", "on_clicked_fn": self._on_selected_button, } self._buttons["Object No.1"] = btn_builder(**dict) self._buttons["Object No.1"].enabled = True dict = { "label": "Object No.2", "type": "button", "text": "002_unkown", "tooltip": "Pick object and move", "on_clicked_fn": self._on_selected_button, } self._buttons["Object No.2"] = btn_builder(**dict) self._buttons["Object No.2"].enabled = True else: with ui.VStack(style=get_style(), spacing=5, height=0): dict = { "label": "Check Objects", "type": "button", "text": "Check", "tooltip": "Check object to pick", "on_clicked_fn": self._on_check, } self._buttons["Check Objects"] = btn_builder(**dict) self._buttons["Check Objects"].enabled = True # dict = { # "label": "Pick Object", # "type": "button", # "text": "Pick", # "tooltip": "Pick object and move", # "on_clicked_fn": self._on_load_world, # } # self._buttons["Pick Object"] = btn_builder(**dict) # self._buttons["Pick Object"].enabled = False dict = { "label": "Reset", "type": "button", "text": "Reset", "tooltip": "Reset robot and environment", "on_clicked_fn": self._on_reset, } self._buttons["Reset"] = btn_builder(**dict) self._buttons["Reset"].enabled = False dict = { "label": "Object No.0", "type": "button", "text": "000_unkown", "tooltip": "Pick object and move", "on_clicked_fn": self._on_selected_button, } self._buttons["Object No.0"] = btn_builder(**dict) self._buttons["Object No.0"].enabled = False dict = { "label": "Object No.1", "type": "button", "text": "001_unkown", "tooltip": "Pick object and move", "on_clicked_fn": self._on_selected_button, } self._buttons["Object No.1"] = btn_builder(**dict) self._buttons["Object No.1"].enabled = False dict = { "label": "Object No.2", "type": "button", "text": "002_unkown", "tooltip": "Pick object and move", "on_clicked_fn": self._on_selected_button, } self._buttons["Object No.2"] = btn_builder(**dict) self._buttons["Object No.2"].enabled = False return def _set_button_tooltip(self, button_name, tool_tip): self._buttons[button_name].set_tooltip(tool_tip) return def _on_load_world(self): async def _on_load_world_async(): await self._sample.load_world_async() await omni.kit.app.get_app().next_update_async() self._sample._world.add_stage_callback("stage_event_1", self.on_stage_event) self._enable_all_buttons(True) self._buttons["Load World"].enabled = False self.post_load_button_event() self._sample._world.add_timeline_callback("stop_reset_event", self._reset_on_stop_event) asyncio.ensure_future(_on_load_world_async()) return def _on_reset(self): async def _on_reset_async(): await self._sample.reset_async() await omni.kit.app.get_app().next_update_async() self.post_reset_button_event() asyncio.ensure_future(_on_reset_async()) return # ++ def _on_check(self): async def _on_check(): # await self._sample.check_async() # await omni.kit.app.get_app().next_update_async() self._enable_all_buttons(True) self._buttons["Check Objects"].enabled = False self.use_custom_updated = False self.post_reset_button_event() asyncio.ensure_future(_on_check()) return def _on_selected_button(self): async def _on_selected_button(): # await self._sample.selected_button_async() # await omni.kit.app.get_app().next_update_async() self._enable_all_buttons(False) self._buttons["Check Objects"].enabled = True self.use_custom_updated = True self.post_reset_button_event() asyncio.ensure_future(_on_selected_button()) return # def _on_check(self): # async def _on_check(): # await self._sample.check_async() # await omni.kit.app.get_app().next_update_async() # self.post_reset_button_event() # asyncio.ensure_future(_on_check()) # return @abstractmethod def post_reset_button_event(self): return @abstractmethod def post_load_button_event(self): return @abstractmethod def post_clear_button_event(self): return def _enable_all_buttons(self, flag): for btn_name, btn in self._buttons.items(): if isinstance(btn, omni.ui._ui.Button): btn.enabled = flag return def _menu_callback(self): self._window.visible = not self._window.visible return def _on_window(self, status): # if status: return def on_shutdown(self): self._extra_frames = [] if self._sample._world is not None: self._sample._world_cleanup() if self._menu_items is not None: self._sample_window_cleanup() if self._buttons is not None: self._buttons["Load World"].enabled = True self._enable_all_buttons(False) self.shutdown_cleanup() return def shutdown_cleanup(self): return def _sample_window_cleanup(self): remove_menu_items(self._menu_items, "Isaac Examples") self._window = None self._menu_items = None self._buttons = None return def on_stage_event(self, event): if event.type == int(omni.usd.StageEventType.CLOSED): if World.instance() is not None: self.sample._world_cleanup() self.sample._world.clear_instance() if hasattr(self, "_buttons"): if self._buttons is not None: self._enable_all_buttons(False) self._buttons["Load World"].enabled = True return def _reset_on_stop_event(self, e): if e.type == int(omni.timeline.TimelineEventType.STOP): self._buttons["Load World"].enabled = False self._buttons["Reset"].enabled = True self.post_clear_button_event() return
15,356
Python
37.878481
135
0.456108
usnuni/isaac-sim/pick-n-place/dockers/ailab_script/ailab_extension.py
# ailabktw # from abc import abstractmethod import omni.ext import omni.ui as ui from omni.kit.menu.utils import add_menu_items, remove_menu_items, MenuItemDescription import weakref from omni.isaac.ui.ui_utils import setup_ui_headers, get_style, btn_builder, scrolling_frame_builder import asyncio from omni.isaac.examples.ailab_script import AILab from omni.isaac.core import World import os # ---- # class AILabExtension(omni.ext.IExt): def __init__(self): super().__init__() self._ext_id= 'omni.isaac.examples-1.5.1' self.use_custom_updated = False self.current_target = None pass def on_startup(self, ext_id: str='omni.isaac.examples-1.5.1'): self._menu_items = None self._buttons = None self._ext_id = ext_id self._sample = None self._extra_frames = [] return def on_custom_startup(self, ext_id: str): super().on_startup(ext_id) super().start_extension( menu_name="", submenu_name="", name="AILab extension", title="AILab extension Example", doc_link="https://docs.omniverse.nvidia.com/app_isaacsim/app_isaacsim/tutorial_core_hello_world.html", overview="This Example introduces the user on how to do cool stuff with Isaac Sim through scripting in asynchronous mode.", file_path=os.path.abspath(__file__), sample=AILab(), ) return def start_extension( self, menu_name: str, submenu_name: str, name: str, title: str, doc_link: str, overview: str, file_path: str, sample=None, number_of_extra_frames=1, window_width=420, keep_window_open=False, ): if sample is None: self._sample = AILab() else: self._sample = sample menu_items = [MenuItemDescription(name=name, onclick_fn=lambda a=weakref.proxy(self): a._menu_callback())] if menu_name == "" or menu_name is None: self._menu_items = menu_items elif submenu_name == "" or submenu_name is None: self._menu_items = [MenuItemDescription(name=menu_name, sub_menu=menu_items)] else: self._menu_items = [ MenuItemDescription( name=menu_name, sub_menu=[MenuItemDescription(name=submenu_name, sub_menu=menu_items)] ) ] add_menu_items(self._menu_items, "Isaac Examples") self._buttons = dict() self._build_ui( name=name, title=title, doc_link=doc_link, overview=overview, file_path=file_path, number_of_extra_frames=number_of_extra_frames, window_width=window_width, keep_window_open=keep_window_open, ) return @property def sample(self): return self._sample def get_frame(self, index): if index >= len(self._extra_frames): raise Exception("there were {} extra frames created only".format(len(self._extra_frames))) return self._extra_frames[index] def get_world(self): return World.instance() def get_buttons(self): return self._buttons def _build_ui( self, name, title, doc_link, overview, file_path, # number_of_extra_frames, window_width, keep_window_open, number_of_extra_frames=1, window_width=420, keep_window_open=False, # use_custom_update=False, **args ): self._window = omni.ui.Window( name, width=window_width, height=0, visible=keep_window_open, dockPreference=ui.DockPreference.LEFT_BOTTOM ) with self._window.frame: with ui.VStack(spacing=5, height=0): setup_ui_headers(self._ext_id, file_path, title, doc_link, overview) self._controls_frame = ui.CollapsableFrame( title="Object Picking", width=ui.Fraction(1), height=0, collapsed=False, style=get_style(), horizontal_scrollbar_policy=ui.ScrollBarPolicy.SCROLLBAR_AS_NEEDED, vertical_scrollbar_policy=ui.ScrollBarPolicy.SCROLLBAR_ALWAYS_ON, ) with ui.VStack(style=get_style(), spacing=5, height=0): for i in range(number_of_extra_frames): self._extra_frames.append( ui.CollapsableFrame( title="", width=ui.Fraction(0.33), height=0, visible=False, collapsed=False, style=get_style(), horizontal_scrollbar_policy=ui.ScrollBarPolicy.SCROLLBAR_AS_NEEDED, vertical_scrollbar_policy=ui.ScrollBarPolicy.SCROLLBAR_ALWAYS_ON, ) ) with self._controls_frame: # = ++ # if use_custom_update: with ui.VStack(style=get_style(), spacing=5, height=0): dict = { "label": "Check Objects", "type": "button", "text": "Check", "tooltip": "Check object to pick", "on_clicked_fn": self._on_check, } self._buttons["Check Objects"] = btn_builder(**dict) self._buttons["Check Objects"].enabled = True dict = { "label": "Reset", "type": "button", "text": "Reset", "tooltip": "Reset robot and environment", "on_clicked_fn": self._on_reset, } self._buttons["Reset"] = btn_builder(**dict) self._buttons["Reset"].enabled = False dict = { "label": "Object No.0", "type": "button", "text": "000_unkown", "tooltip": "Pick object and move", "on_clicked_fn": self._on_button_00, } self._buttons["Object No.0"] = btn_builder(**dict) self._buttons["Object No.0"].enabled = False dict = { "label": "Object No.1", "type": "button", "text": "001_unkown", "tooltip": "Pick object and move", "on_clicked_fn": self._on_button_01, } self._buttons["Object No.1"] = btn_builder(**dict) self._buttons["Object No.1"].enabled = False dict = { "label": "Object No.2", "type": "button", "text": "002_unkown", "tooltip": "Pick object and move", "on_clicked_fn": self._on_button_02, } self._buttons["Object No.2"] = btn_builder(**dict) self._buttons["Object No.2"].enabled = False # # else: # with ui.VStack(style=get_style(), spacing=5, height=0): # dict = { # "label": "Check Objects", # "type": "button", # "text": "Check", # "tooltip": "Check object to pick", # "on_clicked_fn": self._on_check, # } # self._buttons["Check Objects"] = btn_builder(**dict) # self._buttons["Check Objects"].enabled = True # # dict = { # # "label": "Pick Object", # # "type": "button", # # "text": "Pick", # # "tooltip": "Pick object and move", # # "on_clicked_fn": self._on_load_world, # # } # # self._buttons["Pick Object"] = btn_builder(**dict) # # self._buttons["Pick Object"].enabled = False # dict = { # "label": "Reset", # "type": "button", # "text": "Reset", # "tooltip": "Reset robot and environment", # "on_clicked_fn": self._on_reset, # } # self._buttons["Reset"] = btn_builder(**dict) # self._buttons["Reset"].enabled = False # dict = { # "label": "Object No.0", # "type": "button", # "text": "000_unkown", # "tooltip": "Pick object and move", # "on_clicked_fn": self._on_selected_button, # } # self._buttons["Object No.0"] = btn_builder(**dict) # self._buttons["Object No.0"].enabled = False # dict = { # "label": "Object No.1", # "type": "button", # "text": "001_unkown", # "tooltip": "Pick object and move", # "on_clicked_fn": self._on_selected_button, # } # self._buttons["Object No.1"] = btn_builder(**dict) # self._buttons["Object No.1"].enabled = False # dict = { # "label": "Object No.2", # "type": "button", # "text": "002_unkown", # "tooltip": "Pick object and move", # "on_clicked_fn": self._on_selected_button, # } # self._buttons["Object No.2"] = btn_builder(**dict) # self._buttons["Object No.2"].enabled = False return def _set_button_tooltip(self, button_name, tool_tip): self._buttons[button_name].set_tooltip(tool_tip) return def _on_load_world(self): async def _on_load_world_async(): await self._sample.load_world_async() await omni.kit.app.get_app().next_update_async() self._sample._world.add_stage_callback("stage_event_1", self.on_stage_event) self._enable_all_buttons(True) self._buttons["Load World"].enabled = False self.post_load_button_event() self._sample._world.add_timeline_callback("stop_reset_event", self._reset_on_stop_event) asyncio.ensure_future(_on_load_world_async()) return def _on_reset(self): async def _on_reset_async(): await self._sample.reset_async() await omni.kit.app.get_app().next_update_async() self.post_reset_button_event() asyncio.ensure_future(_on_reset_async()) return # ++ def _on_check(self): async def _on_check(): # await self._sample.check_async() # await omni.kit.app.get_app().next_update_async() self._enable_all_buttons(True) self._buttons["Check Objects"].enabled = False self.use_custom_updated = False # self.post_reset_button_event() asyncio.ensure_future(_on_check()) return def _on_selected_button(self): async def _on_selected_button(): # await self._sample.selected_button_async() # await omni.kit.app.get_app().next_update_async() self._enable_all_buttons(False) self._buttons["Check Objects"].enabled = True self.use_custom_updated = True self.post_reset_button_event() asyncio.ensure_future(_on_selected_button()) return def _on_button_00(self): async def _on_button_00(): # await self._sample.check_async() # await omni.kit.app.get_app().next_update_async() self._enable_all_buttons(False) self._buttons["Check Objects"].enabled = True self.use_custom_updated = True self.current_target = "task_object_name_0" self.post_reset_button_event() asyncio.ensure_future(_on_button_00()) return def _on_button_01(self): async def _on_button_01(): # await self._sample.check_async() # await omni.kit.app.get_app().next_update_async() self._enable_all_buttons(False) self._buttons["Check Objects"].enabled = True self.use_custom_updated = True self.current_target = "task_object_name_1" self.post_reset_button_event() asyncio.ensure_future(_on_button_01()) return def _on_button_02(self): async def _on_button_02(): # await self._sample.check_async() # await omni.kit.app.get_app().next_update_async() self._enable_all_buttons(False) self._buttons["Check Objects"].enabled = True self.use_custom_updated = True self.current_target = "task_object_name_2" self.post_reset_button_event() asyncio.ensure_future(_on_button_02()) return # def _on_check(self): # async def _on_check(): # await self._sample.check_async() # await omni.kit.app.get_app().next_update_async() # self.post_reset_button_event() # asyncio.ensure_future(_on_check()) # return @abstractmethod def post_reset_button_event(self): return @abstractmethod def post_load_button_event(self): return @abstractmethod def post_clear_button_event(self): return def _enable_all_buttons(self, flag): for btn_name, btn in self._buttons.items(): if isinstance(btn, omni.ui._ui.Button): btn.enabled = flag return def _menu_callback(self): self._window.visible = not self._window.visible return def _on_window(self, status): # if status: return def on_shutdown(self): self._extra_frames = [] if self._sample._world is not None: self._sample._world_cleanup() if self._menu_items is not None: self._sample_window_cleanup() if self._buttons is not None: self._buttons["Load World"].enabled = True self._enable_all_buttons(False) self.shutdown_cleanup() return def shutdown_cleanup(self): return def _sample_window_cleanup(self): remove_menu_items(self._menu_items, "Isaac Examples") self._window = None self._menu_items = None self._buttons = None return def on_stage_event(self, event): if event.type == int(omni.usd.StageEventType.CLOSED): if World.instance() is not None: self.sample._world_cleanup() self.sample._world.clear_instance() if hasattr(self, "_buttons"): if self._buttons is not None: self._enable_all_buttons(False) self._buttons["Load World"].enabled = True return def _reset_on_stop_event(self, e): if e.type == int(omni.timeline.TimelineEventType.STOP): self._buttons["Load World"].enabled = False self._buttons["Reset"].enabled = True self.post_clear_button_event() return
16,835
Python
36.918919
135
0.464568
usnuni/isaac-sim/pick-n-place/dockers/ailab_script/ailab_extension (org).py
# ailabktw # from abc import abstractmethod import omni.ext import omni.ui as ui from omni.kit.menu.utils import add_menu_items, remove_menu_items, MenuItemDescription import weakref from omni.isaac.ui.ui_utils import setup_ui_headers, get_style, btn_builder, scrolling_frame_builder import asyncio from omni.isaac.examples.ailab_script import AILab from omni.isaac.core import World import os # ---- # class AILabExtension(omni.ext.IExt): def __init__(self): super().__init__() self._ext_id= 'omni.isaac.examples-1.5.1' pass def on_startup(self, ext_id: str='omni.isaac.examples-1.5.1'): self._menu_items = None self._buttons = None self._ext_id = ext_id self._sample = None self._extra_frames = [] return def on_custom_startup(self, ext_id: str): super().on_startup(ext_id) super().start_extension( menu_name="", submenu_name="", name="AILab extension", title="AILab extension Example", doc_link="https://docs.omniverse.nvidia.com/app_isaacsim/app_isaacsim/tutorial_core_hello_world.html", overview="This Example introduces the user on how to do cool stuff with Isaac Sim through scripting in asynchronous mode.", file_path=os.path.abspath(__file__), sample=AILab(), ) return def start_extension( self, menu_name: str, submenu_name: str, name: str, title: str, doc_link: str, overview: str, file_path: str, sample=None, number_of_extra_frames=1, window_width=420, keep_window_open=False, ): if sample is None: self._sample = AILab() else: self._sample = sample menu_items = [MenuItemDescription(name=name, onclick_fn=lambda a=weakref.proxy(self): a._menu_callback())] if menu_name == "" or menu_name is None: self._menu_items = menu_items elif submenu_name == "" or submenu_name is None: self._menu_items = [MenuItemDescription(name=menu_name, sub_menu=menu_items)] else: self._menu_items = [ MenuItemDescription( name=menu_name, sub_menu=[MenuItemDescription(name=submenu_name, sub_menu=menu_items)] ) ] add_menu_items(self._menu_items, "Isaac Examples") self._buttons = dict() self._build_ui( name=name, title=title, doc_link=doc_link, overview=overview, file_path=file_path, number_of_extra_frames=number_of_extra_frames, window_width=window_width, keep_window_open=keep_window_open, ) return @property def sample(self): return self._sample def get_frame(self, index): if index >= len(self._extra_frames): raise Exception("there were {} extra frames created only".format(len(self._extra_frames))) return self._extra_frames[index] def get_world(self): return World.instance() def get_buttons(self): return self._buttons def _build_ui( self, name, title, doc_link, overview, file_path, # number_of_extra_frames, window_width, keep_window_open, number_of_extra_frames=1, window_width=420, keep_window_open=False, # use_custom_update=False, **args ): self._window = omni.ui.Window( name, width=window_width, height=0, visible=keep_window_open, dockPreference=ui.DockPreference.LEFT_BOTTOM ) with self._window.frame: with ui.VStack(spacing=5, height=0): setup_ui_headers(self._ext_id, file_path, title, doc_link, overview) self._controls_frame = ui.CollapsableFrame( title="Object Picking", width=ui.Fraction(1), height=0, collapsed=False, style=get_style(), horizontal_scrollbar_policy=ui.ScrollBarPolicy.SCROLLBAR_AS_NEEDED, vertical_scrollbar_policy=ui.ScrollBarPolicy.SCROLLBAR_ALWAYS_ON, ) with ui.VStack(style=get_style(), spacing=5, height=0): for i in range(number_of_extra_frames): self._extra_frames.append( ui.CollapsableFrame( title="", width=ui.Fraction(0.33), height=0, visible=False, collapsed=False, style=get_style(), horizontal_scrollbar_policy=ui.ScrollBarPolicy.SCROLLBAR_AS_NEEDED, vertical_scrollbar_policy=ui.ScrollBarPolicy.SCROLLBAR_ALWAYS_ON, ) ) with self._controls_frame: with ui.VStack(style=get_style(), spacing=5, height=0): dict = { "label": "Pick Object", "type": "button", "text": "Pick", "tooltip": "Pick object and move", "on_clicked_fn": self._on_load_world, } self._buttons["Pick Object"] = btn_builder(**dict) self._buttons["Pick Object"].enabled = True dict = { "label": "Reset", "type": "button", "text": "Reset", "tooltip": "Reset robot and environment", "on_clicked_fn": self._on_reset, } self._buttons["Reset"] = btn_builder(**dict) self._buttons["Reset"].enabled = False dict = { "label": "Object No.0", "type": "button", "text": "000_unkown", "tooltip": "Pick object and move", "on_clicked_fn": self._on_load_world, } self._buttons["Object No.0"] = btn_builder(**dict) self._buttons["Object No.0"].enabled = True dict = { "label": "Object No.1", "type": "button", "text": "001_unkown", "tooltip": "Pick object and move", "on_clicked_fn": self._on_load_world, } self._buttons["Object No.1"] = btn_builder(**dict) self._buttons["Object No.1"].enabled = True return def _set_button_tooltip(self, button_name, tool_tip): self._buttons[button_name].set_tooltip(tool_tip) return def _on_load_world(self): async def _on_load_world_async(): await self._sample.load_world_async() await omni.kit.app.get_app().next_update_async() self._sample._world.add_stage_callback("stage_event_1", self.on_stage_event) self._enable_all_buttons(True) self._buttons["Load World"].enabled = False self.post_load_button_event() self._sample._world.add_timeline_callback("stop_reset_event", self._reset_on_stop_event) asyncio.ensure_future(_on_load_world_async()) return def _on_reset(self): async def _on_reset_async(): await self._sample.reset_async() await omni.kit.app.get_app().next_update_async() self.post_reset_button_event() asyncio.ensure_future(_on_reset_async()) return @abstractmethod def post_reset_button_event(self): return @abstractmethod def post_load_button_event(self): return @abstractmethod def post_clear_button_event(self): return def _enable_all_buttons(self, flag): for btn_name, btn in self._buttons.items(): if isinstance(btn, omni.ui._ui.Button): btn.enabled = flag return def _menu_callback(self): self._window.visible = not self._window.visible return def _on_window(self, status): # if status: return def on_shutdown(self): self._extra_frames = [] if self._sample._world is not None: self._sample._world_cleanup() if self._menu_items is not None: self._sample_window_cleanup() if self._buttons is not None: self._buttons["Load World"].enabled = True self._enable_all_buttons(False) self.shutdown_cleanup() return def shutdown_cleanup(self): return def _sample_window_cleanup(self): remove_menu_items(self._menu_items, "Isaac Examples") self._window = None self._menu_items = None self._buttons = None return def on_stage_event(self, event): if event.type == int(omni.usd.StageEventType.CLOSED): if World.instance() is not None: self.sample._world_cleanup() self.sample._world.clear_instance() if hasattr(self, "_buttons"): if self._buttons is not None: self._enable_all_buttons(False) self._buttons["Load World"].enabled = True return def _reset_on_stop_event(self, e): if e.type == int(omni.timeline.TimelineEventType.STOP): self._buttons["Load World"].enabled = False self._buttons["Reset"].enabled = True self.post_clear_button_event() return
10,142
Python
34.968085
135
0.508973
usnuni/isaac-sim/pick-n-place/dockers/ailab_script/__init__.py
# Copyright (c) 2021, 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 omni.isaac.examples.ailab_script.ailab import AILab from omni.isaac.examples.ailab_script.ailab_extension import AILabExtension
562
Python
45.916663
76
0.818505
usnuni/isaac-sim/pick-n-place/dockers/ailab_script/ailab.py
# ailabktw # import gc from abc import abstractmethod from omni.isaac.core import World from omni.isaac.core.scenes.scene import Scene from omni.isaac.core.utils.stage import create_new_stage_async, update_stage_async # ---- # class AILab(object): def __init__(self) -> None: self._world = None self._current_tasks = None self._world_settings = {"physics_dt": 1.0 / 60.0, "stage_units_in_meters": 1.0, "rendering_dt": 1.0 / 60.0} # self._logging_info = "" return def get_world(self): return self._world def set_world_settings(self, physics_dt=None, stage_units_in_meters=None, rendering_dt=None): if physics_dt is not None: self._world_settings["physics_dt"] = physics_dt if stage_units_in_meters is not None: self._world_settings["stage_units_in_meters"] = stage_units_in_meters if rendering_dt is not None: self._world_settings["rendering_dt"] = rendering_dt return async def load_world_async(self): """Function called when clicking load buttton """ if World.instance() is None: await create_new_stage_async() self._world = World(**self._world_settings) await self._world.initialize_simulation_context_async() self.setup_scene() else: self._world = World.instance() self._current_tasks = self._world.get_current_tasks() await self._world.reset_async() await self._world.pause_async() await self.setup_post_load() if len(self._current_tasks) > 0: self._world.add_physics_callback("tasks_step", self._world.step_async) return async def reset_async(self): """Function called when clicking reset buttton """ if self._world.is_tasks_scene_built() and len(self._current_tasks) > 0: self._world.remove_physics_callback("tasks_step") await self._world.play_async() await update_stage_async() await self.setup_pre_reset() await self._world.reset_async() await self._world.pause_async() await self.setup_post_reset() if self._world.is_tasks_scene_built() and len(self._current_tasks) > 0: self._world.add_physics_callback("tasks_step", self._world.step_async) return # ++ async def check_async(self): """Function called when clicking reset buttton """ if self._world.is_tasks_scene_built() and len(self._current_tasks) > 0: self._world.remove_physics_callback("tasks_step") await self._world.play_async() await update_stage_async() await self.setup_pre_reset() await self._world.reset_async() await self._world.pause_async() await self.setup_post_reset() if self._world.is_tasks_scene_built() and len(self._current_tasks) > 0: self._world.add_physics_callback("tasks_step", self._world.step_async) return async def selected_button_async(self): """Function called when clicking reset buttton """ if self._world.is_tasks_scene_built() and len(self._current_tasks) > 0: self._world.remove_physics_callback("tasks_step") await self._world.play_async() await update_stage_async() await self.setup_pre_reset() await self._world.reset_async() await self._world.pause_async() await self.setup_post_reset() if self._world.is_tasks_scene_built() and len(self._current_tasks) > 0: self._world.add_physics_callback("tasks_step", self._world.step_async) return @abstractmethod def setup_scene(self, scene: Scene) -> None: """used to setup anything in the world, adding tasks happen here for instance. Args: scene (Scene): [description] """ return @abstractmethod async def setup_post_load(self): """called after first reset of the world when pressing load, intializing provate variables happen here. """ return @abstractmethod async def setup_pre_reset(self): """ called in reset button before resetting the world to remove a physics callback for instance or a controller reset """ return @abstractmethod async def setup_post_reset(self): """ called in reset button after resetting the world which includes one step with rendering """ return @abstractmethod async def setup_post_clear(self): """called after clicking clear button or after creating a new stage and clearing the instance of the world with its callbacks """ return # def log_info(self, info): # self._logging_info += str(info) + "\n" # return def _world_cleanup(self): self._world.stop() self._world.clear_all_callbacks() self._current_tasks = None self.world_cleanup() return def world_cleanup(self): """Function called when extension shutdowns and starts again, (hot reloading feature) """ return async def clear_async(self): """Function called when clicking clear buttton """ await create_new_stage_async() if self._world is not None: self._world_cleanup() self._world.clear_instance() self._world = None gc.collect() await self.setup_post_clear() return
5,568
Python
33.165644
115
0.604346
usnuni/isaac-sim/pick-n-place/lecture/1-1/debug_example.py
a =1 b=1 print(a+b) b=2 print(a+b)
36
Python
4.285714
10
0.555556
usnuni/isaac-sim/pick-n-place/lecture/_for_gui_code/extension.toml
[core] reloadable = true order = 0 [package] version = "1.5.1" category = "Simulation" title = "Isaac Sim Samples" description = "Sample extensions for Isaac Sim" authors = ["NVIDIA"] repository = "" keywords = ["isaac", "samples", "manipulation"] changelog = "docs/CHANGELOG.md" readme = "docs/README.md" preview_image = "data/preview.png" icon = "data/icon.png" writeTarget.kit = true [dependencies] "omni.kit.uiapp" = {} "omni.physx" = {} "omni.physx.vehicle" = {} "omni.isaac.dynamic_control" = {} "omni.isaac.motion_planning" = {} "omni.isaac.synthetic_utils" = {} "omni.isaac.ui" = {} "omni.isaac.core" = {} "omni.isaac.franka" = {} "omni.isaac.manipulators" = {} "omni.isaac.dofbot" = {} "omni.isaac.universal_robots" = {} "omni.isaac.motion_generation" = {} "omni.graph.action" = {} "omni.graph.nodes" = {} "omni.graph.core" = {} "omni.isaac.quadruped" = {} "omni.isaac.wheeled_robots" = {} [[python.module]] name = "omni.isaac.examples.tests" [[python.module]] name = "omni.isaac.examples.kaya_gamepad" [[python.module]] name = "omni.isaac.examples.omnigraph_keyboard" [[python.module]] name = "omni.isaac.examples.follow_target" [[python.module]] name = "omni.isaac.examples.path_planning" [[python.module]] name = "omni.isaac.examples.simple_stack" [[python.module]] name = "omni.isaac.examples.bin_filling" [[python.module]] name = "omni.isaac.examples.robo_factory" [[python.module]] name = "omni.isaac.examples.robo_party" [[python.module]] name = "omni.isaac.examples.hello_world" [[python.module]] name = "omni.isaac.examples.franka_nut_and_bolt" [[python.module]] name = "omni.isaac.examples.replay_follow_target" [[python.module]] name = "omni.isaac.examples.surface_gripper" [[python.module]] name = "omni.isaac.examples.unitree_quadruped" [[python.module]] name = "omni.isaac.examples.user_examples" [[python.module]] name = "omni.isaac.examples.ailab_examples" [[test]] timeout = 960
1,927
TOML
20.186813
49
0.693306
usnuni/isaac-sim/pick-n-place/lecture/_for_gui_code/ailab_examples/ailab_extension.py
# Copyright (c) 2020-2021, 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 omni.isaac.examples.ailab_script import AILabExtension from omni.isaac.examples.ailab_examples import AILab class AILabExtension(AILabExtension): def on_startup(self, ext_id: str): super().on_startup(ext_id) super().start_extension( menu_name="", submenu_name="", name="AILab extension", title="AILab extension Example", doc_link="https://docs.omniverse.nvidia.com/app_isaacsim/app_isaacsim/tutorial_core_hello_world.html", overview="This Example introduces the user on how to do cool stuff with Isaac Sim through scripting in asynchronous mode.", file_path=os.path.abspath(__file__), sample=AILab(), ) return
1,191
Python
41.571427
135
0.702771
usnuni/isaac-sim/pick-n-place/lecture/_for_gui_code/ailab_examples/__init__.py
# Copyright (c) 2021, 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 omni.isaac.examples.ailab_examples.ailab import AILab from omni.isaac.examples.ailab_examples.ailab_extension import AILabExtension
566
Python
46.249996
77
0.819788
usnuni/isaac-sim/pick-n-place/lecture/_for_gui_code/ailab_examples/ailab.py
# Copyright (c) 2020-2021, 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 omni.isaac.examples.base_sample import BaseSample # Note: checkout the required tutorials at https://docs.omniverse.nvidia.com/app_isaacsim/app_isaacsim/overview.html class AILab(BaseSample): def __init__(self) -> None: super().__init__() return def setup_scene(self): world = self.get_world() world.scene.add_default_ground_plane() return async def setup_post_load(self): return async def setup_pre_reset(self): return async def setup_post_reset(self): return def world_cleanup(self): return
1,035
Python
27.777777
116
0.707246
usnuni/isaac-sim/pick-n-place/lecture/_for_gui_code/ailab_script/ailab_extension_old.py
# ailabktw # from abc import abstractmethod import omni.ext import omni.ui as ui from omni.kit.menu.utils import add_menu_items, remove_menu_items, MenuItemDescription import weakref from omni.isaac.ui.ui_utils import setup_ui_headers, get_style, btn_builder, scrolling_frame_builder import asyncio from omni.isaac.examples.ailab_script import AILab from omni.isaac.core import World import os # ---- # class AILabExtension(omni.ext.IExt): def __init__(self): super().__init__() self._ext_id= 'omni.isaac.examples-1.5.1' self.use_custom_updated = False pass def on_startup(self, ext_id: str='omni.isaac.examples-1.5.1'): self._menu_items = None self._buttons = None self._ext_id = ext_id self._sample = None self._extra_frames = [] return def on_custom_startup(self, ext_id: str): super().on_startup(ext_id) super().start_extension( menu_name="", submenu_name="", name="AILab extension", title="AILab extension Example", doc_link="https://docs.omniverse.nvidia.com/app_isaacsim/app_isaacsim/tutorial_core_hello_world.html", overview="This Example introduces the user on how to do cool stuff with Isaac Sim through scripting in asynchronous mode.", file_path=os.path.abspath(__file__), sample=AILab(), ) return def start_extension( self, menu_name: str, submenu_name: str, name: str, title: str, doc_link: str, overview: str, file_path: str, sample=None, number_of_extra_frames=1, window_width=420, keep_window_open=False, ): if sample is None: self._sample = AILab() else: self._sample = sample menu_items = [MenuItemDescription(name=name, onclick_fn=lambda a=weakref.proxy(self): a._menu_callback())] if menu_name == "" or menu_name is None: self._menu_items = menu_items elif submenu_name == "" or submenu_name is None: self._menu_items = [MenuItemDescription(name=menu_name, sub_menu=menu_items)] else: self._menu_items = [ MenuItemDescription( name=menu_name, sub_menu=[MenuItemDescription(name=submenu_name, sub_menu=menu_items)] ) ] add_menu_items(self._menu_items, "Isaac Examples") self._buttons = dict() self._build_ui( name=name, title=title, doc_link=doc_link, overview=overview, file_path=file_path, number_of_extra_frames=number_of_extra_frames, window_width=window_width, keep_window_open=keep_window_open, ) return @property def sample(self): return self._sample def get_frame(self, index): if index >= len(self._extra_frames): raise Exception("there were {} extra frames created only".format(len(self._extra_frames))) return self._extra_frames[index] def get_world(self): return World.instance() def get_buttons(self): return self._buttons def _build_ui( self, name, title, doc_link, overview, file_path, # number_of_extra_frames, window_width, keep_window_open, number_of_extra_frames=1, window_width=420, keep_window_open=False, # use_custom_update=False, **args ): self._window = omni.ui.Window( name, width=window_width, height=0, visible=keep_window_open, dockPreference=ui.DockPreference.LEFT_BOTTOM ) with self._window.frame: with ui.VStack(spacing=5, height=0): setup_ui_headers(self._ext_id, file_path, title, doc_link, overview) self._controls_frame = ui.CollapsableFrame( title="Object Picking", width=ui.Fraction(1), height=0, collapsed=False, style=get_style(), horizontal_scrollbar_policy=ui.ScrollBarPolicy.SCROLLBAR_AS_NEEDED, vertical_scrollbar_policy=ui.ScrollBarPolicy.SCROLLBAR_ALWAYS_ON, ) with ui.VStack(style=get_style(), spacing=5, height=0): for i in range(number_of_extra_frames): self._extra_frames.append( ui.CollapsableFrame( title="", width=ui.Fraction(0.33), height=0, visible=False, collapsed=False, style=get_style(), horizontal_scrollbar_policy=ui.ScrollBarPolicy.SCROLLBAR_AS_NEEDED, vertical_scrollbar_policy=ui.ScrollBarPolicy.SCROLLBAR_ALWAYS_ON, ) ) with self._controls_frame: # = ++ if use_custom_update: with ui.VStack(style=get_style(), spacing=5, height=0): dict = { "label": "Check Objects", "type": "button", "text": "Check", "tooltip": "Check object to pick", "on_clicked_fn": self._on_check, } self._buttons["Check Objects"] = btn_builder(**dict) self._buttons["Check Objects"].enabled = True dict = { "label": "Reset", "type": "button", "text": "Reset", "tooltip": "Reset robot and environment", "on_clicked_fn": self._on_reset, } self._buttons["Reset"] = btn_builder(**dict) self._buttons["Reset"].enabled = True dict = { "label": "Object No.0", "type": "button", "text": "000_unkown", "tooltip": "Pick object and move", "on_clicked_fn": self._on_selected_button, } self._buttons["Object No.0"] = btn_builder(**dict) self._buttons["Object No.0"].enabled = True dict = { "label": "Object No.1", "type": "button", "text": "001_unkown", "tooltip": "Pick object and move", "on_clicked_fn": self._on_selected_button, } self._buttons["Object No.1"] = btn_builder(**dict) self._buttons["Object No.1"].enabled = True dict = { "label": "Object No.2", "type": "button", "text": "002_unkown", "tooltip": "Pick object and move", "on_clicked_fn": self._on_selected_button, } self._buttons["Object No.2"] = btn_builder(**dict) self._buttons["Object No.2"].enabled = True else: with ui.VStack(style=get_style(), spacing=5, height=0): dict = { "label": "Check Objects", "type": "button", "text": "Check", "tooltip": "Check object to pick", "on_clicked_fn": self._on_check, } self._buttons["Check Objects"] = btn_builder(**dict) self._buttons["Check Objects"].enabled = True # dict = { # "label": "Pick Object", # "type": "button", # "text": "Pick", # "tooltip": "Pick object and move", # "on_clicked_fn": self._on_load_world, # } # self._buttons["Pick Object"] = btn_builder(**dict) # self._buttons["Pick Object"].enabled = False dict = { "label": "Reset", "type": "button", "text": "Reset", "tooltip": "Reset robot and environment", "on_clicked_fn": self._on_reset, } self._buttons["Reset"] = btn_builder(**dict) self._buttons["Reset"].enabled = False dict = { "label": "Object No.0", "type": "button", "text": "000_unkown", "tooltip": "Pick object and move", "on_clicked_fn": self._on_selected_button, } self._buttons["Object No.0"] = btn_builder(**dict) self._buttons["Object No.0"].enabled = False dict = { "label": "Object No.1", "type": "button", "text": "001_unkown", "tooltip": "Pick object and move", "on_clicked_fn": self._on_selected_button, } self._buttons["Object No.1"] = btn_builder(**dict) self._buttons["Object No.1"].enabled = False dict = { "label": "Object No.2", "type": "button", "text": "002_unkown", "tooltip": "Pick object and move", "on_clicked_fn": self._on_selected_button, } self._buttons["Object No.2"] = btn_builder(**dict) self._buttons["Object No.2"].enabled = False return def _set_button_tooltip(self, button_name, tool_tip): self._buttons[button_name].set_tooltip(tool_tip) return def _on_load_world(self): async def _on_load_world_async(): await self._sample.load_world_async() await omni.kit.app.get_app().next_update_async() self._sample._world.add_stage_callback("stage_event_1", self.on_stage_event) self._enable_all_buttons(True) self._buttons["Load World"].enabled = False self.post_load_button_event() self._sample._world.add_timeline_callback("stop_reset_event", self._reset_on_stop_event) asyncio.ensure_future(_on_load_world_async()) return def _on_reset(self): async def _on_reset_async(): await self._sample.reset_async() await omni.kit.app.get_app().next_update_async() self.post_reset_button_event() asyncio.ensure_future(_on_reset_async()) return # ++ def _on_check(self): async def _on_check(): # await self._sample.check_async() # await omni.kit.app.get_app().next_update_async() self._enable_all_buttons(True) self._buttons["Check Objects"].enabled = False self.use_custom_updated = False self.post_reset_button_event() asyncio.ensure_future(_on_check()) return def _on_selected_button(self): async def _on_selected_button(): # await self._sample.selected_button_async() # await omni.kit.app.get_app().next_update_async() self._enable_all_buttons(False) self._buttons["Check Objects"].enabled = True self.use_custom_updated = True self.post_reset_button_event() asyncio.ensure_future(_on_selected_button()) return # def _on_check(self): # async def _on_check(): # await self._sample.check_async() # await omni.kit.app.get_app().next_update_async() # self.post_reset_button_event() # asyncio.ensure_future(_on_check()) # return @abstractmethod def post_reset_button_event(self): return @abstractmethod def post_load_button_event(self): return @abstractmethod def post_clear_button_event(self): return def _enable_all_buttons(self, flag): for btn_name, btn in self._buttons.items(): if isinstance(btn, omni.ui._ui.Button): btn.enabled = flag return def _menu_callback(self): self._window.visible = not self._window.visible return def _on_window(self, status): # if status: return def on_shutdown(self): self._extra_frames = [] if self._sample._world is not None: self._sample._world_cleanup() if self._menu_items is not None: self._sample_window_cleanup() if self._buttons is not None: self._buttons["Load World"].enabled = True self._enable_all_buttons(False) self.shutdown_cleanup() return def shutdown_cleanup(self): return def _sample_window_cleanup(self): remove_menu_items(self._menu_items, "Isaac Examples") self._window = None self._menu_items = None self._buttons = None return def on_stage_event(self, event): if event.type == int(omni.usd.StageEventType.CLOSED): if World.instance() is not None: self.sample._world_cleanup() self.sample._world.clear_instance() if hasattr(self, "_buttons"): if self._buttons is not None: self._enable_all_buttons(False) self._buttons["Load World"].enabled = True return def _reset_on_stop_event(self, e): if e.type == int(omni.timeline.TimelineEventType.STOP): self._buttons["Load World"].enabled = False self._buttons["Reset"].enabled = True self.post_clear_button_event() return
15,356
Python
37.878481
135
0.456108
usnuni/isaac-sim/pick-n-place/lecture/_for_gui_code/ailab_script/ailab_extension.py
# ailabktw # from abc import abstractmethod import omni.ext import omni.ui as ui from omni.kit.menu.utils import add_menu_items, remove_menu_items, MenuItemDescription import weakref from omni.isaac.ui.ui_utils import setup_ui_headers, get_style, btn_builder, scrolling_frame_builder import asyncio from omni.isaac.examples.ailab_script import AILab from omni.isaac.core import World import os # ---- # class AILabExtension(omni.ext.IExt): def __init__(self): super().__init__() self._ext_id= 'omni.isaac.examples-1.5.1' self.use_custom_updated = False self.current_target = None pass def on_startup(self, ext_id: str='omni.isaac.examples-1.5.1'): self._menu_items = None self._buttons = None self._ext_id = ext_id self._sample = None self._extra_frames = [] return def on_custom_startup(self, ext_id: str): super().on_startup(ext_id) super().start_extension( menu_name="", submenu_name="", name="AILab extension", title="AILab extension Example", doc_link="https://docs.omniverse.nvidia.com/app_isaacsim/app_isaacsim/tutorial_core_hello_world.html", overview="This Example introduces the user on how to do cool stuff with Isaac Sim through scripting in asynchronous mode.", file_path=os.path.abspath(__file__), sample=AILab(), ) return def start_extension( self, menu_name: str, submenu_name: str, name: str, title: str, doc_link: str, overview: str, file_path: str, sample=None, number_of_extra_frames=1, window_width=420, keep_window_open=False, ): if sample is None: self._sample = AILab() else: self._sample = sample menu_items = [MenuItemDescription(name=name, onclick_fn=lambda a=weakref.proxy(self): a._menu_callback())] if menu_name == "" or menu_name is None: self._menu_items = menu_items elif submenu_name == "" or submenu_name is None: self._menu_items = [MenuItemDescription(name=menu_name, sub_menu=menu_items)] else: self._menu_items = [ MenuItemDescription( name=menu_name, sub_menu=[MenuItemDescription(name=submenu_name, sub_menu=menu_items)] ) ] add_menu_items(self._menu_items, "Isaac Examples") self._buttons = dict() self._build_ui( name=name, title=title, doc_link=doc_link, overview=overview, file_path=file_path, number_of_extra_frames=number_of_extra_frames, window_width=window_width, keep_window_open=keep_window_open, ) return @property def sample(self): return self._sample def get_frame(self, index): if index >= len(self._extra_frames): raise Exception("there were {} extra frames created only".format(len(self._extra_frames))) return self._extra_frames[index] def get_world(self): return World.instance() def get_buttons(self): return self._buttons def _build_ui( self, name, title, doc_link, overview, file_path, # number_of_extra_frames, window_width, keep_window_open, number_of_extra_frames=1, window_width=420, keep_window_open=False, # use_custom_update=False, **args ): self._window = omni.ui.Window( name, width=window_width, height=0, visible=keep_window_open, dockPreference=ui.DockPreference.LEFT_BOTTOM ) with self._window.frame: with ui.VStack(spacing=5, height=0): setup_ui_headers(self._ext_id, file_path, title, doc_link, overview) self._controls_frame = ui.CollapsableFrame( title="Object Picking", width=ui.Fraction(1), height=0, collapsed=False, style=get_style(), horizontal_scrollbar_policy=ui.ScrollBarPolicy.SCROLLBAR_AS_NEEDED, vertical_scrollbar_policy=ui.ScrollBarPolicy.SCROLLBAR_ALWAYS_ON, ) with ui.VStack(style=get_style(), spacing=5, height=0): for i in range(number_of_extra_frames): self._extra_frames.append( ui.CollapsableFrame( title="", width=ui.Fraction(0.33), height=0, visible=False, collapsed=False, style=get_style(), horizontal_scrollbar_policy=ui.ScrollBarPolicy.SCROLLBAR_AS_NEEDED, vertical_scrollbar_policy=ui.ScrollBarPolicy.SCROLLBAR_ALWAYS_ON, ) ) with self._controls_frame: # = ++ # if use_custom_update: with ui.VStack(style=get_style(), spacing=5, height=0): dict = { "label": "Check Objects", "type": "button", "text": "Check", "tooltip": "Check object to pick", "on_clicked_fn": self._on_check, } self._buttons["Check Objects"] = btn_builder(**dict) self._buttons["Check Objects"].enabled = True dict = { "label": "Reset", "type": "button", "text": "Reset", "tooltip": "Reset robot and environment", "on_clicked_fn": self._on_reset, } self._buttons["Reset"] = btn_builder(**dict) self._buttons["Reset"].enabled = False dict = { "label": "Object No.0", "type": "button", "text": "000_unkown", "tooltip": "Pick object and move", "on_clicked_fn": self._on_button_00, } self._buttons["Object No.0"] = btn_builder(**dict) self._buttons["Object No.0"].enabled = False dict = { "label": "Object No.1", "type": "button", "text": "001_unkown", "tooltip": "Pick object and move", "on_clicked_fn": self._on_button_01, } self._buttons["Object No.1"] = btn_builder(**dict) self._buttons["Object No.1"].enabled = False dict = { "label": "Object No.2", "type": "button", "text": "002_unkown", "tooltip": "Pick object and move", "on_clicked_fn": self._on_button_02, } self._buttons["Object No.2"] = btn_builder(**dict) self._buttons["Object No.2"].enabled = False # # else: # with ui.VStack(style=get_style(), spacing=5, height=0): # dict = { # "label": "Check Objects", # "type": "button", # "text": "Check", # "tooltip": "Check object to pick", # "on_clicked_fn": self._on_check, # } # self._buttons["Check Objects"] = btn_builder(**dict) # self._buttons["Check Objects"].enabled = True # # dict = { # # "label": "Pick Object", # # "type": "button", # # "text": "Pick", # # "tooltip": "Pick object and move", # # "on_clicked_fn": self._on_load_world, # # } # # self._buttons["Pick Object"] = btn_builder(**dict) # # self._buttons["Pick Object"].enabled = False # dict = { # "label": "Reset", # "type": "button", # "text": "Reset", # "tooltip": "Reset robot and environment", # "on_clicked_fn": self._on_reset, # } # self._buttons["Reset"] = btn_builder(**dict) # self._buttons["Reset"].enabled = False # dict = { # "label": "Object No.0", # "type": "button", # "text": "000_unkown", # "tooltip": "Pick object and move", # "on_clicked_fn": self._on_selected_button, # } # self._buttons["Object No.0"] = btn_builder(**dict) # self._buttons["Object No.0"].enabled = False # dict = { # "label": "Object No.1", # "type": "button", # "text": "001_unkown", # "tooltip": "Pick object and move", # "on_clicked_fn": self._on_selected_button, # } # self._buttons["Object No.1"] = btn_builder(**dict) # self._buttons["Object No.1"].enabled = False # dict = { # "label": "Object No.2", # "type": "button", # "text": "002_unkown", # "tooltip": "Pick object and move", # "on_clicked_fn": self._on_selected_button, # } # self._buttons["Object No.2"] = btn_builder(**dict) # self._buttons["Object No.2"].enabled = False return def _set_button_tooltip(self, button_name, tool_tip): self._buttons[button_name].set_tooltip(tool_tip) return def _on_load_world(self): async def _on_load_world_async(): await self._sample.load_world_async() await omni.kit.app.get_app().next_update_async() self._sample._world.add_stage_callback("stage_event_1", self.on_stage_event) self._enable_all_buttons(True) self._buttons["Load World"].enabled = False self.post_load_button_event() self._sample._world.add_timeline_callback("stop_reset_event", self._reset_on_stop_event) asyncio.ensure_future(_on_load_world_async()) return def _on_reset(self): async def _on_reset_async(): await self._sample.reset_async() await omni.kit.app.get_app().next_update_async() self.post_reset_button_event() asyncio.ensure_future(_on_reset_async()) return # ++ def _on_check(self): async def _on_check(): # await self._sample.check_async() # await omni.kit.app.get_app().next_update_async() self._enable_all_buttons(True) self._buttons["Check Objects"].enabled = False self.use_custom_updated = False # self.post_reset_button_event() asyncio.ensure_future(_on_check()) return def _on_selected_button(self): async def _on_selected_button(): # await self._sample.selected_button_async() # await omni.kit.app.get_app().next_update_async() self._enable_all_buttons(False) self._buttons["Check Objects"].enabled = True self.use_custom_updated = True self.post_reset_button_event() asyncio.ensure_future(_on_selected_button()) return def _on_button_00(self): async def _on_button_00(): # await self._sample.check_async() # await omni.kit.app.get_app().next_update_async() self._enable_all_buttons(False) self._buttons["Check Objects"].enabled = True self.use_custom_updated = True self.current_target = "task_object_name_0" self.post_reset_button_event() asyncio.ensure_future(_on_button_00()) return def _on_button_01(self): async def _on_button_01(): # await self._sample.check_async() # await omni.kit.app.get_app().next_update_async() self._enable_all_buttons(False) self._buttons["Check Objects"].enabled = True self.use_custom_updated = True self.current_target = "task_object_name_1" self.post_reset_button_event() asyncio.ensure_future(_on_button_01()) return def _on_button_02(self): async def _on_button_02(): # await self._sample.check_async() # await omni.kit.app.get_app().next_update_async() self._enable_all_buttons(False) self._buttons["Check Objects"].enabled = True self.use_custom_updated = True self.current_target = "task_object_name_2" self.post_reset_button_event() asyncio.ensure_future(_on_button_02()) return # def _on_check(self): # async def _on_check(): # await self._sample.check_async() # await omni.kit.app.get_app().next_update_async() # self.post_reset_button_event() # asyncio.ensure_future(_on_check()) # return @abstractmethod def post_reset_button_event(self): return @abstractmethod def post_load_button_event(self): return @abstractmethod def post_clear_button_event(self): return def _enable_all_buttons(self, flag): for btn_name, btn in self._buttons.items(): if isinstance(btn, omni.ui._ui.Button): btn.enabled = flag return def _menu_callback(self): self._window.visible = not self._window.visible return def _on_window(self, status): # if status: return def on_shutdown(self): self._extra_frames = [] if self._sample._world is not None: self._sample._world_cleanup() if self._menu_items is not None: self._sample_window_cleanup() if self._buttons is not None: self._buttons["Load World"].enabled = True self._enable_all_buttons(False) self.shutdown_cleanup() return def shutdown_cleanup(self): return def _sample_window_cleanup(self): remove_menu_items(self._menu_items, "Isaac Examples") self._window = None self._menu_items = None self._buttons = None return def on_stage_event(self, event): if event.type == int(omni.usd.StageEventType.CLOSED): if World.instance() is not None: self.sample._world_cleanup() self.sample._world.clear_instance() if hasattr(self, "_buttons"): if self._buttons is not None: self._enable_all_buttons(False) self._buttons["Load World"].enabled = True return def _reset_on_stop_event(self, e): if e.type == int(omni.timeline.TimelineEventType.STOP): self._buttons["Load World"].enabled = False self._buttons["Reset"].enabled = True self.post_clear_button_event() return
16,835
Python
36.918919
135
0.464568
usnuni/isaac-sim/pick-n-place/lecture/_for_gui_code/ailab_script/ailab_extension (org).py
# ailabktw # from abc import abstractmethod import omni.ext import omni.ui as ui from omni.kit.menu.utils import add_menu_items, remove_menu_items, MenuItemDescription import weakref from omni.isaac.ui.ui_utils import setup_ui_headers, get_style, btn_builder, scrolling_frame_builder import asyncio from omni.isaac.examples.ailab_script import AILab from omni.isaac.core import World import os # ---- # class AILabExtension(omni.ext.IExt): def __init__(self): super().__init__() self._ext_id= 'omni.isaac.examples-1.5.1' pass def on_startup(self, ext_id: str='omni.isaac.examples-1.5.1'): self._menu_items = None self._buttons = None self._ext_id = ext_id self._sample = None self._extra_frames = [] return def on_custom_startup(self, ext_id: str): super().on_startup(ext_id) super().start_extension( menu_name="", submenu_name="", name="AILab extension", title="AILab extension Example", doc_link="https://docs.omniverse.nvidia.com/app_isaacsim/app_isaacsim/tutorial_core_hello_world.html", overview="This Example introduces the user on how to do cool stuff with Isaac Sim through scripting in asynchronous mode.", file_path=os.path.abspath(__file__), sample=AILab(), ) return def start_extension( self, menu_name: str, submenu_name: str, name: str, title: str, doc_link: str, overview: str, file_path: str, sample=None, number_of_extra_frames=1, window_width=420, keep_window_open=False, ): if sample is None: self._sample = AILab() else: self._sample = sample menu_items = [MenuItemDescription(name=name, onclick_fn=lambda a=weakref.proxy(self): a._menu_callback())] if menu_name == "" or menu_name is None: self._menu_items = menu_items elif submenu_name == "" or submenu_name is None: self._menu_items = [MenuItemDescription(name=menu_name, sub_menu=menu_items)] else: self._menu_items = [ MenuItemDescription( name=menu_name, sub_menu=[MenuItemDescription(name=submenu_name, sub_menu=menu_items)] ) ] add_menu_items(self._menu_items, "Isaac Examples") self._buttons = dict() self._build_ui( name=name, title=title, doc_link=doc_link, overview=overview, file_path=file_path, number_of_extra_frames=number_of_extra_frames, window_width=window_width, keep_window_open=keep_window_open, ) return @property def sample(self): return self._sample def get_frame(self, index): if index >= len(self._extra_frames): raise Exception("there were {} extra frames created only".format(len(self._extra_frames))) return self._extra_frames[index] def get_world(self): return World.instance() def get_buttons(self): return self._buttons def _build_ui( self, name, title, doc_link, overview, file_path, # number_of_extra_frames, window_width, keep_window_open, number_of_extra_frames=1, window_width=420, keep_window_open=False, # use_custom_update=False, **args ): self._window = omni.ui.Window( name, width=window_width, height=0, visible=keep_window_open, dockPreference=ui.DockPreference.LEFT_BOTTOM ) with self._window.frame: with ui.VStack(spacing=5, height=0): setup_ui_headers(self._ext_id, file_path, title, doc_link, overview) self._controls_frame = ui.CollapsableFrame( title="Object Picking", width=ui.Fraction(1), height=0, collapsed=False, style=get_style(), horizontal_scrollbar_policy=ui.ScrollBarPolicy.SCROLLBAR_AS_NEEDED, vertical_scrollbar_policy=ui.ScrollBarPolicy.SCROLLBAR_ALWAYS_ON, ) with ui.VStack(style=get_style(), spacing=5, height=0): for i in range(number_of_extra_frames): self._extra_frames.append( ui.CollapsableFrame( title="", width=ui.Fraction(0.33), height=0, visible=False, collapsed=False, style=get_style(), horizontal_scrollbar_policy=ui.ScrollBarPolicy.SCROLLBAR_AS_NEEDED, vertical_scrollbar_policy=ui.ScrollBarPolicy.SCROLLBAR_ALWAYS_ON, ) ) with self._controls_frame: with ui.VStack(style=get_style(), spacing=5, height=0): dict = { "label": "Pick Object", "type": "button", "text": "Pick", "tooltip": "Pick object and move", "on_clicked_fn": self._on_load_world, } self._buttons["Pick Object"] = btn_builder(**dict) self._buttons["Pick Object"].enabled = True dict = { "label": "Reset", "type": "button", "text": "Reset", "tooltip": "Reset robot and environment", "on_clicked_fn": self._on_reset, } self._buttons["Reset"] = btn_builder(**dict) self._buttons["Reset"].enabled = False dict = { "label": "Object No.0", "type": "button", "text": "000_unkown", "tooltip": "Pick object and move", "on_clicked_fn": self._on_load_world, } self._buttons["Object No.0"] = btn_builder(**dict) self._buttons["Object No.0"].enabled = True dict = { "label": "Object No.1", "type": "button", "text": "001_unkown", "tooltip": "Pick object and move", "on_clicked_fn": self._on_load_world, } self._buttons["Object No.1"] = btn_builder(**dict) self._buttons["Object No.1"].enabled = True return def _set_button_tooltip(self, button_name, tool_tip): self._buttons[button_name].set_tooltip(tool_tip) return def _on_load_world(self): async def _on_load_world_async(): await self._sample.load_world_async() await omni.kit.app.get_app().next_update_async() self._sample._world.add_stage_callback("stage_event_1", self.on_stage_event) self._enable_all_buttons(True) self._buttons["Load World"].enabled = False self.post_load_button_event() self._sample._world.add_timeline_callback("stop_reset_event", self._reset_on_stop_event) asyncio.ensure_future(_on_load_world_async()) return def _on_reset(self): async def _on_reset_async(): await self._sample.reset_async() await omni.kit.app.get_app().next_update_async() self.post_reset_button_event() asyncio.ensure_future(_on_reset_async()) return @abstractmethod def post_reset_button_event(self): return @abstractmethod def post_load_button_event(self): return @abstractmethod def post_clear_button_event(self): return def _enable_all_buttons(self, flag): for btn_name, btn in self._buttons.items(): if isinstance(btn, omni.ui._ui.Button): btn.enabled = flag return def _menu_callback(self): self._window.visible = not self._window.visible return def _on_window(self, status): # if status: return def on_shutdown(self): self._extra_frames = [] if self._sample._world is not None: self._sample._world_cleanup() if self._menu_items is not None: self._sample_window_cleanup() if self._buttons is not None: self._buttons["Load World"].enabled = True self._enable_all_buttons(False) self.shutdown_cleanup() return def shutdown_cleanup(self): return def _sample_window_cleanup(self): remove_menu_items(self._menu_items, "Isaac Examples") self._window = None self._menu_items = None self._buttons = None return def on_stage_event(self, event): if event.type == int(omni.usd.StageEventType.CLOSED): if World.instance() is not None: self.sample._world_cleanup() self.sample._world.clear_instance() if hasattr(self, "_buttons"): if self._buttons is not None: self._enable_all_buttons(False) self._buttons["Load World"].enabled = True return def _reset_on_stop_event(self, e): if e.type == int(omni.timeline.TimelineEventType.STOP): self._buttons["Load World"].enabled = False self._buttons["Reset"].enabled = True self.post_clear_button_event() return
10,142
Python
34.968085
135
0.508973
usnuni/isaac-sim/pick-n-place/lecture/_for_gui_code/ailab_script/__init__.py
# Copyright (c) 2021, 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 omni.isaac.examples.ailab_script.ailab import AILab from omni.isaac.examples.ailab_script.ailab_extension import AILabExtension
562
Python
45.916663
76
0.818505
usnuni/isaac-sim/pick-n-place/lecture/_for_gui_code/ailab_script/ailab.py
# ailabktw # import gc from abc import abstractmethod from omni.isaac.core import World from omni.isaac.core.scenes.scene import Scene from omni.isaac.core.utils.stage import create_new_stage_async, update_stage_async # ---- # class AILab(object): def __init__(self) -> None: self._world = None self._current_tasks = None self._world_settings = {"physics_dt": 1.0 / 60.0, "stage_units_in_meters": 1.0, "rendering_dt": 1.0 / 60.0} # self._logging_info = "" return def get_world(self): return self._world def set_world_settings(self, physics_dt=None, stage_units_in_meters=None, rendering_dt=None): if physics_dt is not None: self._world_settings["physics_dt"] = physics_dt if stage_units_in_meters is not None: self._world_settings["stage_units_in_meters"] = stage_units_in_meters if rendering_dt is not None: self._world_settings["rendering_dt"] = rendering_dt return async def load_world_async(self): """Function called when clicking load buttton """ if World.instance() is None: await create_new_stage_async() self._world = World(**self._world_settings) await self._world.initialize_simulation_context_async() self.setup_scene() else: self._world = World.instance() self._current_tasks = self._world.get_current_tasks() await self._world.reset_async() await self._world.pause_async() await self.setup_post_load() if len(self._current_tasks) > 0: self._world.add_physics_callback("tasks_step", self._world.step_async) return async def reset_async(self): """Function called when clicking reset buttton """ if self._world.is_tasks_scene_built() and len(self._current_tasks) > 0: self._world.remove_physics_callback("tasks_step") await self._world.play_async() await update_stage_async() await self.setup_pre_reset() await self._world.reset_async() await self._world.pause_async() await self.setup_post_reset() if self._world.is_tasks_scene_built() and len(self._current_tasks) > 0: self._world.add_physics_callback("tasks_step", self._world.step_async) return # ++ async def check_async(self): """Function called when clicking reset buttton """ if self._world.is_tasks_scene_built() and len(self._current_tasks) > 0: self._world.remove_physics_callback("tasks_step") await self._world.play_async() await update_stage_async() await self.setup_pre_reset() await self._world.reset_async() await self._world.pause_async() await self.setup_post_reset() if self._world.is_tasks_scene_built() and len(self._current_tasks) > 0: self._world.add_physics_callback("tasks_step", self._world.step_async) return async def selected_button_async(self): """Function called when clicking reset buttton """ if self._world.is_tasks_scene_built() and len(self._current_tasks) > 0: self._world.remove_physics_callback("tasks_step") await self._world.play_async() await update_stage_async() await self.setup_pre_reset() await self._world.reset_async() await self._world.pause_async() await self.setup_post_reset() if self._world.is_tasks_scene_built() and len(self._current_tasks) > 0: self._world.add_physics_callback("tasks_step", self._world.step_async) return @abstractmethod def setup_scene(self, scene: Scene) -> None: """used to setup anything in the world, adding tasks happen here for instance. Args: scene (Scene): [description] """ return @abstractmethod async def setup_post_load(self): """called after first reset of the world when pressing load, intializing provate variables happen here. """ return @abstractmethod async def setup_pre_reset(self): """ called in reset button before resetting the world to remove a physics callback for instance or a controller reset """ return @abstractmethod async def setup_post_reset(self): """ called in reset button after resetting the world which includes one step with rendering """ return @abstractmethod async def setup_post_clear(self): """called after clicking clear button or after creating a new stage and clearing the instance of the world with its callbacks """ return # def log_info(self, info): # self._logging_info += str(info) + "\n" # return def _world_cleanup(self): self._world.stop() self._world.clear_all_callbacks() self._current_tasks = None self.world_cleanup() return def world_cleanup(self): """Function called when extension shutdowns and starts again, (hot reloading feature) """ return async def clear_async(self): """Function called when clicking clear buttton """ await create_new_stage_async() if self._world is not None: self._world_cleanup() self._world.clear_instance() self._world = None gc.collect() await self.setup_post_clear() return
5,568
Python
33.165644
115
0.604346
stephenT0/funkyboy-anamorphic-effects/README.md
# Anamorphic Effects An extension that emulates camera effects associated with anamorphic lenses. Download this sample scene to demo the extension: https://drive.google.com/file/d/1ZYNbhNenNNl2WTJeKibXuf8S1eJVl4Cy/view?usp=share_link ## Adding This Extension To add this extension to your Omniverse app: 1. Go into: Extension Manager -> Gear Icon -> Extension Search Path 2. Add this as a search path: `git://github.com/stephenT0/funkyboy-anamorphic-effects?branch=main&dir=exts` Manual installation: 1. Download Zip 2. Extract and place into a directory of your choice 3. Go into: Extension Manager -> Gear Icon -> Extension Search Path 4. Add a custom search path ending with: \funkyboy-anamorphic-effects-master\exts
728
Markdown
35.449998
135
0.788462
stephenT0/funkyboy-anamorphic-effects/tools/scripts/link_app.py
import argparse import json import os import sys import packmanapi import urllib3 def find_omniverse_apps(): http = urllib3.PoolManager() try: r = http.request("GET", "http://127.0.0.1:33480/components") except Exception as e: print(f"Failed retrieving apps from an Omniverse Launcher, maybe it is not installed?\nError: {e}") sys.exit(1) apps = {} for x in json.loads(r.data.decode("utf-8")): latest = x.get("installedVersions", {}).get("latest", "") if latest: for s in x.get("settings", []): if s.get("version", "") == latest: root = s.get("launch", {}).get("root", "") apps[x["slug"]] = (x["name"], root) break return apps def create_link(src, dst): print(f"Creating a link '{src}' -> '{dst}'") packmanapi.link(src, dst) APP_PRIORITIES = ["code", "create", "view"] if __name__ == "__main__": parser = argparse.ArgumentParser(description="Create folder link to Kit App installed from Omniverse Launcher") parser.add_argument( "--path", help="Path to Kit App installed from Omniverse Launcher, e.g.: 'C:/Users/bob/AppData/Local/ov/pkg/create-2021.3.4'", required=False, ) parser.add_argument( "--app", help="Name of Kit App installed from Omniverse Launcher, e.g.: 'code', 'create'", required=False ) args = parser.parse_args() path = args.path if not path: print("Path is not specified, looking for Omniverse Apps...") apps = find_omniverse_apps() if len(apps) == 0: print( "Can't find any Omniverse Apps. Use Omniverse Launcher to install one. 'Code' is the recommended app for developers." ) sys.exit(0) print("\nFound following Omniverse Apps:") for i, slug in enumerate(apps): name, root = apps[slug] print(f"{i}: {name} ({slug}) at: '{root}'") if args.app: selected_app = args.app.lower() if selected_app not in apps: choices = ", ".join(apps.keys()) print(f"Passed app: '{selected_app}' is not found. Specify one of the following found Apps: {choices}") sys.exit(0) else: selected_app = next((x for x in APP_PRIORITIES if x in apps), None) if not selected_app: selected_app = next(iter(apps)) print(f"\nSelected app: {selected_app}") _, path = apps[selected_app] if not os.path.exists(path): print(f"Provided path doesn't exist: {path}") else: SCRIPT_ROOT = os.path.dirname(os.path.realpath(__file__)) create_link(f"{SCRIPT_ROOT}/../../app", path) print("Success!")
2,814
Python
32.117647
133
0.562189
stephenT0/funkyboy-anamorphic-effects/tools/packman/config.packman.xml
<config remotes="cloudfront"> <remote2 name="cloudfront"> <transport actions="download" protocol="https" packageLocation="d4i3qtqj3r0z5.cloudfront.net/${name}@${version}" /> </remote2> </config>
211
XML
34.333328
123
0.691943
stephenT0/funkyboy-anamorphic-effects/tools/packman/bootstrap/install_package.py
# Copyright 2019 NVIDIA CORPORATION # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # http://www.apache.org/licenses/LICENSE-2.0 # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import logging import shutil import sys import tempfile import zipfile __author__ = "hfannar" logging.basicConfig(level=logging.WARNING, format="%(message)s") logger = logging.getLogger("install_package") class TemporaryDirectory: def __init__(self): self.path = None def __enter__(self): self.path = tempfile.mkdtemp() return self.path def __exit__(self, type, value, traceback): # Remove temporary data created shutil.rmtree(self.path) def install_package(package_src_path, package_dst_path): with zipfile.ZipFile(package_src_path, allowZip64=True) as zip_file, TemporaryDirectory() as temp_dir: zip_file.extractall(temp_dir) # Recursively copy (temp_dir will be automatically cleaned up on exit) try: # Recursive copy is needed because both package name and version folder could be missing in # target directory: shutil.copytree(temp_dir, package_dst_path) except OSError as exc: logger.warning("Directory %s already present, packaged installation aborted" % package_dst_path) else: logger.info("Package successfully installed to %s" % package_dst_path) install_package(sys.argv[1], sys.argv[2])
1,844
Python
33.166666
108
0.703362
stephenT0/funkyboy-anamorphic-effects/exts/funkyboy.anamorphic.effects/funkyboy/anamorphic/effects/style.py
# Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. # __all__ = ["julia_modeler_style"] from omni.ui import color as cl from omni.ui import constant as fl from omni.ui import url import omni.kit.app import omni.ui as ui import pathlib EXTENSION_FOLDER_PATH = pathlib.Path( omni.kit.app.get_app().get_extension_manager().get_extension_path_by_module(__name__) ) ATTR_LABEL_WIDTH = 1 BLOCK_HEIGHT = 22 TAIL_WIDTH = 35 WIN_WIDTH = 400 WIN_HEIGHT = 930 # Pre-defined constants. It's possible to change them at runtime. cl.window_bg_color = cl(0.2, 0.2, 0.2, 1.0) cl.window_title_text = cl(.9, .9, .9, .9) cl.collapsible_header_text = cl(.8, .8, .8, .8) cl.collapsible_header_text_hover = cl(.95, .95, .95, 1.0) cl.main_attr_label_text = cl(.65, .65, .65, 1.0) cl.main_attr_label_text_hover = cl(.9, .9, .9, 1.0) cl.multifield_label_text = cl(.65, .65, .65, 1.0) cl.combobox_label_text = cl(.65, .65, .65, 1.0) cl.field_bg = cl(0.18, 0.18, 0.18, 1.0) cl.field_border = cl(1.0, 1.0, 1.0, 0.2) cl.btn_border = cl(1.0, 1.0, 1.0, 0.4) cl.slider_fill = cl(1.0, 1.0, 1.0, 0.3) cl.revert_arrow_enabled = cl(.25, .5, .75, 1.0) cl.revert_arrow_disabled = cl(.35, .35, .35, 1.0) cl.transparent = cl(0, 0, 0, 0) fl.main_label_attr_hspacing = 5 fl.attr_label_v_spacing = 5 fl.collapsable_group_spacing = 0.5 fl.outer_frame_padding = 15 fl.tail_icon_width = 15 fl.border_radius = 25 fl.border_width = 1.5 fl.window_title_font_size = 18 fl.field_text_font_size = 14 fl.main_label_font_size = 14 fl.multi_attr_label_font_size = 14 fl.radio_group_font_size = 14 fl.collapsable_header_font_size = 17.5 fl.range_text_size = 10 url.closed_arrow_icon = f"{EXTENSION_FOLDER_PATH}/icons/closed.svg" url.open_arrow_icon = f"{EXTENSION_FOLDER_PATH}/icons/opened.svg" url.revert_arrow_icon = f"{EXTENSION_FOLDER_PATH}/icons/revert_arrow.svg" url.checkbox_on_icon = f"{EXTENSION_FOLDER_PATH}/icons/checkbox_on.svg" url.checkbox_off_icon = f"{EXTENSION_FOLDER_PATH}/icons/checkbox_off.svg" url.radio_btn_on_icon = f"{EXTENSION_FOLDER_PATH}/icons/radio_btn_on.svg" url.radio_btn_off_icon = f"{EXTENSION_FOLDER_PATH}/icons/radio_btn_off.svg" url.diag_bg_lines_texture = f"{EXTENSION_FOLDER_PATH}/icons/diagonal_texture_screenshot.png" # The main style dict julia_modeler_style = { "Button::tool_button": { "background_color": cl.field_bg, "margin_height": 0, "margin_width": 6, "border_color": cl.btn_border, "border_width": fl.border_width, "font_size": fl.field_text_font_size, }, "CollapsableFrame::group": { "margin_height": fl.collapsable_group_spacing, "background_color": cl.transparent, }, # TODO: For some reason this ColorWidget style doesn't respond much, if at all (ie, border_radius, corner_flag) "ColorWidget": { "border_radius": fl.border_radius, "border_color": cl(0.0, 0.0, 0.0, 0.0), }, "Field": { "background_color": cl.field_bg, "border_radius": fl.border_radius, "border_color": cl.field_border, "border_width": fl.border_width, }, "Field::attr_field": { "corner_flag": ui.CornerFlag.RIGHT, "font_size": 2, # fl.field_text_font_size, # Hack to allow for a smaller field border until field padding works }, "Field::attribute_color": { "font_size": fl.field_text_font_size, }, "Field::multi_attr_field": { "padding": 4, # TODO: Hacky until we get padding fix "font_size": fl.field_text_font_size, }, "Field::path_field": { "corner_flag": ui.CornerFlag.RIGHT, "font_size": fl.field_text_font_size, }, "HeaderLine": {"color": cl(.5, .5, .5, .5)}, "Image::collapsable_opened": { "color": cl.collapsible_header_text, "image_url": url.open_arrow_icon, }, "Image::collapsable_opened:hovered": { "color": cl.collapsible_header_text_hover, "image_url": url.open_arrow_icon, }, "Image::collapsable_closed": { "color": cl.collapsible_header_text, "image_url": url.closed_arrow_icon, }, "Image::collapsable_closed:hovered": { "color": cl.collapsible_header_text_hover, "image_url": url.closed_arrow_icon, }, "Image::radio_on": {"image_url": url.radio_btn_on_icon}, "Image::radio_off": {"image_url": url.radio_btn_off_icon}, "Image::revert_arrow": { "image_url": url.revert_arrow_icon, "color": cl.revert_arrow_enabled, }, "Image::revert_arrow:disabled": {"color": cl.revert_arrow_disabled}, "Image::checked": {"image_url": url.checkbox_on_icon}, "Image::unchecked": {"image_url": url.checkbox_off_icon}, "Image::slider_bg_texture": { "image_url": url.diag_bg_lines_texture, "border_radius": fl.border_radius, "corner_flag": ui.CornerFlag.LEFT, }, "Label::attribute_name": { "alignment": ui.Alignment.RIGHT_TOP, "margin_height": fl.attr_label_v_spacing, "margin_width": fl.main_label_attr_hspacing, "color": cl.main_attr_label_text, "font_size": fl.main_label_font_size, }, "Label::attribute_name:hovered": {"color": cl.main_attr_label_text_hover}, "Label::collapsable_name": {"font_size": fl.collapsable_header_font_size}, "Label::multi_attr_label": { "color": cl.multifield_label_text, "font_size": fl.multi_attr_label_font_size, }, "Label::radio_group_name": { "font_size": fl.radio_group_font_size, "alignment": ui.Alignment.CENTER, "color": cl.main_attr_label_text, }, "Label::range_text": { "font_size": fl.range_text_size, }, "Label::window_title": { "font_size": fl.window_title_font_size, "color": cl.window_title_text, }, "ScrollingFrame::window_bg": { "background_color": cl.window_bg_color, "padding": fl.outer_frame_padding, "border_radius": 20 # Not obvious in a window, but more visible with only a frame }, "Slider::attr_slider": { "draw_mode": ui.SliderDrawMode.FILLED, "padding": 0, "color": cl.transparent, # Meant to be transparent, but completely transparent shows opaque black instead. "background_color": cl(0.28, 0.28, 0.28, 0.01), "secondary_color": cl.slider_fill, "border_radius": fl.border_radius, "corner_flag": ui.CornerFlag.LEFT, # TODO: Not actually working yet OM-53727 }, "Slider::attr_slider2": { "draw_mode": ui.SliderDrawMode.HANDLE, "padding": 0, "color": cl.transparent, # Meant to be transparent, but completely transparent shows opaque black instead. "background_color": cl(0.68, 0.28, 0.28, 0.01), "secondary_color": cl.slider_fill, "border_radius": fl.border_radius, "corner_flag": ui.CornerFlag.LEFT, # TODO: Not actually working yet OM-53727 }, # Combobox workarounds "Rectangle::combobox": { # TODO: remove when ComboBox can have a border "background_color": cl.field_bg, "border_radius": fl.border_radius, "border_color": cl.btn_border, "border_width": fl.border_width, }, "Rectangle::combobox2": { # TODO: remove when ComboBox can have a border "border_radius": fl.border_radius, "border_color": cl.btn_border, "border_width": fl.border_width, }, "ComboBox::dropdown_menu": { "color": cl.combobox_label_text, # label color "padding_height": 1.25, "margin": 2, "background_color": cl.field_bg, "border_radius": fl.border_radius, "font_size": fl.field_text_font_size, "secondary_color": cl.transparent, # button background color }, "Rectangle::combobox_icon_cover": {"background_color": cl.field_bg} }
8,207
Python
37
121
0.631047
stephenT0/funkyboy-anamorphic-effects/exts/funkyboy.anamorphic.effects/funkyboy/anamorphic/effects/extension.py
import omni.ext import omni.ui as ui from .window import AnamorphicEffectsWindow, WINDOW_TITLE class FunkyboyAnamorphicEffectsExtension(omni.ext.IExt): def on_startup(self, ext_id): self._menu_path = f"Window/{WINDOW_TITLE}" self._window = AnamorphicEffectsWindow(WINDOW_TITLE, self._menu_path) self._menu = omni.kit.ui.get_editor_menu().add_item(self._menu_path, self._on_menu_click, True) def on_shutdown(self): omni.kit.ui.get_editor_menu().remove_item(self._menu) if self._window is not None: self._window.destroy() self._window = None def _on_menu_click(self, menu, toggled): if toggled: if self._window is None: self._window = AnamorphicEffectsWindow(WINDOW_TITLE, self._menu_path) else: self._window.show() else: if self._window is not None: self._window.hide()
952
Python
31.862068
103
0.611345
stephenT0/funkyboy-anamorphic-effects/exts/funkyboy.anamorphic.effects/funkyboy/anamorphic/effects/__init__.py
from .extension import *
25
Python
11.999994
24
0.76
stephenT0/funkyboy-anamorphic-effects/exts/funkyboy.anamorphic.effects/funkyboy/anamorphic/effects/style1.py
import omni.ui as ui from omni.ui import color as cl style1 = { # "RadioButton": { # "border_width": 0.5, # "border_radius": 0.0, # "margin": 5.0, # "padding": 5.0 # }, "RadioButton::On:checked": { "background_color": 0xFF00B976, "border_color": 0xFF272727, }, "RadioButton.Label::On": { "color": 0xFFFFFFFF, }, "RadioButton::Off1:checked": { "background_color": 0xFF0000FF, "border_color": 0xFF00B976 }, "Button.Label::Off": { "color": 0xFFFFFFFF }}
573
Python
21.076922
39
0.52007
stephenT0/funkyboy-anamorphic-effects/exts/funkyboy.anamorphic.effects/funkyboy/anamorphic/effects/custom_slider_widget.py
# Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. # __all__ = ["CustomSliderWidget"] from typing import Optional import carb.settings from omni.kit.viewport.window import ViewportWindow import omni.ui as ui from omni.ui import color as cl from omni.ui import constant as fl from .custom_base_widget import CustomBaseWidget NUM_FIELD_WIDTH = 500 SLIDER_WIDTH = ui.Percent(100) FIELD_HEIGHT = 22 # TODO: Once Field padding is fixed, this should be 18 SPACING = 4 TEXTURE_NAME = "slider_bg_texture" class CustomSliderWidget(CustomBaseWidget): """A compound widget for scalar slider input, which contains a Slider and a Field with text input next to it. """ def __init__(self, model: ui.AbstractItemModel = None, num_type: str = "float", min=0.0, max=1.0, default_val=0.0, display_range: bool = False, **kwargs): self.__slider: Optional[ui.AbstractSlider] = None self.__numberfield: Optional[ui.AbstractField] = None self.__min = min self.__max = max self.__default_val = default_val self.__num_type = num_type self.__display_range = display_range # Call at the end, rather than start, so build_fn runs after all the init stuff CustomBaseWidget.__init__(self, model=model, **kwargs) def destroy(self): CustomBaseWidget.destroy() self.__slider = None self.__numberfield = None @property def model(self) -> Optional[ui.AbstractItemModel]: """The widget's model""" if self.__slider: return self.__slider.model @model.setter def model(self, value: ui.AbstractItemModel): """The widget's model""" self.__slider.model = value self.__numberfield.model = value def _on_value_changed(self, *args): """Set revert_img to correct state.""" if self.__num_type == "float": index = self.model.as_float else: index = self.model.as_int self.revert_img.enabled = self.__default_val != index def _restore_default(self): """Restore the default value.""" if self.revert_img.enabled: self.model.set_value(self.__default_val) self.revert_img.enabled = False def _build_display_range(self): """Builds just the tiny text range under the slider.""" with ui.HStack(): ui.Label(str(self.__min), alignment=ui.Alignment.LEFT, name="range_text") if self.__min < 0 and self.__max > 0: # Add middle value (always 0), but it may or may not be centered, # depending on the min/max values. total_range = self.__max - self.__min # subtract 25% to account for end number widths left = 100 * abs(0 - self.__min) / total_range - 25 right = 100 * abs(self.__max - 0) / total_range - 25 ui.Spacer(width=ui.Percent(left)) ui.Label("0", alignment=ui.Alignment.CENTER, name="range_text") ui.Spacer(width=ui.Percent(right)) else: ui.Spacer() ui.Label(str(self.__max), alignment=ui.Alignment.RIGHT, name="range_text") ui.Spacer(height=.75) def _build_body(self): """Main meat of the widget. Draw the Slider, display range text, Field, and set up callbacks to keep them updated. """ with ui.HStack(spacing=0): # the user provided a list of default values with ui.VStack(spacing=3, width=ui.Fraction(3)): with ui.ZStack(): # Put texture image here, with rounded corners, then make slider # bg be fully transparent, and fg be gray and partially transparent with ui.Frame(width=SLIDER_WIDTH, height=FIELD_HEIGHT, horizontal_clipping=True): # Spacing is negative because "tileable" texture wasn't # perfectly tileable, so that adds some overlap to line up better. with ui.HStack(spacing=-12): for i in range(50): # tiling the texture ui.Image(name=TEXTURE_NAME, fill_policy=ui.FillPolicy.PRESERVE_ASPECT_CROP, width=50,) slider_cls = ( ui.FloatSlider if self.__num_type == "float" else ui.IntSlider ) self.__slider = slider_cls( height=FIELD_HEIGHT, min=self.__min, max=self.__max, name="attr_slider" ) if self.__display_range: self._build_display_range() with ui.VStack(width=ui.Fraction(1)): model = self.__slider.model model.set_value(self.__default_val) field_cls = ( ui.FloatField if self.__num_type == "float" else ui.IntField ) # Note: This is a hack to allow for text to fill the Field space more, as there was a bug # with Field padding. It is fixed, and will be available in the next release of Kit. with ui.ZStack(): # height=FIELD_HEIGHT-1 to account for the border, so the field isn't # slightly taller than the slider ui.Rectangle( style_type_name_override="Field", name="attr_field", height=FIELD_HEIGHT - 1 ) with ui.HStack(height=0): ui.Spacer(width=2) self.__numberfield = field_cls( model, height=0, style={ "background_color": cl.transparent, "border_color": cl.transparent, "padding": 4, "font_size": fl.field_text_font_size, }, ) if self.__display_range: ui.Spacer() model.add_value_changed_fn(self._on_value_changed) class AnaBokehSliderWidget(CustomBaseWidget): """A compound widget for scalar slider input, which contains a Slider and a Field with text input next to it. """ def __init__(self, model: ui.AbstractItemModel = None, num_type: str = "float", min=0.0, max=1.0, default_val=0.5, display_range: bool = False, **kwargs): self.__slider: Optional[ui.AbstractSlider] = None self.__numberfield: Optional[ui.AbstractField] = None self.__min = min self.__max = max self.__default_val = default_val self.__num_type = num_type self.__display_range = display_range # Call at the end, rather than start, so build_fn runs after all the init stuff CustomBaseWidget.__init__(self, model=model, **kwargs) def destroy(self): CustomBaseWidget.destroy() self.__slider = None self.__numberfield = None @property def model(self) -> Optional[ui.AbstractItemModel]: """The widget's model""" if self.__slider: return self.__slider.model @model.setter def model(self, value: ui.AbstractItemModel): """The widget's model""" self.__slider.model = value self.__numberfield.model = value def _on_value_changed(self, *args): """Set revert_img to correct state.""" if self.__num_type == "float": index = self.model.as_float else: index = self.model.as_int self.revert_img.enabled = self.__default_val != index def _restore_default(self): """Restore the default value.""" if self.revert_img.enabled: self.model.set_value(self.__default_val) self.revert_img.enabled = False def _build_display_range(self): """Builds just the tiny text range under the slider.""" with ui.HStack(): ui.Label(str(self.__min), alignment=ui.Alignment.LEFT, name="range_text") if self.__min < 0 and self.__max > 0: # Add middle value (always 0), but it may or may not be centered, # depending on the min/max values. total_range = self.__max - self.__min # subtract 25% to account for end number widths left = 100 * abs(0 - self.__min) / total_range - 25 right = 100 * abs(self.__max - 0) / total_range - 25 ui.Spacer(width=ui.Percent(left)) ui.Label("0", alignment=ui.Alignment.CENTER, name="range_text") ui.Spacer(width=ui.Percent(right)) else: ui.Spacer() ui.Label(str(self.__max), alignment=ui.Alignment.RIGHT, name="range_text") ui.Spacer(height=.75) def _build_body(self): """Main meat of the widget. Draw the Slider, display range text, Field, and set up callbacks to keep them updated. """ with ui.HStack(spacing=0): # the user provided a list of default values with ui.VStack(spacing=3, width=ui.Fraction(3)): self._slider_model_anisotropy = ui.SimpleFloatModel() current_anisotropy = 0.5 with ui.ZStack(): # Put texture image here, with rounded corners, then make slider # bg be fully transparent, and fg be gray and partially transparent with ui.Frame(width=SLIDER_WIDTH, height=FIELD_HEIGHT, horizontal_clipping=True): # Spacing is negative because "tileable" texture wasn't # perfectly tileable, so that adds some overlap to line up better. with ui.HStack(spacing=-12): for i in range(50): # tiling the texture ui.Image(name=TEXTURE_NAME, fill_policy=ui.FillPolicy.PRESERVE_ASPECT_CROP, width=50,) slider_cls = ( ui.FloatSlider if self.__num_type == "float" else ui.IntSlider ) self.__slider = slider_cls(self._slider_model_anisotropy, min=0.0, max=1.0, height=FIELD_HEIGHT, name="attr_slider") if self.__display_range: self._build_display_range() def update_anisotropy(value): current_anisotropy = value settings = carb.settings.get_settings() settings.set("/rtx/post/dof/anisotropy", float(current_anisotropy)) if self._slider_model_anisotropy: self._slider_subscription_anisotropy = None self._slider_model_anisotropy.as_float = current_anisotropy self._slider_subscription_anisotropy = self._slider_model_anisotropy.subscribe_value_changed_fn( lambda model: update_anisotropy(model.as_float)) with ui.VStack(width=ui.Fraction(1)): model = self.__slider.model model.set_value(self.__default_val) field_cls = ( ui.FloatField if self.__num_type == "float" else ui.IntField ) # Note: This is a hack to allow for text to fill the Field space more, as there was a bug # with Field padding. It is fixed, and will be available in the next release of Kit. with ui.ZStack(): # height=FIELD_HEIGHT-1 to account for the border, so the field isn't # slightly taller than the slider ui.Rectangle( style_type_name_override="Field", name="attr_field", height=FIELD_HEIGHT - 1 ) with ui.HStack(height=0): ui.Spacer(width=10) self.__numberfield = field_cls( model, height=0, style={ "background_color": cl.transparent, "border_color": cl.transparent, "padding": 4, "font_size": fl.field_text_font_size, }, ) if self.__display_range: ui.Spacer() model.add_value_changed_fn(self._on_value_changed) class LFlareSliderWidget(CustomBaseWidget): """A compound widget for scalar slider input, which contains a Slider and a Field with text input next to it. """ def __init__(self, model: ui.AbstractItemModel = None, num_type: str = "float", min=0.0, max=135.0, default_val=60, display_range: bool = False, **kwargs): self.__slider: Optional[ui.AbstractSlider] = None self.__numberfield: Optional[ui.AbstractField] = None self.__min = min self.__max = max self.__default_val = default_val self.__num_type = num_type self.__display_range = display_range # Call at the end, rather than start, so build_fn runs after all the init stuff CustomBaseWidget.__init__(self, model=model, **kwargs) def destroy(self): CustomBaseWidget.destroy() self.__slider = None self.__numberfield = None @property def model(self) -> Optional[ui.AbstractItemModel]: """The widget's model""" if self.__slider: return self.__slider.model @model.setter def model(self, value: ui.AbstractItemModel): """The widget's model""" self.__slider.model = value self.__numberfield.model = value def _on_value_changed(self, *args): """Set revert_img to correct state.""" if self.__num_type == "float": index = self.model.as_float else: index = self.model.as_int self.revert_img.enabled = self.__default_val != index def _restore_default(self): """Restore the default value.""" if self.revert_img.enabled: self.model.set_value(self.__default_val) self.revert_img.enabled = False def _build_display_range(self): """Builds just the tiny text range under the slider.""" with ui.HStack(): ui.Label(str(self.__min), alignment=ui.Alignment.LEFT, name="range_text") if self.__min < 0 and self.__max > 0: # Add middle value (always 0), but it may or may not be centered, # depending on the min/max values. total_range = self.__max - self.__min # subtract 25% to account for end number widths left = 100 * abs(0 - self.__min) / total_range - 25 right = 100 * abs(self.__max - 0) / total_range - 25 ui.Spacer(width=ui.Percent(left)) ui.Label("0", alignment=ui.Alignment.CENTER, name="range_text") ui.Spacer(width=ui.Percent(right)) else: ui.Spacer() ui.Label(str(self.__max), alignment=ui.Alignment.RIGHT, name="range_text") ui.Spacer(height=.75) def _build_body(self): """Main meat of the widget. Draw the Slider, display range text, Field, and set up callbacks to keep them updated. """ with ui.HStack(spacing=0): # the user provided a list of default values with ui.VStack(spacing=3, width=ui.Fraction(3)): self._slider_model_sensor_size = ui.SimpleFloatModel() current_sensor_size = 60.0 with ui.ZStack(): # Put texture image here, with rounded corners, then make slider # bg be fully transparent, and fg be gray and partially transparent with ui.Frame(width=SLIDER_WIDTH, height=FIELD_HEIGHT, horizontal_clipping=True): # Spacing is negative because "tileable" texture wasn't # perfectly tileable, so that adds some overlap to line up better. with ui.HStack(spacing=-12): for i in range(50): # tiling the texture ui.Image(name=TEXTURE_NAME, fill_policy=ui.FillPolicy.PRESERVE_ASPECT_CROP, width=50,) slider_cls = ( ui.FloatSlider if self.__num_type == "float" else ui.IntSlider ) self.__slider = slider_cls(self._slider_model_sensor_size, min=0.0, max=135.0, height=FIELD_HEIGHT, name="attr_slider") if self.__display_range: self._build_display_range() def update_sensor_size(value): current_sensor_size = value settings = carb.settings.get_settings() settings.set("/rtx/post/lensFlares/sensorDiagonal", float(current_sensor_size)) if self._slider_model_sensor_size: self._slider_subscription_sensor_size = None self._slider_model_sensor_size.as_float = current_sensor_size self._slider_subscription_sensor_size = self._slider_model_sensor_size.subscribe_value_changed_fn( lambda model: update_sensor_size(model.as_float)) with ui.VStack(width=ui.Fraction(1)): model = self.__slider.model model.set_value(self.__default_val) field_cls = ( ui.FloatField if self.__num_type == "float" else ui.IntField ) # Note: This is a hack to allow for text to fill the Field space more, as there was a bug # with Field padding. It is fixed, and will be available in the next release of Kit. with ui.ZStack(): # height=FIELD_HEIGHT-1 to account for the border, so the field isn't # slightly taller than the slider ui.Rectangle( style_type_name_override="Field", name="attr_field", height=FIELD_HEIGHT - 1 ) with ui.HStack(height=0): ui.Spacer(width=10) self.__numberfield = field_cls( model, height=0, style={ "background_color": cl.transparent, "border_color": cl.transparent, "padding": 4, "font_size": fl.field_text_font_size, }, ) if self.__display_range: ui.Spacer() model.add_value_changed_fn(self._on_value_changed) class FlareStretchSliderWidget(CustomBaseWidget): """A compound widget for scalar slider input, which contains a Slider and a Field with text input next to it. """ def __init__(self, model: ui.AbstractItemModel = None, num_type: str = "float", min=0.01, max=15.0, default_val=1.5, display_range: bool = False, **kwargs): self.__slider: Optional[ui.AbstractSlider] = None self.__numberfield: Optional[ui.AbstractField] = None self.__min = min self.__max = max self.__default_val = default_val self.__num_type = num_type self.__display_range = display_range # Call at the end, rather than start, so build_fn runs after all the init stuff CustomBaseWidget.__init__(self, model=model, **kwargs) def destroy(self): CustomBaseWidget.destroy() self.__slider = None self.__numberfield = None @property def model(self) -> Optional[ui.AbstractItemModel]: """The widget's model""" if self.__slider: return self.__slider.model @model.setter def model(self, value: ui.AbstractItemModel): """The widget's model""" self.__slider.model = value self.__numberfield.model = value def _on_value_changed(self, *args): """Set revert_img to correct state.""" if self.__num_type == "float": index = self.model.as_float else: index = self.model.as_int self.revert_img.enabled = self.__default_val != index def _restore_default(self): """Restore the default value.""" if self.revert_img.enabled: self.model.set_value(self.__default_val) self.revert_img.enabled = False def _build_display_range(self): """Builds just the tiny text range under the slider.""" with ui.HStack(): ui.Label(str(self.__min), alignment=ui.Alignment.LEFT, name="range_text") if self.__min < 0 and self.__max > 0: # Add middle value (always 0), but it may or may not be centered, # depending on the min/max values. total_range = self.__max - self.__min # subtract 25% to account for end number widths left = 100 * abs(0 - self.__min) / total_range - 25 right = 100 * abs(self.__max - 0) / total_range - 25 ui.Spacer(width=ui.Percent(left)) ui.Label("0", alignment=ui.Alignment.CENTER, name="range_text") ui.Spacer(width=ui.Percent(right)) else: ui.Spacer() ui.Label(str(self.__max), alignment=ui.Alignment.RIGHT, name="range_text") ui.Spacer(height=.75) def _build_body(self): """Main meat of the widget. Draw the Slider, display range text, Field, and set up callbacks to keep them updated. """ with ui.HStack(spacing=0): # the user provided a list of default values with ui.VStack(spacing=3, width=ui.Fraction(3)): self._slider_model_flare = ui.SimpleFloatModel() current_flare = 1.5 with ui.ZStack(): # Put texture image here, with rounded corners, then make slider # bg be fully transparent, and fg be gray and partially transparent with ui.Frame(width=SLIDER_WIDTH, height=FIELD_HEIGHT, horizontal_clipping=True): # Spacing is negative because "tileable" texture wasn't # perfectly tileable, so that adds some overlap to line up better. with ui.HStack(spacing=-12): for i in range(50): # tiling the texture ui.Image(name=TEXTURE_NAME, fill_policy=ui.FillPolicy.PRESERVE_ASPECT_CROP, width=50,) slider_cls = ( ui.FloatSlider if self.__num_type == "float" else ui.IntSlider ) self.__slider = slider_cls(self._slider_model_flare, min=0.01, max=15.0, height=FIELD_HEIGHT, name="attr_slider") if self.__display_range: self._build_display_range() def update_flare(value): current_flare = value settings = carb.settings.get_settings() settings.set("/rtx/post/lensFlares/sensorAspectRatio", float(current_flare)) if self._slider_model_flare: self._slider_subscription_flare = None self._slider_model_flare.as_float = current_flare self._slider_subscription_flare = self._slider_model_flare.subscribe_value_changed_fn( lambda model: update_flare(model.as_float)) with ui.VStack(width=ui.Fraction(1)): model = self.__slider.model model.set_value(self.__default_val) field_cls = ( ui.FloatField if self.__num_type == "float" else ui.IntField ) # Note: This is a hack to allow for text to fill the Field space more, as there was a bug # with Field padding. It is fixed, and will be available in the next release of Kit. with ui.ZStack(): # height=FIELD_HEIGHT-1 to account for the border, so the field isn't # slightly taller than the slider ui.Rectangle( style_type_name_override="Field", name="attr_field", height=FIELD_HEIGHT - 1 ) with ui.HStack(height=0): ui.Spacer(width=10) self.__numberfield = field_cls( model, height=0, style={ "background_color": cl.transparent, "border_color": cl.transparent, "padding": 4, "font_size": fl.field_text_font_size, }, ) if self.__display_range: ui.Spacer() model.add_value_changed_fn(self._on_value_changed) class BloomIntensitySliderWidget(CustomBaseWidget): """A compound widget for scalar slider input, which contains a Slider and a Field with text input next to it. """ def __init__(self, model: ui.AbstractItemModel = None, num_type: str = "float", min=0.0, max=0.5, default_val=0.1, display_range: bool = False, **kwargs): self.__slider: Optional[ui.AbstractSlider] = None self.__numberfield: Optional[ui.AbstractField] = None self.__min = min self.__max = max self.__default_val = default_val self.__num_type = num_type self.__display_range = display_range # Call at the end, rather than start, so build_fn runs after all the init stuff CustomBaseWidget.__init__(self, model=model, **kwargs) def destroy(self): CustomBaseWidget.destroy() self.__slider = None self.__numberfield = None @property def model(self) -> Optional[ui.AbstractItemModel]: """The widget's model""" if self.__slider: return self.__slider.model @model.setter def model(self, value: ui.AbstractItemModel): """The widget's model""" self.__slider.model = value self.__numberfield.model = value def _on_value_changed(self, *args): """Set revert_img to correct state.""" if self.__num_type == "float": index = self.model.as_float else: index = self.model.as_int self.revert_img.enabled = self.__default_val != index def _restore_default(self): """Restore the default value.""" if self.revert_img.enabled: self.model.set_value(self.__default_val) self.revert_img.enabled = False def _build_display_range(self): """Builds just the tiny text range under the slider.""" with ui.HStack(): ui.Label(str(self.__min), alignment=ui.Alignment.LEFT, name="range_text") if self.__min < 0 and self.__max > 0: # Add middle value (always 0), but it may or may not be centered, # depending on the min/max values. total_range = self.__max - self.__min # subtract 25% to account for end number widths left = 100 * abs(0 - self.__min) / total_range - 25 right = 100 * abs(self.__max - 0) / total_range - 25 ui.Spacer(width=ui.Percent(left)) ui.Label("0", alignment=ui.Alignment.CENTER, name="range_text") ui.Spacer(width=ui.Percent(right)) else: ui.Spacer() ui.Label(str(self.__max), alignment=ui.Alignment.RIGHT, name="range_text") ui.Spacer(height=.75) def _build_body(self): """Main meat of the widget. Draw the Slider, display range text, Field, and set up callbacks to keep them updated. """ with ui.HStack(spacing=0): # the user provided a list of default values with ui.VStack(spacing=3, width=ui.Fraction(3)): self._slider_model_bloom = ui.SimpleFloatModel() current_bloom = 0.1 with ui.ZStack(): # Put texture image here, with rounded corners, then make slider # bg be fully transparent, and fg be gray and partially transparent with ui.Frame(width=SLIDER_WIDTH, height=FIELD_HEIGHT, horizontal_clipping=True): # Spacing is negative because "tileable" texture wasn't # perfectly tileable, so that adds some overlap to line up better. with ui.HStack(spacing=-12): for i in range(50): # tiling the texture ui.Image(name=TEXTURE_NAME, fill_policy=ui.FillPolicy.PRESERVE_ASPECT_CROP, width=50,) slider_cls = ( ui.FloatSlider if self.__num_type == "float" else ui.IntSlider ) self.__slider = slider_cls(self._slider_model_bloom, min=0.0, max=0.5, height=FIELD_HEIGHT, name="attr_slider") if self.__display_range: self._build_display_range() def update_bloom(value): current_bloom = value settings = carb.settings.get_settings() settings.set("/rtx/post/lensFlares/flareScale", float(current_bloom)) if self._slider_model_bloom: self._slider_subscription_bloom = None self._slider_model_bloom.as_float = current_bloom self._slider_subscription_bloom = self._slider_model_bloom.subscribe_value_changed_fn( lambda model: update_bloom(model.as_float)) with ui.VStack(width=ui.Fraction(1)): model = self.__slider.model model.set_value(self.__default_val) field_cls = ( ui.FloatField if self.__num_type == "float" else ui.IntField ) # Note: This is a hack to allow for text to fill the Field space more, as there was a bug # with Field padding. It is fixed, and will be available in the next release of Kit. with ui.ZStack(): # height=FIELD_HEIGHT-1 to account for the border, so the field isn't # slightly taller than the slider ui.Rectangle( style_type_name_override="Field", name="attr_field", height=FIELD_HEIGHT - 1 ) with ui.HStack(height=0): ui.Spacer(width=10) self.__numberfield = field_cls( model, height=0, style={ "background_color": cl.transparent, "border_color": cl.transparent, "padding": 4, "font_size": fl.field_text_font_size, }, ) if self.__display_range: ui.Spacer() model.add_value_changed_fn(self._on_value_changed) class LensBladesSliderWidget(CustomBaseWidget): """A compound widget for scalar slider input, which contains a Slider and a Field with text input next to it. """ def __init__(self, model: ui.AbstractItemModel = None, num_type: str = "float", min=3, max=11, default_val=6, display_range: bool = False, **kwargs): self.__slider: Optional[ui.AbstractSlider] = None self.__numberfield: Optional[ui.AbstractField] = None self.__min = min self.__max = max self.__default_val = default_val self.__num_type = num_type self.__display_range = display_range # Call at the end, rather than start, so build_fn runs after all the init stuff CustomBaseWidget.__init__(self, model=model, **kwargs) def destroy(self): CustomBaseWidget.destroy() self.__slider = None self.__numberfield = None @property def model(self) -> Optional[ui.AbstractItemModel]: """The widget's model""" if self.__slider: return self.__slider.model @model.setter def model(self, value: ui.AbstractItemModel): """The widget's model""" self.__slider.model = value self.__numberfield.model = value def _on_value_changed(self, *args): """Set revert_img to correct state.""" if self.__num_type == "float": index = self.model.as_float else: index = self.model.as_int self.revert_img.enabled = self.__default_val != index def _restore_default(self): """Restore the default value.""" if self.revert_img.enabled: self.model.set_value(self.__default_val) self.revert_img.enabled = False def _build_display_range(self): """Builds just the tiny text range under the slider.""" with ui.HStack(): ui.Label(str(self.__min), alignment=ui.Alignment.LEFT, name="range_text") if self.__min < 0 and self.__max > 0: # Add middle value (always 0), but it may or may not be centered, # depending on the min/max values. total_range = self.__max - self.__min # subtract 25% to account for end number widths left = 100 * abs(0 - self.__min) / total_range - 25 right = 100 * abs(self.__max - 0) / total_range - 25 ui.Spacer(width=ui.Percent(left)) ui.Label("0", alignment=ui.Alignment.CENTER, name="range_text") ui.Spacer(width=ui.Percent(right)) else: ui.Spacer() ui.Label(str(self.__max), alignment=ui.Alignment.RIGHT, name="range_text") ui.Spacer(height=.75) def _build_body(self): """Main meat of the widget. Draw the Slider, display range text, Field, and set up callbacks to keep them updated. """ with ui.HStack(spacing=0): # the user provided a list of default values with ui.VStack(spacing=3, width=ui.Fraction(3)): self._slider_model_blades = ui.SimpleIntModel() current_blades = 6 with ui.ZStack(): # Put texture image here, with rounded corners, then make slider # bg be fully transparent, and fg be gray and partially transparent with ui.Frame(width=SLIDER_WIDTH, height=FIELD_HEIGHT, horizontal_clipping=True): # Spacing is negative because "tileable" texture wasn't # perfectly tileable, so that adds some overlap to line up better. with ui.HStack(spacing=-12): for i in range(50): # tiling the texture ui.Image(name=TEXTURE_NAME, fill_policy=ui.FillPolicy.PRESERVE_ASPECT_CROP, width=50,) slider_cls = ( ui.IntSlider if self.__num_type == "float" else ui.IntSlider ) self.__slider = slider_cls(self._slider_model_blades, min=3, max=11, height=FIELD_HEIGHT, name="attr_slider") if self.__display_range: self._build_display_range() def update_blades(value): current_blades = value settings = carb.settings.get_settings() settings.set("/rtx/post/lensFlares/blades", int(current_blades)) if self._slider_model_blades: self._slider_subscription_blades = None self._slider_model_blades.as_float = current_blades self._slider_subscription_blades = self._slider_model_blades.subscribe_value_changed_fn( lambda model: update_blades(model.as_int)) with ui.VStack(width=ui.Fraction(1)): model = self.__slider.model model.set_value(self.__default_val) field_cls = ( ui.FloatField if self.__num_type == "float" else ui.IntField ) # Note: This is a hack to allow for text to fill the Field space more, as there was a bug # with Field padding. It is fixed, and will be available in the next release of Kit. with ui.ZStack(): # height=FIELD_HEIGHT-1 to account for the border, so the field isn't # slightly taller than the slider ui.Rectangle( style_type_name_override="Field", name="attr_field", height=FIELD_HEIGHT - 1 ) with ui.HStack(height=0): ui.Spacer(width=10) self.__numberfield = field_cls( model, height=0, style={ "background_color": cl.transparent, "border_color": cl.transparent, "padding": 4, "font_size": fl.field_text_font_size, }, ) if self.__display_range: ui.Spacer() model.add_value_changed_fn(self._on_value_changed) class BladeRotationWidget(CustomBaseWidget): """A compound widget for scalar slider input, which contains a Slider and a Field with text input next to it. """ def __init__(self, model: ui.AbstractItemModel = None, num_type: str = "float", min=0.0, max=100.0, default_val=50.0, display_range: bool = False, **kwargs): self.__slider: Optional[ui.AbstractSlider] = None self.__numberfield: Optional[ui.AbstractField] = None self.__min = min self.__max = max self.__default_val = default_val self.__num_type = num_type self.__display_range = display_range # Call at the end, rather than start, so build_fn runs after all the init stuff CustomBaseWidget.__init__(self, model=model, **kwargs) def destroy(self): CustomBaseWidget.destroy() self.__slider = None self.__numberfield = None @property def model(self) -> Optional[ui.AbstractItemModel]: """The widget's model""" if self.__slider: return self.__slider.model @model.setter def model(self, value: ui.AbstractItemModel): """The widget's model""" self.__slider.model = value self.__numberfield.model = value def _on_value_changed(self, *args): """Set revert_img to correct state.""" if self.__num_type == "float": index = self.model.as_float else: index = self.model.as_int self.revert_img.enabled = self.__default_val != index def _restore_default(self): """Restore the default value.""" if self.revert_img.enabled: self.model.set_value(self.__default_val) self.revert_img.enabled = False def _build_display_range(self): """Builds just the tiny text range under the slider.""" with ui.HStack(): ui.Label(str(self.__min), alignment=ui.Alignment.LEFT, name="range_text") if self.__min < 0 and self.__max > 0: # Add middle value (always 0), but it may or may not be centered, # depending on the min/max values. total_range = self.__max - self.__min # subtract 25% to account for end number widths left = 100 * abs(0 - self.__min) / total_range - 25 right = 100 * abs(self.__max - 0) / total_range - 25 ui.Spacer(width=ui.Percent(left)) ui.Label("0", alignment=ui.Alignment.CENTER, name="range_text") ui.Spacer(width=ui.Percent(right)) else: ui.Spacer() ui.Label(str(self.__max), alignment=ui.Alignment.RIGHT, name="range_text") ui.Spacer(height=.75) def _build_body(self): """Main meat of the widget. Draw the Slider, display range text, Field, and set up callbacks to keep them updated. """ with ui.HStack(spacing=0): # the user provided a list of default values with ui.VStack(spacing=3, width=ui.Fraction(3)): self._slider_model_blade_rotation = ui.SimpleFloatModel() current_blade_rotation = 50.0 with ui.ZStack(): # Put texture image here, with rounded corners, then make slider # bg be fully transparent, and fg be gray and partially transparent with ui.Frame(width=SLIDER_WIDTH, height=FIELD_HEIGHT, horizontal_clipping=True): # Spacing is negative because "tileable" texture wasn't # perfectly tileable, so that adds some overlap to line up better. with ui.HStack(spacing=-12): for i in range(50): # tiling the texture ui.Image(name=TEXTURE_NAME, fill_policy=ui.FillPolicy.PRESERVE_ASPECT_CROP, width=50,) slider_cls = ( ui.FloatSlider if self.__num_type == "float" else ui.IntSlider ) self.__slider = slider_cls(self._slider_model_blade_rotation, min=0.0, max=100.0, height=FIELD_HEIGHT, name="attr_slider") if self.__display_range: self._build_display_range() def update_blade_rotation(value): current_blade_rotation = value settings = carb.settings.get_settings() settings.set("/rtx/post/lensFlares/apertureRotation", float(current_blade_rotation)) if self._slider_model_blade_rotation: self._slider_subscription_blade_rotation = None self._slider_model_blade_rotation.as_float = current_blade_rotation self._slider_subscription_blade_rotatation = self._slider_model_blade_rotation.subscribe_value_changed_fn( lambda model: update_blade_rotation(model.as_float)) with ui.VStack(width=ui.Fraction(1)): model = self.__slider.model model.set_value(self.__default_val) field_cls = ( ui.FloatField if self.__num_type == "float" else ui.IntField ) # Note: This is a hack to allow for text to fill the Field space more, as there was a bug # with Field padding. It is fixed, and will be available in the next release of Kit. with ui.ZStack(): # height=FIELD_HEIGHT-1 to account for the border, so the field isn't # slightly taller than the slider ui.Rectangle( style_type_name_override="Field", name="attr_field", height=FIELD_HEIGHT - 1 ) with ui.HStack(height=0): ui.Spacer(width=10) self.__numberfield = field_cls( model, height=0, style={ "background_color": cl.transparent, "border_color": cl.transparent, "padding": 4, "font_size": fl.field_text_font_size, }, ) if self.__display_range: ui.Spacer() model.add_value_changed_fn(self._on_value_changed) class CustomRatioSliderWidget(CustomBaseWidget): """A compound widget for scalar slider input, which contains a Slider and a Field with text input next to it. """ def __init__(self, model: ui.AbstractItemModel = None, num_type: str = "float", min=0.5, max=4.5, default_val=2.39, display_range: bool = False, **kwargs): self.__slider: Optional[ui.AbstractSlider] = None self.__numberfield: Optional[ui.AbstractField] = None self.__min = min self.__max = max self.__default_val = default_val self.__num_type = num_type self.__display_range = display_range # Call at the end, rather than start, so build_fn runs after all the init stuff CustomBaseWidget.__init__(self, model=model, **kwargs) def destroy(self): CustomBaseWidget.destroy() self.__slider = None self.__numberfield = None @property def model(self) -> Optional[ui.AbstractItemModel]: """The widget's model""" if self.__slider: return self.__slider.model @model.setter def model(self, value: ui.AbstractItemModel): """The widget's model""" self.__slider.model = value self.__numberfield.model = value def _on_value_changed(self, *args): """Set revert_img to correct state.""" if self.__num_type == "float": index = self.model.as_float else: index = self.model.as_int self.revert_img.enabled = self.__default_val != index def _restore_default(self): """Restore the default value.""" if self.revert_img.enabled: self.model.set_value(self.__default_val) self.revert_img.enabled = False def _build_display_range(self): """Builds just the tiny text range under the slider.""" with ui.HStack(): ui.Label(str(self.__min), alignment=ui.Alignment.LEFT, name="range_text") if self.__min < 0 and self.__max > 0: # Add middle value (always 0), but it may or may not be centered, # depending on the min/max values. total_range = self.__max - self.__min # subtract 25% to account for end number widths left = 100 * abs(0 - self.__min) / total_range - 25 right = 100 * abs(self.__max - 0) / total_range - 25 ui.Spacer(width=ui.Percent(left)) ui.Label("0", alignment=ui.Alignment.CENTER, name="range_text") ui.Spacer(width=ui.Percent(right)) else: ui.Spacer() ui.Label(str(self.__max), alignment=ui.Alignment.RIGHT, name="range_text") ui.Spacer(height=.75) def _build_body(self): """Main meat of the widget. Draw the Slider, display range text, Field, and set up callbacks to keep them updated. """ with ui.HStack(spacing=0): # the user provided a list of default values with ui.VStack(spacing=3, width=ui.Fraction(3)): self._model_ratio_width = ui.SimpleFloatModel() current_ratio_width = 2.39 with ui.ZStack(): field = ui.FloatField(self._model_ratio_width, height=15, width=35) # Put texture image here, with rounded corners, then make slider # bg be fully transparent, and fg be gray and partially transparent with ui.Frame(width=SLIDER_WIDTH, height=FIELD_HEIGHT, horizontal_clipping=True): # Spacing is negative because "tileable" texture wasn't # perfectly tileable, so that adds some overlap to line up better. with ui.HStack(spacing=-12): for i in range(5): # tiling the texture ui.Image(name=TEXTURE_NAME, fill_policy=ui.FillPolicy.PRESERVE_ASPECT_CROP, width=50,) slider_cls = ( ui.FloatSlider if self.__num_type == "float" else ui.IntSlider ) self.__slider = slider_cls(model=field.model, min=0.5, max=4.5, name="attr_slider") if self.__display_range: self._build_display_range() def update_ratio_width(value): self.current_ratio_width = value active_window = ViewportWindow.active_window viewport_api = active_window.viewport_api texture_res = viewport_api.get_texture_resolution() width = texture_res[0] height = width/self.current_ratio_width viewport_api.resolution = (width,height) if self._model_ratio_width: self._slider_subscription_ratio_width = None self._model_ratio_width.as_float = current_ratio_width self._slider_subscription_ratio_width = self._model_ratio_width.subscribe_value_changed_fn( lambda model: update_ratio_width(model.as_float)) with ui.VStack(width=ui.Fraction(1)): model = self.__slider.model model.set_value(self.__default_val) field_cls = ( ui.FloatField if self.__num_type == "float" else ui.IntField ) # Note: This is a hack to allow for text to fill the Field space more, as there was a bug # with Field padding. It is fixed, and will be available in the next release of Kit. with ui.ZStack(): # height=FIELD_HEIGHT-1 to account for the border, so the field isn't # slightly taller than the slider ui.Rectangle( style_type_name_override="Field", name="attr_field", height=FIELD_HEIGHT - 1 ) with ui.HStack(height=0): ui.Spacer(width=10) self.__numberfield = field_cls( model, height=0, style={ "background_color": cl.transparent, "border_color": cl.transparent, "padding": 4, "font_size": fl.field_text_font_size, }, ) if self.__display_range: ui.Spacer() model.add_value_changed_fn(self._on_value_changed)
53,968
Python
42.664239
142
0.510951
stephenT0/funkyboy-anamorphic-effects/exts/funkyboy.anamorphic.effects/funkyboy/anamorphic/effects/custom_base_widget.py
# Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. # __all__ = ["CustomBaseWidget"] from typing import Optional import omni.ui as ui from .style import ATTR_LABEL_WIDTH class CustomBaseWidget: """The base widget for custom widgets that follow the pattern of Head (Label), Body Widgets, Tail Widget""" def __init__(self, *args, model=None, **kwargs): self.existing_model: Optional[ui.AbstractItemModel] = kwargs.pop("model", None) self.revert_img = None self.__attr_label: Optional[str] = kwargs.pop("label", "") self.__frame = ui.Frame() with self.__frame: self._build_fn() def destroy(self): self.existing_model = None self.revert_img = None self.__attr_label = None self.__frame = None def __getattr__(self, attr): """Pretend it's self.__frame, so we have access to width/height and callbacks. """ return getattr(self.__frame, attr) def _build_head(self): """Build the left-most piece of the widget line (label in this case)""" ui.Label( self.__attr_label, name="attribute_name", width=ATTR_LABEL_WIDTH ) def _build_body(self): """Build the custom part of the widget. Most custom widgets will override this method, as it is where the meat of the custom widget is. """ ui.Spacer() def _build_tail(self): """Build the right-most piece of the widget line. In this case, we have a Revert Arrow button at the end of each widget line. """ with ui.HStack(width=0): ui.Spacer(width=5) with ui.VStack(height=0): ui.Spacer(height=3) self.revert_img = ui.Image( name="revert_arrow", fill_policy=ui.FillPolicy.PRESERVE_ASPECT_FIT, width=12, height=13, enabled=False, ) ui.Spacer(width=5) # call back for revert_img click, to restore the default value self.revert_img.set_mouse_pressed_fn( lambda x, y, b, m: self._restore_default()) def _build_fn(self): """Puts the 3 pieces together.""" with ui.HStack(): self._build_head() self._build_body() self._build_tail()
2,781
Python
32.518072
87
0.591514
stephenT0/funkyboy-anamorphic-effects/exts/funkyboy.anamorphic.effects/funkyboy/anamorphic/effects/window.py
import omni.ui as ui import carb.settings from omni.kit.viewport.window import ViewportWindow from pathlib import Path from .custom_slider_widget import AnaBokehSliderWidget, LFlareSliderWidget, FlareStretchSliderWidget, BloomIntensitySliderWidget, LensBladesSliderWidget, BladeRotationWidget from .style import julia_modeler_style, ATTR_LABEL_WIDTH, BLOCK_HEIGHT from .style1 import style1 WINDOW_TITLE = "Anamorphic Effects" MY_IMAGE = Path(__file__).parent.parent.parent.parent / "data" / "AE.png" LABEL_WIDTH = 120 SPACING = 4 options = ["2.39:1 Cinemascope", "2.35:1 Scope", "2.20:1 Todd-AO", "2.76:1 Panavision Ultra-70", "2:1 2x Anamorphic", "1.77:1 Standard Widescreen (16x9)", "1.33:1 Standard Television (4x3)", "0.56:1 Mobile (9x16)", "1:1 Square"] NUM_FIELD_WIDTH = 500 SLIDER_WIDTH = ui.Percent(100) FIELD_HEIGHT = 22 SPACING = 4 TEXTURE_NAME = "slider_bg_texture" class AnamorphicEffectsWindow(ui.Window): def __init__(self, title: str, delegate=None, **kwargs,): self.__label_width = ATTR_LABEL_WIDTH super().__init__(title, **kwargs, width=375, height=425) self.frame.style = julia_modeler_style self.frame.set_build_fn(self._build_fn) ui.dock_window_in_window("Anamorphic Effects", "Property", ui.DockPosition.SAME, 0.3) def destroy(self): super().destroy() def label_width(self): return self.__label_width def _build_collapsable_header(self, collapsed, title): """Build a custom title of CollapsableFrame""" with ui.VStack(): ui.Spacer(height=8) with ui.HStack(): ui.Label(title, name="collapsable_name") if collapsed: image_name = "collapsable_opened" else: image_name = "collapsable_closed" ui.Image(name=image_name, width=10, height=10) ui.Spacer(height=8) ui.Line(style_type_name_override="HeaderLine") def _build_fn(self): def effect_off(): active_window = ViewportWindow.active_window viewport_api = active_window.viewport_api texture_res = viewport_api.get_texture_resolution() width = texture_res[0] height = ((width/16)*9) viewport_api.resolution = (width,height) settings = carb.settings.get_settings() settings.set("/rtx/post/dof/anisotropy", 0.0) settings.set("/rtx/post/lensFlares/enabled", False) self.aspect_frame.collapsed = True self.lens_frame.collapsed = True def effect_on(): active_window = ViewportWindow.active_window viewport_api = active_window.viewport_api texture_res = viewport_api.get_texture_resolution() first = texture_res[0] height = first/2.39 viewport_api.resolution = (first,height) settings = carb.settings.get_settings() settings.set("/rtx/post/dof/anisotropy", 0.5) settings.set("/rtx/post/lensFlares/flareScale", 0.1) settings.set("/rtx/post/lensFlares/enabled", True) settings.set("/rtx/post/lensFlares/sensorAspectRatio", 1.5) settings.set("/rtx/post/lensFlares/blades", 3) self.aspect_frame.collapsed = False self.lens_frame.collapsed = False def combo_changed(item_model: ui.AbstractItemModel, item: ui.AbstractItem): value_model = item_model.get_item_value_model(item) current_index = value_model.as_int option = options[current_index] if option == "2.39:1 Cinemascope": active_window = ViewportWindow.active_window viewport_api = active_window.viewport_api texture_res = viewport_api.get_texture_resolution() width = texture_res[0] height = width/2.39 viewport_api.resolution = (width,height) self._model_ratio_width.set_value(2.39) if option == "2.35:1 Scope": active_window = ViewportWindow.active_window viewport_api = active_window.viewport_api texture_res = viewport_api.get_texture_resolution() width = texture_res[0] height = width/2.35 viewport_api.resolution = (width,height) self._model_ratio_width.set_value(2.35) if option == "2.20:1 Todd-AO": active_window = ViewportWindow.active_window viewport_api = active_window.viewport_api texture_res = viewport_api.get_texture_resolution() width = texture_res[0] height = width/2.20 viewport_api.resolution = (width,height) self._model_ratio_width.set_value(2.20) if option == "2.76:1 Panavision Ultra-70": active_window = ViewportWindow.active_window viewport_api = active_window.viewport_api texture_res = viewport_api.get_texture_resolution() width = texture_res[0] height = width/1.76 viewport_api.resolution = (width,height) self._model_ratio_width.set_value(2.76) if option == "2:1 2x Anamorphic": active_window = ViewportWindow.active_window viewport_api = active_window.viewport_api texture_res = viewport_api.get_texture_resolution() width = texture_res[0] height = width/2 viewport_api.resolution = (width,height) self._model_ratio_width.set_value(2.1) if option == "1.77:1 Standard Widescreen (16x9)": active_window = ViewportWindow.active_window viewport_api = active_window.viewport_api texture_res = viewport_api.get_texture_resolution() width = texture_res[0] height = ((width/16)*9) viewport_api.resolution = (width,height) self._model_ratio_width.set_value(1.77) if option == "1.33:1 Standard Television (4x3)": active_window = ViewportWindow.active_window viewport_api = active_window.viewport_api texture_res = viewport_api.get_texture_resolution() width = texture_res[0] height = width/1.33 viewport_api.resolution = (width,height) self._model_ratio_width.set_value(1.33) if option == "0.56:1 Mobile (9x16)": active_window = ViewportWindow.active_window viewport_api = active_window.viewport_api texture_res = viewport_api.get_texture_resolution() width = texture_res[0] height = ((width/9)*16) viewport_api.resolution = (width,height) self._model_ratio_width.set_value(0.56) if option == "1:1 Square": active_window = ViewportWindow.active_window viewport_api = active_window.viewport_api texture_res = viewport_api.get_texture_resolution() width = texture_res[0] height = width viewport_api.resolution = (width,height) self._model_ratio_width.set_value(1.0) with ui.ScrollingFrame(): with ui.VStack(height=0): with ui.HStack(): ui.Spacer(width=55) ui.Image(str(MY_IMAGE), fill_policy=ui.FillPolicy.PRESERVE_ASPECT_FIT, alignment=ui.Alignment.CENTER, height=45,) collection = ui.RadioCollection() with ui.HStack(style=style1): ui.Label("Activate:", width=10, style={"font_size":16}) ui.RadioButton(text ="Off", radio_collection=collection, clicked_fn=effect_off, name="Off") ui.RadioButton(text ="On", radio_collection=collection, clicked_fn=effect_on, name="On") self.aspect_frame = ui.CollapsableFrame("Aspect Ratio".upper(), name="group", build_header_fn=self._build_collapsable_header, collapsed=True) with self.aspect_frame: with ui.VStack(height=0): with ui.HStack(): ui.Label(" Aspect Ratio Preset: ", height=0, width=0) with ui.ZStack(): ui.Rectangle(name="combobox", height=BLOCK_HEIGHT) option_list = options combo_model: ui.AbstractItemModel = ui.ComboBox( 0, *option_list, name="dropdown_menu", height=10 ).model ui.Spacer(width=ui.Percent(10)) self.combo_sub = combo_model.subscribe_item_changed_fn(combo_changed) self._model_ratio_width = ui.SimpleFloatModel() current_ratio_width = 2.39 with ui.HStack(height=0): ui.Spacer(width=5) ui.Label("Custom Ratio: ", height=0, width=0) ui.Spacer(width=10) field = ui.FloatField(self._model_ratio_width, height=15, width=35) ui.Label(":1", height=15, width=15, style={"font_size": 20}) with ui.ZStack(): ui.Rectangle(name="combobox2", height=BLOCK_HEIGHT) ui.FloatSlider(model=field.model, min=0.5, max=4.5, name="attr_slider",) def update_ratio_width(value): self.current_ratio_width = value active_window = ViewportWindow.active_window viewport_api = active_window.viewport_api texture_res = viewport_api.get_texture_resolution() width = texture_res[0] height = width/self.current_ratio_width viewport_api.resolution = (width,height) if self._model_ratio_width: self._slider_subscription_ratio_width = None self._model_ratio_width.as_float = current_ratio_width self._slider_subscription_ratio_width = self._model_ratio_width.subscribe_value_changed_fn( lambda model: update_ratio_width(model.as_float)) self.lens_frame = ui.CollapsableFrame("Lens Effects".upper(), name="group", build_header_fn=self._build_collapsable_header, collapsed=True) with self.lens_frame: with ui.VStack(height=0): with ui.HStack(): ui.Spacer(width=5) ui.Label("Anamorphic Bokeh", height=0, width=0, tooltip="Controls Aniostropy value in Depth of Field Overrides located in the Post Processing menu") ui.Spacer(width=8) AnaBokehSliderWidget() with ui.HStack(): ui.Spacer(width=5) ui.Label("Lens Flare Intensity", height=0, width=0, tooltip="Controls Sensor Diagonal value in FFT Bloom located in the Post Processing menu") ui.Spacer(width=4) LFlareSliderWidget() with ui.HStack(): ui.Spacer(width=5) ui.Label("Lens Flare Stretch", height=0, width=0, tooltip="Controls Sensor Aspect Ratio value in FFT Bloom located in the Post Processing menu") ui.Spacer(width=13) FlareStretchSliderWidget() with ui.HStack(): ui.Spacer(width=5) ui.Label("Bloom Intensity", height=0, width=0, tooltip="Controls Bloom Intensity value in FFT Bloom located in the Post Processing menu") ui.Spacer(width=27) BloomIntensitySliderWidget() with ui.HStack(): ui.Spacer(width=5) ui.Label("Lens Blades", height=0, width=0, tooltip="Controls Lens Blades value in FFT Bloom located in the Post Processing menu") ui.Spacer(width=49) LensBladesSliderWidget() with ui.HStack(): ui.Spacer(width=5) ui.Label("Blade Rotation", height=0, width=0, tooltip="Controls Aperture Rotation value in FFT Bloom located in the Post Processing menu") ui.Spacer(width=34) BladeRotationWidget()
13,636
Python
50.851711
228
0.520387
stephenT0/funkyboy-anamorphic-effects/exts/funkyboy.anamorphic.effects/funkyboy/anamorphic/effects/tests/__init__.py
from .test_hello_world import *
31
Python
30.999969
31
0.774194
stephenT0/funkyboy-anamorphic-effects/exts/funkyboy.anamorphic.effects/funkyboy/anamorphic/effects/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 funkyboy.anamorphic.camera # 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 = funkyboy.anamorphic.camera.some_public_function(4) self.assertEqual(result, 256) async def test_window_button(self): # Find a label in our window label = ui_test.find("My Window//Frame/**/Label[*]") # Find buttons in our window add_button = ui_test.find("My Window//Frame/**/Button[*].text=='Add'") reset_button = ui_test.find("My Window//Frame/**/Button[*].text=='Reset'") # Click reset button await reset_button.click() self.assertEqual(label.widget.text, "empty") await add_button.click() self.assertEqual(label.widget.text, "count: 1") await add_button.click() self.assertEqual(label.widget.text, "count: 2")
1,688
Python
34.936169
142
0.684834
stephenT0/funkyboy-anamorphic-effects/exts/funkyboy.anamorphic.effects/config/extension.toml
[package] # Semantic Versioning is used: https://semver.org/ version = "1.1.0" # Lists people or organizations that are considered the "authors" of the package. authors = ["Funky Boy"] # The title and description fields are primarily for displaying extension info in UI title = "Anamorphic Effects" description="An extension that emulates camera effects associated with anamorphic lenses." # 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 = "Rendering" # Keywords for the extension keywords = ["Rendering", "Film", "Cine", "Cinema", "Post-Process"] # 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 funkyboy.anamorphic.camera". [[python.module]] name = "funkyboy.anamorphic.effects" [[test]] # Extra dependencies only to be used during test run dependencies = [ "omni.kit.ui_test" # UI testing extension ]
1,635
TOML
33.083333
118
0.747401
stephenT0/funkyboy-anamorphic-effects/exts/funkyboy.anamorphic.effects/docs/CHANGELOG.md
# Changelog The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/). ## [1.0.0] - 2023-03-02 - Initial version of anamorphic camera ## [1.1.0] - 2023-05-08 - added quality of life updates
215
Markdown
20.599998
80
0.683721
stephenT0/funkyboy-anamorphic-effects/exts/funkyboy.anamorphic.effects/docs/README.md
# Anamorphic Effects An extension that emulates camera effects associated with anamorphic lenses
99
Markdown
18.999996
75
0.838384
stephenT0/funkyboy-anamorphic-effects/exts/funkyboy.anamorphic.effects/docs/index.rst
funkyboy.anamorphic.camera ############################# Example of Python only extension .. toctree:: :maxdepth: 1 README CHANGELOG .. automodule::"funkyboy.anamorphic.camera" :platform: Windows-x86_64, Linux-x86_64 :members: :undoc-members: :show-inheritance: :imported-members: :exclude-members: contextmanager
353
reStructuredText
15.857142
43
0.634561
stephenT0/funkyboy-exts-CornellBoxmaker/README.md
# Cornell Box Maker Make a Cornell Box that is customizable in real time. ## Adding This Extension To add this extension to your Omniverse app: 1. Go into: Extension Manager -> Gear Icon -> Extension Search Path 2. Add this as a search path: `git://github.com/stephenT0/funkyboy-exts-CornellBoxmaker?branch=main&dir=exts` Manual installation: 1. Download Zip 2. Extract and place into a directory of your choice 3. Go into: Extension Manager -> Gear Icon -> Extension Search Path 4. Add a custom search path ending with: \funkyboy-exts-CornellBoxmaker-master\exts ## Acknowledgments Thanks to the Nvidia Omniverse Discord for helping me make this extension. In particular AshleyG and Mati.
698
Markdown
35.789472
109
0.776504
stephenT0/funkyboy-exts-CornellBoxmaker/tools/scripts/link_app.py
import os import argparse import sys import json import packmanapi import urllib3 def find_omniverse_apps(): http = urllib3.PoolManager() try: r = http.request("GET", "http://127.0.0.1:33480/components") except Exception as e: print(f"Failed retrieving apps from an Omniverse Launcher, maybe it is not installed?\nError: {e}") sys.exit(1) apps = {} for x in json.loads(r.data.decode("utf-8")): latest = x.get("installedVersions", {}).get("latest", "") if latest: for s in x.get("settings", []): if s.get("version", "") == latest: root = s.get("launch", {}).get("root", "") apps[x["slug"]] = (x["name"], root) break return apps def create_link(src, dst): print(f"Creating a link '{src}' -> '{dst}'") packmanapi.link(src, dst) APP_PRIORITIES = ["code", "create", "view"] if __name__ == "__main__": parser = argparse.ArgumentParser(description="Create folder link to Kit App installed from Omniverse Launcher") parser.add_argument( "--path", help="Path to Kit App installed from Omniverse Launcher, e.g.: 'C:/Users/bob/AppData/Local/ov/pkg/create-2021.3.4'", required=False, ) parser.add_argument( "--app", help="Name of Kit App installed from Omniverse Launcher, e.g.: 'code', 'create'", required=False ) args = parser.parse_args() path = args.path if not path: print("Path is not specified, looking for Omniverse Apps...") apps = find_omniverse_apps() if len(apps) == 0: print( "Can't find any Omniverse Apps. Use Omniverse Launcher to install one. 'Code' is the recommended app for developers." ) sys.exit(0) print("\nFound following Omniverse Apps:") for i, slug in enumerate(apps): name, root = apps[slug] print(f"{i}: {name} ({slug}) at: '{root}'") if args.app: selected_app = args.app.lower() if selected_app not in apps: choices = ", ".join(apps.keys()) print(f"Passed app: '{selected_app}' is not found. Specify one of the following found Apps: {choices}") sys.exit(0) else: selected_app = next((x for x in APP_PRIORITIES if x in apps), None) if not selected_app: selected_app = next(iter(apps)) print(f"\nSelected app: {selected_app}") _, path = apps[selected_app] if not os.path.exists(path): print(f"Provided path doesn't exist: {path}") else: SCRIPT_ROOT = os.path.dirname(os.path.realpath(__file__)) create_link(f"{SCRIPT_ROOT}/../../app", path) print("Success!")
2,813
Python
32.5
133
0.562389
stephenT0/funkyboy-exts-CornellBoxmaker/tools/packman/config.packman.xml
<config remotes="cloudfront"> <remote2 name="cloudfront"> <transport actions="download" protocol="https" packageLocation="d4i3qtqj3r0z5.cloudfront.net/${name}@${version}" /> </remote2> </config>
211
XML
34.333328
123
0.691943
stephenT0/funkyboy-exts-CornellBoxmaker/tools/packman/bootstrap/install_package.py
# Copyright 2019 NVIDIA CORPORATION # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # http://www.apache.org/licenses/LICENSE-2.0 # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import logging import zipfile import tempfile import sys import shutil __author__ = "hfannar" logging.basicConfig(level=logging.WARNING, format="%(message)s") logger = logging.getLogger("install_package") class TemporaryDirectory: def __init__(self): self.path = None def __enter__(self): self.path = tempfile.mkdtemp() return self.path def __exit__(self, type, value, traceback): # Remove temporary data created shutil.rmtree(self.path) def install_package(package_src_path, package_dst_path): with zipfile.ZipFile( package_src_path, allowZip64=True ) as zip_file, TemporaryDirectory() as temp_dir: zip_file.extractall(temp_dir) # Recursively copy (temp_dir will be automatically cleaned up on exit) try: # Recursive copy is needed because both package name and version folder could be missing in # target directory: shutil.copytree(temp_dir, package_dst_path) except OSError as exc: logger.warning( "Directory %s already present, packaged installation aborted" % package_dst_path ) else: logger.info("Package successfully installed to %s" % package_dst_path) install_package(sys.argv[1], sys.argv[2])
1,888
Python
31.568965
103
0.68697
stephenT0/funkyboy-exts-CornellBoxmaker/exts/funkyboy.cornell.box/funkyboy/cornell/box/extension.py
import omni.ext import omni.kit.ui from .window import CornellBoxWindow, WINDOW_TITLE class CornellBoxExtension(omni.ext.IExt): def on_startup(self, ext_id): self._menu_path = f"Window/{WINDOW_TITLE}" self._window = CornellBoxWindow(WINDOW_TITLE, self._menu_path) self._menu = omni.kit.ui.get_editor_menu().add_item(self._menu_path, self._on_menu_click, True) def on_shutdown(self): omni.kit.ui.get_editor_menu().remove_item(self._menu) if self._window is not None: self._window.destroy() self._window = None def _on_menu_click(self, menu, toggled): if toggled: if self._window is None: self._window = CornellBoxWindow(WINDOW_TITLE, self._menu_path) else: self._window.show() else: if self._window is not None: self._window.hide()
922
Python
29.766666
103
0.591106
stephenT0/funkyboy-exts-CornellBoxmaker/exts/funkyboy.cornell.box/funkyboy/cornell/box/__init__.py
from .extension import *
25
Python
11.999994
24
0.76
stephenT0/funkyboy-exts-CornellBoxmaker/exts/funkyboy.cornell.box/funkyboy/cornell/box/box_maker.py
import omni.kit.commands import omni.usd import omni.kit.undo from pxr import Gf, Sdf, Usd class BoxMaker: def __init__(self) -> None: self._stage:Usd.Stage = omni.usd.get_context().get_stage() omni.kit.commands.execute('DeletePrims', paths=["/World/CB_Looks", "/World/Cornell_Box", "/World/defaultLight", "/Environment"]) self.Create_Box() def Create_Panel(self): plane_prim_path = omni.usd.get_stage_next_free_path(self._stage, self.geom_xform_path.AppendPath("Plane"), False) omni.kit.commands.execute('CreateMeshPrimWithDefaultXform',prim_type='Plane') omni.kit.commands.execute('MovePrim', path_from='/World/Plane', path_to=plane_prim_path) mtl_path = Sdf.Path(omni.usd.get_stage_next_free_path(self._stage, self.looks_scope_path.AppendPath("OmniPBR"), False)) omni.kit.commands.execute('CreateMdlMaterialPrim', mtl_url='OmniPBR.mdl', mtl_name='OmniPBR', mtl_path=str(mtl_path)) omni.kit.commands.execute('BindMaterial', prim_path=plane_prim_path, material_path=str(mtl_path), strength=['strongerThanDescendants']) plane_prim = self._stage.GetPrimAtPath(plane_prim_path) plane_prim.GetAttribute("xformOp:scale").Set(Gf.Vec3d(4,4,4)) shader_prim = self._stage.GetPrimAtPath(mtl_path.AppendPath("Shader")) mtl_color_attr = shader_prim.CreateAttribute("inputs:diffuse_color_constant", Sdf.ValueTypeNames.Color3f) mtl_color_attr.Set((0.9, 0.9, 0.9)) return plane_prim def Create_Box(self): with omni.kit.undo.group(): self.geom_xform_path = Sdf.Path(omni.usd.get_stage_next_free_path(self._stage, "/World/Cornell_Box", False)) self.looks_scope_path = Sdf.Path(omni.usd.get_stage_next_free_path(self._stage, "/World/CB_Looks", False)) self.geom_xform_path2 = Sdf.Path(omni.usd.get_stage_next_free_path(self._stage, "/World/Cornell_Box/Panels", False)) omni.kit.commands.execute('CreatePrimWithDefaultXform', prim_type='Xform', prim_path=str(self.geom_xform_path)) omni.kit.commands.execute('CreatePrimWithDefaultXform', prim_type='Xform', prim_path=str(self.geom_xform_path2)) omni.kit.commands.execute('CreatePrimWithDefaultXform', prim_type='Scope', prim_path=str(self.looks_scope_path)) #create floor panel = self.Create_Panel() panel.GetAttribute("xformOp:scale").Set(Gf.Vec3d( 4, 4, 15)) #create back wall panel = self.Create_Panel() panel.GetAttribute("xformOp:rotateXYZ").Set(Gf.Vec3d(90, 0, 90)) panel.GetAttribute("xformOp:translate").Set(Gf.Vec3d(0, 200, -400)) #create front wall # panel = self.Create_Panel() # panel.GetAttribute("xformOp:rotateXYZ").Set(Gf.Vec3d(90, 0, 90)) # panel.GetAttribute("xformOp:translate").Set(Gf.Vec3d(0, 100, 100)) #create ceiling panel = self.Create_Panel() panel.GetAttribute("xformOp:translate").Set(Gf.Vec3d(0, 400, 0)) panel.GetAttribute("xformOp:scale").Set(Gf.Vec3d(4, 4, 15)) #create colored wall 1 panel = self.Create_Panel() panel.GetAttribute("xformOp:rotateXYZ").Set(Gf.Vec3d(0, 0, 90)) panel.GetAttribute("xformOp:translate").Set(Gf.Vec3d(-200, 200, 0)) panel.GetAttribute("xformOp:scale").Set(Gf.Vec3d(4, 4, 15)) #create colored wall 2 panel = self.Create_Panel() panel.GetAttribute("xformOp:rotateXYZ").Set(Gf.Vec3d(0, 0, 90)) panel.GetAttribute("xformOp:translate").Set(Gf.Vec3d(200, 200, 0)) panel.GetAttribute("xformOp:scale").Set(Gf.Vec3d(4, 4, 15)) #move panels omni.kit.commands.execute('MovePrim', path_from='/World/Cornell_Box/Plane', path_to='/World/Cornell_Box/Panels/Plane') omni.kit.commands.execute('MovePrim', path_from='/World/Cornell_Box/Plane_01', path_to='/World/Cornell_Box/Panels/Plane_01') omni.kit.commands.execute('MovePrim', path_from='/World/Cornell_Box/Plane_02', path_to='/World/Cornell_Box/Panels/Plane_02') omni.kit.commands.execute('MovePrim', path_from='/World/Cornell_Box/Plane_03', path_to='/World/Cornell_Box/Panels/Plane_03') omni.kit.commands.execute('MovePrim', path_from='/World/Cornell_Box/Plane_04', path_to='/World/Cornell_Box/Panels/Plane_04') #make wall red omni.kit.commands.execute('ChangeProperty', prop_path=Sdf.Path('/World/CB_Looks/OmniPBR_03/Shader.inputs:diffuse_color_constant'), value=Gf.Vec3f(1.0, 0.0, 0.0), prev=Gf.Vec3f(0.9, 0.9, 0.9)) #make wall green omni.kit.commands.execute('ChangeProperty', prop_path=Sdf.Path('/World/CB_Looks/OmniPBR_04/Shader.inputs:diffuse_color_constant'), value=Gf.Vec3f(0.0, 0.9, 0.2), prev=Gf.Vec3f(0.9, 0.9, 0.9)) #create rectangle light light_prim_path = omni.usd.get_stage_next_free_path(self._stage, self.geom_xform_path.AppendPath("RectLight"), False) omni.kit.commands.execute('CreatePrim',prim_type='RectLight', attributes={'width': 150, 'height': 100, 'intensity': 17500}) omni.kit.commands.execute('ChangeProperty', prop_path=Sdf.Path('/World/RectLight.xformOp:translate'), value=Gf.Vec3d(0.0, 399.9000, 125), prev=Gf.Vec3d(0.0, 0.0, 0.0)) omni.kit.commands.execute('ChangeProperty', prop_path=Sdf.Path('/World/RectLight.xformOp:rotateXYZ'), value=Gf.Vec3d(0.0, -90.0, -90.0), prev=Gf.Vec3d(0.0, 0.0, 0.0)) omni.kit.commands.execute('ChangeProperty', prop_path=Sdf.Path('/World/RectLight.visibleInPrimaryRay'), value=True, prev=None) omni.kit.commands.execute('MovePrim', path_from='/World/RectLight', path_to='/World/Cornell_Box/RectLight') light_prim = self._stage.GetPrimAtPath(light_prim_path) #Visible light #light_prim.GetAttribute("xformOp:scale").Set(Gf.Vec3d(4,4,4)) light_prim.CreateAttribute("visibleInPrimaryRay", Sdf.ValueTypeNames.Bool).Set(True) #Create Camera omni.kit.commands.execute('CreatePrimWithDefaultXform', prim_type='Camera', attributes={'focusDistance': 400, 'focalLength': 27.5}) omni.kit.commands.execute('ChangeProperty', prop_path=Sdf.Path('/World/Camera.xformOp:translate'), value=Gf.Vec3d(0.0, 200.0, 1180.10002), prev=Gf.Vec3d(0.0, 200.0, 1200.0)) omni.kit.commands.execute('MovePrim', path_from='/World/Camera', path_to='/World/Cornell_Box/Camera') #Create Cubes omni.kit.commands.execute('CreateMeshPrimWithDefaultXform', prim_type='Cube') omni.kit.commands.execute('TransformPrimSRT', path=Sdf.Path('/World/Cube'), new_translation=Gf.Vec3d(0.0, 50.0, 100.0), new_rotation_euler=Gf.Vec3d(0.0, 0.0, 0.0), new_rotation_order=Gf.Vec3i(0, 1, 2), new_scale=Gf.Vec3d(1.0, 1.0, 1.0), old_translation=Gf.Vec3d(0.0, 0.0, 0.0), old_rotation_euler=Gf.Vec3d(0.0, 0.0, 0.0), old_rotation_order=Gf.Vec3i(0, 1, 2), old_scale=Gf.Vec3d(1.0, 1.0, 1.0)) omni.kit.commands.execute('ChangeProperty', prop_path=Sdf.Path('/World/Cube.xformOp:rotateXYZ'), value=Gf.Vec3d(0.0, -45, 0.0), prev=Gf.Vec3d(0.0, 0.0, 0.0)) omni.kit.commands.execute('BindMaterial', material_path='/World/CB_Looks/OmniPBR', prim_path=['/World/Cube'], strength=['weakerThanDescendants']) omni.kit.commands.execute('CopyPrims', paths_from=['/World/Cube'], duplicate_layers=False, combine_layers=False, flatten_references=False) omni.kit.commands.execute('TransformPrimSRT', path=Sdf.Path('/World/Cube_01'), new_translation=Gf.Vec3d(99.8525344330427, 49.99999999997604, -83.82421861450064), new_rotation_euler=Gf.Vec3d(0.0, -45.0, 0.0), new_rotation_order=Gf.Vec3i(0, 1, 2), new_scale=Gf.Vec3d(1.0, 1.0, 1.0), old_translation=Gf.Vec3d(0.0, 50.0, 100.0), old_rotation_euler=Gf.Vec3d(0.0, -45.0, 0.0), old_rotation_order=Gf.Vec3i(0, 1, 2), old_scale=Gf.Vec3d(1.0, 1.0, 1.0)) omni.kit.commands.execute('ChangeProperty', prop_path=Sdf.Path('/World/Cube_01.xformOp:scale'), value=Gf.Vec3d(1.0, 1.5, 1.0), prev=Gf.Vec3d(1.0, 1.598320722579956, 1.0)) omni.kit.commands.execute('TransformPrimSRT', path=Sdf.Path('/World/Cube_01'), new_translation=Gf.Vec3d(99.85253443304272, 74.75868843615456, -100.0), new_rotation_euler=Gf.Vec3d(0.0, -45.0, 0.0), new_rotation_order=Gf.Vec3i(0, 1, 2), new_scale=Gf.Vec3d(1.0, 1.5, 1.0), old_translation=Gf.Vec3d(99.8525344330427, 49.99999999997604, -83.82421861450064), old_rotation_euler=Gf.Vec3d(0.0, -45.0, 0.0), old_rotation_order=Gf.Vec3i(0, 1, 2), old_scale=Gf.Vec3d(1.0, 1.5, 1.0)) omni.kit.commands.execute('CopyPrims', paths_from=['/World/Cube_01'], duplicate_layers=False, combine_layers=False, flatten_references=False) omni.kit.commands.execute('TransformPrimSRT', path=Sdf.Path('/World/Cube_02'), new_translation=Gf.Vec3d(-100.31094017767478, 74.75868843615382, -200.65476487048673), new_rotation_euler=Gf.Vec3d(0.0, -45.0, 0.0), new_rotation_order=Gf.Vec3i(0, 1, 2), new_scale=Gf.Vec3d(1.0, 1.5, 1.0), old_translation=Gf.Vec3d(99.85253443304272, 74.75868843615456, -100.0), old_rotation_euler=Gf.Vec3d(0.0, -45.0, 0.0), old_rotation_order=Gf.Vec3i(0, 1, 2), old_scale=Gf.Vec3d(1.0, 1.5, 1.0)) omni.kit.commands.execute('ChangeProperty', prop_path=Sdf.Path('/World/Cube_02.xformOp:scale'), value=Gf.Vec3d(1.0, 2.0, 1.0), prev=Gf.Vec3d(1.0, 1.5, 1.0)) omni.kit.commands.execute('TransformPrimSRT', path=Sdf.Path('/World/Cube_02'), new_translation=Gf.Vec3d(-100.31094017767478, 100.0, -200.65476487048673), new_rotation_euler=Gf.Vec3d(0.0, -45.0, 0.0), new_rotation_order=Gf.Vec3i(0, 1, 2), new_scale=Gf.Vec3d(1.0, 2.0, 1.0), old_translation=Gf.Vec3d(-100.31094017767478, 74.75868843615382, -200.65476487048673), old_rotation_euler=Gf.Vec3d(0.0, -45.0, 0.0), old_rotation_order=Gf.Vec3i(0, 1, 2), old_scale=Gf.Vec3d(1.0, 2.0, 1.0)) omni.kit.commands.execute('MovePrim', path_from='/World/Cube', path_to='/World/Cornell_Box/Cube') omni.kit.commands.execute('MovePrim', path_from='/World/Cube_01', path_to='/World/Cornell_Box/Cube_01') omni.kit.commands.execute('MovePrim', path_from='/World/Cube_02', path_to='/World/Cornell_Box/Cube_02')
12,213
Python
39.849498
136
0.563089
stephenT0/funkyboy-exts-CornellBoxmaker/exts/funkyboy.cornell.box/funkyboy/cornell/box/window.py
import omni.ext import omni.ui as ui import omni.kit.commands import omni.usd from pxr import Gf, Sdf from .box_maker import BoxMaker from omni.ui import color as cl from omni.ui import constant as fl WINDOW_TITLE = "Cornell Box Maker" SPACING = 4 combo_sub = None options = ["Classic", "SIGGRAPH 1984", "NVIDIA Omniverse"] class CornellBoxWindow(ui.Window): def __init__(self, title, menu_path): super().__init__(title, width=450, height=280) self._menu_path = menu_path self.set_visibility_changed_fn(self._on_visibility_changed) self.frame.set_build_fn(self._build_window) #color widget variables self._color_model = None self._color_model_2 = None self._color_changed_subs = [] self._color_changed_subs_2 = [] self._path_model = None self._path_model_2 = None self._change_info_path_subscription = None self._change_info_path_subscription_2 = None self._stage = omni.usd.get_context().get_stage() self._OmniPBR_Path_03 = "/World/CB_Looks/OmniPBR_03/Shader.inputs:diffuse_color_constant" self._OmniPBR_Path_04 = "/World/CB_Looks/OmniPBR_04/Shader.inputs:diffuse_color_constant" #subscribe mat 1 attr_path = self._OmniPBR_Path_03 color_attr = self._stage.GetAttributeAtPath(attr_path) if color_attr: self._change_info_path_subscription = omni.usd.get_watcher().subscribe_to_change_info_path( attr_path, self._on_mtl_attr_changed) #subscribe mat 2 attr_path_2 = self._OmniPBR_Path_04 color_attr_2 = self._stage.GetAttributeAtPath(attr_path_2) if color_attr_2: self._change_info_path_subscription_2 = omni.usd.get_watcher().subscribe_to_change_info_path( attr_path_2, self._on_mtl_attr_changed_2) #combox group variables self.combo_sub = None #main ui Window def _build_window(self): #with self.frame: with ui.ScrollingFrame(): with ui.VStack(height=0): def on_click(): BoxMaker() with ui.HStack(height=0, spacing=SPACING): ui.Label("Start Here: ", height=40, width=0) ui.Button("Make Box", clicked_fn=lambda: on_click()) with ui.CollapsableFrame("Color", name="group", height=50): with ui.VStack(height=0, spacing=SPACING): with ui.HStack(height=0, spacing=SPACING): ui.Label("Colored Wall #1: ", height=0, width=0) self._color_model = ui.ColorWidget(0.9, 0.0, 0.0, height=0).model for item in self._color_model.get_item_children(): component = self._color_model.get_item_value_model(item) self._color_changed_subs.append(component.subscribe_value_changed_fn(self._on_color_changed)) #ui.FloatDrag(component) self._path_model = self._OmniPBR_Path_03 with ui.HStack(height=0, spacing=SPACING): ui.Label("Colored Wall #2: ", height=0, width=0) self._color_model_2 = ui.ColorWidget(0.0, 0.9, 0.2, height=0).model for item in self._color_model_2.get_item_children(): component = self._color_model_2.get_item_value_model(item) self._color_changed_subs_2.append(component.subscribe_value_changed_fn(self._on_color_changed_2)) #ui.FloatDrag(component) self._path_model_2 = self._OmniPBR_Path_04 #combobox group with ui.HStack(height=0, spacing=SPACING): ui.Label("Select Preset Style:", height=0, width=0) combo_model: ui.AbstractItemModel = ui.ComboBox(0, *options).model def combo_changed(item_model: ui.AbstractItemModel, item: ui.AbstractItem): value_model = item_model.get_item_value_model(item) current_index = value_model.as_int option = options[current_index] #print(f"Selected '{option}' at index {current_index}.") if option == "Classic": mtl_path_1 = "/World/CB_Looks/OmniPBR_03/Shader" shader_prim_1 = self._stage.GetPrimAtPath(mtl_path_1) mtl_color_attr_1 = shader_prim_1.CreateAttribute("inputs:diffuse_color_constant", Sdf.ValueTypeNames.Color3f) mtl_color_attr_1.Set((0.9, 0.0, 0.0)) mtl_path_2 = "/World/CB_Looks/OmniPBR_04/Shader" shader_prim_2 = self._stage.GetPrimAtPath(mtl_path_2) mtl_color_attr_2 = shader_prim_2.CreateAttribute("inputs:diffuse_color_constant", Sdf.ValueTypeNames.Color3f) mtl_color_attr_2.Set((0.0, 0.9, 0.2)) if option == "SIGGRAPH 1984": mtl_path_1 = "/World/CB_Looks/OmniPBR_03/Shader" shader_prim_1 = self._stage.GetPrimAtPath(mtl_path_1) mtl_color_attr_1 = shader_prim_1.CreateAttribute("inputs:diffuse_color_constant", Sdf.ValueTypeNames.Color3f) mtl_color_attr_1.Set((0.9, 0.0, 0.0)) mtl_path_2 = "/World/CB_Looks/OmniPBR_04/Shader" shader_prim_2 = self._stage.GetPrimAtPath(mtl_path_2) mtl_color_attr_2 = shader_prim_2.CreateAttribute("inputs:diffuse_color_constant", Sdf.ValueTypeNames.Color3f) mtl_color_attr_2.Set((0.0, 0.0, 0.9)) if option == "NVIDIA Omniverse": mtl_path_1 = "/World/CB_Looks/OmniPBR_03/Shader" shader_prim_1 = self._stage.GetPrimAtPath(mtl_path_1) mtl_color_attr_1 = shader_prim_1.CreateAttribute("inputs:diffuse_color_constant", Sdf.ValueTypeNames.Color3f) mtl_color_attr_1.Set((0.069, 0.069, 0.069)) # self._color_model.Set((0.069, 0.069, 0.069)) mtl_path_2 = "/World/CB_Looks/OmniPBR_04/Shader" shader_prim_2 = self._stage.GetPrimAtPath(mtl_path_2) mtl_color_attr_2 = shader_prim_2.CreateAttribute("inputs:diffuse_color_constant", Sdf.ValueTypeNames.Color3f) mtl_color_attr_2.Set((0.4, 0.8, 0.0)) self.combo_sub = combo_model.subscribe_item_changed_fn(combo_changed) ui.Spacer(width=1) ui.Spacer(width=0,height=0) #scale sliders for cornell box xform self._slider_model_x = ui.SimpleFloatModel() self._slider_model_y = ui.SimpleFloatModel() self._slider_model_z = ui.SimpleFloatModel() self._source_prim_model = ui.SimpleStringModel() with ui.CollapsableFrame("Scale", name="group", height=100,): with ui.VStack(height=0, spacing=SPACING): with ui.HStack(): ui.Spacer(width=5) ui.Label("Box Width: ", height=0, width=0) #ui.Spacer(width=5) #ui.FloatDrag(self._slider_model, min=0.1, max=5) ui.FloatSlider(self._slider_model_x, min=0.1, max=10, step=0.05) #ui.Spacer(width=10) def update_scale_x(prim_name, value): usd_context = omni.usd.get_context() stage = usd_context.get_stage() cube_prim = stage.GetPrimAtPath("/World/Cornell_Box/Panels") scale_attr = cube_prim.GetAttribute("xformOp:scale") scale = scale_attr.Get() scale_attr.Set(Gf.Vec3d(value, scale[1], scale[2])) if self._slider_model_x: self._slider_subscription_x = None self._slider_model_x.as_float = 1.0 self._slider_subscription_x = self._slider_model_x.subscribe_value_changed_fn( lambda m, #the following is where we change from self.model to self._source_prim_model p=self._source_prim_model: update_scale_x(p, m.as_float) ) with ui.HStack(): ui.Spacer(width=5) ui.Label("Box Height: ", height=0, width=0) #ui.Spacer(width=5) ui.FloatSlider(self._slider_model_y, min=0.1, max=10, step=0.05) #ui.Spacer(width=10) def update_scale_y(prim_name, value): usd_context = omni.usd.get_context() stage = usd_context.get_stage() cube_prim = stage.GetPrimAtPath("/World/Cornell_Box/Panels") scale_attr = cube_prim.GetAttribute("xformOp:scale") scale = scale_attr.Get() scale_attr.Set(Gf.Vec3d(scale[0], value, scale[2])) #usd_context = omni.usd.get_context() #stage = usd_context.get_stage() light_prim = stage.GetPrimAtPath("/World/Cornell_Box/RectLight") trans_attr = light_prim.GetAttribute("xformOp:translate") trans = trans_attr.Get() trans_attr.Set(Gf.Vec3d(trans[0], ((399.9) * value), trans[2])) if self._slider_model_y: self._slider_subscription_y = None self._slider_model_y.as_float = 1.0 self._slider_subscription = self._slider_model_y.subscribe_value_changed_fn( lambda m, #the following is where we change from self.model to self._source_prim_model p=self._source_prim_model: update_scale_y(p, m.as_float) ) with ui.HStack(): ui.Spacer(width=5) ui.Label("Box Length: ", height=0, width=0) #ui.Spacer(width=5) ui.FloatSlider(self._slider_model_z, min=0.1, max=10, step=0.05) #ui.Spacer(width=10) def update_scale_z(prim_name, value): usd_context = omni.usd.get_context() stage = usd_context.get_stage() cube_prim = stage.GetPrimAtPath("/World/Cornell_Box/Panels") scale_attr = cube_prim.GetAttribute("xformOp:scale") scale = scale_attr.Get() scale_attr.Set(Gf.Vec3d(scale[0], scale[1], value)) if self._slider_model_z: self._slider_subscription_z = None self._slider_model_z.as_float = 1.0 self._slider_subscription_z = self._slider_model_z.subscribe_value_changed_fn( lambda m, #the following is where we change from self.model to self._source_prim_model p=self._source_prim_model: update_scale_z(p, m.as_float)) #dock super().dock_in_window("Environments", ui.DockPosition.SAME) #functions for color picker def _on_mtl_attr_changed(self, path): color_attr = self._stage.GetAttributeAtPath(path) color_model_items = self._color_model.get_item_children() if color_attr: color = color_attr.Get() for i in range(len(color)): component = self._color_model.get_item_value_model(color_model_items[i]) component.set_value(color[i]) def _on_mtl_attr_changed_2(self, path): color_attr = self._stage.GetAttributeAtPath(path) color_model_items = self._color_model_2.get_item_children() if color_attr: color = color_attr.Get() for i in range(len(color)): component = self._color_model_2.get_item_value_model(color_model_items[i]) component.set_value(color[i]) def _on_color_changed(self, model): values = [] for item in self._color_model.get_item_children(): component = self._color_model.get_item_value_model(item) values.append(component.as_float) if Sdf.Path.IsValidPathString(self._path_model): attr_path = Sdf.Path(self._path_model) color_attr = self._stage.GetAttributeAtPath(attr_path) if color_attr: color_attr.Set(Gf.Vec3f(*values[0:3])) def _on_color_changed_2(self, model): values = [] for item in self._color_model_2.get_item_children(): component = self._color_model_2.get_item_value_model(item) values.append(component.as_float) if Sdf.Path.IsValidPathString(self._path_model_2): attr_path = Sdf.Path(self._path_model_2) color_attr = self._stage.GetAttributeAtPath(attr_path) if color_attr: color_attr.Set(Gf.Vec3f(*values[0:3])) def _on_visibility_changed(self, visible): omni.kit.ui.get_editor_menu().set_value(self._menu_path, visible) def destroy(self) -> None: self._change_info_path_subscription = None self._color_changed_subs = None return super().destroy() def on_shutdown(self): self._win = None def show(self): self.visible = True self.focus() def hide(self): self.visible = False
15,194
Python
47.701923
146
0.490325
stephenT0/funkyboy-exts-CornellBoxmaker/exts/funkyboy.cornell.box/config/extension.toml
[package] # Semantic Versionning is used: https://semver.org/ version = "1.2.1" # The title and description fields are primarily for displaying extension info in UI title = "Cornell Box Maker" description="Make a cornell box and customize its appearance and dimensions" icon = "data/icon.png" preview_image = "data/preview.png" # Path (relative to the root) or content of readme markdown file for UI. readme = "docs/README.md" # URL of the extension source repository. repository = "" # One of categories for UI. category = "Modeling" # Keywords for the extension keywords = ["Box", "Cornell", "Maker"] # Use omni.ui to build simple UI [dependencies] "omni.kit.uiapp" = {} # Main python module this extension provides, it will be publicly available as "import funkyboy.cornell.box". [[python.module]] name = "funkyboy.cornell.box"
840
TOML
26.129031
109
0.736905
stephenT0/funkyboy-exts-CornellBoxmaker/exts/funkyboy.cornell.box/docs/CHANGELOG.md
# Changelog ## [0.1.0] 2022-08-18 -Initial version of Cornell Box Maker ## [0.1.1] 2022-09-21 -Color widget working ## [0.1.2] 2022-10-02 -Added Combo Box Widget -Added Docking
177
Markdown
18.777776
37
0.689266
stephenT0/funkyboy-exts-CornellBoxmaker/exts/funkyboy.cornell.box/docs/README.md
Make a Cornell Box that is customizable in real time. Extension works best from a new scene. -extension currently works best started from a new scene with the extension freshly loaded To do: -Lots of small issues to reslove -overall stability and usability -improve UI issues: -takes 3 clicks to close window -reliant on a World xform to work -color widgets not reliable after a new scene is created
405
Markdown
30.230767
92
0.790123
stephenT0/funkyboy-camera-speed/README.md
# Tea Time 10 Camera speed presets for scene navigation ## Adding This Extension To add this extension to your Omniverse app: 1. Go into: Extension Manager -> Gear Icon -> Extension Search Path 2. Add this as a search path: `git://github.com//stephenT0/funkyboy-exts-camera-speed-selector?branch=main&dir=exts` Manual installation: 1. Download Zip 2. Extract and place into a directory of your choice 3. Go into: Extension Manager -> Gear Icon -> Extension Search Path 4. Add a custom search path ending with: \funkyboy-exts-camera-speed-selector-master\exts ## Acknowledgments Thanks to the Nvidia Omniverse Discord for helping me make this extension. In particular Jen, Mati, and @ericcraft-mh.
705
Markdown
36.157893
119
0.771631
stephenT0/funkyboy-camera-speed/tools/scripts/link_app.py
import os import argparse import sys import json import packmanapi import urllib3 def find_omniverse_apps(): http = urllib3.PoolManager() try: r = http.request("GET", "http://127.0.0.1:33480/components") except Exception as e: print(f"Failed retrieving apps from an Omniverse Launcher, maybe it is not installed?\nError: {e}") sys.exit(1) apps = {} for x in json.loads(r.data.decode("utf-8")): latest = x.get("installedVersions", {}).get("latest", "") if latest: for s in x.get("settings", []): if s.get("version", "") == latest: root = s.get("launch", {}).get("root", "") apps[x["slug"]] = (x["name"], root) break return apps def create_link(src, dst): print(f"Creating a link '{src}' -> '{dst}'") packmanapi.link(src, dst) APP_PRIORITIES = ["code", "create", "view"] if __name__ == "__main__": parser = argparse.ArgumentParser(description="Create folder link to Kit App installed from Omniverse Launcher") parser.add_argument( "--path", help="Path to Kit App installed from Omniverse Launcher, e.g.: 'C:/Users/bob/AppData/Local/ov/pkg/create-2021.3.4'", required=False, ) parser.add_argument( "--app", help="Name of Kit App installed from Omniverse Launcher, e.g.: 'code', 'create'", required=False ) args = parser.parse_args() path = args.path if not path: print("Path is not specified, looking for Omniverse Apps...") apps = find_omniverse_apps() if len(apps) == 0: print( "Can't find any Omniverse Apps. Use Omniverse Launcher to install one. 'Code' is the recommended app for developers." ) sys.exit(0) print("\nFound following Omniverse Apps:") for i, slug in enumerate(apps): name, root = apps[slug] print(f"{i}: {name} ({slug}) at: '{root}'") if args.app: selected_app = args.app.lower() if selected_app not in apps: choices = ", ".join(apps.keys()) print(f"Passed app: '{selected_app}' is not found. Specify one of the following found Apps: {choices}") sys.exit(0) else: selected_app = next((x for x in APP_PRIORITIES if x in apps), None) if not selected_app: selected_app = next(iter(apps)) print(f"\nSelected app: {selected_app}") _, path = apps[selected_app] if not os.path.exists(path): print(f"Provided path doesn't exist: {path}") else: SCRIPT_ROOT = os.path.dirname(os.path.realpath(__file__)) create_link(f"{SCRIPT_ROOT}/../../app", path) print("Success!")
2,813
Python
32.5
133
0.562389
stephenT0/funkyboy-camera-speed/tools/packman/config.packman.xml
<config remotes="cloudfront"> <remote2 name="cloudfront"> <transport actions="download" protocol="https" packageLocation="d4i3qtqj3r0z5.cloudfront.net/${name}@${version}" /> </remote2> </config>
211
XML
34.333328
123
0.691943
stephenT0/funkyboy-camera-speed/tools/packman/bootstrap/install_package.py
# Copyright 2019 NVIDIA CORPORATION # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # http://www.apache.org/licenses/LICENSE-2.0 # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import logging import zipfile import tempfile import sys import shutil __author__ = "hfannar" logging.basicConfig(level=logging.WARNING, format="%(message)s") logger = logging.getLogger("install_package") class TemporaryDirectory: def __init__(self): self.path = None def __enter__(self): self.path = tempfile.mkdtemp() return self.path def __exit__(self, type, value, traceback): # Remove temporary data created shutil.rmtree(self.path) def install_package(package_src_path, package_dst_path): with zipfile.ZipFile( package_src_path, allowZip64=True ) as zip_file, TemporaryDirectory() as temp_dir: zip_file.extractall(temp_dir) # Recursively copy (temp_dir will be automatically cleaned up on exit) try: # Recursive copy is needed because both package name and version folder could be missing in # target directory: shutil.copytree(temp_dir, package_dst_path) except OSError as exc: logger.warning( "Directory %s already present, packaged installation aborted" % package_dst_path ) else: logger.info("Package successfully installed to %s" % package_dst_path) install_package(sys.argv[1], sys.argv[2])
1,888
Python
31.568965
103
0.68697
stephenT0/funkyboy-camera-speed/exts/Funkyboy.cameraspeed/Funkyboy/cameraspeed/_window_copy.py
import omni.ext import omni.ui as ui import carb.settings import carb import omni.kit.commands from .style import style1 LABEL_WIDTH = 120 SPACING = 4 class SimpleCamWindow(ui.Window): def __init__(self, title: str, delegate=None, **kwargs): self.__label_width = LABEL_WIDTH super().__init__(title, **kwargs) self.frame.set_build_fn(self._build_fn) def destroy(self): # It will destroy all the children super().destroy() @property def label_width(self): """The width of the attribute label""" return self.__label_width @label_width.setter def label_width(self, value): """The width of the attribute label""" self.__label_width = value self.frame.rebuild() def _build_fn(self): """ The method that is called to build all the UI once the window is visible. """ CAMERA_VEL = "/persistent/app/viewport/camMoveVelocity" # Camera velocity setting self._settings = carb.settings.get_settings() # Grab carb settings with self.frame: with ui.VStack(): ui.Button("Select a Camera Speed", style={"background_color":0xFF6FF, "color":0xFF00B976, "font_size":20,}, tooltip=" right click + WASD to fly ") def on_click(): self._settings.set(CAMERA_VEL, 0.01) carb.log_info(f"Camera velocity set to {self._settings.get_as_float(CAMERA_VEL)}") def on_click2(): self._settings.set(CAMERA_VEL, 0.1) carb.log_info(f"Camera velocity set to {self._settings.get_as_float(CAMERA_VEL)}") def on_click3(): self._settings.set(CAMERA_VEL, 0.5) carb.log_info(f"Camera velocity set to {self._settings.get_as_float(CAMERA_VEL)}") def on_click4(): self._settings.set(CAMERA_VEL, 2.5) carb.log_info(f"Camera velocity set to {self._settings.get_as_float(CAMERA_VEL)}") def on_click5(): self._settings.set(CAMERA_VEL, 5.0) carb.log_info(f"Camera velocity set to {self._settings.get_as_float(CAMERA_VEL)}") def on_click6(): self._settings.set(CAMERA_VEL, 7.5) carb.log_info(f"Camera velocity set to {self._settings.get_as_float(CAMERA_VEL)}") def on_click7(): self._settings.set(CAMERA_VEL, 10.0) carb.log_info(f"Camera velocity set to {self._settings.get_as_float(CAMERA_VEL)}") def on_click8(): self._settings.set(CAMERA_VEL, 20.0) carb.log_info(f"Camera velocity set to: {self._settings.get_as_float(CAMERA_VEL)}") def on_click9(): self._settings.set(CAMERA_VEL, 30.0) carb.log_info(f"Camera velocity set to: {self._settings.get_as_float(CAMERA_VEL)}") def on_click10(): self._settings.set(CAMERA_VEL, 50.0) carb.log_info(f"Camera velocity set to: {self._settings.get_as_float(CAMERA_VEL)}") def on_click11(): omni.kit.commands.execute('DuplicateFromActiveViewportCameraCommand', viewport_name='Viewport') # Added a clicked function to handle the click call def call_clicked(val:int): if val == 0: radbt0.call_clicked_fn() if val == 1: radbt1.call_clicked_fn() if val == 2: radbt2.call_clicked_fn() if val == 3: radbt3.call_clicked_fn() if val == 4: radbt4.call_clicked_fn() if val == 5: radbt5.call_clicked_fn() if val == 6: radbt6.call_clicked_fn() if val == 7: radbt7.call_clicked_fn() if val == 8: radbt8.call_clicked_fn() if val == 9: radbt9.call_clicked_fn() #the slider collection = ui.RadioCollection() intSlider = ui.IntSlider( collection.model, min=0, max=9, style={ "draw_mode": ui.SliderDrawMode.HANDLE, "background_color": 0xFF00B976, "color": 0xFF00B976, "font_size": 14.0, }) intSlider.model.add_value_changed_fn(lambda val:call_clicked(val.get_value_as_int())) #the buttons with ui.HStack(style=style1): radbt0 = ui.RadioButton(text ="1", name="one", radio_collection=collection, clicked_fn=lambda: on_click()) radbt1 = ui.RadioButton(text ="2", name="two", radio_collection=collection, clicked_fn=lambda: on_click2()) radbt2 = ui.RadioButton(text ="3", name="three", radio_collection=collection, clicked_fn=lambda: on_click3()) radbt3 = ui.RadioButton(text ="4", name="four", radio_collection=collection, clicked_fn=lambda: on_click4()) radbt4 = ui.RadioButton(text ="5", name="five", radio_collection=collection, clicked_fn=lambda: on_click5()) radbt5 = ui.RadioButton(text ="6", name="six", radio_collection=collection, clicked_fn=lambda: on_click6()) radbt6 = ui.RadioButton(text ="7", name="seven", radio_collection=collection, clicked_fn=lambda: on_click7()) radbt7 = ui.RadioButton(text ="8", name="eight", radio_collection=collection, clicked_fn=lambda: on_click8()) radbt8 = ui.RadioButton(text ="9", name="nine", radio_collection=collection, clicked_fn=lambda: on_click9()) radbt9 = ui.RadioButton(text ="10", name="ten", radio_collection=collection, clicked_fn=lambda: on_click10())
6,418
Python
47.263158
165
0.509037
stephenT0/funkyboy-camera-speed/exts/Funkyboy.cameraspeed/Funkyboy/cameraspeed/style.py
import omni.ui as ui style1 = { # "RadioButton": { # "border_width": 0.5, # "border_radius": 0.0, # "margin": 5.0, # "padding": 5.0 # }, "RadioButton::one": { "background_color": 0xFF00B976, "border_color": 0xFF272727, }, "RadioButton.Label::one": { "color": 0xFFFFFFFF, }, "RadioButton::two": { "background_color": 0xFF00B976, "border_color": 0xFF00B976 }, "Button.Label::two": { "color": 0xFFFFFFFF }, "RadioButton::three": { "background_color": 0xFF00B976, "border_color": 0xFF00B976 }, "Button.Label::three": { "color": 0xFFFFFFFF }, "RadioButton::four": { "background_color": 0xFF00B976, "border_color": 0xFF00B976 }, "Button.Label::four": { "color": 0xFFFFFFFF }, "RadioButton::five": { "background_color": 0xFF00B976, "border_color": 0xFF00B976 }, "Button.Label::five": { "color": 0xFFFFFFFF }, "RadioButton::six": { "background_color": 0xFF00B976, "border_color": 0xFF00B976 }, "Button.Label::six": { "color": 0xFFFFFFFF }, "RadioButton::seven": { "background_color": 0xFF00B976, "border_color": 0xFF00B976 }, "Button.Label::seven": { "color": 0xFFFFFFFF }, "RadioButton::eight": { "background_color": 0xFF00B976, "border_color": 0xFF00B976 }, "Button.Label::eight": { "color": 0xFFFFFFFF }, "RadioButton::nine": { "background_color": 0xFF00B976, "border_color": 0xFF00B976 }, "Button.Label::nine": { "color": 0xFFFFFFFF }, "RadioButton::ten": { "background_color": 0xFF00B976, "border_color": 0xFF00B976 }, "Button.Label::ten": { "color": 0xFFFFFFFF },}
2,514
Python
29.670731
47
0.393795
stephenT0/funkyboy-camera-speed/exts/Funkyboy.cameraspeed/Funkyboy/cameraspeed/extension.py
#__all__ = ["ExampleWindowExtension"] from .window import SimpleCamWindow, WINDOW_TITLE import omni.ext import omni.kit.ui class SimpleCamExtension(omni.ext.IExt): def on_startup(self, ext_id): self._menu_path = f"Window/{WINDOW_TITLE}" self._window = SimpleCamWindow(WINDOW_TITLE, self._menu_path) self._menu = omni.kit.ui.get_editor_menu().add_item(self._menu_path, self._on_menu_click, True) def on_shutdown(self): omni.kit.ui.get_editor_menu().remove_item(self._menu) if self._window is not None: self._window.destroy() self._window = None def _on_menu_click(self, menu, toggled): if toggled: if self._window is None: self._window = SimpleCamWindow(WINDOW_TITLE, self._menu_path) else: self._window.show() else: if self._window is not None: self._window.hide()
957
Python
25.61111
103
0.591432
stephenT0/funkyboy-camera-speed/exts/Funkyboy.cameraspeed/Funkyboy/cameraspeed/__init__.py
from .extension import *
25
Python
11.999994
24
0.76
stephenT0/funkyboy-camera-speed/exts/Funkyboy.cameraspeed/Funkyboy/cameraspeed/sample_code_for_cam_speed.py
import omni.ext import omni.ui as ui import carb.settings import carb class MyExtension(omni.ext.IExt): def on_startup(self, ext_id): CAMERA_VEL = "/persistent/app/viewport/camMoveVelocity" # Camera velocity setting self._settings = carb.settings.get_settings() # Grab carb settings self._window = ui.Window("My Window", width=300, height=300) with self._window.frame: with ui.VStack(): ui.Label("Some Label") def on_click(): carb.log_info(f"Camera velocity before: {self._settings.get_as_string(CAMERA_VEL)}") # Here is the function we use to set setting values. Setting values are stored inside of carb # so we have to give it the path for that setting, hence why we have CAMERA_VEL # 100 is the new camera speed that is hard coded in, you could put any number there self._settings.set(CAMERA_VEL, 100) carb.log_info(f"Camera velocity after: {self._settings.get_as_string(CAMERA_VEL)}") ui.Button("Click Me", clicked_fn=lambda: on_click()) def on_shutdown(self): print("[omni.code.snippets] MyExtension shutdown") #Thank you Jen from Nvidia Omniverse Discord
1,292
Python
46.888887
113
0.623065
stephenT0/funkyboy-camera-speed/exts/Funkyboy.cameraspeed/Funkyboy/cameraspeed/_ext_copy.py
#__all__ = ["ExampleWindowExtension"] from .window import SimpleCamWindow from functools import partial import asyncio import omni.ext import omni.kit.ui import omni.ui as ui class SimpleCamExtension(omni.ext.IExt): """The entry point for the Simple Cam Window""" WINDOW_NAME = "Camera Speed Selector" MENU_PATH = f"Window/{WINDOW_NAME}" def on_startup(self): # The ability to show up the window if the system requires it. We use it # in QuickLayout. ui.Workspace.set_show_window_fn(SimpleCamExtension.WINDOW_NAME, partial(self.show_window, None)) # Put the new menu editor_menu = omni.kit.ui.get_editor_menu() if editor_menu: self._menu = editor_menu.add_item( SimpleCamExtension.MENU_PATH, self.show_window, toggle=True, value=True ) # Show the window. It will call `self.show_window` ui.Workspace.show_window(SimpleCamExtension.WINDOW_NAME) def on_shutdown(self): self._menu = None if self._window: self._window.destroy() self._window = None # Deregister the function that shows the window from omni.ui ui.Workspace.set_show_window_fn(SimpleCamExtension.WINDOW_NAME, None) def _set_menu(self, value): """Set the menu to create this window on and off""" editor_menu = omni.kit.ui.get_editor_menu() if editor_menu: editor_menu.set_value(SimpleCamExtension.MENU_PATH, value) async def _destroy_window_async(self): # wait one frame, this is due to the one frame defer # in Window::_moveToMainOSWindow() await omni.kit.app.get_app().next_update_async() if self._window: self._window.destroy() self._window = None def _visiblity_changed_fn(self, visible): # Called when the user pressed "X" self._set_menu(visible) if not visible: # Destroy the window, since we are creating new window # in show_window asyncio.ensure_future(self._destroy_window_async()) def show_window(self, menu, value): if value: self._window = SimpleCamWindow(SimpleCamExtension.WINDOW_NAME, width=300, height=150) self._window.set_visibility_changed_fn(self._visiblity_changed_fn) elif self._window: self._window.visible = False
2,413
Python
33.485714
104
0.633237
stephenT0/funkyboy-camera-speed/exts/Funkyboy.cameraspeed/Funkyboy/cameraspeed/_ext_window.py
import carb import omni.ext import omni.kit.ui from .window import MyCustomWindow, WINDOW_TITLE class WindowMenuAddExtension(omni.ext.IExt): def on_startup(self, ext_id): carb.log_info("[maticodes.example.window.add] WindowMenuAddExtension startup") # Note the "Window" part of the path that directs the new menu item to the "Window" menu. self._menu_path = f"Window/{WINDOW_TITLE}" self._window = None self._menu = omni.kit.ui.get_editor_menu().add_item(self._menu_path, self._on_menu_click, True) def on_shutdown(self): carb.log_info("[maticodes.example.window.add] WindowMenuAddExtension shutdown") omni.kit.ui.get_editor_menu().remove_item(self._menu) if self._window is not None: self._window.destroy() self._window = None def _on_menu_click(self, menu, toggled): """Handles showing and hiding the window from the 'Windows' menu.""" if toggled: if self._window is None: self._window = MyCustomWindow(WINDOW_TITLE, self._menu_path) else: self._window.show() else: if self._window is not None: self._window.hide()
1,232
Python
34.22857
103
0.621753
stephenT0/funkyboy-camera-speed/exts/Funkyboy.cameraspeed/Funkyboy/cameraspeed/sample_code_for_slider.py
import omni.ext import omni.ui as ui class MyExtension(omni.ext.IExt): radbt0 = ui.RadioButton radbt1 = ui.RadioButton def on_startup(self, ext_id): print("[funkyboy.hello.world.1] MyExtension startup") self._window = ui.Window("My Window", width=300, height=300) with self._window.frame: with ui.VStack(): def on_click(): print("clicked!") def on_click2(): print("clicked!2") # Added a clicked function to handle the click call def call_clicked(val:int): if val == 0: radbt0.call_clicked_fn() if val == 1: radbt1.call_clicked_fn() collection = ui.RadioCollection() intSlider = ui.IntSlider( collection.model, min=0, max=1, style={ "draw_mode": ui.SliderDrawMode.HANDLE, "background_color": 0xFF00B976, "color": 0xFF00B976, "font_size": 18.0, }) # pass lambda arg.get_value_as_int() to call_Clicked(arg.get_value_as_int()) intSlider.model.add_value_changed_fn(lambda val:call_clicked(val.get_value_as_int())) with ui.HStack(): radbt0 = ui.RadioButton(text ="1",radio_collection=collection, clicked_fn=lambda: on_click()) radbt1 = ui.RadioButton(text ="2", radio_collection=collection, clicked_fn=lambda: on_click2()) def on_shutdown(self): print("[funkyboy.hello.world.1] MyExtension shutdown") #Here is the version with the dictionary. # import omni.ext # import omni.ui as ui # class MyExtension(omni.ext.IExt): # radbt0 = ui.RadioButton # radbt1 = ui.RadioButton # def on_startup(self, ext_id): # print("[funkyboy.hello.world.1] MyExtension startup") # self._window = ui.Window("My Window", width=300, height=300) # with self._window.frame: # with ui.VStack(): # def on_click(): # print("clicked!") # def on_click2(): # print("clicked!2") # collection = ui.RadioCollection() # intSlider = ui.IntSlider( # collection.model, # min=0, # max=1, # style={ # "draw_mode": ui.SliderDrawMode.HANDLE, # "background_color": 0xFF00B976, # "color": 0xFF00B976, # "font_size": 18.0, # }) # # pass lambda arg.get_value_as_int() to call_clicked[(]arg.get_value_as_int()]() # intSlider.model.add_value_changed_fn(lambda val:call_clicked[val.get_value_as_int()]()) # with ui.HStack(): # radbt0 = ui.RadioButton(text ="1",radio_collection=collection, clicked_fn=lambda: on_click()) # radbt1 = ui.RadioButton(text ="2", radio_collection=collection, clicked_fn=lambda: on_click2()) # # call_clicked ditionary approach # # NOTE: no () at the end of the line, instead it is at the end of the add_value_changed_fn call # call_clicked = { # 0:radbt0.call_clicked_fn, # 1:radbt1.call_clicked_fn # } # def on_shutdown(self): # print("[funkyboy.hello.world.1] MyExtension shutdown") #Thank you @ericcraft-mh from Nvidia Omniverse Discord
3,820
Python
46.172839
117
0.491099
stephenT0/funkyboy-camera-speed/exts/Funkyboy.cameraspeed/Funkyboy/cameraspeed/window.py
import omni.ext import omni.ui as ui import carb.settings import carb import omni.kit.commands from .style import style1 WINDOW_TITLE = "Camera Speed Selector" class SimpleCamWindow(ui.Window): def __init__(self, title, menu_path): super().__init__(title, width=300, height=150) self._menu_path = menu_path self.set_visibility_changed_fn(self._on_visibility_changed) self._build_ui() def on_shutdown(self): self._win = None def show(self): self.visible = True self.focus() def hide(self): self.visible = False def _build_ui(self): """ The method that is called to build all the UI once the window is visible. """ CAMERA_VEL = "/persistent/app/viewport/camMoveVelocity" # Camera velocity setting self._settings = carb.settings.get_settings() # Grab carb settings with self.frame: with ui.VStack(): ui.Button("Select a Camera Speed", style={"background_color":0xFF6FF, "color":0xFF00B976, "font_size":20,}, tooltip=" right click + WASD to fly ") # Defining function to Change the Camera Speed def on_click(): self._settings.set(CAMERA_VEL, 0.01) carb.log_info(f"Camera velocity set to {self._settings.get_as_float(CAMERA_VEL)}") def on_click2(): self._settings.set(CAMERA_VEL, 0.1) carb.log_info(f"Camera velocity set to {self._settings.get_as_float(CAMERA_VEL)}") def on_click3(): self._settings.set(CAMERA_VEL, 0.5) carb.log_info(f"Camera velocity set to {self._settings.get_as_float(CAMERA_VEL)}") def on_click4(): self._settings.set(CAMERA_VEL, 2.5) carb.log_info(f"Camera velocity set to {self._settings.get_as_float(CAMERA_VEL)}") def on_click5(): self._settings.set(CAMERA_VEL, 5.0) carb.log_info(f"Camera velocity set to {self._settings.get_as_float(CAMERA_VEL)}") def on_click6(): self._settings.set(CAMERA_VEL, 7.5) carb.log_info(f"Camera velocity set to {self._settings.get_as_float(CAMERA_VEL)}") def on_click7(): self._settings.set(CAMERA_VEL, 10.0) carb.log_info(f"Camera velocity set to {self._settings.get_as_float(CAMERA_VEL)}") def on_click8(): self._settings.set(CAMERA_VEL, 20.0) carb.log_info(f"Camera velocity set to: {self._settings.get_as_float(CAMERA_VEL)}") def on_click9(): self._settings.set(CAMERA_VEL, 30.0) carb.log_info(f"Camera velocity set to: {self._settings.get_as_float(CAMERA_VEL)}") def on_click10(): self._settings.set(CAMERA_VEL, 50.0) carb.log_info(f"Camera velocity set to: {self._settings.get_as_float(CAMERA_VEL)}") def on_click11(): omni.kit.commands.execute('DuplicateFromActiveViewportCameraCommand', viewport_name='Viewport') # Added a clicked function to handle the click call def call_clicked(val:int): if val == 0: radbt0.call_clicked_fn() if val == 1: radbt1.call_clicked_fn() if val == 2: radbt2.call_clicked_fn() if val == 3: radbt3.call_clicked_fn() if val == 4: radbt4.call_clicked_fn() if val == 5: radbt5.call_clicked_fn() if val == 6: radbt6.call_clicked_fn() if val == 7: radbt7.call_clicked_fn() if val == 8: radbt8.call_clicked_fn() if val == 9: radbt9.call_clicked_fn() #the slider collection = ui.RadioCollection() intSlider = ui.IntSlider( collection.model, min=0, max=9, style={ "draw_mode": ui.SliderDrawMode.HANDLE, "background_color": 0xFF00B976, "color": 0xFF00B976, "font_size": 14.0, }) intSlider.model.add_value_changed_fn(lambda val:call_clicked(val.get_value_as_int())) #the buttons with ui.HStack(style=style1): radbt0 = ui.RadioButton(text ="1", name="one", radio_collection=collection, clicked_fn=lambda: on_click()) radbt1 = ui.RadioButton(text ="2", name="two", radio_collection=collection, clicked_fn=lambda: on_click2()) radbt2 = ui.RadioButton(text ="3", name="three", radio_collection=collection, clicked_fn=lambda: on_click3()) radbt3 = ui.RadioButton(text ="4", name="four", radio_collection=collection, clicked_fn=lambda: on_click4()) radbt4 = ui.RadioButton(text ="5", name="five", radio_collection=collection, clicked_fn=lambda: on_click5()) radbt5 = ui.RadioButton(text ="6", name="six", radio_collection=collection, clicked_fn=lambda: on_click6()) radbt6 = ui.RadioButton(text ="7", name="seven", radio_collection=collection, clicked_fn=lambda: on_click7()) radbt7 = ui.RadioButton(text ="8", name="eight", radio_collection=collection, clicked_fn=lambda: on_click8()) radbt8 = ui.RadioButton(text ="9", name="nine", radio_collection=collection, clicked_fn=lambda: on_click9()) radbt9 = ui.RadioButton(text ="10", name="ten", radio_collection=collection, clicked_fn=lambda: on_click10()) #Docking super().dock_in_window("Environments", ui.DockPosition.SAME) def _on_visibility_changed(self, visible): omni.kit.ui.get_editor_menu().set_value(self._menu_path, visible)
6,493
Python
49.341085
165
0.514246
stephenT0/funkyboy-camera-speed/exts/Funkyboy.cameraspeed/config/extension.toml
[package] # Semantic Versionning is used: https://semver.org/ version = "1.2" # The title and description fields are primarily for displaying extension info in UI title = "Simple Camera Speed Selector" description="10 presets for camera speed. Use right click + WASD to fly around" icon = "data/icon.png" preview_image = "data/preview.png" # Path (relative to the root) or content of readme markdown file for UI. readme = "docs/README.md" # URL of the extension source repository. repository = "" # One of categories for UI. category = "UI, Camera" # Keywords for the extension keywords = ["Camera", "Speed", "Scene Navigation"] # Use omni.ui to build simple UI [dependencies] "omni.kit.uiapp" = {} # Main python module this extension provides, it will be publicly available as "import Funkyboy.cameraspeed". [[python.module]] name = "Funkyboy.cameraspeed"
866
TOML
26.967741
109
0.737875
stephenT0/funkyboy-camera-speed/exts/Funkyboy.cameraspeed/docs/CHANGELOG.md
# Changelog ## [0.1.0] 2022-08-18 -Initial version of Simple Camera Speed Selector ## [0.1.1] 2022-09-27 -test for omniverse community tab ## [0.1.2] 2022-10-03 -added Docking
176
Markdown
21.124997
48
0.698864
stephenT0/funkyboy-camera-speed/exts/Funkyboy.cameraspeed/docs/README.md
10 Camera speed presets for scene navigation
49
Markdown
8.999998
45
0.77551