file_path
stringlengths
21
202
content
stringlengths
19
1.02M
size
int64
19
1.02M
lang
stringclasses
8 values
avg_line_length
float64
5.88
100
max_line_length
int64
12
993
alphanum_fraction
float64
0.27
0.93
omniverse-code/kit/exts/usdrt.scenegraph/include/usdrt/scenegraph/interface/IRtAttribute105.h
// Copyright (c) 2022-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. // #pragma once #include "Common.h" #include "IRtAttribute.h" #include <omni/core/IObject.h> #include <omni/fabric/AttrNameAndType.h> #include <omni/fabric/IFabric.h> #include <vector> namespace usdrt { // we must always forward declare each interface that will be referenced here. OMNI_DECLARE_INTERFACE(IRtAttribute105); class IRtAttribute105_abi : public omni::core::Inherits<usdrt::IRtAttribute, OMNI_TYPE_ID("usdrt.IRtAttribute105")> { protected: // all ABI functions must always be 'protected'. // This should have returned ConstSpanC in the original implementation // but it's too late now, so fix it here virtual OMNI_ATTR("not_prop") omni::fabric::ConstSpanC getValueGpuRd_abi() noexcept = 0; virtual bool isCpuDataValid_abi() noexcept = 0; virtual bool isGpuDataValid_abi() noexcept = 0; virtual bool updateCpuDataFromGpu_abi() noexcept = 0; virtual bool updateGpuDataFromCpu_abi() noexcept = 0; // Querying and Editing Connections virtual bool addConnection_abi(const omni::fabric::Connection source, ListPosition position) noexcept = 0; virtual bool removeConnection_abi(const omni::fabric::Connection source) noexcept = 0; virtual bool setConnections_abi(OMNI_ATTR("in, count=size") const omni::fabric::Connection* sources, uint32_t size) noexcept = 0; virtual bool clearConnections_abi() noexcept = 0; virtual bool getConnections_abi(OMNI_ATTR("out, count=size") omni::fabric::Connection* sources, uint32_t size) noexcept = 0; virtual bool hasAuthoredConnections_abi() noexcept = 0; virtual uint32_t numConnections_abi() noexcept = 0; }; } // namespace usdrt #include "IRtAttribute105.gen.h"
2,185
C
39.481481
115
0.729519
omniverse-code/kit/exts/usdrt.scenegraph/include/usdrt/scenegraph/interface/IRtStage.gen.h
// Copyright (c) 2021-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/Interface.h> #include <omni/core/OmniAttr.h> #include <omni/core/ResultError.h> #include <functional> #include <type_traits> #include <utility> #ifndef OMNI_BIND_INCLUDE_INTERFACE_IMPL template <> class omni::core::Generated<usdrt::IRtStage_abi> : public usdrt::IRtStage_abi { public: OMNI_PLUGIN_INTERFACE("usdrt::IRtStage") omni::core::ObjectPtr<usdrt::IRtStage> open(const char* identifier) noexcept; omni::core::ObjectPtr<usdrt::IRtStage> createNew(const char* identifier) noexcept; omni::core::ObjectPtr<usdrt::IRtStage> createInMemory(const char* identifier) noexcept; omni::core::ObjectPtr<usdrt::IRtStage> attach(omni::fabric::UsdStageId stageId, omni::fabric::StageReaderWriterId stageReaderWriterId) noexcept; omni::core::ObjectPtr<usdrt::IRtStage> attachUnknown(omni::fabric::UsdStageId stageId) noexcept; omni::core::ObjectPtr<usdrt::IRtPrim> getDefaultPrim() noexcept; omni::core::ObjectPtr<usdrt::IRtPrim> getPrimAtPath(omni::fabric::PathC path) noexcept; omni::core::ObjectPtr<usdrt::IRtPrim> definePrim(omni::fabric::PathC path, omni::fabric::TokenC typeName) noexcept; bool removePrim(omni::fabric::PathC path) noexcept; omni::core::ObjectPtr<usdrt::IRtAttribute> getAttributeAtPath(omni::fabric::PathC path) noexcept; omni::core::ObjectPtr<usdrt::IRtRelationship> getRelationshipAtPath(omni::fabric::PathC path) noexcept; void done() noexcept; omni::fabric::UsdStageId getStageId() noexcept; void write(const char* filepath) noexcept; bool hasPrimAtPath(omni::fabric::PathC path) noexcept; }; #endif #ifndef OMNI_BIND_INCLUDE_INTERFACE_DECL inline omni::core::ObjectPtr<usdrt::IRtStage> omni::core::Generated<usdrt::IRtStage_abi>::open(const char* identifier) noexcept { return omni::core::steal(open_abi(identifier)); } inline omni::core::ObjectPtr<usdrt::IRtStage> omni::core::Generated<usdrt::IRtStage_abi>::createNew( const char* identifier) noexcept { return omni::core::steal(createNew_abi(identifier)); } inline omni::core::ObjectPtr<usdrt::IRtStage> omni::core::Generated<usdrt::IRtStage_abi>::createInMemory( const char* identifier) noexcept { return omni::core::steal(createInMemory_abi(identifier)); } inline omni::core::ObjectPtr<usdrt::IRtStage> omni::core::Generated<usdrt::IRtStage_abi>::attach( omni::fabric::UsdStageId stageId, omni::fabric::StageReaderWriterId stageReaderWriterId) noexcept { return omni::core::steal(attach_abi(stageId, stageReaderWriterId)); } inline omni::core::ObjectPtr<usdrt::IRtStage> omni::core::Generated<usdrt::IRtStage_abi>::attachUnknown( omni::fabric::UsdStageId stageId) noexcept { return omni::core::steal(attachUnknown_abi(stageId)); } inline omni::core::ObjectPtr<usdrt::IRtPrim> omni::core::Generated<usdrt::IRtStage_abi>::getDefaultPrim() noexcept { return omni::core::steal(getDefaultPrim_abi()); } inline omni::core::ObjectPtr<usdrt::IRtPrim> omni::core::Generated<usdrt::IRtStage_abi>::getPrimAtPath( omni::fabric::PathC path) noexcept { return omni::core::steal(getPrimAtPath_abi(path)); } inline omni::core::ObjectPtr<usdrt::IRtPrim> omni::core::Generated<usdrt::IRtStage_abi>::definePrim( omni::fabric::PathC path, omni::fabric::TokenC typeName) noexcept { return omni::core::steal(definePrim_abi(path, typeName)); } inline bool omni::core::Generated<usdrt::IRtStage_abi>::removePrim(omni::fabric::PathC path) noexcept { return removePrim_abi(path); } inline omni::core::ObjectPtr<usdrt::IRtAttribute> omni::core::Generated<usdrt::IRtStage_abi>::getAttributeAtPath( omni::fabric::PathC path) noexcept { return omni::core::steal(getAttributeAtPath_abi(path)); } inline omni::core::ObjectPtr<usdrt::IRtRelationship> omni::core::Generated<usdrt::IRtStage_abi>::getRelationshipAtPath( omni::fabric::PathC path) noexcept { return omni::core::steal(getRelationshipAtPath_abi(path)); } inline void omni::core::Generated<usdrt::IRtStage_abi>::done() noexcept { done_abi(); } inline omni::fabric::UsdStageId omni::core::Generated<usdrt::IRtStage_abi>::getStageId() noexcept { return getStageId_abi(); } inline void omni::core::Generated<usdrt::IRtStage_abi>::write(const char* filepath) noexcept { write_abi(filepath); } inline bool omni::core::Generated<usdrt::IRtStage_abi>::hasPrimAtPath(omni::fabric::PathC path) noexcept { return hasPrimAtPath_abi(path); } #endif #undef OMNI_BIND_INCLUDE_INTERFACE_DECL #undef OMNI_BIND_INCLUDE_INTERFACE_IMPL
5,183
C
29.315789
127
0.731623
omniverse-code/kit/exts/usdrt.scenegraph/include/usdrt/scenegraph/interface/IRtPrimRange.h
// Copyright (c) 2021-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 "IRtPrim.h" #include <omni/core/IObject.h> namespace usdrt { // we must always forward declare each interface that will be referenced here. OMNI_DECLARE_INTERFACE(IRtPrimRange); // OMNI_DECLARE_INTERFACE(IRtPrim); // ********************************************************************************************************************* // ********************************************************************************************************************* // ********************************************************************************************************************* // // ATTENTION ATTENTION ATTENTION ATTENTION ATTENTION ATTENTION ATTENTION ATTENTION // // The interfaces within these obnoxious comment blocks are now locked for long-term support. // Any changes you wish to make should be added in a new interface. // See this document for more details: // https://docs.google.com/document/d/1xyONwFtiM-lWXP5HjQt6pkOgl7xF_4b_Jp4wUS3_d3I/edit?usp=sharing // // Please do not break our precious ABIs! // // ATTENTION ATTENTION ATTENTION ATTENTION ATTENTION ATTENTION ATTENTION ATTENTION // // ********************************************************************************************************************* // ********************************************************************************************************************* // ********************************************************************************************************************* class IRtPrimRange_abi : public omni::core::Inherits<omni::core::IObject, OMNI_TYPE_ID("usdrt.IRtPrimRange")> { protected: // all ABI functions must always be 'protected'. virtual IRtPrimRange* create_abi(OMNI_ATTR("not_null") IRtPrim* start) noexcept = 0; virtual IRtPrim* get_abi() noexcept = 0; virtual bool next_abi() noexcept = 0; virtual bool done_abi() noexcept = 0; virtual void pruneChildren_abi() noexcept = 0; }; // ********************************************************************************************************************* // ********************************************************************************************************************* // ********************************************************************************************************************* // // ATTENTION ATTENTION ATTENTION ATTENTION ATTENTION ATTENTION ATTENTION ATTENTION // // End of locked interfaces. Enjoy the rest of your day. // // ATTENTION ATTENTION ATTENTION ATTENTION ATTENTION ATTENTION ATTENTION ATTENTION // // ********************************************************************************************************************* // ********************************************************************************************************************* // ********************************************************************************************************************* } // namespace usdrt #include "IRtPrimRange.gen.h"
3,525
C
49.371428
120
0.420142
omniverse-code/kit/exts/usdrt.scenegraph/include/usdrt/scenegraph/interface/Common.h
// Copyright (c) 2022-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. // #pragma once #include <omni/core/IObject.h> namespace usdrt { /// \enum UsdSchemaType /// /// An enum representing which type of schema a given schema class belongs to /// enum class UsdSchemaType { /// Represents abstract or base schema types that are interface-only /// and cannot be instantiated. These are reserved for core base classes /// known to the usdGenSchema system, so this should never be assigned to /// generated schema classes. AbstractBase, /// Represents a non-concrete typed schema AbstractTyped, /// Represents a concrete typed schema ConcreteTyped, /// Non-applied API schema NonAppliedAPI, /// Single Apply API schema SingleApplyAPI, /// Multiple Apply API Schema MultipleApplyAPI }; enum class OMNI_ATTR("prefix=e") ListPosition : uint32_t { eFrontOfPrepend, eBackOfPrepend, eFrontOfAppend, eBackOfAppend }; }
1,355
C
26.673469
77
0.732103
omniverse-code/kit/exts/usdrt.scenegraph/include/usdrt/scenegraph/interface/IRtObject.gen.h
// Copyright (c) 2021-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/Interface.h> #include <omni/core/OmniAttr.h> #include <omni/core/ResultError.h> #include <functional> #include <type_traits> #include <utility> #ifndef OMNI_BIND_INCLUDE_INTERFACE_IMPL template <> class omni::core::Generated<usdrt::IRtObject_abi> : public usdrt::IRtObject_abi { public: OMNI_PLUGIN_INTERFACE("usdrt::IRtObject") bool isValid() noexcept; omni::fabric::TokenC getName() noexcept; omni::fabric::PathC getPrimPath() noexcept; omni::fabric::PathC getPath() noexcept; }; #endif #ifndef OMNI_BIND_INCLUDE_INTERFACE_DECL inline bool omni::core::Generated<usdrt::IRtObject_abi>::isValid() noexcept { return isValid_abi(); } inline omni::fabric::TokenC omni::core::Generated<usdrt::IRtObject_abi>::getName() noexcept { return getName_abi(); } inline omni::fabric::PathC omni::core::Generated<usdrt::IRtObject_abi>::getPrimPath() noexcept { return getPrimPath_abi(); } inline omni::fabric::PathC omni::core::Generated<usdrt::IRtObject_abi>::getPath() noexcept { return getPath_abi(); } #endif #undef OMNI_BIND_INCLUDE_INTERFACE_DECL #undef OMNI_BIND_INCLUDE_INTERFACE_IMPL
1,741
C
22.54054
94
0.724871
omniverse-code/kit/exts/usdrt.scenegraph/include/usdrt/scenegraph/interface/IRtAttribute.gen.h
// Copyright (c) 2021-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/Interface.h> #include <omni/core/OmniAttr.h> #include <omni/core/ResultError.h> #include <functional> #include <type_traits> #include <utility> #ifndef OMNI_BIND_INCLUDE_INTERFACE_IMPL template <> class omni::core::Generated<usdrt::IRtAttribute_abi> : public usdrt::IRtAttribute_abi { public: OMNI_PLUGIN_INTERFACE("usdrt::IRtAttribute") bool hasValue() noexcept; bool hasAuthoredValue() noexcept; bool hasAuthoredValueGpu() noexcept; omni::fabric::ConstSpanC getValue() noexcept; omni::fabric::SpanC getValueGpu() noexcept; omni::fabric::SpanC setValue() noexcept; omni::fabric::SpanC setValueGpu() noexcept; size_t getValueArraySize() noexcept; void setValueNewArraySize(size_t size) noexcept; omni::fabric::TypeC getTypeName() noexcept; }; #endif #ifndef OMNI_BIND_INCLUDE_INTERFACE_DECL inline bool omni::core::Generated<usdrt::IRtAttribute_abi>::hasValue() noexcept { return hasValue_abi(); } inline bool omni::core::Generated<usdrt::IRtAttribute_abi>::hasAuthoredValue() noexcept { return hasAuthoredValue_abi(); } inline bool omni::core::Generated<usdrt::IRtAttribute_abi>::hasAuthoredValueGpu() noexcept { return hasAuthoredValueGpu_abi(); } inline omni::fabric::ConstSpanC omni::core::Generated<usdrt::IRtAttribute_abi>::getValue() noexcept { return getValue_abi(); } inline omni::fabric::SpanC omni::core::Generated<usdrt::IRtAttribute_abi>::getValueGpu() noexcept { return getValueGpu_abi(); } inline omni::fabric::SpanC omni::core::Generated<usdrt::IRtAttribute_abi>::setValue() noexcept { return setValue_abi(); } inline omni::fabric::SpanC omni::core::Generated<usdrt::IRtAttribute_abi>::setValueGpu() noexcept { return setValueGpu_abi(); } inline size_t omni::core::Generated<usdrt::IRtAttribute_abi>::getValueArraySize() noexcept { return getValueArraySize_abi(); } inline void omni::core::Generated<usdrt::IRtAttribute_abi>::setValueNewArraySize(size_t size) noexcept { setValueNewArraySize_abi(size); } inline omni::fabric::TypeC omni::core::Generated<usdrt::IRtAttribute_abi>::getTypeName() noexcept { return getTypeName_abi(); } #endif #undef OMNI_BIND_INCLUDE_INTERFACE_DECL #undef OMNI_BIND_INCLUDE_INTERFACE_IMPL
2,864
C
22.483606
102
0.73324
omniverse-code/kit/exts/usdrt.scenegraph/include/usdrt/scenegraph/interface/IRtAssetPath.h
// Copyright (c) 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. // #pragma once #include <omni/core/IObject.h> #include <omni/fabric/IToken.h> namespace usdrt { // we must always forward declare each interface that will be referenced here. OMNI_DECLARE_INTERFACE(IRtAssetPath); class IRtAssetPath_abi : public omni::core::Inherits<omni::core::IObject, OMNI_TYPE_ID("usdrt.IRtAssetPath")> { protected: // all ABI functions must always be 'protected'. virtual IRtAssetPath* create_abi(OMNI_ATTR("not_null, c_str") const char* assetPath) noexcept = 0; virtual IRtAssetPath* createWithResolved_abi(OMNI_ATTR("not_null, c_str") const char* assetPath, OMNI_ATTR("not_null, c_str") const char* resolvedPath) noexcept = 0; virtual OMNI_ATTR("not_prop") const char* getAssetPath_abi() noexcept = 0; virtual OMNI_ATTR("not_prop") const char* getResolvedPath_abi() noexcept = 0; // RT-only virtual IRtAssetPath* createFromFabric_abi(OMNI_ATTR("not_null, in") const void* fabricAssetPath) noexcept = 0; virtual OMNI_ATTR("not_prop") omni::fabric::TokenC getAssetPathC_abi() noexcept = 0; virtual OMNI_ATTR("not_prop") omni::fabric::TokenC getResolvedPathC_abi() noexcept = 0; }; } // namespace usdrt #include "IRtAssetPath.gen.h"
1,675
C
40.899999
117
0.724776
omniverse-code/kit/exts/usdrt.scenegraph/include/usdrt/scenegraph/interface/IRtPrimRange.gen.h
// Copyright (c) 2021-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/Interface.h> #include <omni/core/OmniAttr.h> #include <omni/core/ResultError.h> #include <functional> #include <type_traits> #include <utility> #ifndef OMNI_BIND_INCLUDE_INTERFACE_IMPL template <> class omni::core::Generated<usdrt::IRtPrimRange_abi> : public usdrt::IRtPrimRange_abi { public: OMNI_PLUGIN_INTERFACE("usdrt::IRtPrimRange") omni::core::ObjectPtr<usdrt::IRtPrimRange> create(omni::core::ObjectParam<usdrt::IRtPrim> start) noexcept; omni::core::ObjectPtr<usdrt::IRtPrim> get() noexcept; bool next() noexcept; bool done() noexcept; void pruneChildren() noexcept; }; #endif #ifndef OMNI_BIND_INCLUDE_INTERFACE_DECL inline omni::core::ObjectPtr<usdrt::IRtPrimRange> omni::core::Generated<usdrt::IRtPrimRange_abi>::create( omni::core::ObjectParam<usdrt::IRtPrim> start) noexcept { return omni::core::steal(create_abi(start.get())); } inline omni::core::ObjectPtr<usdrt::IRtPrim> omni::core::Generated<usdrt::IRtPrimRange_abi>::get() noexcept { return omni::core::steal(get_abi()); } inline bool omni::core::Generated<usdrt::IRtPrimRange_abi>::next() noexcept { return next_abi(); } inline bool omni::core::Generated<usdrt::IRtPrimRange_abi>::done() noexcept { return done_abi(); } inline void omni::core::Generated<usdrt::IRtPrimRange_abi>::pruneChildren() noexcept { pruneChildren_abi(); } #endif #undef OMNI_BIND_INCLUDE_INTERFACE_DECL #undef OMNI_BIND_INCLUDE_INTERFACE_IMPL
2,063
C
23.86747
110
0.724673
omniverse-code/kit/exts/usdrt.scenegraph/include/usdrt/scenegraph/interface/IRtAttribute.h
// Copyright (c) 2021-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 "IRtProperty.h" #include <omni/core/IObject.h> #include <omni/fabric/AttrNameAndType.h> #include <omni/fabric/IFabric.h> #include <vector> namespace usdrt { // we must always forward declare each interface that will be referenced here. OMNI_DECLARE_INTERFACE(IRtAttribute); // ********************************************************************************************************************* // ********************************************************************************************************************* // ********************************************************************************************************************* // // ATTENTION ATTENTION ATTENTION ATTENTION ATTENTION ATTENTION ATTENTION ATTENTION // // The interfaces within these obnoxious comment blocks are now locked for long-term support. // Any changes you wish to make should be added in a new interface. // See this document for more details: // https://docs.google.com/document/d/1xyONwFtiM-lWXP5HjQt6pkOgl7xF_4b_Jp4wUS3_d3I/edit?usp=sharing // // Please do not break our precious ABIs! // // ATTENTION ATTENTION ATTENTION ATTENTION ATTENTION ATTENTION ATTENTION ATTENTION // // ********************************************************************************************************************* // ********************************************************************************************************************* // ********************************************************************************************************************* class IRtAttribute_abi : public omni::core::Inherits<usdrt::IRtProperty, OMNI_TYPE_ID("usdrt.IRtAttribute")> { protected: // all ABI functions must always be 'protected'. // ---- values virtual bool hasValue_abi() noexcept = 0; virtual bool hasAuthoredValue_abi() noexcept = 0; virtual bool hasAuthoredValueGpu_abi() noexcept = 0; virtual OMNI_ATTR("not_prop") omni::fabric::ConstSpanC getValue_abi() noexcept = 0; virtual OMNI_ATTR("not_prop") omni::fabric::SpanC getValueGpu_abi() noexcept = 0; virtual OMNI_ATTR("not_prop") omni::fabric::SpanC setValue_abi() noexcept = 0; virtual OMNI_ATTR("not_prop") omni::fabric::SpanC setValueGpu_abi() noexcept = 0; virtual OMNI_ATTR("not_prop") size_t getValueArraySize_abi() noexcept = 0; // setValueNewArraySize() should be called before setValue() when // writing a new array value to fabric virtual OMNI_ATTR("not_prop") void setValueNewArraySize_abi(size_t size) noexcept = 0; // ---- metadata virtual OMNI_ATTR("not_prop") omni::fabric::TypeC getTypeName_abi() noexcept = 0; }; // ********************************************************************************************************************* // ********************************************************************************************************************* // ********************************************************************************************************************* // // ATTENTION ATTENTION ATTENTION ATTENTION ATTENTION ATTENTION ATTENTION ATTENTION // // End of locked interfaces. Enjoy the rest of your day. // // ATTENTION ATTENTION ATTENTION ATTENTION ATTENTION ATTENTION ATTENTION ATTENTION // // ********************************************************************************************************************* // ********************************************************************************************************************* // ********************************************************************************************************************* } // namespace usdrt #include "IRtAttribute.gen.h"
4,228
C
48.752941
120
0.46736
omniverse-code/kit/exts/usdrt.scenegraph/include/usdrt/scenegraph/interface/IRtStage105.h
// Copyright (c) 2021-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. // #pragma once #include "IRtStage.h" #include <omni/core/IObject.h> #include <omni/fabric/IFabric.h> #include <omni/fabric/IPath.h> #include <omni/fabric/IToken.h> #include <usdrt/gf/range.h> namespace usdrt { // we must always forward declare each interface that will be referenced here. OMNI_DECLARE_INTERFACE(IRtStage105); class IRtStage105_abi : public omni::core::Inherits<IRtStage, OMNI_TYPE_ID("usdrt.IRtStage105")> { protected: // all ABI functions must always be 'protected'. virtual uint32_t findCount_abi(omni::fabric::TokenC typeName, OMNI_ATTR("in, count=apiNamesSize") const omni::fabric::TokenC* apiNames, uint32_t apiNamesSize) noexcept = 0; virtual bool find_abi(omni::fabric::TokenC typeName, OMNI_ATTR("in, count=apiNamesSize") const omni::fabric::TokenC* apiNames, uint32_t apiNamesSize, OMNI_ATTR("out, count=outPathCount") omni::fabric::PathC* outPaths, uint32_t outPathCount) noexcept = 0; virtual bool computeWorldBound_abi(OMNI_ATTR("out") GfRange3d* result) noexcept = 0; // ---- new attr methods to include token virtual OMNI_ATTR("not_prop") IRtAttribute* getAttributeAtPath105_abi(omni::fabric::PathC path, omni::fabric::TokenC prop) noexcept = 0; virtual OMNI_ATTR("not_prop") IRtRelationship* getRelationshipAtPath105_abi(omni::fabric::PathC path, omni::fabric::TokenC prop) noexcept = 0; // ---- additional flag on hasPrimAtPath to ignore tags from stage query api virtual bool hasPrimAtPath105_abi(omni::fabric::PathC path, bool excludeTags) noexcept = 0; }; } // namespace usdrt #include "IRtStage105.gen.h"
2,349
C
44.192307
120
0.65049
omniverse-code/kit/exts/usdrt.scenegraph/include/usdrt/scenegraph/interface/IRtPrim105.h
// Copyright (c) 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. // #pragma once #include "IRtAttribute.h" #include "IRtPrim.h" #include <omni/core/IObject.h> #include <omni/fabric/Type.h> namespace usdrt { // we must always forward declare each interface that will be referenced here. OMNI_DECLARE_INTERFACE(IRtPrim105); class IRtPrim105_abi : public omni::core::Inherits<IRtPrim, OMNI_TYPE_ID("usdrt.IRtPrim105")> { protected: // all ABI functions must always be 'protected'. virtual OMNI_ATTR("not_prop") uint32_t getAttributesWithTypeCount_abi(omni::fabric::TypeC attrType) noexcept = 0; virtual OMNI_ATTR("not_prop, no_api") bool getAttributesWithType_abi(omni::fabric::TypeC attrType, OMNI_ATTR("out, count=attrsSize, *not_null") IRtAttribute** attrs, uint32_t attrsSize) noexcept = 0; }; } // namespace usdrt #include "IRtPrim105.gen.h" // clang-format off OMNI_DEFINE_INTERFACE_API(usdrt::IRtPrim105) { public: bool getAttributesWithType(omni::fabric::TypeC attrType, usdrt::IRtAttribute** attrs, uint32_t attrsSize) noexcept { if (attrsSize == 0) { return false; } return getAttributesWithType_abi(attrType, attrs, attrsSize); } }; // clang-format on
1,825
C
32.199999
118
0.644384
omniverse-code/kit/exts/usdrt.scenegraph/include/usdrt/scenegraph/interface/IRtStage104QuerySupport.gen.h
// Copyright (c) 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. // // --------- Warning: This is a build system generated file. ---------- // //! @file //! //! @brief This file was generated by <i>omni.bind</i>. #include <omni/core/Interface.h> #include <omni/core/OmniAttr.h> #include <omni/core/ResultError.h> #include <functional> #include <type_traits> #include <utility> #ifndef OMNI_BIND_INCLUDE_INTERFACE_IMPL template <> class omni::core::Generated<usdrt::IRtStage104QuerySupport_abi> : public usdrt::IRtStage104QuerySupport_abi { public: OMNI_PLUGIN_INTERFACE("usdrt::IRtStage104QuerySupport") uint32_t findCount(omni::fabric::TokenC typeName, const omni::fabric::TokenC* apiNames, uint32_t apiNamesSize) noexcept; bool find(omni::fabric::TokenC typeName, const omni::fabric::TokenC* apiNames, uint32_t apiNamesSize, omni::fabric::PathC* outPaths, uint32_t outPathCount) noexcept; bool computeWorldBound(usdrt::GfRange3d* result) noexcept; }; #endif #ifndef OMNI_BIND_INCLUDE_INTERFACE_DECL inline uint32_t omni::core::Generated<usdrt::IRtStage104QuerySupport_abi>::findCount(omni::fabric::TokenC typeName, const omni::fabric::TokenC* apiNames, uint32_t apiNamesSize) noexcept { return findCount_abi(typeName, apiNames, apiNamesSize); } inline bool omni::core::Generated<usdrt::IRtStage104QuerySupport_abi>::find(omni::fabric::TokenC typeName, const omni::fabric::TokenC* apiNames, uint32_t apiNamesSize, omni::fabric::PathC* outPaths, uint32_t outPathCount) noexcept { return find_abi(typeName, apiNames, apiNamesSize, outPaths, outPathCount); } inline bool omni::core::Generated<usdrt::IRtStage104QuerySupport_abi>::computeWorldBound(usdrt::GfRange3d* result) noexcept { return computeWorldBound_abi(result); } #endif #undef OMNI_BIND_INCLUDE_INTERFACE_DECL #undef OMNI_BIND_INCLUDE_INTERFACE_IMPL
2,753
C
35.236842
124
0.615692
omniverse-code/kit/exts/usdrt.scenegraph/include/usdrt/scenegraph/interface/IRtRelationship.gen.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. // // --------- Warning: This is a build system generated file. ---------- // //! @file //! //! @brief This file was generated by <i>omni.bind</i>. #include <omni/core/Interface.h> #include <omni/core/OmniAttr.h> #include <omni/core/ResultError.h> #include <functional> #include <type_traits> #include <utility> #ifndef OMNI_BIND_INCLUDE_INTERFACE_IMPL template <> class omni::core::Generated<usdrt::IRtRelationship_abi> : public usdrt::IRtRelationship_abi { public: OMNI_PLUGIN_INTERFACE("usdrt::IRtRelationship") bool hasAuthoredTargets() noexcept; bool addTarget(omni::fabric::PathC path, usdrt::ListPosition position) noexcept; bool removeTarget(omni::fabric::PathC path) noexcept; bool setTargets(const omni::fabric::PathC* paths, uint32_t size) noexcept; bool clearTargets() noexcept; uint32_t numTargets() noexcept; bool getTargets(omni::fabric::PathC* paths, uint32_t size) noexcept; }; #endif #ifndef OMNI_BIND_INCLUDE_INTERFACE_DECL inline bool omni::core::Generated<usdrt::IRtRelationship_abi>::hasAuthoredTargets() noexcept { return hasAuthoredTargets_abi(); } inline bool omni::core::Generated<usdrt::IRtRelationship_abi>::addTarget(omni::fabric::PathC path, usdrt::ListPosition position) noexcept { return addTarget_abi(path, position); } inline bool omni::core::Generated<usdrt::IRtRelationship_abi>::removeTarget(omni::fabric::PathC path) noexcept { return removeTarget_abi(path); } inline bool omni::core::Generated<usdrt::IRtRelationship_abi>::setTargets(const omni::fabric::PathC* paths, uint32_t size) noexcept { return setTargets_abi(paths, size); } inline bool omni::core::Generated<usdrt::IRtRelationship_abi>::clearTargets() noexcept { return clearTargets_abi(); } inline uint32_t omni::core::Generated<usdrt::IRtRelationship_abi>::numTargets() noexcept { return numTargets_abi(); } inline bool omni::core::Generated<usdrt::IRtRelationship_abi>::getTargets(omni::fabric::PathC* paths, uint32_t size) noexcept { return getTargets_abi(paths, size); } #endif #undef OMNI_BIND_INCLUDE_INTERFACE_DECL #undef OMNI_BIND_INCLUDE_INTERFACE_IMPL
2,729
C
26.3
125
0.702089
omniverse-code/kit/exts/usdrt.scenegraph/include/usdrt/scenegraph/interface/IRtProperty.h
// Copyright (c) 2021-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 "IRtObject.h" #include <omni/core/IObject.h> #include <omni/extras/OutArrayUtils.h> #include <omni/fabric/IPath.h> #include <omni/fabric/IToken.h> #include <omni/str/IReadOnlyCString.h> #include <vector> namespace usdrt { // we must always forward declare each interface that will be referenced here. OMNI_DECLARE_INTERFACE(IRtProperty); // ********************************************************************************************************************* // ********************************************************************************************************************* // ********************************************************************************************************************* // // ATTENTION ATTENTION ATTENTION ATTENTION ATTENTION ATTENTION ATTENTION ATTENTION // // The interfaces within these obnoxious comment blocks are now locked for long-term support. // Any changes you wish to make should be added in a new interface. // See this document for more details: // https://docs.google.com/document/d/1xyONwFtiM-lWXP5HjQt6pkOgl7xF_4b_Jp4wUS3_d3I/edit?usp=sharing // // Please do not break our precious ABIs! // // ATTENTION ATTENTION ATTENTION ATTENTION ATTENTION ATTENTION ATTENTION ATTENTION // // ********************************************************************************************************************* // ********************************************************************************************************************* // ********************************************************************************************************************* class IRtProperty_abi : public omni::core::Inherits<usdrt::IRtObject, OMNI_TYPE_ID("usdrt.IRtPropety")> { protected: // all ABI functions must always be 'protected'. // ---- property name virtual OMNI_ATTR("not_prop") omni::str::IReadOnlyCString* getBaseName_abi() noexcept = 0; virtual OMNI_ATTR("not_prop") omni::str::IReadOnlyCString* getNamespace_abi() noexcept = 0; virtual OMNI_ATTR("no_api") omni::core::Result splitName_abi(OMNI_ATTR("out, count=*partsCount, *not_null") omni::str::IReadOnlyCString** parts, OMNI_ATTR("out, not_null") uint32_t* partsCount) noexcept = 0; }; // ********************************************************************************************************************* // ********************************************************************************************************************* // ********************************************************************************************************************* // // ATTENTION ATTENTION ATTENTION ATTENTION ATTENTION ATTENTION ATTENTION ATTENTION // // End of locked interfaces. Enjoy the rest of your day. // // ATTENTION ATTENTION ATTENTION ATTENTION ATTENTION ATTENTION ATTENTION ATTENTION // // ********************************************************************************************************************* // ********************************************************************************************************************* // ********************************************************************************************************************* } // namespace usdrt #include "IRtProperty.gen.h" // clang-format off OMNI_DEFINE_INTERFACE_API(usdrt::IRtProperty) { public: std::vector<std::string> splitName() noexcept { std::vector<omni::core::ObjectPtr<omni::str::IReadOnlyCString>> vec; auto result = omni::extras::getOutArray<omni::str::IReadOnlyCString*>( [this](omni::str::IReadOnlyCString** out, uint32_t* outCount) // get func { std::memset(out, 0, sizeof(omni::str::IReadOnlyCString*) * *outCount); // incoming ptrs must be nullptr return this->splitName_abi(out, outCount); }, [&vec](omni::str::IReadOnlyCString** in, uint32_t inCount) // fill func { vec.reserve(inCount); for (uint32_t i = 0; i < inCount; ++i) { vec.emplace_back(in[i], omni::core::kSteal); } } ); std::vector<std::string> out; out.reserve(vec.size()); for (const auto& roc : vec) { out.push_back(std::string(roc->getBuffer())); } return out; } }; // clang-format on
4,985
C
43.517857
120
0.45677
omniverse-code/kit/exts/usdrt.scenegraph/include/usdrt/scenegraph/interface/IRtAttribute105.gen.h
// Copyright (c) 2022-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. // // --------- Warning: This is a build system generated file. ---------- // //! @file //! //! @brief This file was generated by <i>omni.bind</i>. #include <omni/core/Interface.h> #include <omni/core/OmniAttr.h> #include <omni/core/ResultError.h> #include <functional> #include <type_traits> #include <utility> #ifndef OMNI_BIND_INCLUDE_INTERFACE_IMPL template <> class omni::core::Generated<usdrt::IRtAttribute105_abi> : public usdrt::IRtAttribute105_abi { public: OMNI_PLUGIN_INTERFACE("usdrt::IRtAttribute105") omni::fabric::ConstSpanC getValueGpuRd() noexcept; bool isCpuDataValid() noexcept; bool isGpuDataValid() noexcept; bool updateCpuDataFromGpu() noexcept; bool updateGpuDataFromCpu() noexcept; bool addConnection(omni::fabric::Connection source, usdrt::ListPosition position) noexcept; bool removeConnection(omni::fabric::Connection source) noexcept; bool setConnections(const omni::fabric::Connection* sources, uint32_t size) noexcept; bool clearConnections() noexcept; bool getConnections(omni::fabric::Connection* sources, uint32_t size) noexcept; bool hasAuthoredConnections() noexcept; uint32_t numConnections() noexcept; }; #endif #ifndef OMNI_BIND_INCLUDE_INTERFACE_DECL inline omni::fabric::ConstSpanC omni::core::Generated<usdrt::IRtAttribute105_abi>::getValueGpuRd() noexcept { return getValueGpuRd_abi(); } inline bool omni::core::Generated<usdrt::IRtAttribute105_abi>::isCpuDataValid() noexcept { return isCpuDataValid_abi(); } inline bool omni::core::Generated<usdrt::IRtAttribute105_abi>::isGpuDataValid() noexcept { return isGpuDataValid_abi(); } inline bool omni::core::Generated<usdrt::IRtAttribute105_abi>::updateCpuDataFromGpu() noexcept { return updateCpuDataFromGpu_abi(); } inline bool omni::core::Generated<usdrt::IRtAttribute105_abi>::updateGpuDataFromCpu() noexcept { return updateGpuDataFromCpu_abi(); } inline bool omni::core::Generated<usdrt::IRtAttribute105_abi>::addConnection(omni::fabric::Connection source, usdrt::ListPosition position) noexcept { return addConnection_abi(source, position); } inline bool omni::core::Generated<usdrt::IRtAttribute105_abi>::removeConnection(omni::fabric::Connection source) noexcept { return removeConnection_abi(source); } inline bool omni::core::Generated<usdrt::IRtAttribute105_abi>::setConnections(const omni::fabric::Connection* sources, uint32_t size) noexcept { return setConnections_abi(sources, size); } inline bool omni::core::Generated<usdrt::IRtAttribute105_abi>::clearConnections() noexcept { return clearConnections_abi(); } inline bool omni::core::Generated<usdrt::IRtAttribute105_abi>::getConnections(omni::fabric::Connection* sources, uint32_t size) noexcept { return getConnections_abi(sources, size); } inline bool omni::core::Generated<usdrt::IRtAttribute105_abi>::hasAuthoredConnections() noexcept { return hasAuthoredConnections_abi(); } inline uint32_t omni::core::Generated<usdrt::IRtAttribute105_abi>::numConnections() noexcept { return numConnections_abi(); } #endif #undef OMNI_BIND_INCLUDE_INTERFACE_DECL #undef OMNI_BIND_INCLUDE_INTERFACE_IMPL
3,866
C
26.425532
121
0.708226
omniverse-code/kit/exts/usdrt.scenegraph/include/usdrt/scenegraph/interface/IRtObject.h
// Copyright (c) 2021-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/core/IObject.h> #include <omni/fabric/IPath.h> #include <omni/fabric/IToken.h> #include <vector> namespace usdrt { // we must always forward declare each interface that will be referenced here. OMNI_DECLARE_INTERFACE(IRtObject); OMNI_DECLARE_INTERFACE(IRtPrim); OMNI_DECLARE_INTERFACE(IRtStage); // ********************************************************************************************************************* // ********************************************************************************************************************* // ********************************************************************************************************************* // // ATTENTION ATTENTION ATTENTION ATTENTION ATTENTION ATTENTION ATTENTION ATTENTION // // The interfaces within these obnoxious comment blocks are now locked for long-term support. // Any changes you wish to make should be added in a new interface. // See this document for more details: // https://docs.google.com/document/d/1xyONwFtiM-lWXP5HjQt6pkOgl7xF_4b_Jp4wUS3_d3I/edit?usp=sharing // // Please do not break our precious ABIs! // // ATTENTION ATTENTION ATTENTION ATTENTION ATTENTION ATTENTION ATTENTION ATTENTION // // ********************************************************************************************************************* // ********************************************************************************************************************* // ********************************************************************************************************************* class IRtObject_abi : public omni::core::Inherits<omni::core::IObject, OMNI_TYPE_ID("usdrt.IRtObject")> { protected: // all ABI functions must always be 'protected'. // ---- validity virtual bool isValid_abi() noexcept = 0; // ---- context virtual OMNI_ATTR("not_prop, no_api") IRtPrim* getPrim_abi() noexcept = 0; virtual OMNI_ATTR("not_prop, no_api") IRtStage* getStage_abi() noexcept = 0; virtual OMNI_ATTR("not_prop") omni::fabric::TokenC getName_abi() noexcept = 0; virtual OMNI_ATTR("not_prop") omni::fabric::PathC getPrimPath_abi() noexcept = 0; virtual OMNI_ATTR("not_prop") omni::fabric::PathC getPath_abi() noexcept = 0; }; // ********************************************************************************************************************* // ********************************************************************************************************************* // ********************************************************************************************************************* // // ATTENTION ATTENTION ATTENTION ATTENTION ATTENTION ATTENTION ATTENTION ATTENTION // // End of locked interfaces. Enjoy the rest of your day. // // ATTENTION ATTENTION ATTENTION ATTENTION ATTENTION ATTENTION ATTENTION ATTENTION // // ********************************************************************************************************************* // ********************************************************************************************************************* // ********************************************************************************************************************* } // namespace usdrt #include "IRtObject.gen.h" // FIXME omni.bind doesn't generate ObjectPtr correctly with forward declarations, // as far as I can tell, or I'm missing something important // clang-format off OMNI_DEFINE_INTERFACE_API(usdrt::IRtObject) { public: omni::core::ObjectPtr<usdrt::IRtPrim> getPrim() noexcept { return omni::core::steal(getPrim_abi()); } omni::core::ObjectPtr<usdrt::IRtStage> getStage() noexcept { return omni::core::steal(getStage_abi()); } }; // clang-format on
4,320
C
44.010416
120
0.466435
omniverse-code/kit/exts/usdrt.scenegraph/include/usdrt/scenegraph/interface/IRtSchemaRegistry.gen.h
// Copyright (c) 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. // // --------- Warning: This is a build system generated file. ---------- // //! @file //! //! @brief This file was generated by <i>omni.bind</i>. #include <omni/core/Interface.h> #include <omni/core/OmniAttr.h> #include <omni/core/ResultError.h> #include <functional> #include <type_traits> #include <utility> #ifndef OMNI_BIND_INCLUDE_INTERFACE_IMPL template <> class omni::core::Generated<usdrt::IRtSchemaRegistry_abi> : public usdrt::IRtSchemaRegistry_abi { public: OMNI_PLUGIN_INTERFACE("usdrt::IRtSchemaRegistry") omni::core::ObjectPtr<usdrt::IRtSchemaRegistry> initRegistry() noexcept; bool isConcrete(omni::fabric::TokenC primTypeC) noexcept; bool isAppliedAPISchema(omni::fabric::TokenC apiSchemaTypeC) noexcept; bool isMultipleApplyAPISchema(omni::fabric::TokenC apiSchemaTypeC) noexcept; bool isA(omni::fabric::TokenC sourceTypeNameC, omni::fabric::TokenC queryTypeNameC) noexcept; omni::fabric::TokenC getAliasFromName(omni::fabric::TokenC nameC) noexcept; }; #endif #ifndef OMNI_BIND_INCLUDE_INTERFACE_DECL inline omni::core::ObjectPtr<usdrt::IRtSchemaRegistry> omni::core::Generated<usdrt::IRtSchemaRegistry_abi>::initRegistry() noexcept { return omni::core::steal(initRegistry_abi()); } inline bool omni::core::Generated<usdrt::IRtSchemaRegistry_abi>::isConcrete(omni::fabric::TokenC primTypeC) noexcept { return isConcrete_abi(primTypeC); } inline bool omni::core::Generated<usdrt::IRtSchemaRegistry_abi>::isAppliedAPISchema(omni::fabric::TokenC apiSchemaTypeC) noexcept { return isAppliedAPISchema_abi(apiSchemaTypeC); } inline bool omni::core::Generated<usdrt::IRtSchemaRegistry_abi>::isMultipleApplyAPISchema( omni::fabric::TokenC apiSchemaTypeC) noexcept { return isMultipleApplyAPISchema_abi(apiSchemaTypeC); } inline bool omni::core::Generated<usdrt::IRtSchemaRegistry_abi>::isA(omni::fabric::TokenC sourceTypeNameC, omni::fabric::TokenC queryTypeNameC) noexcept { return isA_abi(sourceTypeNameC, queryTypeNameC); } inline omni::fabric::TokenC omni::core::Generated<usdrt::IRtSchemaRegistry_abi>::getAliasFromName( omni::fabric::TokenC nameC) noexcept { return getAliasFromName_abi(nameC); } #endif #undef OMNI_BIND_INCLUDE_INTERFACE_DECL #undef OMNI_BIND_INCLUDE_INTERFACE_IMPL
2,790
C
29.010752
131
0.743011
omniverse-code/kit/exts/usdrt.scenegraph/include/usdrt/scenegraph/interface/IRtStage.h
// Copyright (c) 2021-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 "IRtAttribute.h" #include "IRtPrim.h" #include "IRtRelationship.h" #include <omni/core/IObject.h> #include <omni/fabric/IFabric.h> #include <omni/fabric/IPath.h> #include <omni/fabric/IToken.h> namespace usdrt { // we must always forward declare each interface that will be referenced here. OMNI_DECLARE_INTERFACE(IRtStage); // ********************************************************************************************************************* // ********************************************************************************************************************* // ********************************************************************************************************************* // // ATTENTION ATTENTION ATTENTION ATTENTION ATTENTION ATTENTION ATTENTION ATTENTION // // The interfaces within these obnoxious comment blocks are now locked for long-term support. // Any changes you wish to make should be added in a new interface. // See this document for more details: // https://docs.google.com/document/d/1xyONwFtiM-lWXP5HjQt6pkOgl7xF_4b_Jp4wUS3_d3I/edit?usp=sharing // // Please do not break our precious ABIs! // // ATTENTION ATTENTION ATTENTION ATTENTION ATTENTION ATTENTION ATTENTION ATTENTION // // ********************************************************************************************************************* // ********************************************************************************************************************* // ********************************************************************************************************************* class IRtStage_abi : public omni::core::Inherits<omni::core::IObject, OMNI_TYPE_ID("usdrt.IRtStage")> { protected: // all ABI functions must always be 'protected'. // ---- static methods virtual IRtStage* open_abi(OMNI_ATTR("c_str, in, not_null") const char* identifier) noexcept = 0; virtual IRtStage* createNew_abi(OMNI_ATTR("c_str, in, not_null") const char* identifier) noexcept = 0; virtual IRtStage* createInMemory_abi(OMNI_ATTR("c_str, in, not_null") const char* identifier) noexcept = 0; virtual IRtStage* attach_abi(omni::fabric::UsdStageId stageId, omni::fabric::StageReaderWriterId stageReaderWriterId) noexcept = 0; virtual IRtStage* attachUnknown_abi(omni::fabric::UsdStageId stageId) noexcept = 0; // ---- prim methods virtual OMNI_ATTR("not_prop") IRtPrim* getDefaultPrim_abi() noexcept = 0; virtual OMNI_ATTR("not_prop") IRtPrim* getPrimAtPath_abi(omni::fabric::PathC path) noexcept = 0; virtual IRtPrim* definePrim_abi(omni::fabric::PathC path, omni::fabric::TokenC typeName) noexcept = 0; virtual bool removePrim_abi(omni::fabric::PathC path) noexcept = 0; // ---- attr methods virtual OMNI_ATTR("not_prop") IRtAttribute* getAttributeAtPath_abi(omni::fabric::PathC path) noexcept = 0; virtual OMNI_ATTR("not_prop") IRtRelationship* getRelationshipAtPath_abi(omni::fabric::PathC path) noexcept = 0; // ---- rt methods virtual void done_abi() noexcept = 0; virtual OMNI_ATTR("not_prop") omni::fabric::UsdStageId getStageId_abi() noexcept = 0; virtual OMNI_ATTR("not_prop, no_api") omni::fabric::StageReaderWriterId getStageInProgressId_abi() noexcept = 0; virtual void write_abi(OMNI_ATTR("c_str, in") const char* filepath) noexcept = 0; virtual bool hasPrimAtPath_abi(omni::fabric::PathC path) noexcept = 0; }; // ********************************************************************************************************************* // ********************************************************************************************************************* // ********************************************************************************************************************* // // ATTENTION ATTENTION ATTENTION ATTENTION ATTENTION ATTENTION ATTENTION ATTENTION // // End of locked interfaces. Enjoy the rest of your day. // // ATTENTION ATTENTION ATTENTION ATTENTION ATTENTION ATTENTION ATTENTION ATTENTION // // ********************************************************************************************************************* // ********************************************************************************************************************* // ********************************************************************************************************************* } // namespace usdrt #include "IRtStage.gen.h" // clang-format off OMNI_DEFINE_INTERFACE_API(usdrt::IRtStage) { public: omni::fabric::StageReaderWriterId getStageReaderWriterId() { return getStageInProgressId_abi(); } }; // clang-format on
5,247
C
48.980952
120
0.512483
omniverse-code/kit/exts/usdrt.scenegraph/include/usdrt/scenegraph/interface/IRtAssetPath.gen.h
// Copyright (c) 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. // // --------- Warning: This is a build system generated file. ---------- // //! @file //! //! @brief This file was generated by <i>omni.bind</i>. #include <omni/core/Interface.h> #include <omni/core/OmniAttr.h> #include <omni/core/ResultError.h> #include <functional> #include <type_traits> #include <utility> #ifndef OMNI_BIND_INCLUDE_INTERFACE_IMPL template <> class omni::core::Generated<usdrt::IRtAssetPath_abi> : public usdrt::IRtAssetPath_abi { public: OMNI_PLUGIN_INTERFACE("usdrt::IRtAssetPath") omni::core::ObjectPtr<usdrt::IRtAssetPath> create(const char* assetPath) noexcept; omni::core::ObjectPtr<usdrt::IRtAssetPath> createWithResolved(const char* assetPath, const char* resolvedPath) noexcept; const char* getAssetPath() noexcept; const char* getResolvedPath() noexcept; omni::core::ObjectPtr<usdrt::IRtAssetPath> createFromFabric(const void* fabricAssetPath) noexcept; omni::fabric::TokenC getAssetPathC() noexcept; omni::fabric::TokenC getResolvedPathC() noexcept; }; #endif #ifndef OMNI_BIND_INCLUDE_INTERFACE_DECL inline omni::core::ObjectPtr<usdrt::IRtAssetPath> omni::core::Generated<usdrt::IRtAssetPath_abi>::create( const char* assetPath) noexcept { return omni::core::steal(create_abi(assetPath)); } inline omni::core::ObjectPtr<usdrt::IRtAssetPath> omni::core::Generated<usdrt::IRtAssetPath_abi>::createWithResolved( const char* assetPath, const char* resolvedPath) noexcept { return omni::core::steal(createWithResolved_abi(assetPath, resolvedPath)); } inline const char* omni::core::Generated<usdrt::IRtAssetPath_abi>::getAssetPath() noexcept { return getAssetPath_abi(); } inline const char* omni::core::Generated<usdrt::IRtAssetPath_abi>::getResolvedPath() noexcept { return getResolvedPath_abi(); } inline omni::core::ObjectPtr<usdrt::IRtAssetPath> omni::core::Generated<usdrt::IRtAssetPath_abi>::createFromFabric( const void* fabricAssetPath) noexcept { return omni::core::steal(createFromFabric_abi(fabricAssetPath)); } inline omni::fabric::TokenC omni::core::Generated<usdrt::IRtAssetPath_abi>::getAssetPathC() noexcept { return getAssetPathC_abi(); } inline omni::fabric::TokenC omni::core::Generated<usdrt::IRtAssetPath_abi>::getResolvedPathC() noexcept { return getResolvedPathC_abi(); } #endif #undef OMNI_BIND_INCLUDE_INTERFACE_DECL #undef OMNI_BIND_INCLUDE_INTERFACE_IMPL
2,912
C
27.558823
117
0.729739
omniverse-code/kit/exts/usdrt.scenegraph/include/usdrt/scenegraph/interface/IRtBoundable.h
// Copyright (c) 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. // #pragma once #include "IRtPrim.h" #include <omni/core/IObject.h> namespace usdrt { // we must always forward declare each interface that will be referenced here. OMNI_DECLARE_INTERFACE(IRtBoundable); class IRtBoundable_abi : public omni::core::Inherits<omni::core::IObject, OMNI_TYPE_ID("usdrt.IRtBoundable")> { protected: // all ABI functions must always be 'protected'. virtual OMNI_ATTR("not_prop") bool setWorldExtentFromUsd_abi(OMNI_ATTR("not_null") IRtPrim* prim) noexcept = 0; }; } // namespace usdrt #include "IRtBoundable.gen.h"
985
C
29.812499
115
0.765482
omniverse-code/kit/exts/usdrt.scenegraph/include/usdrt/scenegraph/interface/IRtPrim.gen.h
// Copyright (c) 2021-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/Interface.h> #include <omni/core/OmniAttr.h> #include <omni/core/ResultError.h> #include <functional> #include <type_traits> #include <utility> #ifndef OMNI_BIND_INCLUDE_INTERFACE_IMPL template <> class omni::core::Generated<usdrt::IRtPrim_abi> : public usdrt::IRtPrim_abi { public: OMNI_PLUGIN_INTERFACE("usdrt::IRtPrim") bool hasAttribute(omni::fabric::TokenC attrName) noexcept; omni::core::ObjectPtr<usdrt::IRtAttribute> getAttribute(omni::fabric::TokenC attrName) noexcept; omni::core::ObjectPtr<usdrt::IRtAttribute> createAttribute(omni::fabric::TokenC name, omni::fabric::TypeC typeName, bool custom, usdrt::Variability varying) noexcept; bool hasRelationship(omni::fabric::TokenC relName) noexcept; omni::core::ObjectPtr<usdrt::IRtRelationship> getRelationship(omni::fabric::TokenC relName) noexcept; omni::core::ObjectPtr<usdrt::IRtRelationship> createRelationship(omni::fabric::TokenC relName, bool custom) noexcept; bool removeProperty(omni::fabric::TokenC propName) noexcept; omni::core::ObjectPtr<usdrt::IRtPrim> getChild(omni::fabric::TokenC name) noexcept; omni::core::ObjectPtr<usdrt::IRtPrim> getParent() noexcept; omni::core::ObjectPtr<usdrt::IRtPrim> getNextSibling() noexcept; omni::fabric::TokenC getTypeName() noexcept; bool setTypeName(omni::fabric::TokenC typeName) noexcept; bool hasAuthoredTypeName() noexcept; bool clearTypeName() noexcept; }; #endif #ifndef OMNI_BIND_INCLUDE_INTERFACE_DECL inline bool omni::core::Generated<usdrt::IRtPrim_abi>::hasAttribute(omni::fabric::TokenC attrName) noexcept { return hasAttribute_abi(attrName); } inline omni::core::ObjectPtr<usdrt::IRtAttribute> omni::core::Generated<usdrt::IRtPrim_abi>::getAttribute( omni::fabric::TokenC attrName) noexcept { return omni::core::steal(getAttribute_abi(attrName)); } inline omni::core::ObjectPtr<usdrt::IRtAttribute> omni::core::Generated<usdrt::IRtPrim_abi>::createAttribute( omni::fabric::TokenC name, omni::fabric::TypeC typeName, bool custom, usdrt::Variability varying) noexcept { return omni::core::steal(createAttribute_abi(name, typeName, custom, varying)); } inline bool omni::core::Generated<usdrt::IRtPrim_abi>::hasRelationship(omni::fabric::TokenC relName) noexcept { return hasRelationship_abi(relName); } inline omni::core::ObjectPtr<usdrt::IRtRelationship> omni::core::Generated<usdrt::IRtPrim_abi>::getRelationship( omni::fabric::TokenC relName) noexcept { return omni::core::steal(getRelationship_abi(relName)); } inline omni::core::ObjectPtr<usdrt::IRtRelationship> omni::core::Generated<usdrt::IRtPrim_abi>::createRelationship( omni::fabric::TokenC relName, bool custom) noexcept { return omni::core::steal(createRelationship_abi(relName, custom)); } inline bool omni::core::Generated<usdrt::IRtPrim_abi>::removeProperty(omni::fabric::TokenC propName) noexcept { return removeProperty_abi(propName); } inline omni::core::ObjectPtr<usdrt::IRtPrim> omni::core::Generated<usdrt::IRtPrim_abi>::getChild( omni::fabric::TokenC name) noexcept { return omni::core::steal(getChild_abi(name)); } inline omni::core::ObjectPtr<usdrt::IRtPrim> omni::core::Generated<usdrt::IRtPrim_abi>::getParent() noexcept { return omni::core::steal(getParent_abi()); } inline omni::core::ObjectPtr<usdrt::IRtPrim> omni::core::Generated<usdrt::IRtPrim_abi>::getNextSibling() noexcept { return omni::core::steal(getNextSibling_abi()); } inline omni::fabric::TokenC omni::core::Generated<usdrt::IRtPrim_abi>::getTypeName() noexcept { return getTypeName_abi(); } inline bool omni::core::Generated<usdrt::IRtPrim_abi>::setTypeName(omni::fabric::TokenC typeName) noexcept { return setTypeName_abi(typeName); } inline bool omni::core::Generated<usdrt::IRtPrim_abi>::hasAuthoredTypeName() noexcept { return hasAuthoredTypeName_abi(); } inline bool omni::core::Generated<usdrt::IRtPrim_abi>::clearTypeName() noexcept { return clearTypeName_abi(); } #endif #undef OMNI_BIND_INCLUDE_INTERFACE_DECL #undef OMNI_BIND_INCLUDE_INTERFACE_IMPL
4,904
C
29.277778
121
0.713499
omniverse-code/kit/exts/usdrt.scenegraph/include/usdrt/scenegraph/interface/IRtXformable.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 "IRtPrim.h" #include <omni/core/IObject.h> namespace usdrt { // we must always forward declare each interface that will be referenced here. OMNI_DECLARE_INTERFACE(IRtXformable); // ********************************************************************************************************************* // ********************************************************************************************************************* // ********************************************************************************************************************* // // ATTENTION ATTENTION ATTENTION ATTENTION ATTENTION ATTENTION ATTENTION ATTENTION // // The interfaces within these obnoxious comment blocks are now locked for long-term support. // Any changes you wish to make should be added in a new interface. // See this document for more details: // https://docs.google.com/document/d/1xyONwFtiM-lWXP5HjQt6pkOgl7xF_4b_Jp4wUS3_d3I/edit?usp=sharing // // Please do not break our precious ABIs! // // ATTENTION ATTENTION ATTENTION ATTENTION ATTENTION ATTENTION ATTENTION ATTENTION // // ********************************************************************************************************************* // ********************************************************************************************************************* // ********************************************************************************************************************* class IRtXformable_abi : public omni::core::Inherits<omni::core::IObject, OMNI_TYPE_ID("usdrt.IRtXformable")> { protected: // all ABI functions must always be 'protected'. virtual OMNI_ATTR("not_prop") bool setWorldXformFromUsd_abi(OMNI_ATTR("not_null") IRtPrim* prim) noexcept = 0; virtual OMNI_ATTR("not_prop") bool setLocalXformFromUsd_abi(OMNI_ATTR("not_null") IRtPrim* prim) noexcept = 0; }; // ********************************************************************************************************************* // ********************************************************************************************************************* // ********************************************************************************************************************* // // ATTENTION ATTENTION ATTENTION ATTENTION ATTENTION ATTENTION ATTENTION ATTENTION // // End of locked interfaces. Enjoy the rest of your day. // // ATTENTION ATTENTION ATTENTION ATTENTION ATTENTION ATTENTION ATTENTION ATTENTION // // ********************************************************************************************************************* // ********************************************************************************************************************* // ********************************************************************************************************************* } // namespace usdrt #include "IRtXformable.gen.h"
3,445
C
51.21212
120
0.416546
omniverse-code/kit/exts/usdrt.scenegraph/include/usdrt/scenegraph/interface/IRtPrim.h
// Copyright (c) 2021-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 "IRtAttribute.h" #include "IRtObject.h" #include "IRtRelationship.h" #include <omni/core/IObject.h> #include <omni/extras/OutArrayUtils.h> #include <omni/fabric/IToken.h> #include <omni/str/IReadOnlyCString.h> #include <vector> namespace usdrt { enum class OMNI_ATTR("prefix=e") Variability : uint32_t { eVarying, eUniform }; // we must always forward declare each interface that will be referenced here. OMNI_DECLARE_INTERFACE(IRtPrim); // ********************************************************************************************************************* // ********************************************************************************************************************* // ********************************************************************************************************************* // // ATTENTION ATTENTION ATTENTION ATTENTION ATTENTION ATTENTION ATTENTION ATTENTION // // The interfaces within these obnoxious comment blocks are now locked for long-term support. // Any changes you wish to make should be added in a new interface. // See this document for more details: // https://docs.google.com/document/d/1xyONwFtiM-lWXP5HjQt6pkOgl7xF_4b_Jp4wUS3_d3I/edit?usp=sharing // // Please do not break our precious ABIs! // // ATTENTION ATTENTION ATTENTION ATTENTION ATTENTION ATTENTION ATTENTION ATTENTION // // ********************************************************************************************************************* // ********************************************************************************************************************* // ********************************************************************************************************************* class IRtPrim_abi : public omni::core::Inherits<usdrt::IRtObject, OMNI_TYPE_ID("usdrt.IRtPrim")> { protected: // all ABI functions must always be 'protected'. // ---- attributes virtual bool hasAttribute_abi(omni::fabric::TokenC attrName) noexcept = 0; virtual OMNI_ATTR("not_prop") IRtAttribute* getAttribute_abi(omni::fabric::TokenC attrName) noexcept = 0; virtual IRtAttribute* createAttribute_abi(omni::fabric::TokenC name, omni::fabric::TypeC typeName, bool custom, Variability varying) noexcept = 0; virtual OMNI_ATTR("no_api") omni::core::Result getAttributes_abi( // disable omni.bind until OM-21202 OMNI_ATTR("out, count=*outCount, *not_null") IRtAttribute** out, OMNI_ATTR("out, not_null") uint32_t* outCount) noexcept = 0; virtual OMNI_ATTR("no_api") omni::core::Result getAuthoredAttributes_abi( // disable omni.bind until OM-21202 OMNI_ATTR("out, count=*outCount, *not_null") IRtAttribute** out, OMNI_ATTR("out, not_null") uint32_t* outCount) noexcept = 0; // ---- relationships virtual bool hasRelationship_abi(omni::fabric::TokenC relName) noexcept = 0; virtual OMNI_ATTR("not_prop") IRtRelationship* getRelationship_abi(omni::fabric::TokenC relName) noexcept = 0; virtual IRtRelationship* createRelationship_abi(omni::fabric::TokenC relName, bool custom) noexcept = 0; virtual OMNI_ATTR("no_api") omni::core::Result getRelationships_abi( // disable omni.bind until OM-21202 OMNI_ATTR("out, count=*outCount, *not_null") IRtRelationship** out, OMNI_ATTR("out, not_null") uint32_t* outCount) noexcept = 0; virtual OMNI_ATTR("no_api") omni::core::Result getAuthoredRelationships_abi( // disable omni.bind until OM-21202 OMNI_ATTR("out, count=*outCount, *not_null") IRtRelationship** out, OMNI_ATTR("out, not_null") uint32_t* outCount) noexcept = 0; // ---- properties virtual bool removeProperty_abi(omni::fabric::TokenC propName) noexcept = 0; // ---- hierarchy virtual OMNI_ATTR("not_prop") IRtPrim* getChild_abi(omni::fabric::TokenC name) noexcept = 0; virtual OMNI_ATTR("no_api") omni::core::Result getChildren_abi( // disable omni.bind until OM-21202 OMNI_ATTR("out, count=*outCount, *not_null") IRtPrim** out, OMNI_ATTR("out, not_null") uint32_t* outCount) noexcept = 0; virtual OMNI_ATTR("not_prop") IRtPrim* getParent_abi() noexcept = 0; virtual OMNI_ATTR("not_prop") IRtPrim* getNextSibling_abi() noexcept = 0; // ---- types virtual OMNI_ATTR("not_prop") omni::fabric::TokenC getTypeName_abi() noexcept = 0; virtual OMNI_ATTR("not_prop") bool setTypeName_abi(omni::fabric::TokenC typeName) noexcept = 0; virtual bool hasAuthoredTypeName_abi() noexcept = 0; virtual bool clearTypeName_abi() noexcept = 0; }; // ********************************************************************************************************************* // ********************************************************************************************************************* // ********************************************************************************************************************* // // ATTENTION ATTENTION ATTENTION ATTENTION ATTENTION ATTENTION ATTENTION ATTENTION // // End of locked interfaces. Enjoy the rest of your day. // // ATTENTION ATTENTION ATTENTION ATTENTION ATTENTION ATTENTION ATTENTION ATTENTION // // ********************************************************************************************************************* // ********************************************************************************************************************* // ********************************************************************************************************************* } // namespace usdrt #include "IRtPrim.gen.h" // clang-format off OMNI_DEFINE_INTERFACE_API(usdrt::IRtPrim) { public: std::vector<omni::core::ObjectPtr<usdrt::IRtAttribute>> getAttributes() noexcept { std::vector<omni::core::ObjectPtr<usdrt::IRtAttribute>> vec; auto result = omni::extras::getOutArray<usdrt::IRtAttribute*>( [this](usdrt::IRtAttribute** out, uint32_t* outCount) // get func { std::memset(out, 0, sizeof(usdrt::IRtAttribute*) * *outCount); // incoming ptrs must be nullptr return this->getAttributes_abi(out, outCount); }, [&vec](usdrt::IRtAttribute** in, uint32_t inCount) // fill func { vec.reserve(inCount); for (uint32_t i = 0; i < inCount; ++i) { vec.emplace_back(in[i], omni::core::kSteal); } } ); return vec; } std::vector<omni::core::ObjectPtr<usdrt::IRtAttribute>> getAuthoredAttributes() noexcept { std::vector<omni::core::ObjectPtr<usdrt::IRtAttribute>> vec; auto result = omni::extras::getOutArray<usdrt::IRtAttribute*>( [this](usdrt::IRtAttribute** out, uint32_t* outCount) // get func { std::memset(out, 0, sizeof(usdrt::IRtAttribute*) * *outCount); // incoming ptrs must be nullptr return this->getAuthoredAttributes_abi(out, outCount); }, [&vec](usdrt::IRtAttribute** in, uint32_t inCount) // fill func { vec.reserve(inCount); for (uint32_t i = 0; i < inCount; ++i) { vec.emplace_back(in[i], omni::core::kSteal); } }); return vec; } std::vector<omni::core::ObjectPtr<usdrt::IRtRelationship>> getRelationships() noexcept { std::vector<omni::core::ObjectPtr<usdrt::IRtRelationship>> vec; auto result = omni::extras::getOutArray<usdrt::IRtRelationship*>( [this](usdrt::IRtRelationship** out, uint32_t* outCount) // get func { std::memset(out, 0, sizeof(usdrt::IRtRelationship*) * *outCount); // incoming ptrs must be nullptr return this->getRelationships_abi(out, outCount); }, [&vec](usdrt::IRtRelationship** in, uint32_t inCount) // fill func { vec.reserve(inCount); for (uint32_t i = 0; i < inCount; ++i) { vec.emplace_back(in[i], omni::core::kSteal); } } ); return vec; } std::vector<omni::core::ObjectPtr<usdrt::IRtRelationship>> getAuthoredRelationships() noexcept { std::vector<omni::core::ObjectPtr<usdrt::IRtRelationship>> vec; auto result = omni::extras::getOutArray<usdrt::IRtRelationship*>( [this](usdrt::IRtRelationship** out, uint32_t* outCount) // get func { std::memset(out, 0, sizeof(usdrt::IRtRelationship*) * *outCount); // incoming ptrs must be nullptr return this->getAuthoredRelationships_abi(out, outCount); }, [&vec](usdrt::IRtRelationship** in, uint32_t inCount) // fill func { vec.reserve(inCount); for (uint32_t i = 0; i < inCount; ++i) { vec.emplace_back(in[i], omni::core::kSteal); } }); return vec; } std::vector<omni::core::ObjectPtr<usdrt::IRtPrim>> getChildren() noexcept { std::vector<omni::core::ObjectPtr<usdrt::IRtPrim>> vec; auto result = omni::extras::getOutArray<usdrt::IRtPrim*>( [this](usdrt::IRtPrim** out, uint32_t* outCount) // get func { std::memset(out, 0, sizeof(usdrt::IRtPrim*) * *outCount); // incoming ptrs must be nullptr return this->getChildren_abi(out, outCount); }, [&vec](usdrt::IRtPrim** in, uint32_t inCount) // fill func { vec.reserve(inCount); for (uint32_t i = 0; i < inCount; ++i) { vec.emplace_back(in[i], omni::core::kSteal); } } ); return vec; } }; // clang-format on
10,498
C
43.867521
120
0.529244
omniverse-code/kit/exts/usdrt.scenegraph/include/usdrt/scenegraph/interface/IRtRelationship.h
// Copyright (c) 2022-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. // #pragma once #include "Common.h" #include "IRtProperty.h" #include <omni/core/IObject.h> #include <omni/fabric/AttrNameAndType.h> #include <omni/fabric/IFabric.h> #include <vector> namespace usdrt { // we must always forward declare each interface that will be referenced here. OMNI_DECLARE_INTERFACE(IRtRelationship); // ********************************************************************************************************************* // ********************************************************************************************************************* // ********************************************************************************************************************* // // ATTENTION ATTENTION ATTENTION ATTENTION ATTENTION ATTENTION ATTENTION ATTENTION // // The interfaces within these obnoxious comment blocks are now locked for long-term support. // Any changes you wish to make should be added in a new interface. // See this document for more details: // https://docs.google.com/document/d/1xyONwFtiM-lWXP5HjQt6pkOgl7xF_4b_Jp4wUS3_d3I/edit?usp=sharing // // Please do not break our precious ABIs! // // ATTENTION ATTENTION ATTENTION ATTENTION ATTENTION ATTENTION ATTENTION ATTENTION // // ********************************************************************************************************************* // ********************************************************************************************************************* // ********************************************************************************************************************* class IRtRelationship_abi : public omni::core::Inherits<usdrt::IRtProperty, OMNI_TYPE_ID("usdrt.IRtRelationship")> { protected: // all ABI functions must always be 'protected'. // ---- targets virtual bool hasAuthoredTargets_abi() noexcept = 0; // Note: As of this implementation, Fabric does not support // lists of targets for relationships, so the behavior of some // of these may diverge from USD until that support is added virtual bool addTarget_abi(omni::fabric::PathC path, ListPosition position) noexcept = 0; virtual bool removeTarget_abi(omni::fabric::PathC path) noexcept = 0; virtual bool OMNI_ATTR("not_prop") setTargets_abi(OMNI_ATTR("in, count=size") const omni::fabric::PathC* paths, uint32_t size) noexcept = 0; virtual bool clearTargets_abi() noexcept = 0; virtual uint32_t numTargets_abi() noexcept = 0; virtual bool OMNI_ATTR("not_prop") getTargets_abi(OMNI_ATTR("out, count=size") omni::fabric::PathC* paths, uint32_t size) noexcept = 0; }; // ********************************************************************************************************************* // ********************************************************************************************************************* // ********************************************************************************************************************* // // ATTENTION ATTENTION ATTENTION ATTENTION ATTENTION ATTENTION ATTENTION ATTENTION // // End of locked interfaces. Enjoy the rest of your day. // // ATTENTION ATTENTION ATTENTION ATTENTION ATTENTION ATTENTION ATTENTION ATTENTION // // ********************************************************************************************************************* // ********************************************************************************************************************* // ********************************************************************************************************************* } // namespace usdrt #include "IRtRelationship.gen.h"
4,191
C
50.121951
120
0.467907
omniverse-code/kit/exts/usdrt.scenegraph/include/usdrt/scenegraph/interface/IRtSchemaRegistry.h
// Copyright (c) 2022-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. // #pragma once #include "Common.h" #include <omni/fabric/IToken.h> namespace usdrt { // we must always forward declare each interface that will be referenced here. OMNI_DECLARE_INTERFACE(IRtSchemaRegistry); class IRtSchemaRegistry_abi : public omni::core::Inherits<omni::core::IObject, OMNI_TYPE_ID("usdrt.IRtSchemaRegistry")> { protected: // all ABI functions must always be 'protected'. virtual IRtSchemaRegistry* initRegistry_abi() noexcept = 0; virtual bool isConcrete_abi(omni::fabric::TokenC primTypeC) noexcept = 0; virtual bool isAppliedAPISchema_abi(omni::fabric::TokenC apiSchemaTypeC) noexcept = 0; virtual bool isMultipleApplyAPISchema_abi(omni::fabric::TokenC apiSchemaTypeC) noexcept = 0; virtual bool isA_abi(omni::fabric::TokenC sourceTypeNameC, omni::fabric::TokenC queryTypeNameC) noexcept = 0; virtual OMNI_ATTR("not_prop") omni::fabric::TokenC getAliasFromName_abi(omni::fabric::TokenC nameC) noexcept = 0; }; } // namespace usdrt #include "IRtSchemaRegistry.gen.h"
1,455
C
39.444443
119
0.770447
omniverse-code/kit/exts/usdrt.scenegraph/include/usdrt/scenegraph/interface/IRtStage105.gen.h
// Copyright (c) 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. // // --------- Warning: This is a build system generated file. ---------- // //! @file //! //! @brief This file was generated by <i>omni.bind</i>. #include <omni/core/Interface.h> #include <omni/core/OmniAttr.h> #include <omni/core/ResultError.h> #include <functional> #include <type_traits> #include <utility> #ifndef OMNI_BIND_INCLUDE_INTERFACE_IMPL template <> class omni::core::Generated<usdrt::IRtStage105_abi> : public usdrt::IRtStage105_abi { public: OMNI_PLUGIN_INTERFACE("usdrt::IRtStage105") uint32_t findCount(omni::fabric::TokenC typeName, const omni::fabric::TokenC* apiNames, uint32_t apiNamesSize) noexcept; bool find(omni::fabric::TokenC typeName, const omni::fabric::TokenC* apiNames, uint32_t apiNamesSize, omni::fabric::PathC* outPaths, uint32_t outPathCount) noexcept; bool computeWorldBound(usdrt::GfRange3d* result) noexcept; omni::core::ObjectPtr<usdrt::IRtAttribute> getAttributeAtPath105(omni::fabric::PathC path, omni::fabric::TokenC prop) noexcept; omni::core::ObjectPtr<usdrt::IRtRelationship> getRelationshipAtPath105(omni::fabric::PathC path, omni::fabric::TokenC prop) noexcept; bool hasPrimAtPath105(omni::fabric::PathC path, bool excludeTags) noexcept; }; #endif #ifndef OMNI_BIND_INCLUDE_INTERFACE_DECL inline uint32_t omni::core::Generated<usdrt::IRtStage105_abi>::findCount(omni::fabric::TokenC typeName, const omni::fabric::TokenC* apiNames, uint32_t apiNamesSize) noexcept { return findCount_abi(typeName, apiNames, apiNamesSize); } inline bool omni::core::Generated<usdrt::IRtStage105_abi>::find(omni::fabric::TokenC typeName, const omni::fabric::TokenC* apiNames, uint32_t apiNamesSize, omni::fabric::PathC* outPaths, uint32_t outPathCount) noexcept { return find_abi(typeName, apiNames, apiNamesSize, outPaths, outPathCount); } inline bool omni::core::Generated<usdrt::IRtStage105_abi>::computeWorldBound(usdrt::GfRange3d* result) noexcept { return computeWorldBound_abi(result); } inline omni::core::ObjectPtr<usdrt::IRtAttribute> omni::core::Generated<usdrt::IRtStage105_abi>::getAttributeAtPath105( omni::fabric::PathC path, omni::fabric::TokenC prop) noexcept { return omni::core::steal(getAttributeAtPath105_abi(path, prop)); } inline omni::core::ObjectPtr<usdrt::IRtRelationship> omni::core::Generated<usdrt::IRtStage105_abi>::getRelationshipAtPath105( omni::fabric::PathC path, omni::fabric::TokenC prop) noexcept { return omni::core::steal(getRelationshipAtPath105_abi(path, prop)); } inline bool omni::core::Generated<usdrt::IRtStage105_abi>::hasPrimAtPath105(omni::fabric::PathC path, bool excludeTags) noexcept { return hasPrimAtPath105_abi(path, excludeTags); } #endif #undef OMNI_BIND_INCLUDE_INTERFACE_DECL #undef OMNI_BIND_INCLUDE_INTERFACE_IMPL
3,900
C
36.152381
125
0.625128
omniverse-code/kit/exts/usdrt.scenegraph/include/usdrt/xformcache/IXformCache.h
// Copyright (c) 2022-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. // #pragma once #include <omni/core/IObject.h> #include <omni/fabric/IFabric.h> #include <omni/fabric/IPath.h> #include <omni/fabric/IdTypes.h> #include <usdrt/gf/matrix.h> namespace usdrt { namespace xformcache { OMNI_DECLARE_INTERFACE(IXformCache); class IXformCache_abi : public omni::core::Inherits<omni::core::IObject, OMNI_TYPE_ID("usdrt.xformcache.IXformCache")> { protected: virtual bool attachToStage_abi(const omni::fabric::UsdStageId stageId) noexcept = 0; virtual omni::fabric::UsdStageId getStageId_abi() noexcept = 0; virtual void syncXforms_abi() noexcept = 0; virtual void syncTargetedXforms_abi(const omni::fabric::PathC targetPath) noexcept = 0; virtual OMNI_ATTR("not_prop") usdrt::GfMatrix4d getLatestWorldXform_abi(const omni::fabric::PathC path) noexcept = 0; virtual usdrt::GfMatrix4d computeWorldXform_abi(const omni::fabric::PathC path) noexcept = 0; }; } // namespace xformcache } // namespace usdrt #include "IXformCache.gen.h"
1,426
C
31.431817
121
0.76087
omniverse-code/kit/exts/usdrt.scenegraph/include/usdrt/xformcache/ISharedXformCache.h
// Copyright (c) 2022-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. // #pragma once #include "IXformCache.h" namespace usdrt { namespace xformcache { OMNI_DECLARE_INTERFACE(ISharedXformCache); class ISharedXformCache_abi : public omni::core::Inherits<omni::core::IObject, OMNI_TYPE_ID("usdrt.xformcache.ISharedXformCache")> { protected: virtual bool hasCache_abi(const omni::fabric::UsdStageId stageId) noexcept = 0; virtual OMNI_ATTR("no_api") IXformCache* getCache_abi(const omni::fabric::UsdStageId stageId) noexcept = 0; virtual OMNI_ATTR("no_api") IXformCache* getOrCreateCache_abi(const omni::fabric::UsdStageId stageId) noexcept = 0; virtual bool clear_abi() noexcept = 0; }; } // namespace xformcache } // namespace usdrt #include "ISharedXformCache.gen.h" // clang-format off OMNI_DEFINE_INTERFACE_API(usdrt::xformcache::ISharedXformCache) { public: omni::core::ObjectPtr<usdrt::xformcache::IXformCache> getCache(omni::fabric::UsdStageId stageId) noexcept { return omni::core::borrow(getCache_abi(stageId)); } omni::core::ObjectPtr<usdrt::xformcache::IXformCache> getOrCreateCache(omni::fabric::UsdStageId stageId) noexcept { return omni::core::borrow(getOrCreateCache_abi(stageId)); } }; // clang-format on
1,657
C
29.703703
119
0.747737
omniverse-code/kit/exts/usdrt.scenegraph/include/usdrt/xformcache/IXformCache.gen.h
// Copyright (c) 2022-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. // // --------- Warning: This is a build system generated file. ---------- // //! @file //! //! @brief This file was generated by <i>omni.bind</i>. #include <omni/core/Interface.h> #include <omni/core/OmniAttr.h> #include <omni/core/ResultError.h> #include <functional> #include <type_traits> #include <utility> #ifndef OMNI_BIND_INCLUDE_INTERFACE_IMPL template <> class omni::core::Generated<usdrt::xformcache::IXformCache_abi> : public usdrt::xformcache::IXformCache_abi { public: OMNI_PLUGIN_INTERFACE("usdrt::xformcache::IXformCache") bool attachToStage(omni::fabric::UsdStageId stageId) noexcept; omni::fabric::UsdStageId getStageId() noexcept; void syncXforms() noexcept; void syncTargetedXforms(omni::fabric::PathC targetPath) noexcept; usdrt::GfMatrix4d getLatestWorldXform(omni::fabric::PathC path) noexcept; usdrt::GfMatrix4d computeWorldXform(omni::fabric::PathC path) noexcept; }; #endif #ifndef OMNI_BIND_INCLUDE_INTERFACE_DECL inline bool omni::core::Generated<usdrt::xformcache::IXformCache_abi>::attachToStage(omni::fabric::UsdStageId stageId) noexcept { return attachToStage_abi(stageId); } inline omni::fabric::UsdStageId omni::core::Generated<usdrt::xformcache::IXformCache_abi>::getStageId() noexcept { return getStageId_abi(); } inline void omni::core::Generated<usdrt::xformcache::IXformCache_abi>::syncXforms() noexcept { syncXforms_abi(); } inline void omni::core::Generated<usdrt::xformcache::IXformCache_abi>::syncTargetedXforms(omni::fabric::PathC targetPath) noexcept { syncTargetedXforms_abi(targetPath); } inline usdrt::GfMatrix4d omni::core::Generated<usdrt::xformcache::IXformCache_abi>::getLatestWorldXform( omni::fabric::PathC path) noexcept { return getLatestWorldXform_abi(path); } inline usdrt::GfMatrix4d omni::core::Generated<usdrt::xformcache::IXformCache_abi>::computeWorldXform( omni::fabric::PathC path) noexcept { return computeWorldXform_abi(path); } #endif #undef OMNI_BIND_INCLUDE_INTERFACE_DECL #undef OMNI_BIND_INCLUDE_INTERFACE_IMPL
2,507
C
26.260869
130
0.750698
omniverse-code/kit/exts/usdrt.scenegraph/docs/index.rst
usdrt.scenegraph: USDRT Scenegraph API for Kit ############################################## This extension loads the usdrt.scenegraph plugin and adds the USDRT Python bindings into the Python path for Kit. USDRT is developed out of the usdrt repo and delivered via the usdrt packman package. This extension is the meant to be the singular load point for the usdrt.scenegraph plugin within Kit. Public documentation here: https://docs.omniverse.nvidia.com/kit/docs/usdrt .. toctree:: :maxdepth: 1 CHANGELOG
523
reStructuredText
20.833332
55
0.713193
omniverse-code/kit/exts/omni.kit.quicklayout/config/extension.toml
[package] version = "1.1.1" authors = ["NVIDIA"] title = "Layout Control Tools" description = "Set of tools for controlling layout." readme = "docs/README.md" repository = "" category = "Core" feature = true keywords = ["layout", "workspace"] changelog = "docs/CHANGELOG.md" preview_image = "data/preview.png" icon = "data/icon.svg" [dependencies] "omni.kit.mainwindow" = {} "omni.kit.window.filepicker" = {} "omni.client" = {} "omni.ui" = {} "omni.usd.libs" = {} "omni.kit.menu.utils" = {} [[python.module]] name = "omni.kit.quicklayout" [settings] persistent.app.quicklayout.defaultLayout = "$$last_used$$" persistent.app.quicklayout.lastUsedLayout = "$$none$$" [[test]] args = [ "--/app/window/dpiScaleOverride=1.0", "--/app/window/scaleToMonitor=false", "--no-window" ] pyCoverageIncludeDependencies = false dependencies = [ "omni.kit.mainwindow", "omni.kit.renderer.capture", "omni.kit.window.preferences", "omni.kit.menu.utils", "omni.kit.ui_test", "omni.kit.test_suite.helpers", ]
1,031
TOML
20.957446
58
0.668283
omniverse-code/kit/exts/omni.kit.quicklayout/omni/kit/quicklayout/quicklayout.py
# Copyright (c) 2018-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.kit.widget.filebrowser import FileBrowserItem from omni.kit.window.filepicker import FilePickerDialog from pathlib import Path from omni.ui.workspace_utils import CompareDelegate import carb import carb.tokens import json import omni.client import omni.ui as ui import traceback class QuickLayout: """Namespace that has the methods to load and save the layout""" def __init__(self): self._dialog = None def destroy(self): # pragma: no cover if self._dialog: self._dialog.destroy() self._dialog = None def __on_filter_item(self, item: FileBrowserItem) -> bool: if not item or item.is_folder: return True if self._dialog.current_filter_option == 0: # Show only files with listed extensions if item.path.endswith(".json"): return True else: return False else: # Show All Files (*) return True @staticmethod def __get_workspace_dir() -> str: """Return the workspace file""" token = carb.tokens.get_tokens_interface() dir = token.resolve("${data}") # FilePickerDialog needs the capital drive. In case it's linux, the # first letter will be / and it's still OK. dir = dir[:1].upper() + dir[1:] return dir @staticmethod def __get_workspace_file() -> str: """Return the workspace file""" dir = QuickLayout.__get_workspace_dir() return f"{dir}/user.layout.json" def __on_apply_save(self, filename: str, dir: str): """Called when the user presses the Save button in the dialog""" # Get the file extension from the filter if self._dialog.current_filter_option == 0 and not filename.lower().endswith(".json"): filename += ".json" self._dialog.hide() self.save_file(omni.client.combine_urls(dir if dir.endswith("/") else dir+"/", filename)) def __on_apply_load(self, filename, dir): """Called when the user presses the Load button in the dialog""" self._dialog.hide() self.load_file(omni.client.combine_urls(dir if dir.endswith("/") else dir+"/", filename)) @staticmethod def save_file(workspace_file: str): """Save the layout to the workspace file""" workspace_dump = ui.Workspace.dump_workspace() payload = bytes(json.dumps(workspace_dump, sort_keys=True, indent=2).encode("utf-8")) result = omni.client.write_file(workspace_file, payload) if result != omni.client.Result.OK: # pragma: no cover carb.log_error(f"[quicklayout] The workspace cannot be written to {workspace_file}, error code: {result}") return carb.log_info(f"[quicklayout] The workspace saved to {workspace_file}") @staticmethod def load_file(workspace_file: str, keep_windows_open=False): """Load the layout from the workspace file""" result, _, content = omni.client.read_file(workspace_file) if result != omni.client.Result.OK: # pragma: no cover carb.log_error(f"[quicklayout] Can't read the workspace file {workspace_file}, error code: {result}") return data = json.loads(memoryview(content).tobytes().decode("utf-8")) ui.Workspace.restore_workspace(data, keep_windows_open) carb.log_info(f"[quicklayout] The workspace is loaded from {workspace_file}") @staticmethod def compare_file(workspace_file: str, compare_delegate: CompareDelegate=CompareDelegate()): """Load the layout from the workspace file""" result, _, content = omni.client.read_file(workspace_file) if result != omni.client.Result.OK: # pragma: no cover carb.log_error(f"[quicklayout] Can't read the workspace file {workspace_file}, error code: {result}") return data = json.loads(memoryview(content).tobytes().decode("utf-8")) result = ui.Workspace.compare_workspace(data, compare_delegate=compare_delegate) carb.log_info(f"[quicklayout] compared {workspace_file} with workspace") return result def save(self, menu: str, value: bool): """Save layout with the dialog""" # Remove previously opened dialog self.destroy() self._dialog = FilePickerDialog( "Select File to Save Layout", apply_button_label="Save", current_directory=QuickLayout.__get_workspace_dir(), click_apply_handler=self.__on_apply_save, item_filter_options=["JSON Files (*.json)", "All Files (*)"], item_filter_fn=self.__on_filter_item, ) def load(self, menu: str, value: bool): """Load layout with the dialog""" # Remove previously opened dialog self.destroy() self._dialog = FilePickerDialog( "Select File to Load Layout", apply_button_label="Load", current_directory=QuickLayout.__get_workspace_dir(), click_apply_handler=self.__on_apply_load, item_filter_options=["JSON Files (*.json)", "All Files (*)"], item_filter_fn=self.__on_filter_item, ) @staticmethod def quick_save(menu: str, value: bool): workspace_file = QuickLayout.__get_workspace_file() QuickLayout.save_file(workspace_file) @staticmethod def quick_load(menu: str, value: bool): workspace_file = QuickLayout.__get_workspace_file() QuickLayout.load_file(workspace_file)
5,988
Python
38.662251
118
0.635939
omniverse-code/kit/exts/omni.kit.quicklayout/omni/kit/quicklayout/quicklayout_extension.py
# Copyright (c) 2018-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 .quicklayout import QuickLayout import omni.ext import omni.kit.ui class QuickLayoutExtension(omni.ext.IExt): def on_startup(self, ext_id): self.__quick_layout = QuickLayout() editor_menu = omni.kit.ui.get_editor_menu() if editor_menu: self._menu_save = editor_menu.add_item("Window/Layout/Save Layout...", self.__quick_layout.save) self._menu_load = editor_menu.add_item("Window/Layout/Load Layout...", self.__quick_layout.load) self._menu_quick_save = editor_menu.add_item("Window/Layout/Quick Save", QuickLayout.quick_save) self._menu_quick_load = editor_menu.add_item("Window/Layout/Quick Load", QuickLayout.quick_load) def on_shutdown(self): # pragma: no cover self._menu_save = None self._menu_load = None self._menu_quick_save = None self._menu_quick_load = None self._menu = None self.__quick_layout.destroy() self.__quick_layout = None
1,423
Python
42.151514
108
0.691497
omniverse-code/kit/exts/omni.kit.quicklayout/omni/kit/quicklayout/layout_templates_page.py
# Copyright (c) 2018-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. # import re import os import carb.settings import omni.kit.app import omni.ui as ui from omni.kit.window.preferences import PreferenceBuilder, SettingType, PERSISTENT_SETTINGS_PREFIX from omni.kit.quicklayout import QuickLayout class LayoutTemplatesPreferences(PreferenceBuilder): def __init__(self): super().__init__("Template Startup") def build(self): layout_names = {"Open Last Used Layout": "$$last_used$$"} for item in QuickLayout.get_default_layouts(): layout_names[item[0]] = item[0] with ui.VStack(height=0): with self.add_frame("Default Layout"): with ui.VStack(): self.create_setting_widget_combo("Default Layout", PERSISTENT_SETTINGS_PREFIX + "/app/quicklayout/defaultLayout", layout_names, setting_is_index=True)
1,262
Python
38.468749
170
0.722662
omniverse-code/kit/exts/omni.kit.quicklayout/omni/kit/quicklayout/tests/test_quicklayout_menu.py
## Copyright (c) 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. ## import os import carb import omni.kit.app from omni.kit.test.async_unittest import AsyncTestCase import omni.usd import omni.ui as ui from omni.kit import ui_test from pxr import Vt, Gf from omni.kit.test_suite.helpers import get_test_data_path, arrange_windows from omni.kit.quicklayout import QuickLayout from omni.kit.menu.utils import MenuItemDescription, MenuAlignment from omni.kit.ui_test.query import MenuRef PERSISTENT_SETTINGS_PREFIX = "/persistent" class TestQuicklayoutMenu(AsyncTestCase): # Before running each test async def setUp(self): await arrange_windows() # carb.settings.get_settings().set(PERSISTENT_SETTINGS_PREFIX + "/app/quicklayout/defaultLayout", "$$last_used$$") self.assertEqual(QuickLayout.get_default_layouts(), []) data_path = get_test_data_path(__name__) self._layout_data = [ ["Test 1", f"{data_path}/layouts/test1.json", carb.input.KeyboardInput.KEY_1], ["Test 2", f"{data_path}/layouts/test2.json", carb.input.KeyboardInput.KEY_2]] QuickLayout.add_default_layouts(self._layout_data) # After running each test async def tearDown(self): QuickLayout.remove_default_layouts(self._layout_data) carb.settings.get_settings().set(PERSISTENT_SETTINGS_PREFIX + "/app/quicklayout/defaultLayout", "$$last_used$$") self.assertEqual(QuickLayout.get_default_layouts(), []) async def test_layout_menu(self): # add layout placeholder menu_placeholder = [MenuItemDescription(name="placeholder", show_fn=lambda: False)] omni.kit.menu.utils.add_menu_items(menu_placeholder, name="Layout") await ui_test.human_delay(10) layout_menu_items = [] def add_layout_menu_entry(name, parameter, key): item = MenuItemDescription(name=name) layout_menu_items.append(item) for item in QuickLayout.get_default_layouts(): add_layout_menu_entry(f"{item[0]}", item[1], item[2]) # add menu layout_delegate = QuickLayout.LayoutMenuDelegate(read_fn=lambda: "Test 2", layout_id="Test 2", text_width=175, hotkey_width=75) omni.kit.menu.utils.add_menu_items(layout_menu_items, "Layout", delegate=layout_delegate) await ui_test.human_delay(10) # click layout layout_menu = omni.kit.ui_test.get_menubar().find_menu("Layout") await layout_menu.click() await ui_test.human_delay(10) # verify menu icon status layout_menu_icons = layout_menu.widget.delegate._layout_menu_icons self.assertFalse(layout_menu.widget.delegate._layout_menu_icons['Test 1']['selected_image'].enabled) self.assertTrue(layout_menu.widget.delegate._layout_menu_icons['Test 2']['selected_image'].enabled) # remove menus omni.kit.menu.utils.remove_menu_items(layout_menu_items, name="Layout") omni.kit.menu.utils.remove_menu_items(menu_placeholder, name="Layout") await ui_test.human_delay(10)
3,637
Python
42.309523
121
0.659335
omniverse-code/kit/exts/omni.kit.quicklayout/omni/kit/quicklayout/tests/test_menus.py
## Copyright (c) 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. ## from omni.ui.tests.test_base import OmniUiTest import omni.kit import omni.ui as ui import omni.kit.ui_test as ui_test class TestQuickLayoutMenus(OmniUiTest): async def test_menus(self): menu_widget = ui_test.get_menubar() await menu_widget.find_menu("Window").click() await menu_widget.find_menu("Layout").click() await menu_widget.find_menu("Quick Save").click() await ui_test.human_delay(10) await menu_widget.find_menu("Window").click() await menu_widget.find_menu("Layout").click() await menu_widget.find_menu("Quick Load").click() await ui_test.human_delay(10)
1,082
Python
39.11111
77
0.719963
omniverse-code/kit/exts/omni.kit.quicklayout/omni/kit/quicklayout/tests/quicklayout_test.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 ..quicklayout import QuickLayout from omni.ui.tests.test_base import OmniUiTest from pathlib import Path import json import omni.kit import omni.ui as ui import os import tempfile from omni.kit.mainwindow import get_main_window CURRENT_PATH = Path(__file__).parent.joinpath("../../../../data") ROOT_WINDOW_NAME = "DockSpace" class TestQuickLayout(OmniUiTest): # Before running each test async def setUp(self): await super().setUp() self._golden_img_dir = CURRENT_PATH.absolute().resolve().joinpath("tests") self._dump_workspace = ui.Workspace.dump_workspace() # After running each test async def tearDown(self): self._golden_img_dir = None ui.Workspace.restore_workspace(self._dump_workspace) await super().tearDown() async def test_floating(self): ui.Workspace.clear() window_left = ui.Window("Left", width=100, height=100, position_x=10, position_y=10) window_right = ui.Window("Right", width=100, height=100, position_x=120, position_y=10) await omni.kit.app.get_app().next_update_async() temp_file = Path(tempfile.gettempdir()).joinpath("workspace_" + next(tempfile._get_candidate_names()) + ".json") QuickLayout.save_file(f"{temp_file}") with open(f"{temp_file}") as json_file: data = json.load(json_file) os.remove(f"{temp_file}") left_pos = 0 right_pos = 0 for win in data: if "title" in win: if win["title"] == "Left": left_pos = win['position_x'] elif win["title"] == "Right": right_pos = win['position_x'] # self.assertEqual(len(data), 3) # Not true if test_restore is run first self.assertEqual(left_pos, 10.0) self.assertEqual(right_pos, 120.0) async def test_docking(self): ui.Workspace.clear() window_left = ui.Window("Left2", width=100, height=100, position_x=10, position_y=10) window_right = ui.Window("Right2", width=100, height=100, position_x=120, position_y=10) target_window = ui.Workspace.get_window(ROOT_WINDOW_NAME) await omni.kit.app.get_app().next_update_async() window_left.dock_in(target_window, ui.DockPosition.SAME) window_right.dock_in(window_left, ui.DockPosition.RIGHT, 0.5) await omni.kit.app.get_app().next_update_async() temp_file = Path(tempfile.gettempdir()).joinpath("workspace_" + next(tempfile._get_candidate_names()) + ".json") QuickLayout.save_file(f"{temp_file}") with open(f"{temp_file}") as json_file: data = json.load(json_file) os.remove(f"{temp_file}") self.assertEqual(len(data[0]["children"]), 2) self.assertIn(data[0]["children"][0]["position"], ["LEFT", "RIGHT"]) self.assertIn(data[0]["children"][1]["position"], ["LEFT", "RIGHT"]) async def test_restore(self): data = [ { "children": [ { "children": [ { "dock_id": 1, "height": 100, "selected_in_dock": True, "title": "LeftDocked", "visible": True, "width": 100, } ], "dock_id": 1, "position": "LEFT", }, { "children": [ { "dock_id": 2, "height": 100, "selected_in_dock": False, "title": "RightDocked", "visible": True, "width": 100, } ], "dock_id": 2, "position": "RIGHT", }, ], "dock_id": 0, } ] await self.create_test_area() window_left = ui.Window("LeftDocked") with window_left.frame: ui.Rectangle(style={"background_color": 0xFFF07E4D}) window_right = ui.Window("RightDocked") with window_right.frame: ui.Rectangle(style={"background_color": 0xFF7DF0A6}) await omni.kit.app.get_app().next_update_async() temp_file = Path(tempfile.gettempdir()).joinpath("workspace_" + next(tempfile._get_candidate_names()) + ".json") # Save data to json file and open it in QuickLayout with open(f"{temp_file}", "w") as json_file: json.dump(data, json_file, sort_keys=True, indent=2) QuickLayout.load_file(f"{temp_file}") await omni.kit.app.get_app().next_update_async() # for code coverage. Real QuickLayout.compare_file test is in omni.kit.test_suite.layout as it needs windows QuickLayout.compare_file(f"{temp_file}") # We don't test tab bar window_left.dock_tab_bar_visible = False window_right.dock_tab_bar_visible = False os.remove(f"{temp_file}") await self.finalize_test(golden_img_dir=self._golden_img_dir)
5,838
Python
35.72327
120
0.538883
omniverse-code/kit/exts/omni.kit.quicklayout/docs/CHANGELOG.md
# QUICKLAYOUT CHANGELOG ## [1.1.1] - 2023-01-31 ### Changed - Removed python.module for tests, from extension.toml - Fixed tests that broke when run in random order ## [1.1.0] - 2023-01-11 ### Changed - Adding default layout template ## [1.0.2] - 2023-01-20 ### Changed - Fixed saving/loading using nucleus paths ## [1.0.1] - 2021-05-25 ### Changed - Using `omni.client` for saving and loading the workspace ## [1.0.0] - 2021-02-02 ### Added - Initial extension that saves/loads the layout to the userdirectory
515
Markdown
22.454544
68
0.691262
omniverse-code/kit/exts/omni.kit.quicklayout/docs/README.md
# Layout Control Tools [omni.kit.quicklayout] Set of tools for controlling layout. Creates two menu items. - `Window/Layout/Save Layout`: saves the current layout to the file `"${data}/user.layout.json"` - `Window/Layout/Load Layout`: loads the layout from the file `"${data}/user.layout.json"`
298
Markdown
32.222219
96
0.738255
omniverse-code/kit/exts/omni.kit.menu.common/config/extension.toml
[package] # Semantic Versioning is used: https://semver.org/ version = "1.0.3" category = "Internal" # Lists people or organizations that are considered the "authors" of the package. authors = ["NVIDIA"] # The title and description fields are primarily for displaying extension info in UI title = "Common Menu" description="Implementation of parts of Window and Help menus." # URL of the extension source repository. repository = "" # Keywords for the extension keywords = ["kit", "ui", "menu"] # 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. Folder named "data" automatically goes in git lfs (see .gitattributes file). preview_image = "data/preview.png" [dependencies] "omni.usd" = {} "omni.kit.menu.utils" = {} [[python.module]] name = "omni.kit.menu.common" [settings] # Setting this to false because we also set F11 in this ext. exts."omni.appwindow".listenF11 = false exts."omni.kit.menu.common".external_kit_sdk_url = "https://docs.omniverse.nvidia.com/prod_kit/prod_kit/overview.html" exts."omni.kit.menu.common".internal_kit_sdk_url = "https://omniverse.gitlab-master-pages.nvidia.com/omni-docs/prod_kit/prod_kit/overview.html" exts."omni.kit.menu.common".external_kit_manual_url = "https://docs.omniverse.nvidia.com/py/kit/index.html" exts."omni.kit.menu.common".internal_kit_manual_url = "https://omniverse-docs.s3-website-us-east-1.amazonaws.com/kit-manual/index-internal.html" [[test]] args = [ "--/renderer/enabled=pxr", "--/renderer/active=pxr", "--/renderer/multiGpu/enabled=false", "--/renderer/multiGpu/autoEnable=false", # Disable mGPU with PXR due to OM-51026, OM-53611 "--/renderer/multiGpu/maxGpuCount=1", "--/app/asyncRendering=false", "--/app/file/ignoreUnsavedStage=true", "--/app/window/dpiScaleOverride=1.0", "--/app/window/scaleToMonitor=false", "--/app/menu/legacy_mode=false", # "--no-window", # Need window for fullscreen tests ] dependencies = [ "omni.hydra.pxr", "omni.kit.renderer.capture", "omni.kit.mainwindow", "omni.kit.ui_test", "omni.kit.material.library", "omni.kit.viewport.utility", "omni.kit.hotkeys.core" ] stdoutFailPatterns.exclude = [ "*HydraRenderer failed to render this frame*", # Can drop a frame or two rendering with OpenGL interop "*Cannot use omni.hydra.pxr without OpenGL interop*" # Linux TC configs with multi-GPU might not have OpenGL available ] timeout = 900
2,579
TOML
34.342465
144
0.714618
omniverse-code/kit/exts/omni.kit.menu.common/omni/kit/menu/common/scripts/common.py
import omni.ext import omni.kit.menu.utils from .legacy_help import HelpExtension from .legacy_window import WindowExtension class CommonMenuExtension(omni.ext.IExt): def on_startup(self, ext_id): self._legacy_help = HelpExtension() self._legacy_window = WindowExtension() def on_shutdown(self): del self._legacy_help del self._legacy_window
385
Python
24.733332
47
0.706494
omniverse-code/kit/exts/omni.kit.menu.common/omni/kit/menu/common/scripts/legacy_window.py
import carb import carb.input import carb.settings import omni.kit.ui import omni.appwindow import omni.kit.menu.utils import omni.ui as ui from carb.input import KeyboardInput as Key class WindowExtension: def __init__(self): self._appwindow = omni.appwindow.get_default_app_window() self._settings = carb.settings.get_settings() self.WINDOW_UI_TOGGLE_VISIBILITY_MENU = "Window/UI Toggle Visibility" self.WINDOW_FULLSCREEN_MODE_MENU = "Window/Fullscreen Mode" self.WINDOW_DPI_SCALE_INCREASE_MENU = "Window/DPI Scale/Increase" self.WINDOW_DPI_SCALE_DECREASE_MENU = "Window/DPI Scale/Decrease" self.WINDOW_DPI_SCALE_RESET_MENU = "Window/DPI Scale/Reset" self.SHOW_DPI_SCALE_MENU_SETTING = "/app/window/showDpiScaleMenu" self.DPI_SCALE_OVERRIDE_SETTING = "/app/window/dpiScaleOverride" self.DPI_SCALE_OVERRIDE_DEFAULT = -1.0 self.DPI_SCALE_OVERRIDE_MIN = 0.5 self.DPI_SCALE_OVERRIDE_MAX = 5.0 self.DPI_SCALE_OVERRIDE_STEP = 0.5 self.menus = [] menu = omni.kit.ui.get_editor_menu() if menu: window_ui_toggle_visibility_menu = menu.add_item(self.WINDOW_UI_TOGGLE_VISIBILITY_MENU, None, priority=51) window_ui_toggle_visibility_action = omni.kit.menu.utils.add_action_to_menu(self.WINDOW_UI_TOGGLE_VISIBILITY_MENU, lambda *_: self.on_toggle_ui(), "UiToggle", (0, Key.F7)) self.menus.append((window_ui_toggle_visibility_menu, window_ui_toggle_visibility_action)) window_fullscreen_mode_menu = menu.add_item(self.WINDOW_FULLSCREEN_MODE_MENU, None, priority=52) window_fullscreen_mode_menu_action = omni.kit.menu.utils.add_action_to_menu(self.WINDOW_FULLSCREEN_MODE_MENU, lambda *_: self.on_fullscreen(), "FullscreenMode", (0, Key.F11)) self.menus.append((window_fullscreen_mode_menu, window_fullscreen_mode_menu_action)) self._settings.set_default_bool(self.SHOW_DPI_SCALE_MENU_SETTING, False) if self._settings.get_as_bool(self.SHOW_DPI_SCALE_MENU_SETTING): window_dpi_scale_increase_menu = menu.add_item(self.WINDOW_DPI_SCALE_INCREASE_MENU, None, priority=53) window_dpi_scale_increase_menu_action = omni.kit.menu.utils.add_action_to_menu(self.WINDOW_DPI_SCALE_INCREASE_MENU, lambda *_: self.on_dpi_scale_increase(), "DPIScaleIncrease", (carb.input.KEYBOARD_MODIFIER_FLAG_CONTROL, Key.EQUAL)) self.menus.append((window_dpi_scale_increase_menu, window_dpi_scale_increase_menu_action)) window_dpi_scale_decrease_menu = menu.add_item(self.WINDOW_DPI_SCALE_DECREASE_MENU, None, priority=54) window_dpi_scale_decrease_menu_action = omni.kit.menu.utils.add_action_to_menu(self.WINDOW_DPI_SCALE_DECREASE_MENU, lambda *_: self.on_dpi_scale_decrease(), "DPIScaleDecrease", (carb.input.KEYBOARD_MODIFIER_FLAG_CONTROL, Key.MINUS)) self.menus.append((window_dpi_scale_decrease_menu, window_dpi_scale_decrease_menu_action)) window_dpi_scale_reset_menu = menu.add_item(self.WINDOW_DPI_SCALE_RESET_MENU, None, priority=55) window_dpi_scale_reset_menu_action = omni.kit.menu.utils.add_action_to_menu(self.WINDOW_DPI_SCALE_RESET_MENU, lambda *_: self.on_dpi_scale_reset(), "DPIScaleReset") self.menus.append((window_dpi_scale_reset_menu, window_dpi_scale_reset_menu_action)) # Sort top level menus: menu.set_priority("Window", -6) def __del__(self): self.menus = None def add_menu(self, *argv, **kwargs): new_menu = omni.kit.ui.get_editor_menu().add_item(*argv, **kwargs) self.menus.append(new_menu) return new_menu def set_ui_hidden(self, hide): self._settings.set("/app/window/hideUi", hide) def is_ui_hidden(self): return self._settings.get("/app/window/hideUi") def on_toggle_ui(self): self.set_ui_hidden(not self.is_ui_hidden()) def on_fullscreen(self): display_mode_lock = self._settings.get(f"/app/window/displayModeLock") if display_mode_lock: # Always stay in fullscreen_mode, only hide or show UI. self.set_ui_hidden(not self.is_ui_hidden()) else: # Only toggle fullscreen on/off when not display_mode_lock was_fullscreen = self._appwindow.is_fullscreen() self._appwindow.set_fullscreen(not was_fullscreen) # Always hide UI in fullscreen self.set_ui_hidden(not was_fullscreen) def step_and_clamp_dpi_scale_override(self, increase): # Get the current value. dpi_scale = self._settings.get_as_float(self.DPI_SCALE_OVERRIDE_SETTING) if dpi_scale == self.DPI_SCALE_OVERRIDE_DEFAULT: dpi_scale = ui.Workspace.get_dpi_scale() # Increase or decrease the current value by the setp value. if increase: dpi_scale += self.DPI_SCALE_OVERRIDE_STEP else: dpi_scale -= self.DPI_SCALE_OVERRIDE_STEP # Clamp the new value between the min/max values. dpi_scale = max(min(dpi_scale, self.DPI_SCALE_OVERRIDE_MAX), self.DPI_SCALE_OVERRIDE_MIN) # Set the new value. self._settings.set(self.DPI_SCALE_OVERRIDE_SETTING, dpi_scale) def on_dpi_scale_increase(self): self.step_and_clamp_dpi_scale_override(True) def on_dpi_scale_decrease(self): self.step_and_clamp_dpi_scale_override(False) def on_dpi_scale_reset(self): self._settings.set(self.DPI_SCALE_OVERRIDE_SETTING, self.DPI_SCALE_OVERRIDE_DEFAULT)
5,631
Python
48.840708
248
0.665068
omniverse-code/kit/exts/omni.kit.menu.common/omni/kit/menu/common/scripts/legacy_help.py
import webbrowser import os import carb import carb.input import carb.settings import omni.kit.app import omni.kit.menu.utils from carb.input import KeyboardInput as Key from omni.kit.menu.utils import MenuItemDescription class HelpExtension: def __init__(self): def get_discover_kit_sdk_path(settings): if omni.kit.app.get_app().is_app_external(): return settings.get("/exts/omni.kit.menu.common/external_kit_sdk_url") else: return settings.get("/exts/omni.kit.menu.common/internal_kit_sdk_url") def get_manual_url_path(settings): if omni.kit.app.get_app().is_app_external(): return settings.get("/exts/omni.kit.menu.common/external_kit_manual_url") else: return settings.get("/exts/omni.kit.menu.common/internal_kit_manual_url") def get_discover_reference_guide_path(settings): if omni.kit.app.get_app().is_app_external(): return settings.get("/exts/omni.kit.menu.common/external_reference_guide_url") else: return settings.get("/exts/omni.kit.menu.common/internal_reference_guide_url") settings = carb.settings.get_settings() discover_reference_guide_path = get_discover_reference_guide_path(settings) discover_kit_sdk_path = get_discover_kit_sdk_path(settings) manual_url_path = get_manual_url_path(settings) self._register_actions("omni.kit.menu.common", discover_reference_guide_path, discover_kit_sdk_path, manual_url_path) reference_guide_name = settings.get("/exts/omni.kit.menu.common/reference_guide_name") kit_sdk_name = settings.get("/exts/omni.kit.menu.common/kit_sdk_name") kit_manual_name = settings.get("/exts/omni.kit.menu.common/kit_manual_name") self._help_menu = [] if reference_guide_name: self._help_menu.append(MenuItemDescription( name=reference_guide_name, onclick_action=("omni.kit.menu.common", "OpenRefGuide"), hotkey=(0, Key.F1), enabled=False if reference_guide_name is None else True )) if kit_sdk_name: self._help_menu.append(MenuItemDescription( name=kit_sdk_name, onclick_action=("omni.kit.menu.common", "OpenDevKitSDK"), enabled=False if discover_kit_sdk_path is None else True )) if kit_manual_name: self._help_menu.append(MenuItemDescription( name=kit_manual_name, onclick_action=("omni.kit.menu.common", "OpenDevManual"), enabled=False if manual_url_path is None else True )) if self._help_menu: omni.kit.menu.utils.add_menu_items(self._help_menu, "Help", 99) def __del__(self): omni.kit.menu.utils.remove_menu_items(self._help_menu, "Help") self._deregister_actions("omni.kit.menu.common") self.menus = None def _register_actions(self, extension_id, discover_reference_guide_path, discover_kit_sdk_path, manual_url_path): action_registry = omni.kit.actions.core.get_action_registry() actions_tag = "Help Menu Actions" # actions action_registry.register_action( extension_id, "OpenRefGuide", lambda: webbrowser.open(discover_reference_guide_path), display_name="Help->Reference Guide", description="Reference Guide", tag=actions_tag, ) action_registry.register_action( extension_id, "OpenDevKitSDK", lambda: webbrowser.open(discover_kit_sdk_path), display_name="Help->Discover Kit SDK", description="Discover Kit SDK", tag=actions_tag, ) action_registry.register_action( extension_id, "OpenDevManual", lambda: webbrowser.open(manual_url_path), display_name="Help->Developers Manual", description="Developers Manual", tag=actions_tag, ) def _deregister_actions(self, extension_id): action_registry = omni.kit.actions.core.get_action_registry() if action_registry: action_registry.deregister_all_actions_for_extension(extension_id)
4,436
Python
38.616071
125
0.606402
omniverse-code/kit/exts/omni.kit.menu.common/omni/kit/menu/common/scripts/__init__.py
from .common import *
22
Python
10.499995
21
0.727273
omniverse-code/kit/exts/omni.kit.menu.common/omni/kit/menu/common/tests/__init__.py
from .common_tests import *
28
Python
13.499993
27
0.75
omniverse-code/kit/exts/omni.kit.menu.common/omni/kit/menu/common/tests/test_func_common_window.py
import asyncio import carb import omni.usd import omni.ui as ui from omni.kit import ui_test from carb.input import KeyboardInput from omni.kit.menu.utils import MenuItemDescription, MenuLayout from omni.kit.viewport.utility import get_active_viewport_window, get_num_viewports DPI_SCALE_OVERRIDE_SETTING = "/app/window/dpiScaleOverride" def get_hide_ui(): hide_ui = carb.settings.get_settings().get("/app/window/hideUi") if hide_ui == None: return False return hide_ui async def common_test_func_window_viewport(tester, menu_item = None): # XXX: Unclear where this API is used, but it originally took an unused menu_item if menu_item: carb.log_error("common_test_func_window_new_viewport_window does not use a menu_item") # Get the default Viewport name, most likely 'Viewport' default_vp_window_name = carb.settings.get_settings().get("/exts/omni.kit.viewport.window/startup/windowName") default_vp_window_name = default_vp_window_name or "Viewport" window_menu = ui_test.get_menubar().find_menu("Window") tester.assertIsNotNone(window_menu) # There will always be a "Viewport" menu item, but on legacy it is a single item otherwise a sub-menu container viewport_menu = window_menu.find_menu("Viewport") tester.assertIsNotNone(viewport_menu) # Build up the sub-menu (and full menu-path) that will be used vp_menu_entry_name = f"{default_vp_window_name} 1" full_default_vp_menu_path = f"Window/Viewport/{default_vp_window_name} 1" # If it doesnt't exists as a child of the "Viewport" menu-item, assume legacy vp_show_menu_entry = viewport_menu.find_menu(vp_menu_entry_name) if not vp_show_menu_entry: viewport_menu = window_menu vp_menu_entry_name = default_vp_window_name full_default_vp_menu_path = f"Window/{default_vp_window_name}" vp_show_menu_entry = window_menu.find_menu(vp_menu_entry_name) # Needs to be valid by now tester.assertIsNotNone(vp_show_menu_entry) # Pre-check that the Viewport Window can also be found viewport_window = get_active_viewport_window(window_name=default_vp_window_name) tester.assertIsNotNone(viewport_window) # verify initial visibility and check state tester.assertTrue(viewport_window.visible) tester.assertTrue(vp_show_menu_entry.widget.checked) # use menu await ui_test.menu_click(full_default_vp_menu_path) await ui_test.human_delay() # verify tester.assertFalse(viewport_window.visible) tester.assertFalse(vp_show_menu_entry.widget.checked) # use menu await ui_test.menu_click(full_default_vp_menu_path) await ui_test.human_delay() # verify tester.assertTrue(viewport_window.visible) tester.assertTrue(vp_show_menu_entry.widget.checked) async def common_test_func_window_ui_toggle_visibility(tester, menu_item: MenuItemDescription): # verify default state tester.assertTrue(get_hide_ui() == False) # use menu await ui_test.menu_click("Window/UI Toggle Visibility") await ui_test.human_delay(50) # verify state tester.assertTrue(get_hide_ui() == True) # cannot use menu so use hotkey instead await ui_test.emulate_keyboard_press(menu_item.hotkey[1], menu_item.hotkey[0]) await ui_test.human_delay(50) # verify state tester.assertTrue(get_hide_ui() == False) async def common_test_hotkey_func_window_ui_toggle_visibility(tester, menu_item: MenuItemDescription): # verify default state tester.assertTrue(get_hide_ui() == False) # hotkey await ui_test.emulate_keyboard_press(menu_item.hotkey[1], menu_item.hotkey[0]) await ui_test.human_delay(50) # verify state tester.assertTrue(get_hide_ui() == True) # hotkey await ui_test.emulate_keyboard_press(menu_item.hotkey[1], menu_item.hotkey[0]) await ui_test.human_delay(50) # verify state tester.assertTrue(get_hide_ui() == False) async def common_test_func_window_fullscreen_mode(tester, menu_item: MenuItemDescription): # verify default state tester.assertTrue(omni.appwindow.get_default_app_window().is_fullscreen() == False) # use menu await ui_test.menu_click("Window/Fullscreen Mode") await ui_test.human_delay(50) # verify state tester.assertTrue(omni.appwindow.get_default_app_window().is_fullscreen() == True) # cannot use menu so use hotkey instead await ui_test.emulate_keyboard_press(menu_item.hotkey[1], menu_item.hotkey[0]) await ui_test.human_delay(50) # verify state tester.assertTrue(omni.appwindow.get_default_app_window().is_fullscreen() == False) async def common_test_hotkey_func_window_fullscreen_mode(tester, menu_item: MenuItemDescription): # verify default state tester.assertTrue(omni.appwindow.get_default_app_window().is_fullscreen() == False) # hotkey await ui_test.emulate_keyboard_press(menu_item.hotkey[1], menu_item.hotkey[0]) await ui_test.human_delay(50) # verify state tester.assertTrue(omni.appwindow.get_default_app_window().is_fullscreen() == True) # hotkey await ui_test.emulate_keyboard_press(menu_item.hotkey[1], menu_item.hotkey[0]) await ui_test.human_delay(50) # verify state tester.assertTrue(omni.appwindow.get_default_app_window().is_fullscreen() == False) async def common_test_func_window_new_viewport_window(tester, menu_item = None): # XXX: Unclear where this API is used, but it originally took an unused menu_item if menu_item: carb.log_error("common_test_func_window_new_viewport_window does not use a menu_item") # verify default state tester.assertEqual(get_num_viewports(), 1) # All functionaliyt contained in Window menu window_menu = ui_test.get_menubar().find_menu("Window") tester.assertIsNotNone(window_menu) # There will always be a "Viewport" menu item, but on legacy it is a single item otherwise a sub-menu container viewport_menu = window_menu.find_menu("Viewport") tester.assertIsNotNone(viewport_menu) # use menu if viewport_menu.find_menu("Viewport 2"): await ui_test.menu_click("Window/Viewport/Viewport 2") else: await ui_test.menu_click("Window/New Viewport Window") await ui_test.human_delay() # verify tester.assertEqual(get_num_viewports(), 2) # close new viewport window viewport_window = get_active_viewport_window(window_name="Viewport 2") if viewport_window: viewport_window.visible = False viewport_window.destroy() del viewport_window async def common_test_func_window_dpi_scale_increase(tester, menu_item: MenuItemDescription): # verify default state tester.assertEqual(omni.appwindow.get_default_app_window().get_dpi_scale_override(), 1.0) # use menu await ui_test.menu_click("Window/DPI Scale/Increase") await ui_test.human_delay(50) # verify state tester.assertEqual(omni.appwindow.get_default_app_window().get_dpi_scale_override(), 1.5) # cannot use menu so use hotkey instead await ui_test.emulate_keyboard_press(menu_item.hotkey[1], menu_item.hotkey[0]) await ui_test.human_delay(50) # verify state tester.assertEqual(omni.appwindow.get_default_app_window().get_dpi_scale_override(), 2.0) # reset state carb.settings.get_settings().set(DPI_SCALE_OVERRIDE_SETTING, 1.0) tester.assertEqual(omni.appwindow.get_default_app_window().get_dpi_scale_override(), 1.0) async def common_test_hotkey_func_window_dpi_scale_increase(tester, menu_item: MenuItemDescription): # verify default state tester.assertEqual(omni.appwindow.get_default_app_window().get_dpi_scale_override(), 1.0) # hotkey await ui_test.emulate_keyboard_press(menu_item.hotkey[1], menu_item.hotkey[0]) await ui_test.human_delay(50) # verify state tester.assertEqual(omni.appwindow.get_default_app_window().get_dpi_scale_override(), 1.5) # hotkey await ui_test.emulate_keyboard_press(menu_item.hotkey[1], menu_item.hotkey[0]) await ui_test.human_delay(50) # verify state tester.assertEqual(omni.appwindow.get_default_app_window().get_dpi_scale_override(), 2.0) # reset state carb.settings.get_settings().set(DPI_SCALE_OVERRIDE_SETTING, 1.0) tester.assertEqual(omni.appwindow.get_default_app_window().get_dpi_scale_override(), 1.0) async def common_test_func_window_dpi_scale_decrease(tester, menu_item: MenuItemDescription): # verify default state tester.assertEqual(omni.appwindow.get_default_app_window().get_dpi_scale_override(), 1.0) # use menu await ui_test.menu_click("Window/DPI Scale/Decrease") await ui_test.human_delay(50) # verify state tester.assertEqual(omni.appwindow.get_default_app_window().get_dpi_scale_override(), 0.5) # cannot use menu so use hotkey instead await ui_test.emulate_keyboard_press(menu_item.hotkey[1], menu_item.hotkey[0]) await ui_test.human_delay(50) # verify state - still 0.5 because it gets clamped to the min tester.assertEqual(omni.appwindow.get_default_app_window().get_dpi_scale_override(), 0.5) # reset state carb.settings.get_settings().set(DPI_SCALE_OVERRIDE_SETTING, 1.0) tester.assertEqual(omni.appwindow.get_default_app_window().get_dpi_scale_override(), 1.0) async def common_test_hotkey_func_window_dpi_scale_decrease(tester, menu_item: MenuItemDescription): # verify default state tester.assertEqual(omni.appwindow.get_default_app_window().get_dpi_scale_override(), 1.0) # hotkey await ui_test.emulate_keyboard_press(menu_item.hotkey[1], menu_item.hotkey[0]) await ui_test.human_delay(50) # verify state tester.assertEqual(omni.appwindow.get_default_app_window().get_dpi_scale_override(), 0.5) # hotkey await ui_test.emulate_keyboard_press(menu_item.hotkey[1], menu_item.hotkey[0]) await ui_test.human_delay(50) # verify state - still 0.5 because it gets clamped to the min tester.assertEqual(omni.appwindow.get_default_app_window().get_dpi_scale_override(), 0.5) # reset state carb.settings.get_settings().set(DPI_SCALE_OVERRIDE_SETTING, 1.0) tester.assertEqual(omni.appwindow.get_default_app_window().get_dpi_scale_override(), 1.0) async def common_test_func_window_dpi_scale_reset(tester, menu_item: MenuItemDescription): # verify default state tester.assertEqual(omni.appwindow.get_default_app_window().get_dpi_scale_override(), 1.0) # use menu await ui_test.menu_click("Window/DPI Scale/Reset") await ui_test.human_delay(50) # verify state tester.assertEqual(omni.appwindow.get_default_app_window().get_dpi_scale_override(), -1.0) # reset state carb.settings.get_settings().set(DPI_SCALE_OVERRIDE_SETTING, 1.0) tester.assertEqual(omni.appwindow.get_default_app_window().get_dpi_scale_override(), 1.0)
10,876
Python
36.506896
115
0.713406
omniverse-code/kit/exts/omni.kit.menu.common/omni/kit/menu/common/tests/test_func_common_help.py
import asyncio import carb import omni.usd import omni.ui as ui from omni.kit import ui_test from omni.kit.menu.utils import MenuItemDescription, MenuLayout async def common_test_func_help_usd_reference_guide(tester, menu_item: MenuItemDescription): carb.log_warn("Help/USD Reference Guide - No test") # don't know how to test this as it opens a webpage async def common_test_hotkey_func_help_usd_reference_guide(tester, menu_item: MenuItemDescription): carb.log_warn("Help/USD Reference Guide - No test") # don't know how to test this as it opens a webpage async def common_test_func_help_developers_manual(tester, menu_item: MenuItemDescription): carb.log_warn("Help/Developers Manual - No test") # don't know how to test this as it opens a webpage async def common_test_func_help_discover_kit_sdk(tester, menu_item: MenuItemDescription): carb.log_warn("Help/Discover Kit SDK - No test") # don't know how to test this as it opens a webpage
983
Python
34.142856
99
0.748728
omniverse-code/kit/exts/omni.kit.menu.common/docs/CHANGELOG.md
# Changelog The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/). ## [1.0.3] - 2022-10-07 ### Changes - Adjust fullscreen test to work with hotkeys.core - Add listenF11 setting for appwindow ## [1.0.2] - 2022-10-04 ### Changes - Test against new Viewport sub-menu ## [1.0.1] - 2022-05-23 ### Changes - Support legacy and new Viewport API - Add dependency on omni.kit.viewport.utility ## [1.0.0] - 2021-11-16 ### Changes - Created from python/extensions-bundled/omni/kit/builtin/menu.py
518
Markdown
22.590908
80
0.698842
omniverse-code/kit/exts/omni.kit.menu.common/docs/index.rst
omni.kit.menu.common ########################### Common Menu .. toctree:: :maxdepth: 1 CHANGELOG
111
reStructuredText
6.466666
27
0.468468
omniverse-code/kit/exts/omni.appwindow/omni/appwindow/__init__.py
import carb.events from ._appwindow import *
45
Python
14.333329
25
0.777778
omniverse-code/kit/exts/omni.appwindow/omni/appwindow/_appwindow.pyi
from __future__ import annotations import omni.appwindow._appwindow import typing import carb._carb import carb.events._events __all__ = [ "IAppWindow", "IAppWindowFactory", "POSITION_CENTERED", "POSITION_UNSET", "WindowType", "acquire_app_window_factory_interface", "get_default_app_window" ] class IAppWindow(): def broadcast_input_blocking_state(self, arg0: bool) -> None: ... def get_action_mapping_set_path(self) -> str: ... def get_clipboard(self) -> str: ... def get_cursor_blink(self) -> bool: ... def get_dpi_scale(self) -> float: ... def get_dpi_scale_override(self) -> float: ... @staticmethod def get_gamepad(*args, **kwargs) -> typing.Any: ... def get_height(self) -> int: ... @staticmethod def get_input_blocking_state(*args, **kwargs) -> typing.Any: ... @staticmethod def get_keyboard(*args, **kwargs) -> typing.Any: ... @staticmethod def get_mouse(*args, **kwargs) -> typing.Any: ... def get_position(self) -> carb._carb.Int2: ... def get_size(self) -> carb._carb.Uint2: ... def get_title(self) -> str: ... def get_ui_scale(self) -> float: ... def get_width(self) -> int: ... @staticmethod def get_window(*args, **kwargs) -> typing.Any: ... def get_window_close_event_stream(self) -> carb.events._events.IEventStream: ... def get_window_content_scale_event_stream(self) -> carb.events._events.IEventStream: ... def get_window_drop_event_stream(self) -> carb.events._events.IEventStream: ... def get_window_focus_event_stream(self) -> carb.events._events.IEventStream: ... def get_window_minimize_event_stream(self) -> carb.events._events.IEventStream: ... def get_window_move_event_stream(self) -> carb.events._events.IEventStream: ... def get_window_resize_event_stream(self) -> carb.events._events.IEventStream: ... def is_fullscreen(self) -> bool: ... def is_maximized(self) -> bool: ... def maximize_window(self) -> None: ... def move(self, arg0: int, arg1: int) -> None: ... def resize(self, arg0: int, arg1: int) -> None: ... def restore_window(self) -> None: ... def set_clipboard(self, arg0: str) -> None: ... def set_dpi_scale_override(self, arg0: float) -> None: ... def set_fullscreen(self, arg0: bool) -> None: ... @staticmethod def set_input_blocking_state(*args, **kwargs) -> typing.Any: ... def shutdown(self) -> bool: ... def startup(self, name: str = '') -> bool: ... def startup_with_desc(self, title: str, width: int, height: int, x: int = 18446744073709551614, y: int = 18446744073709551614, decorations: bool = True, resize: bool = True, always_on_top: bool = False, scale_to_monitor: bool = True, dpi_scale_override: float = -1.0, cursor_blink: bool = True) -> None: ... def update(self, arg0: float) -> None: ... @property def ui_scale_multiplier(self) -> float: """ :type: float """ @ui_scale_multiplier.setter def ui_scale_multiplier(self, arg1: float) -> None: pass pass class IAppWindowFactory(): def create_window_by_type(self, arg0: WindowType) -> IAppWindow: ... def create_window_from_settings(self) -> IAppWindow: ... def create_window_ptr_by_type(self, arg0: WindowType) -> IAppWindow: ... def create_window_ptr_from_settings(self) -> IAppWindow: ... def destroy_window_ptr(self, arg0: IAppWindow) -> None: ... def get_app_window(self) -> IAppWindow: ... def get_default_window(self) -> IAppWindow: ... def get_window_at(self, arg0: int) -> IAppWindow: ... def get_window_count(self) -> int: ... def get_windows(self) -> tuple: ... def set_default_window(self, arg0: IAppWindow) -> None: ... pass class WindowType(): """ Members: OS VIRTUAL """ def __eq__(self, other: object) -> bool: ... def __getstate__(self) -> int: ... def __hash__(self) -> int: ... def __index__(self) -> int: ... def __init__(self, value: int) -> None: ... def __int__(self) -> int: ... def __ne__(self, other: object) -> bool: ... def __repr__(self) -> str: ... def __setstate__(self, state: int) -> None: ... @property def name(self) -> str: """ :type: str """ @property def value(self) -> int: """ :type: int """ OS: omni.appwindow._appwindow.WindowType # value = <WindowType.OS: 1> VIRTUAL: omni.appwindow._appwindow.WindowType # value = <WindowType.VIRTUAL: 0> __members__: dict # value = {'OS': <WindowType.OS: 1>, 'VIRTUAL': <WindowType.VIRTUAL: 0>} pass def acquire_app_window_factory_interface(*args, **kwargs) -> typing.Any: pass def get_default_app_window(*args, **kwargs) -> typing.Any: pass POSITION_CENTERED = 18446744073709551615 POSITION_UNSET = 18446744073709551614
4,864
unknown
38.877049
311
0.609581
omniverse-code/kit/exts/omni.appwindow/omni/appwindow/tests/test_appwindow.py
import omni.kit.app import omni.kit.test import carb.windowing import carb.settings import omni.appwindow WINDOW_ENABLED_PATH = "/app/window/enabled" LINUX_WM_LATENCY_MAX = 100 class Test(omni.kit.test.AsyncTestCase): async def setUp(self): self._windowing = carb.windowing.acquire_windowing_interface() self._app_window_factory = omni.appwindow.acquire_app_window_factory_interface() self._settings = carb.settings.acquire_settings_interface() async def tearDown(self): self._app_window_factory = None def _cmp_vectors_and_delta(self, vec_result, vec_base, delta): return (vec_result[0] == vec_base[0] + delta[0]) and (vec_result[1] == vec_base[1] + delta[1]) async def test_create_os_window(self): self._app_window = self._app_window_factory.create_window_from_settings() self._app_window.startup_with_desc( title="Test OS window", width=100, height=100, x=omni.appwindow.POSITION_CENTERED, y=omni.appwindow.POSITION_CENTERED, decorations=True, resize=True, always_on_top=False, scale_to_monitor=False, dpi_scale_override=-1.0 ) self._native_app_window = self._app_window.get_window() self.assertNotEqual(self._native_app_window, None) self._windowing.show_window(self._native_app_window) await omni.kit.app.get_app().next_update_async() self._app_window.shutdown() self._app_window = None async def test_create_virtual_window(self): is_window_enabled = self._settings.get(WINDOW_ENABLED_PATH) self._settings.set(WINDOW_ENABLED_PATH, False) self._app_window = self._app_window_factory.create_window_from_settings() self._app_window.startup_with_desc( title="Test virtual window", width=100, height=100, x=omni.appwindow.POSITION_CENTERED, y=omni.appwindow.POSITION_CENTERED, decorations=True, resize=True, always_on_top=False, scale_to_monitor=False, dpi_scale_override=-1.0 ) self._native_app_window = self._app_window.get_window() self.assertEqual(self._native_app_window, None) await omni.kit.app.get_app().next_update_async() self._app_window.shutdown() self._app_window = None self._settings.set(WINDOW_ENABLED_PATH, is_window_enabled) async def test_move_os_window(self): self._app_window = self._app_window_factory.create_window_from_settings() self._app_window.startup_with_desc( title="Test OS window", width=100, height=100, x=omni.appwindow.POSITION_CENTERED, y=omni.appwindow.POSITION_CENTERED, decorations=True, resize=True, always_on_top=False, scale_to_monitor=False, dpi_scale_override=-1.0 ) self._native_app_window = self._app_window.get_window() self.assertNotEqual(self._native_app_window, None) self._windowing.show_window(self._native_app_window) move_delta = [10, 20] pos = self._app_window.get_position() pos_native = self._windowing.get_window_position(self._native_app_window) self.assertEqual(pos_native[0], pos[0]) self.assertEqual(pos_native[1], pos[1]) self._app_window.move(pos[0] + move_delta[0], pos[1] + move_delta[1]) for i in range(LINUX_WM_LATENCY_MAX): await omni.kit.app.get_app().next_update_async() # This code is needed due to Linux WM latency; window operations do not happen # immediately, and not deterministically new_pos = self._app_window.get_position() move_happened = self._cmp_vectors_and_delta(new_pos, pos, move_delta) if move_happened: break new_pos = self._app_window.get_position() new_pos_native = self._windowing.get_window_position(self._native_app_window) self.assertEqual(new_pos[0], pos[0] + move_delta[0]) self.assertEqual(new_pos[1], pos[1] + move_delta[1]) self.assertEqual(new_pos_native[0], new_pos[0]) self.assertEqual(new_pos_native[1], new_pos[1]) self._app_window.shutdown() self._app_window = None async def test_resize_os_window(self): self._app_window = self._app_window_factory.create_window_from_settings() self._app_window.startup_with_desc( title="Test OS window", width=100, height=100, x=omni.appwindow.POSITION_CENTERED, y=omni.appwindow.POSITION_CENTERED, decorations=True, resize=True, always_on_top=False, scale_to_monitor=False, dpi_scale_override=-1.0 ) self._native_app_window = self._app_window.get_window() self.assertNotEqual(self._native_app_window, None) self._windowing.show_window(self._native_app_window) resize_delta = [10, 20] size = self._app_window.get_size() size_native = [self._windowing.get_window_width(self._native_app_window), self._windowing.get_window_height(self._native_app_window)] self.assertEqual(size_native[0], size[0]) self.assertEqual(size_native[1], size[1]) self._app_window.resize(size[0] + resize_delta[0], size[1] + resize_delta[1]) for i in range(LINUX_WM_LATENCY_MAX): await omni.kit.app.get_app().next_update_async() # This code is needed due to Linux WM latency; window operations do not happen # immediately, and not deterministically new_size = self._app_window.get_size() resize_happened = self._cmp_vectors_and_delta(new_size, size, resize_delta) if resize_happened: break new_size = self._app_window.get_size() new_size_native = [self._windowing.get_window_width(self._native_app_window), self._windowing.get_window_height(self._native_app_window)] self.assertEqual(new_size[0], size[0] + resize_delta[0]) self.assertEqual(new_size[1], size[1] + resize_delta[1]) self.assertEqual(new_size_native[0], new_size[0]) self.assertEqual(new_size_native[1], new_size[1]) self._app_window.shutdown() self._app_window = None async def test_multiple_os_windows(self): self._app_window1 = self._app_window_factory.create_window_from_settings() self._app_window1.startup_with_desc( title="Test OS window", width=100, height=100, x=omni.appwindow.POSITION_CENTERED, y=omni.appwindow.POSITION_CENTERED, decorations=True, resize=True, always_on_top=False, scale_to_monitor=False, dpi_scale_override=-1.0 ) self._native_app_window1 = self._app_window1.get_window() self.assertNotEqual(self._native_app_window1, None) self._windowing.show_window(self._native_app_window1) self._app_window2 = self._app_window_factory.create_window_from_settings() self._app_window2.startup_with_desc( title="Test OS window", width=100, height=100, x=omni.appwindow.POSITION_CENTERED, y=omni.appwindow.POSITION_CENTERED, decorations=True, resize=True, always_on_top=False, scale_to_monitor=False, dpi_scale_override=-1.0 ) self._native_app_window2 = self._app_window2.get_window() self.assertNotEqual(self._native_app_window2, None) self._windowing.show_window(self._native_app_window2) resize_delta = [30, 40] size = self._app_window1.get_size() size_native = [self._windowing.get_window_width(self._native_app_window1), self._windowing.get_window_height(self._native_app_window1)] self.assertEqual(size_native[0], size[0]) self.assertEqual(size_native[1], size[1]) move_delta = [50, 60] pos = self._app_window2.get_position() pos_native = self._windowing.get_window_position(self._native_app_window2) self.assertEqual(pos_native[0], pos[0]) self.assertEqual(pos_native[1], pos[1]) self._app_window1.resize(size[0] + resize_delta[0], size[1] + resize_delta[1]) self._app_window2.move(pos[0] + move_delta[0], pos[1] + move_delta[1]) for i in range(LINUX_WM_LATENCY_MAX): await omni.kit.app.get_app().next_update_async() # This code is needed due to Linux WM latency; window operations do not happen # immediately, and not deterministically new_size = self._app_window1.get_size() new_pos = self._app_window2.get_position() resize_happened = self._cmp_vectors_and_delta(new_size, size, resize_delta) move_happened = self._cmp_vectors_and_delta(new_pos, pos, move_delta) if resize_happened and move_happened: break new_size = self._app_window1.get_size() new_size_native = [self._windowing.get_window_width(self._native_app_window1), self._windowing.get_window_height(self._native_app_window1)] self.assertEqual(new_size[0], size[0] + resize_delta[0]) self.assertEqual(new_size[1], size[1] + resize_delta[1]) self.assertEqual(new_size_native[0], new_size[0]) self.assertEqual(new_size_native[1], new_size[1]) new_pos = self._app_window2.get_position() new_pos_native = self._windowing.get_window_position(self._native_app_window2) self.assertEqual(new_pos[0], pos[0] + move_delta[0]) self.assertEqual(new_pos[1], pos[1] + move_delta[1]) self.assertEqual(new_pos_native[0], new_pos[0]) self.assertEqual(new_pos_native[1], new_pos[1]) self._app_window1.shutdown() self._app_window2.shutdown() self._app_window1 = None self._app_window2 = None async def test_create_no_cursor_blink_window(self): self._app_window = self._app_window_factory.create_window_from_settings() self._app_window.startup_with_desc( title="Test window, no cursor blink set", width=100, height=100, x=omni.appwindow.POSITION_CENTERED, y=omni.appwindow.POSITION_CENTERED, decorations=True, resize=True, always_on_top=False, scale_to_monitor=False, dpi_scale_override=-1.0, cursor_blink=False ) self._native_app_window = self._app_window.get_window() self.assertNotEqual(self._native_app_window, None) self._windowing.show_window(self._native_app_window) await omni.kit.app.get_app().next_update_async() self.assertFalse(self._app_window.get_cursor_blink()) self._app_window.shutdown() self._app_window = None
11,127
Python
40.992453
147
0.609329
omniverse-code/kit/exts/omni.appwindow/omni/appwindow/tests/__init__.py
from .test_appwindow import *
30
Python
14.499993
29
0.766667
omniverse-code/kit/exts/omni.kit.window.stage/config/extension.toml
[package] title = "Kit Stage Window" description = "Omniverse Kit Stage Window" version = "2.3.12" category = "Internal" feature = true authors = ["NVIDIA"] repository = "" keywords = ["stage", "outliner", "scene"] changelog = "docs/CHANGELOG.md" [dependencies] "omni.ui" = {} "omni.usd" = {} "omni.kit.widget.stage" = {} "omni.kit.widget.stage_icons" = {} "omni.kit.window.drop_support" = {} "omni.kit.menu.utils" = {} [[python.module]] name = "omni.kit.window.stage" # Additional python module with tests, to make them discoverable by test system. [[python.module]] name = "omni.kit.window.stage.tests" [[test]] args = [ "--/app/window/dpiScaleOverride=1.0", "--/app/window/scaleToMonitor=false", "--no-window" ] dependencies = [ "omni.kit.mainwindow", "omni.kit.renderer.capture", "omni.kit.ui_test" ]
834
TOML
20.410256
80
0.659472
omniverse-code/kit/exts/omni.kit.window.stage/omni/kit/window/stage/stage_extension.py
# Copyright (c) 2018-2020, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. # __all__ = ["StageExtension"] import asyncio import omni.ext import omni.kit.ui import omni.ui as ui from omni.kit.menu.utils import MenuItemDescription from .stage_window import StageWindow class StageExtension(omni.ext.IExt): """The entry point for Stage Window""" WINDOW_NAME = "Stage" MENU_GROUP = "Window" def on_startup(self): self._window = None ui.Workspace.set_show_window_fn(StageExtension.WINDOW_NAME, self.show_window) self._menu = [MenuItemDescription( name=StageExtension.WINDOW_NAME, ticked=True, # menu item is ticked ticked_fn=self._is_visible, # gets called when the menu needs to get the state of the ticked menu onclick_fn=self._toggle_window )] omni.kit.menu.utils.add_menu_items(self._menu, name=StageExtension.MENU_GROUP) ui.Workspace.show_window(StageExtension.WINDOW_NAME) def on_shutdown(self): omni.kit.menu.utils.remove_menu_items(self._menu, name=StageExtension.MENU_GROUP) self._menu = None if self._window: self._window.destroy() self._window = None ui.Workspace.set_show_window_fn(StageExtension.WINDOW_NAME, None) def _set_menu(self, value): """Set the menu to create this window on and off""" # this only tags test menu to update when menu is opening, so it # doesn't matter that is called before window has been destroyed omni.kit.menu.utils.refresh_menu_items(StageExtension.MENU_GROUP) 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): 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, value): if value: self._window = StageWindow() self._window.set_visibility_changed_listener(self._visiblity_changed_fn) elif self._window: self._window.visible = False def _is_visible(self) -> bool: return False if self._window is None else self._window.visible def _toggle_window(self): if self._is_visible(): self.show_window(False) else: self.show_window(True)
3,049
Python
35.309523
109
0.654969
omniverse-code/kit/exts/omni.kit.window.stage/omni/kit/window/stage/external_drag_drop_helper.py
import omni.ui as ui from typing import List from pxr import Sdf from omni.kit.window.drop_support import ExternalDragDrop external_drag_drop = None def setup_external_drag_drop(window_name :str, stage_widget): global external_drag_drop destroy_external_drag_drop() external_drag_drop = ExternalDragDrop(window_name=window_name, drag_drop_fn=lambda e, p, m=stage_widget.get_model(): _on_ext_drag_drop(e, p, m)) def destroy_external_drag_drop(): global external_drag_drop if external_drag_drop: external_drag_drop.destroy() external_drag_drop = None def _on_ext_drag_drop(edd: ExternalDragDrop, payload: List[str], model: ui.AbstractItemModel): import omni.usd default_prim_path = Sdf.Path("/") stage = omni.usd.get_context().get_stage() if stage.HasDefaultPrim(): default_prim_path = stage.GetDefaultPrim().GetPath() target_item = model.find(default_prim_path) for file_path in edd.expand_payload(payload): model.drop(target_item, file_path.replace("\\", "/"))
1,088
Python
31.029411
123
0.674632
omniverse-code/kit/exts/omni.kit.window.stage/omni/kit/window/stage/stage_window.py
# Copyright (c) 2018-2020, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. # __all__ = ["StageWindow"] from .selection_watch import SelectionWatch from .external_drag_drop_helper import setup_external_drag_drop, destroy_external_drag_drop from .stage_settings import StageSettings from omni.kit.widget.stage import StageWidget from typing import List from typing import Optional from typing import Tuple from pxr import Usd import carb.events import carb.settings import omni.ui as ui import omni.usd class CustomizedStageWidget(StageWidget): @StageWidget.show_prim_display_name.setter def show_prim_display_name(self, value): StageWidget.show_prim_display_name.fset(self, value) StageSettings().show_prim_displayname = value @StageWidget.children_reorder_supported.setter def children_reorder_supported(self, value): StageWidget.children_reorder_supported.fset(self, value) StageSettings().should_keep_children_order = value @StageWidget.auto_reload_prims.setter def auto_reload_prims(self, value): StageWidget.auto_reload_prims.fset(self, value) StageSettings().auto_reload_prims = value def get_treeview(self): return self._tree_view def get_delegate(self): return self._delegate class StageWindow(ui.Window): """The Stage window""" def __init__(self, usd_context_name: str = ""): self._usd_context = omni.usd.get_context(usd_context_name) self._visiblity_changed_listener = None super().__init__( "Stage", width=600, height=800, flags=ui.WINDOW_FLAGS_NO_SCROLLBAR, dockPreference=ui.DockPreference.RIGHT_TOP, ) self.set_visibility_changed_fn(self._visibility_changed_fn) # Dock it to the same space where Layers is docked, make it the first tab and the active tab. self.deferred_dock_in("Layers", ui.DockPolicy.CURRENT_WINDOW_IS_ACTIVE) self.dock_order = 0 # Get list of columns from settings self._settings = carb.settings.get_settings() self._columns_settings_path = "/persistent/exts/omni.kit.window.stage/columns" columns: Optional[str] = self._settings.get(self._columns_settings_path) if columns is None: # By default Visibility and Type are enabled columns self._columns = ["Visibility","Type"] else: self._columns = columns.split("|") with self.frame: self._stage_widget = CustomizedStageWidget( None, columns_enabled=self._columns, children_reorder_supported=StageSettings().should_keep_children_order, show_prim_display_name=StageSettings().show_prim_displayname, auto_reload_prims=StageSettings().auto_reload_prims ) # The Open/Close Stage logic self._stage_subscription = self._usd_context.get_stage_event_stream().create_subscription_to_pop( self._on_usd_context_event, name="Stage Window USD Stage Open/Closing Listening" ) self._on_stage_opened() # The selection logic self._selection = SelectionWatch(usd_context=self._usd_context) self._stage_widget.set_selection_watch(self._selection) # Callback when columns are changed or toggled self._columns_changed_sub = self._stage_widget.subscribe_columns_changed(self._columns_changed) def _columns_changed(self, columns: List[Tuple[str, bool]]): """ Called by StageWidget when columns are changed or toggled. """ enabled_columns = [c[0] for c in columns if c[1]] self._settings.set_string(self._columns_settings_path, "|".join(enabled_columns)) def _visibility_changed_fn(self, visible): if self._visiblity_changed_listener: self._visiblity_changed_listener(visible) if not visible: if self._selection: self._selection.destroy() self._selection = None else: self._selection = SelectionWatch(usd_context=self._usd_context) if self._stage_widget: self._stage_widget.set_selection_watch(self._selection) def set_visibility_changed_listener(self, listener): self._visiblity_changed_listener = listener def destroy(self): """ Called by extension before destroying this object. It doesn't happen automatically. Without this hot reloading doesn't work. """ self._visiblity_changed_listener = None if self._selection: self._selection._tree_view = None self._selection._events = None self._selection._stage_event_sub = None self._selection = None self._stage_widget.destroy() self._stage_widget = None self._stage_subscription = None self._settings = None self._columns_changed_sub = None super().destroy() destroy_external_drag_drop() def _on_usd_context_event(self, event: carb.events.IEvent): """Called on USD Context event""" if event.type == int(omni.usd.StageEventType.OPENED): self._on_stage_opened() elif event.type == int(omni.usd.StageEventType.CLOSING): self._on_stage_closing() def _on_stage_opened(self): """Called when opening a new stage""" stage = self._usd_context.get_stage() if not stage: return self._stage_widget.open_stage(stage) setup_external_drag_drop("Stage", self._stage_widget) def _on_stage_closing(self): """Called when close the stage""" self._stage_widget.open_stage(None) setup_external_drag_drop("Stage", self._stage_widget) def get_widget(self) -> CustomizedStageWidget: return self._stage_widget
6,244
Python
36.172619
105
0.653107
omniverse-code/kit/exts/omni.kit.window.stage/omni/kit/window/stage/stage_settings.py
# Copyright (c) 2018-2020, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. # # Selection Watch implementation has been moved omni.kit.widget.stage. # Import it here for keeping back compatibility. import carb.settings import omni.kit.usd.layers as layers from .singleton import Singleton SETTINGS_SHOW_PRIM_DISPLAYNAME = "/persistent/ext/omni.kit.widget.stage/show_prim_displayname" SETTINGS_KEEP_CHILDREN_ORDER = "/persistent/ext/omni.usd/keep_children_order" @Singleton class StageSettings: def __init__(self): super().__init__() self._settings = carb.settings.get_settings() self._settings.set_default_bool(SETTINGS_SHOW_PRIM_DISPLAYNAME, False) self._settings.set_default_bool(layers.SETTINGS_AUTO_RELOAD_NON_SUBLAYERS, False) self._settings.set_default_bool(SETTINGS_KEEP_CHILDREN_ORDER, False) @property def show_prim_displayname(self): return self._settings.get_as_bool(SETTINGS_SHOW_PRIM_DISPLAYNAME) @show_prim_displayname.setter def show_prim_displayname(self, enabled: bool): self._settings.set(SETTINGS_SHOW_PRIM_DISPLAYNAME, enabled) @property def auto_reload_prims(self): return self._settings.get_as_bool(layers.SETTINGS_AUTO_RELOAD_NON_SUBLAYERS) @auto_reload_prims.setter def auto_reload_prims(self, enabled: bool): self._settings.set(layers.SETTINGS_AUTO_RELOAD_NON_SUBLAYERS, enabled) @property def should_keep_children_order(self): return self._settings.get_as_bool(SETTINGS_KEEP_CHILDREN_ORDER) @should_keep_children_order.setter def should_keep_children_order(self, value): self._settings.set(SETTINGS_KEEP_CHILDREN_ORDER, value)
2,068
Python
37.314814
94
0.738878
omniverse-code/kit/exts/omni.kit.window.stage/omni/kit/window/stage/tests/stage_window_test.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. ## import omni.kit.test from omni.ui.tests.test_base import OmniUiTest from pathlib import Path import carb import omni.kit.app import omni.ui as ui import omni.usd import omni.kit.commands from omni.kit import ui_test from unittest.mock import Mock, patch, ANY from ..stage_window import StageWindow CURRENT_PATH = Path(__file__).parent.joinpath("../../../../../data") class TestStageWindow(OmniUiTest): # Before running each test async def setUp(self): await super().setUp() self._golden_img_dir = CURRENT_PATH.absolute().resolve().joinpath("tests") self._w = ui.Workspace.get_window("Stage") self._usd_context = omni.usd.get_context() # After running each test async def tearDown(self): self._w = None self._golden_img_dir = None await super().tearDown() async def test_general(self): # New stage with a sphere await self._usd_context.new_stage_async() omni.kit.commands.execute("CreatePrim", prim_path="/Sphere", prim_type="Sphere", select_new_prim=False) # Loading icon takes time. # TODO: We need a mode that blocks UI until icons are loaded await self.wait(10) await self.docked_test_window( window=self._w, width=450, height=100, restore_window=ui.Workspace.get_window("Layer"), restore_position=ui.DockPosition.SAME, ) await self.finalize_test(golden_img_dir=self._golden_img_dir) async def test_multi_visibility_change(self): """Testing visibility of StageWidget""" await self.docked_test_window( window=self._w, width=450, height=200, ) # New stage with three prims await self._usd_context.new_stage_async() omni.kit.commands.execute("CreatePrim", prim_path="/A", prim_type="Sphere", select_new_prim=False) omni.kit.commands.execute("CreatePrim", prim_path="/B", prim_type="Sphere", select_new_prim=False) omni.kit.commands.execute("CreatePrim", prim_path="/C", prim_type="Sphere", select_new_prim=False) await ui_test.wait_n_updates(5) # select both A and C self._usd_context.get_selection().set_selected_prim_paths(["/A", "/C"], True) # make A invisible await ui_test.wait_n_updates(5) stage_widget = ui_test.find("Stage//Frame/**/ScrollingFrame/TreeView[*].visible==True") eye_icon = stage_widget.find_all("**/ToolButton[*]")[0] await eye_icon.click() await ui_test.wait_n_updates(5) # check C will also be invisible await self.finalize_test(golden_img_dir=self._golden_img_dir) async def wait(self, n=100): for i in range(n): await omni.kit.app.get_app().next_update_async() async def test_header_columns(self): from omni.kit import ui_test await ui_test.find("Stage").focus() stage_widget = ui_test.find("Stage//Frame/**/ScrollingFrame/TreeView[*].visible==True") name_column = stage_widget.find("**/Label[*].text=='Name (Old to New)'") self.assertTrue(name_column) await ui_test.emulate_mouse_move(name_column.center) await name_column.right_click() with self.assertRaises(Exception): await ui_test.select_context_menu("Create") await self.wait() await name_column.click() await self.wait() name_column = stage_widget.find("**/Label[*].text=='Name (A to Z)'") self.assertTrue(name_column) await name_column.click() await self.wait() name_column = stage_widget.find("**/Label[*].text=='Name (Z to A)'") self.assertTrue(name_column) await name_column.click() await self.wait() name_column = stage_widget.find("**/Label[*].text=='Name (New to Old)'") self.assertTrue(name_column) await name_column.click() await self.wait() name_column = stage_widget.find("**/Label[*].text=='Name (Old to New)'") self.assertTrue(name_column) await self.finalize_test_no_image() async def test_rename_with_context_menu(self): from omni.kit import ui_test await ui_test.find("Stage").focus() stage_widget = ui_test.find("Stage//Frame/**/ScrollingFrame/TreeView[*].visible==True") # New stage with three prims await self._usd_context.new_stage_async() stage = omni.usd.get_context().get_stage() stage.GetRootLayer().Clear() await ui_test.wait_n_updates(5) prim = stage.DefinePrim("/test", "Xform") await ui_test.wait_n_updates(5) prim_item = stage_widget.find("**/Label[*].text=='test'") self.assertTrue(prim_item) prim_name_field = stage_widget.find("**/StringField[*].identifier=='rename_field'") self.assertTrue(prim_name_field) await prim_item.double_click() self.assertTrue(prim_name_field.widget.selected) prim_name_field.model.set_value("") await prim_name_field.input("test2") await ui_test.input.emulate_keyboard_press(carb.input.KeyboardInput.ENTER) await ui_test.wait_n_updates(5) old_prim = stage.GetPrimAtPath("/test") self.assertFalse(old_prim) new_prim = stage.GetPrimAtPath("/test2") self.assertTrue(new_prim) # Rename with context menu prim_item = stage_widget.find("**/Label[*].text=='test2'") self.assertTrue(prim_item) prim_name_field = stage_widget.find("**/StringField[*].identifier=='rename_field'") self.assertTrue(prim_name_field) await prim_item.right_click() await ui_test.select_context_menu("Rename") self.assertTrue(prim_name_field.widget.selected) await prim_name_field.input("test3") await ui_test.input.emulate_keyboard_press(carb.input.KeyboardInput.ENTER) await ui_test.wait_n_updates(5) old_prim = stage.GetPrimAtPath("/test") self.assertFalse(old_prim) new_prim = stage.GetPrimAtPath("/test2test3") self.assertTrue(new_prim) await self.finalize_test_no_image() async def test_window_destroyed_when_hidden(self): """Test that hiding stage window destroys it, and showing creates a new instance.""" ui.Workspace.show_window("Stage") self.assertTrue(ui.Workspace.get_window("Stage").visible) with patch.object(StageWindow, "destroy", autospec=True) as mock_destroy_dialog: ui.Workspace.show_window("Stage", False) await ui_test.wait_n_updates(5) mock_destroy_dialog.assert_called() self.assertFalse(ui.Workspace.get_window("Stage").visible) await self.finalize_test_no_image()
7,238
Python
37.505319
111
0.63664
omniverse-code/kit/exts/omni.kit.window.stage/docs/CHANGELOG.md
# Changelog ## [2.3.12] - 2023-01-11 ### Added - Move SelectionWatch into omni.kit.widget.stage to provide default implementation. ## [2.3.11] - 2022-11-29 ### Added - Unitests for header of name column. ## [2.3.10] - 2022-11-01 ### Added - Test for renaming prim. ## [2.3.9] - 2022-09-30 ### Fixed - Set the menu checkbox when the window is appearing ## [2.3.8] - 2022-08-04 ### Added - Test for toggling visibility for multiple prims ## [2.3.7] - 2022-05-24 ### Changed - Optimize selection of stage window by reducing allocations of Sdf.Path. ## [2.3.6] - 2022-03-03 ### Changed - Use command for selection in widget so it can be undoable. ## [2.3.5] - 2021-10-20 ### Changed - External drag/drop doesn't use windows slashes ## [2.3.4] - 2021-05-25 ### Fixed - Bug when hide and show the Stage window ## [2.3.3] - 2021-04-27 ## Removed - `omni.stageupdate` is deprecated and doesn't work well with multiple usd contexts ## [2.3.2] - 2020-11-19 ### Changed - Refusing selection of grayed prims in search mode ## [2.3.1] - 2020-10-22 ### Added - Dependency on omni.kit.widget.stage_icons ## [2.3.0] - 2020-09-16 ### Changed - Split to two parts: omni.kit.widget.stage and omni.kit.window.stage ## [2.2.0] - 2020-09-15 ### Changed - Detached from Editor and using UsdNotice for notifications
1,310
Markdown
21.220339
83
0.670229
omniverse-code/kit/exts/omni.kit.procedural.mesh/config/extension.toml
[package] version = "0.1.0" title = "Procedural Mesh" category = "Internal" # Main module of the python interface [[python.module]] name = "omni.kit.procedural.mesh" # Watch the .ogn files for hot reloading (only works for Python files) [fswatcher.patterns] include = ["*.ogn", "*.py"] exclude = ["Ogn*Database.py"] # Other extensions that must be loaded before this one [dependencies] "omni.usd" = {} "omni.ui" = {} "omni.graph" = {} "omni.graph.tools" = {} "omni.kit.menu.utils" = {} [[native.plugin]] path = "bin/*.plugin" recursive = false
551
TOML
18.034482
70
0.669691
omniverse-code/kit/exts/omni.kit.procedural.mesh/omni/kit/procedural/mesh/__init__.py
from .scripts.extension import * from .scripts.command import *
64
Python
20.66666
32
0.78125
omniverse-code/kit/exts/omni.kit.procedural.mesh/omni/kit/procedural/mesh/ogn/OgnProceduralMeshSphereDatabase.py
"""Support for simplified access to data on nodes of type omni.kit.procedural.mesh.CreateMeshSphere If necessary, create a new mesh representing a shpere """ import omni.graph.core as og import omni.graph.core._omni_graph_core as _og import omni.graph.tools.ogn as ogn import numpy class OgnProceduralMeshSphereDatabase(og.Database): """Helper class providing simplified access to data on nodes of type omni.kit.procedural.mesh.CreateMeshSphere Class Members: node: Node being evaluated Attribute Value Properties: Inputs: inputs.diameter inputs.latitudeResolution inputs.longitudeResolution inputs.parameterCheck Outputs: outputs.extent outputs.faceVertexCounts outputs.faceVertexIndices outputs.parameterCheck outputs.points outputs.stIndices outputs.sts """ # This is an internal object that provides per-class storage of a per-node data dictionary PER_NODE_DATA = {} # This is an internal object that describes unchanging attributes in a generic way # The values in this list are in no particular order, as a per-attribute tuple # Name, Type, ExtendedTypeIndex, UiName, Description, Metadata, # Is_Required, DefaultValue, Is_Deprecated, DeprecationMsg # You should not need to access any of this data directly, use the defined database interfaces INTERFACE = og.Database._get_interface([ ('inputs:diameter', 'float', 0, None, 'Sphere diameter', {ogn.MetadataKeys.DEFAULT: '100'}, True, 100, False, ''), ('inputs:latitudeResolution', 'int', 0, None, 'Sphere Resolution', {ogn.MetadataKeys.DEFAULT: '10'}, True, 10, False, ''), ('inputs:longitudeResolution', 'int', 0, None, 'Sphere Resolution', {ogn.MetadataKeys.DEFAULT: '10'}, True, 10, False, ''), ('inputs:parameterCheck', 'int', 0, None, 'Previous crc value', {ogn.MetadataKeys.DEFAULT: '-1'}, True, -1, False, ''), ('outputs:extent', 'float3[]', 0, None, 'Extent of the mesh', {}, True, None, False, ''), ('outputs:faceVertexCounts', 'int[]', 0, None, 'Vertex count of faces', {}, True, None, False, ''), ('outputs:faceVertexIndices', 'int[]', 0, None, 'Vertex indices of faces', {}, True, None, False, ''), ('outputs:parameterCheck', 'int', 0, None, 'Current crc value', {}, True, None, False, ''), ('outputs:points', 'float3[]', 0, None, 'Points', {}, True, None, False, ''), ('outputs:stIndices', 'int[]', 0, None, 'Texture coordinate indices of faces', {}, True, None, False, ''), ('outputs:sts', 'float2[]', 0, None, 'Texture coordinate of vertices', {}, True, None, False, ''), ]) class ValuesForInputs(og.DynamicAttributeAccess): LOCAL_PROPERTY_NAMES = {"diameter", "latitudeResolution", "longitudeResolution", "parameterCheck", "_setting_locked", "_batchedReadAttributes", "_batchedReadValues"} """Helper class that creates natural hierarchical access to input attributes""" def __init__(self, node: og.Node, attributes, dynamic_attributes: og.DynamicAttributeInterface): """Initialize simplified access for the attribute data""" context = node.get_graph().get_default_graph_context() super().__init__(context, node, attributes, dynamic_attributes) self._batchedReadAttributes = [self._attributes.diameter, self._attributes.latitudeResolution, self._attributes.longitudeResolution, self._attributes.parameterCheck] self._batchedReadValues = [100, 10, 10, -1] @property def diameter(self): return self._batchedReadValues[0] @diameter.setter def diameter(self, value): self._batchedReadValues[0] = value @property def latitudeResolution(self): return self._batchedReadValues[1] @latitudeResolution.setter def latitudeResolution(self, value): self._batchedReadValues[1] = value @property def longitudeResolution(self): return self._batchedReadValues[2] @longitudeResolution.setter def longitudeResolution(self, value): self._batchedReadValues[2] = value @property def parameterCheck(self): return self._batchedReadValues[3] @parameterCheck.setter def parameterCheck(self, value): self._batchedReadValues[3] = value def __getattr__(self, item: str): if item in self.LOCAL_PROPERTY_NAMES: return object.__getattribute__(self, item) else: return super().__getattr__(item) def __setattr__(self, item: str, new_value): if item in self.LOCAL_PROPERTY_NAMES: object.__setattr__(self, item, new_value) else: super().__setattr__(item, new_value) def _prefetch(self): readAttributes = self._batchedReadAttributes newValues = _og._prefetch_input_attributes_data(readAttributes) if len(readAttributes) == len(newValues): self._batchedReadValues = newValues class ValuesForOutputs(og.DynamicAttributeAccess): LOCAL_PROPERTY_NAMES = {"parameterCheck", "_batchedWriteValues"} """Helper class that creates natural hierarchical access to output attributes""" def __init__(self, node: og.Node, attributes, dynamic_attributes: og.DynamicAttributeInterface): """Initialize simplified access for the attribute data""" context = node.get_graph().get_default_graph_context() super().__init__(context, node, attributes, dynamic_attributes) self.extent_size = None self.faceVertexCounts_size = None self.faceVertexIndices_size = None self.points_size = None self.stIndices_size = None self.sts_size = None self._batchedWriteValues = { } @property def extent(self): data_view = og.AttributeValueHelper(self._attributes.extent) return data_view.get(reserved_element_count=self.extent_size) @extent.setter def extent(self, value): data_view = og.AttributeValueHelper(self._attributes.extent) data_view.set(value) self.extent_size = data_view.get_array_size() @property def faceVertexCounts(self): data_view = og.AttributeValueHelper(self._attributes.faceVertexCounts) return data_view.get(reserved_element_count=self.faceVertexCounts_size) @faceVertexCounts.setter def faceVertexCounts(self, value): data_view = og.AttributeValueHelper(self._attributes.faceVertexCounts) data_view.set(value) self.faceVertexCounts_size = data_view.get_array_size() @property def faceVertexIndices(self): data_view = og.AttributeValueHelper(self._attributes.faceVertexIndices) return data_view.get(reserved_element_count=self.faceVertexIndices_size) @faceVertexIndices.setter def faceVertexIndices(self, value): data_view = og.AttributeValueHelper(self._attributes.faceVertexIndices) data_view.set(value) self.faceVertexIndices_size = data_view.get_array_size() @property def points(self): data_view = og.AttributeValueHelper(self._attributes.points) return data_view.get(reserved_element_count=self.points_size) @points.setter def points(self, value): data_view = og.AttributeValueHelper(self._attributes.points) data_view.set(value) self.points_size = data_view.get_array_size() @property def stIndices(self): data_view = og.AttributeValueHelper(self._attributes.stIndices) return data_view.get(reserved_element_count=self.stIndices_size) @stIndices.setter def stIndices(self, value): data_view = og.AttributeValueHelper(self._attributes.stIndices) data_view.set(value) self.stIndices_size = data_view.get_array_size() @property def sts(self): data_view = og.AttributeValueHelper(self._attributes.sts) return data_view.get(reserved_element_count=self.sts_size) @sts.setter def sts(self, value): data_view = og.AttributeValueHelper(self._attributes.sts) data_view.set(value) self.sts_size = data_view.get_array_size() @property def parameterCheck(self): value = self._batchedWriteValues.get(self._attributes.parameterCheck) if value: return value else: data_view = og.AttributeValueHelper(self._attributes.parameterCheck) return data_view.get() @parameterCheck.setter def parameterCheck(self, value): self._batchedWriteValues[self._attributes.parameterCheck] = value def __getattr__(self, item: str): if item in self.LOCAL_PROPERTY_NAMES: return object.__getattribute__(self, item) else: return super().__getattr__(item) def __setattr__(self, item: str, new_value): if item in self.LOCAL_PROPERTY_NAMES: object.__setattr__(self, item, new_value) else: super().__setattr__(item, new_value) def _commit(self): _og._commit_output_attributes_data(self._batchedWriteValues) self._batchedWriteValues = { } class ValuesForState(og.DynamicAttributeAccess): """Helper class that creates natural hierarchical access to state attributes""" def __init__(self, node: og.Node, attributes, dynamic_attributes: og.DynamicAttributeInterface): """Initialize simplified access for the attribute data""" context = node.get_graph().get_default_graph_context() super().__init__(context, node, attributes, dynamic_attributes) def __init__(self, node): super().__init__(node) dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_INPUT) self.inputs = OgnProceduralMeshSphereDatabase.ValuesForInputs(node, self.attributes.inputs, dynamic_attributes) dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_OUTPUT) self.outputs = OgnProceduralMeshSphereDatabase.ValuesForOutputs(node, self.attributes.outputs, dynamic_attributes) dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_STATE) self.state = OgnProceduralMeshSphereDatabase.ValuesForState(node, self.attributes.state, dynamic_attributes)
10,957
Python
46.030043
177
0.637127
omniverse-code/kit/exts/omni.kit.procedural.mesh/omni/kit/procedural/mesh/scripts/extension.py
import omni.ext from ..bindings._omni_kit_procedural_mesh import * from .menu import * class PublicExtension(omni.ext.IExt): def on_startup(self): self._interface = acquire_interface() self._menu = Menu() def on_shutdown(self): self._menu.on_shutdown() self._menu = None release_interface(self._interface)
357
Python
22.866665
50
0.644258
omniverse-code/kit/exts/omni.kit.procedural.mesh/omni/kit/procedural/mesh/scripts/procedural_mesh_omnigraph_utils.py
""" A set of utilities """ import omni.kit.app import omni.usd from pxr import Sdf, UsdGeom import omni.graph.core as og def get_parent(stage, parentPath): if parentPath: parentPrim = stage.GetPrimAtPath(parentPath) if parentPrim: return parentPrim, False # fallback to default behavior (creating a parent xform prim) omni.kit.commands.execute( "CreatePrimWithDefaultXform", prim_type="Xform", prim_path=omni.usd.get_stage_next_free_path(stage, "/" + "ProceduralMeshXform", True), select_new_prim=True, create_default_xform=False, ) paths = omni.usd.get_context().get_selection().get_selected_prim_paths() for path in paths: parentPrim = stage.GetPrimAtPath(path) return parentPrim, True def create_mesh_computer(stage, prim_name: str, evaluator_name: str, node_type: str, parentPath=None): parentPrim, isParentOwned = get_parent(stage, parentPath) omni.kit.commands.execute( "CreatePrimWithDefaultXform", prim_type="Mesh", prim_path=omni.usd.get_stage_next_free_path( stage, str(parentPrim.GetPath().AppendElementString(prim_name)), False ), select_new_prim=True, create_default_xform=False, ) paths = omni.usd.get_context().get_selection().get_selected_prim_paths() for path in paths: mesh = stage.GetPrimAtPath(path) helper = og.OmniGraphHelper() computer = helper.create_node(str(mesh.GetPath().AppendElementString(evaluator_name)), node_type) if isParentOwned: return parentPrim, mesh, computer else: return mesh, mesh, computer def init_common_attributes(prim): # parameter check # sschirm parameterCheckAttr = prim.CreateAttribute("proceduralMesh:parameterCheck", Sdf.ValueTypeNames.Int) parameterCheckAttr.Set(0) # basic attributes pointsAttr = prim.GetAttribute("points") faceVertexCountsAttr = prim.GetAttribute("faceVertexCounts") faceVertexIndicesAttr = prim.GetAttribute("faceVertexIndices") # extent extentAttr = prim.GetAttribute("extent") def connect_common_attributes(prim, computer): helper = og.OmniGraphHelper() ognPrim = helper.attach_to_prim(prim) # connect parameterCheck attribute as in and output helper.connect(ognPrim, "proceduralMesh:parameterCheck", computer, "inputs:parameterCheck") helper.connect(computer, "outputs:parameterCheck", ognPrim, "proceduralMesh:parameterCheck") # connect basic attributes helper.connect(computer, "outputs:points", ognPrim, "points") helper.connect(computer, "outputs:faceVertexCounts", ognPrim, "faceVertexCounts") helper.connect(computer, "outputs:faceVertexIndices", ognPrim, "faceVertexIndices") # connect to extent helper.connect(computer, "outputs:extent", ognPrim, "extent") def init_crease_attributes(prim): creaseIndicesAttr = prim.GetAttribute("creaseIndices") creaseLengthsAttr = prim.GetAttribute("creaseLengths") creaseSharpnessesAttr = prim.GetAttribute("creaseSharpnesses") def connect_crease_attributes(prim, computer): helper = og.OmniGraphHelper() ognPrim = helper.attach_to_prim(prim) # connect smooth group related attributes helper.connect(computer, "outputs:creaseIndices", ognPrim, "creaseIndices") helper.connect(computer, "outputs:creaseLengths", ognPrim, "creaseLengths") helper.connect(computer, "outputs:creaseSharpnesses", ognPrim, "creaseSharpnesses") def init_corner_attributes(prim): cornerIndicesAttr = prim.GetAttribute("cornerIndices") cornerSharpnessesAttr = prim.GetAttribute("cornerSharpnesses") def connect_corner_attributes(prim, computer): helper = og.OmniGraphHelper() ognPrim = helper.attach_to_prim(prim) # connect smooth group related attributes helper.connect(computer, "outputs:cornerIndices", ognPrim, "cornerIndices") helper.connect(computer, "outputs:cornerSharpnesses", ognPrim, "cornerSharpnesses") def init_normals_facevarying_attributes(prim): mesh = UsdGeom.Mesh(prim) # authored normals only works when subdivision is none mesh.CreateSubdivisionSchemeAttr("none") normalsVar = mesh.CreatePrimvar("normals", Sdf.ValueTypeNames.Normal3fArray) normalsAttr = prim.GetAttribute("primvars:normals") normalIndicesAttr = prim.CreateAttribute("primvars:normals:indices", Sdf.ValueTypeNames.IntArray, False) normalsVar.SetInterpolation("faceVarying") def connect_normals_facevarying_attributes(prim, computer): helper = og.OmniGraphHelper() ognPrim = helper.attach_to_prim(prim) # connect normal related attributes helper.connect(computer, "outputs:normals", ognPrim, "primvars:normals") helper.connect(computer, "outputs:normalIndices", ognPrim, "primvars:normals:indices") def init_texture_coords_facevarying_attributes(prim): mesh = UsdGeom.Mesh(prim) # st related attributes stsVar = mesh.CreatePrimvar("st", Sdf.ValueTypeNames.TexCoord2fArray, UsdGeom.Tokens.faceVarying) stsAttr = prim.GetAttribute("primvars:st") stIndicesAttr = prim.CreateAttribute("primvars:st:indices", Sdf.ValueTypeNames.IntArray, False) def connect_texture_coords_facevarying_attributes(prim, computer): helper = og.OmniGraphHelper() ognPrim = helper.attach_to_prim(prim) # connect st related attributes helper.connect(computer, "outputs:sts", ognPrim, "primvars:st") helper.connect(computer, "outputs:stIndices", ognPrim, "primvars:st:indices") def init_texture_coords_attributes(prim): mesh = UsdGeom.Mesh(prim) # st related attributes stsVar = mesh.CreatePrimvar("st", Sdf.ValueTypeNames.TexCoord2fArray, UsdGeom.Tokens.vertex) stsAttr = prim.GetAttribute("primvars:st") def connect_texture_coords_attributes(prim, computer): helper = og.OmniGraphHelper() ognPrim = helper.attach_to_prim(prim) # connect st related attributes helper.connect(computer, "outputs:sts", ognPrim, "primvars:st") def create_procedural_mesh_cube( stage, parentPath=None, xLength=100, yLength=100, zLength=100, xResolution=10, yResolution=10, zResolution=10 ): root, cube, computer = create_mesh_computer( stage, "ProceduralMeshCube", "CubeEvaluator", "omni.kit.procedural.mesh.CreateMeshCube", parentPath ) helper = og.OmniGraphHelper() # omnigraph node for the mesh init helper.set_values( computer, [ ["inputs:xLength", xLength], ["inputs:yLength", yLength], ["inputs:zLength", zLength], ["inputs:xResolution", xResolution], ["inputs:yResolution", xResolution], ["inputs:zResolution", zResolution], ], ) # setup mesh attributes and node inputs/outputs init_common_attributes(cube) init_crease_attributes(cube) init_normals_facevarying_attributes(cube) init_texture_coords_facevarying_attributes(cube) connect_common_attributes(cube, computer) connect_crease_attributes(cube, computer) connect_normals_facevarying_attributes(cube, computer) connect_texture_coords_facevarying_attributes(cube, computer) return root, cube def create_procedural_mesh_sphere(stage, parentPath=None, diameter=100, longitudeResolution=10, latitudeResolution=10): root, sphere, computer = create_mesh_computer( stage, "ProceduralMeshSphere", "SphereEvaluator", "omni.kit.procedural.mesh.CreateMeshSphere", parentPath ) helper = og.OmniGraphHelper() # omnigraph node for the mesh init helper.set_values( computer, [ ["inputs:diameter", diameter], ["inputs:longitudeResolution", longitudeResolution], ["inputs:latitudeResolution", latitudeResolution], ], ) # setup mesh attributes and node inputs/outputs init_common_attributes(sphere) init_texture_coords_facevarying_attributes(sphere) connect_common_attributes(sphere, computer) connect_texture_coords_facevarying_attributes(sphere, computer) return root, sphere def create_procedural_mesh_capsule( stage, parentPath=None, diameter=100, yLength=200, longitudeResolution=10, hemisphereLatitudeResolution=10, middleLatitudeResolution=10, ): root, capsule, computer = create_mesh_computer( stage, "ProceduralMeshCapsule", "CapsuleEvaluator", "omni.kit.procedural.mesh.CreateMeshCapsule", parentPath ) helper = og.OmniGraphHelper() # omnigraph node for the mesh init helper.set_values( computer, [ ["inputs:diameter", diameter], ["inputs:yLength", yLength], ["inputs:longitudeResolution", longitudeResolution], ["inputs:hemisphereLatitudeResolution", hemisphereLatitudeResolution], ["inputs:middleLatitudeResolution", middleLatitudeResolution], ], ) # setup mesh attributes and node inputs/outputs init_common_attributes(capsule) init_texture_coords_facevarying_attributes(capsule) connect_common_attributes(capsule, computer) connect_texture_coords_facevarying_attributes(capsule, computer) return root, capsule def create_procedural_mesh_cylinder( stage, parentPath=None, diameter=100, height=100, longitudeResolution=10, latitudeResolution=10, capResolution=10 ): root, cylinder, computer = create_mesh_computer( stage, "ProceduralMeshCylinder", "CylinderEvaluator", "omni.kit.procedural.mesh.CreateMeshCylinder", parentPath ) helper = og.OmniGraphHelper() # omnigraph node for the mesh init helper.set_values( computer, [ ["inputs:diameter", diameter], ["inputs:height", height], ["inputs:longitudeResolution", longitudeResolution], ["inputs:latitudeResolution", latitudeResolution], ["inputs:capResolution", capResolution], ], ) # setup mesh attributes and node inputs/outputs init_common_attributes(cylinder) init_crease_attributes(cylinder) init_normals_facevarying_attributes(cylinder) init_texture_coords_facevarying_attributes(cylinder) connect_common_attributes(cylinder, computer) connect_crease_attributes(cylinder, computer) connect_normals_facevarying_attributes(cylinder, computer) connect_texture_coords_facevarying_attributes(cylinder, computer) return root, cylinder def create_procedural_mesh_cone( stage, parentPath=None, diameter=100, height=100, longitudeResolution=10, latitudeResolution=10, capResolution=10 ): root, cone, computer = create_mesh_computer( stage, "ProceduralMeshCone", "ConeEvaluator", "omni.kit.procedural.mesh.CreateMeshCone", parentPath ) helper = og.OmniGraphHelper() # omnigraph node for the mesh init helper.set_values( computer, [ ["inputs:diameter", diameter], ["inputs:height", height], ["inputs:longitudeResolution", longitudeResolution], ["inputs:latitudeResolution", latitudeResolution], ["inputs:capResolution", capResolution], ], ) # setup mesh attributes and node inputs/outputs init_common_attributes(cone) init_crease_attributes(cone) init_corner_attributes(cone) init_normals_facevarying_attributes(cone) init_texture_coords_facevarying_attributes(cone) connect_common_attributes(cone, computer) connect_crease_attributes(cone, computer) connect_corner_attributes(cone, computer) connect_normals_facevarying_attributes(cone, computer) connect_texture_coords_facevarying_attributes(cone, computer) return root, cone def create_procedural_mesh_torus( stage, parentPath=None, diameter=200, sectionDiameter=50, sectionTwist=0, loopResolution=10, sectionResolution=10 ): root, torus, computer = create_mesh_computer( stage, "ProceduralMeshTorus", "TorusEvaluator", "omni.kit.procedural.mesh.CreateMeshTorus", parentPath ) helper = og.OmniGraphHelper() # omnigraph node for the mesh init helper.set_values( computer, [ ["inputs:diameter", diameter], ["inputs:sectionDiameter", sectionDiameter], ["inputs:sectionTwist", sectionTwist], ["inputs:loopResolution", loopResolution], ["inputs:sectionResolution", sectionResolution], ], ) # setup mesh attributes and node inputs/outputs init_common_attributes(torus) init_texture_coords_facevarying_attributes(torus) connect_common_attributes(torus, computer) connect_texture_coords_facevarying_attributes(torus, computer) return root, torus def create_procedural_mesh_disk(stage, parentPath=None, diameter=100, longitudeResolution=10, capResolution=10): root, disk, computer = create_mesh_computer( stage, "ProceduralMeshDisk", "DiskEvaluator", "omni.kit.procedural.mesh.CreateMeshDisk", parentPath ) helper = og.OmniGraphHelper() # omnigraph node for the mesh init helper.set_values( computer, [ ["inputs:diameter", diameter], ["inputs:longitudeResolution", longitudeResolution], ["inputs:capResolution", capResolution], ], ) # setup mesh attributes and node inputs/outputs init_common_attributes(disk) init_texture_coords_attributes(disk) connect_common_attributes(disk, computer) connect_texture_coords_attributes(disk, computer) return root, disk def create_procedural_mesh_plane(stage, parentPath=None, xLength=100, zLength=100, xResolution=10, zResolution=10): root, plane, computer = create_mesh_computer( stage, "ProceduralMeshPlane", "PlaneEvaluator", "omni.kit.procedural.mesh.CreateMeshPlane", parentPath ) helper = og.OmniGraphHelper() # omnigraph node for the mesh init helper.set_values( computer, [ ["inputs:xLength", xLength], ["inputs:zLength", zLength], ["inputs:xResolution", xResolution], ["inputs:zResolution", zResolution], ], ) # setup mesh attributes and node inputs/outputs init_common_attributes(plane) init_texture_coords_attributes(plane) connect_common_attributes(plane, computer) connect_texture_coords_attributes(plane, computer) return root, plane
14,417
Python
33.910412
119
0.703614
omniverse-code/kit/exts/omni.kit.procedural.mesh/omni/kit/procedural/mesh/scripts/menu.py
import omni.kit.ui import omni.usd # ====================================================================== MENU_CREATE_BUILTIN_PROCEDURAL_MESH_CUBE = ( f'OmniGraph/{omni.kit.ui.get_custom_glyph_code("${glyphs}/menu_prim.svg")} Procedural Mesh/Cube' ) MENU_CREATE_BUILTIN_PROCEDURAL_MESH_SPHERE = ( f'OmniGraph/{omni.kit.ui.get_custom_glyph_code("${glyphs}/menu_prim.svg")} Procedural Mesh/Sphere' ) MENU_CREATE_BUILTIN_PROCEDURAL_MESH_CAPSULE = ( f'OmniGraph/{omni.kit.ui.get_custom_glyph_code("${glyphs}/menu_prim.svg")} Procedural Mesh/Capsule' ) MENU_CREATE_BUILTIN_PROCEDURAL_MESH_CYLINDER = ( f'OmniGraph/{omni.kit.ui.get_custom_glyph_code("${glyphs}/menu_prim.svg")} Procedural Mesh/Cylinder' ) MENU_CREATE_BUILTIN_PROCEDURAL_MESH_CONE = ( f'OmniGraph/{omni.kit.ui.get_custom_glyph_code("${glyphs}/menu_prim.svg")} Procedural Mesh/Cone' ) MENU_CREATE_BUILTIN_PROCEDURAL_MESH_TORUS = ( f'OmniGraph/{omni.kit.ui.get_custom_glyph_code("${glyphs}/menu_prim.svg")} Procedural Mesh/Torus' ) MENU_CREATE_BUILTIN_PROCEDURAL_MESH_PLANE = ( f'OmniGraph/{omni.kit.ui.get_custom_glyph_code("${glyphs}/menu_prim.svg")} Procedural Mesh/Plane' ) MENU_CREATE_BUILTIN_PROCEDURAL_MESH_DISK = ( f'OmniGraph/{omni.kit.ui.get_custom_glyph_code("${glyphs}/menu_prim.svg")} Procedural Mesh/Disk' ) class Menu: def __init__(self): self.on_startup() def on_startup(self): self.menus = [] editor_menu = omni.kit.ui.get_editor_menu() self.menus.append(editor_menu.add_item(MENU_CREATE_BUILTIN_PROCEDURAL_MESH_CUBE, self._on_menu_click)) self.menus.append(editor_menu.add_item(MENU_CREATE_BUILTIN_PROCEDURAL_MESH_SPHERE, self._on_menu_click)) self.menus.append(editor_menu.add_item(MENU_CREATE_BUILTIN_PROCEDURAL_MESH_CAPSULE, self._on_menu_click)) self.menus.append(editor_menu.add_item(MENU_CREATE_BUILTIN_PROCEDURAL_MESH_CYLINDER, self._on_menu_click)) self.menus.append(editor_menu.add_item(MENU_CREATE_BUILTIN_PROCEDURAL_MESH_CONE, self._on_menu_click)) self.menus.append(editor_menu.add_item(MENU_CREATE_BUILTIN_PROCEDURAL_MESH_PLANE, self._on_menu_click)) self.menus.append(editor_menu.add_item(MENU_CREATE_BUILTIN_PROCEDURAL_MESH_TORUS, self._on_menu_click)) self.menus.append(editor_menu.add_item(MENU_CREATE_BUILTIN_PROCEDURAL_MESH_DISK, self._on_menu_click)) def _on_menu_click(self, menu_item, value): if menu_item == MENU_CREATE_BUILTIN_PROCEDURAL_MESH_CUBE: omni.kit.commands.execute("CreateProceduralMeshCube") elif menu_item == MENU_CREATE_BUILTIN_PROCEDURAL_MESH_SPHERE: omni.kit.commands.execute("CreateProceduralMeshSphere") elif menu_item == MENU_CREATE_BUILTIN_PROCEDURAL_MESH_CAPSULE: omni.kit.commands.execute("CreateProceduralMeshCapsule") elif menu_item == MENU_CREATE_BUILTIN_PROCEDURAL_MESH_CYLINDER: omni.kit.commands.execute("CreateProceduralMeshCylinder") elif menu_item == MENU_CREATE_BUILTIN_PROCEDURAL_MESH_CONE: omni.kit.commands.execute("CreateProceduralMeshCone") elif menu_item == MENU_CREATE_BUILTIN_PROCEDURAL_MESH_TORUS: omni.kit.commands.execute("CreateProceduralMeshTorus") elif menu_item == MENU_CREATE_BUILTIN_PROCEDURAL_MESH_PLANE: omni.kit.commands.execute("CreateProceduralMeshPlane") elif menu_item == MENU_CREATE_BUILTIN_PROCEDURAL_MESH_DISK: omni.kit.commands.execute("CreateProceduralMeshDisk") def on_shutdown(self): self.menus = []
3,576
Python
50.840579
114
0.694631
omniverse-code/kit/exts/omni.kit.procedural.mesh/omni/kit/procedural/mesh/scripts/command.py
import omni from pxr import UsdGeom, Usd, Vt, Kind, Sdf from .procedural_mesh_omnigraph_utils import ( create_procedural_mesh_cube, create_procedural_mesh_sphere, create_procedural_mesh_capsule, create_procedural_mesh_cylinder, create_procedural_mesh_cone, create_procedural_mesh_torus, create_procedural_mesh_plane, create_procedural_mesh_disk, ) class CreateProceduralMeshCommand(omni.kit.commands.Command): def __init__(self): self._create = None self._stage = omni.usd.get_context().get_stage() self._selection = omni.usd.get_context().get_selection() def do(self): xForm, mesh = self._create(self._stage) self._prim_path = xForm.GetPath() # set the new prim as the active selection self._selection.set_prim_path_selected(self._prim_path.pathString, True, False, True, True) return xForm def undo(self): prim = self._stage.GetPrimAtPath(self._prim_path) if prim: self._stage.RemovePrim(self._prim_path) class CreateProceduralMeshCubeCommand(CreateProceduralMeshCommand): def __init__(self): super().__init__() self._create = create_procedural_mesh_cube class CreateProceduralMeshSphereCommand(CreateProceduralMeshCommand): def __init__(self): super().__init__() self._create = create_procedural_mesh_sphere class CreateProceduralMeshCapsuleCommand(CreateProceduralMeshCommand): def __init__(self): super().__init__() self._create = create_procedural_mesh_capsule class CreateProceduralMeshCylinderCommand(CreateProceduralMeshCommand): def __init__(self): super().__init__() self._create = create_procedural_mesh_cylinder class CreateProceduralMeshConeCommand(CreateProceduralMeshCommand): def __init__(self): super().__init__() self._create = create_procedural_mesh_cone class CreateProceduralMeshTorusCommand(CreateProceduralMeshCommand): def __init__(self): super().__init__() self._create = create_procedural_mesh_torus class CreateProceduralMeshPlaneCommand(CreateProceduralMeshCommand): def __init__(self): super().__init__() self._create = create_procedural_mesh_plane class CreateProceduralMeshDiskCommand(CreateProceduralMeshCommand): def __init__(self): super().__init__() self._create = create_procedural_mesh_disk omni.kit.commands.register(CreateProceduralMeshCubeCommand) omni.kit.commands.register(CreateProceduralMeshSphereCommand) omni.kit.commands.register(CreateProceduralMeshCapsuleCommand) omni.kit.commands.register(CreateProceduralMeshCylinderCommand) omni.kit.commands.register(CreateProceduralMeshConeCommand) omni.kit.commands.register(CreateProceduralMeshTorusCommand) omni.kit.commands.register(CreateProceduralMeshPlaneCommand) omni.kit.commands.register(CreateProceduralMeshDiskCommand)
2,939
Python
31.307692
99
0.714869
omniverse-code/kit/exts/omni.kit.gfn/config/extension.toml
[package] title = "NVIDIA GFN Integration" category = "Streaming" # Semantic Versioning is used: https://semver.org/ version = "1.1.0" [dependencies] #"omni.usd" = {} [[python.module]] name = "omni.kit.gfn" [[native.plugin]] path = "bin/*.plugin" recursive = false [settings] #exts."omni.kit.gfn".enable = false [[test]] waiver = "Tests are in omni.gfn.autoload"
369
TOML
15.086956
50
0.674797
omniverse-code/kit/exts/omni.kit.gfn/omni/kit/gfn/__init__.py
from ._kit_gfn import * # Cached interface instance pointer def get_geforcenow_interface() -> IGeForceNow: """Returns cached :class:`omni.kit.gfn.IGeForceNow` interface""" if not hasattr(get_geforcenow_interface, "geforcenow"): get_geforcenow_interface.geforcenow = acquire_geforcenow_interface() return get_geforcenow_interface.geforcenow
362
Python
35.299996
76
0.745856
omniverse-code/kit/exts/omni.kit.gfn/omni/kit/gfn/_kit_gfn.pyi
"""pybind11 omni.kit.gfn bindings""" from __future__ import annotations import omni.kit.gfn._kit_gfn import typing __all__ = [ "IGeForceNow", "acquire_geforcenow_interface", "release_geforcenow_interface" ] class IGeForceNow(): def get_partner_secure_data(self) -> str: ... def shutdown(self) -> None: ... def startup(self, sdk_library_path: str = '') -> None: ... pass def acquire_geforcenow_interface(plugin_name: str = None, library_path: str = None) -> IGeForceNow: pass def release_geforcenow_interface(arg0: IGeForceNow) -> None: pass
580
unknown
25.40909
99
0.668966
omniverse-code/kit/exts/omni.kit.welcome.open/omni/kit/welcome/open/thumbnail_grid.py
from functools import partial from typing import Callable, Dict, List, Optional import omni.ui as ui from omni.ui import constant as fl from .style import ICON_PATH class ThumbnailItem(ui.AbstractItem): """ Data item for a thumbnail. Args: thumbnail (str): Url to thumbnail. url (str): Url to item. text (str): Display text for this item. Default use file name of url. """ def __init__(self, thumbnail: str, url: str, text: Optional[str] = None): self.thumbnail = thumbnail self.url = url self.text = text if text else url.split("/")[-1] super().__init__() def execute(self): pass class ThumbnailModel(ui.AbstractItemModel): """ Data model for thumbnail items. Args: items (List[ThumbnailItem]): List of thumbnail items """ def __init__(self, items: List[ThumbnailItem]): super().__init__() self._items = items def get_item_children(self, item: Optional[ThumbnailItem] = None) -> List[ThumbnailItem]: return self._items class ThumbnailGrid: """ Widget to show a grid (thumbnail + label). Args: model (ThumbnailModel): Data model. label_height (int): Height for item label. Default 30. thumbnail_width (int): Thumbnail width. Default 128. thumbnail_height (int): Thumbnail height. Default 128. thumbnail_padding_x (int): X padding between different thumbnail items. Default 2. thumbnail_padding_y (int): Y padding between different thumbnail items. Default 4. """ def __init__( self, model: ThumbnailModel, on_selection_changed: Callable[[Optional[ThumbnailItem]], None] = None, label_height:int=fl._find("welcome_open_lable_size"), thumbnail_width: int=fl._find("welcome_open_thumbnail_size"), thumbnail_height: int=fl._find("welcome_open_thumbnail_size"), thumbnail_padding_x: int=2, thumbnail_padding_y: int=4, ): self._model = model self._on_selection_changed = on_selection_changed self._label_height = label_height self._thumbnail_width = thumbnail_width self._thumbnail_height = thumbnail_height self._thumbnail_padding_x = thumbnail_padding_x self._thumbnail_padding_y = thumbnail_padding_y self._column_width = self._thumbnail_width + 2 * self._thumbnail_padding_x self._row_height = self._thumbnail_height + 2 * self._thumbnail_padding_y + self._label_height self.__selected_thumbnail: Optional[ThumbnailItem] = None self.__frames: Dict[ThumbnailItem, ui.Frame] = {} self._build_ui() @property def selected(self) -> Optional[ThumbnailItem]: return self.__selected_thumbnail @selected.setter def selected(self, item: Optional[ThumbnailItem]) -> None: self.select_item(item) def _build_ui(self): self._container = ui.ScrollingFrame( style_type_name_override="ThumbnailGrid.Frame", vertical_scrollbar_policy=ui.ScrollBarPolicy.SCROLLBAR_AS_NEEDED, horizontal_scrollbar_policy=ui.ScrollBarPolicy.SCROLLBAR_ALWAYS_OFF, ) self._refresh() self._sub_model = self._model.subscribe_item_changed_fn(lambda m, i: self._refresh()) def _refresh(self): self._container.clear() with self._container: self._grid = ui.VGrid( column_width=self._column_width, row_hegiht=self._row_height, content_clipping=True, ) with self._grid: children = self._model.get_item_children() if not children: return for item in children: with ui.VStack(): ui.Spacer(height=self._thumbnail_padding_y) with ui.HStack(): ui.Spacer(width=self._thumbnail_padding_x) self.__frames[item] = ui.Frame( build_fn=lambda i=item: self._build_thumbnail_item(i), mouse_double_clicked_fn=lambda x, y, a, f, i=item: i.execute(), mouse_pressed_fn=lambda x, y, a, f, i=item: self.select_item(i), ) ui.Spacer(width=self._thumbnail_padding_x) ui.Spacer(height=self._thumbnail_padding_y) self._grid.set_mouse_pressed_fn(lambda x, y, btn, flag: self.select_item(None)) def _build_thumbnail_item(self, item: ThumbnailItem) -> None: with ui.ZStack(): with ui.VStack(): self.build_thumbnail(item) self.build_label(item) ui.Rectangle(style_type_name_override="ThumbnailGrid.Selection") def build_thumbnail(self, item: ThumbnailItem) -> None: def on_image_progress(default_image: ui.Image, thumbnail_image: ui.Image, progress: float): """Called when the image loading progress is changed.""" if progress != 1.0: # We only need to catch the moment when the image is loaded. return # Hide the default_image at the back. default_image.visible = False # Remove the callback to avoid circular references. thumbnail_image.set_progress_changed_fn(None) with ui.ZStack(width=self._thumbnail_width, height=self._thumbnail_height): # Default image for thumbnail not defined or invalid thumbnail url or download in progress # Hidden when actually thumbnail downloaded default_image = ui.Image(f"{ICON_PATH}/usd_stage_256.png", style_type_name_override="ThumbnailGrid.Image") if item.thumbnail: thumbnail_image = ui.Image(item.thumbnail, style_type_name_override="ThumbnailGrid.Image") thumbnail_image.set_progress_changed_fn(partial(on_image_progress, default_image, thumbnail_image)) def build_label(self, item: ThumbnailItem) -> None: with ui.ZStack(): ui.Rectangle(style_type_name_override="ThumbnailGrid.Item.Background") ui.Label( item.text, height=self._label_height, word_wrap=True, elided_text=True, skip_draw_when_clipped=True, alignment=ui.Alignment.CENTER, style_type_name_override="ThumbnailGrid.Item", ) def select_item(self, item: Optional[ThumbnailItem]) -> None: if self.__selected_thumbnail: self.__frames[self.__selected_thumbnail].selected = False if item: self.__frames[item].selected = True self.__selected_thumbnail = item if self._on_selection_changed: self._on_selection_changed(item) def find_item(self, url: str) -> Optional[ThumbnailItem]: for item in self._model.get_item_children(None): if item.url == url: return item return None def select_url(self, url: str) -> None: if url: item = self.find_item(url) self.select_item(item) else: self.select_item(None)
7,367
Python
38.612903
118
0.586806
omniverse-code/kit/exts/omni.kit.welcome.open/omni/kit/welcome/open/stage_tab.py
from typing import Optional import carb import omni.ui as ui from omni.ui import constant as fl from omni.kit.welcome.window import show_window as show_welcome_window from .recent_widget import RecentWidget from .template_grid import TemplateGrid from .thumbnail_grid import ThumbnailItem SETTING_SHOW_TEMPLATES = "/exts/omni.kit.welcome.open/show_templates" class StageTab: """ Tab to show stage content. """ def __init__(self): self._checkpoint_combobox = None self._build_ui() def destroy(self): self._recent_widget.destroy() def _build_ui(self): with ui.VStack(): # Templates if carb.settings.get_settings().get_as_bool(SETTING_SHOW_TEMPLATES): with ui.HStack(height=0): ui.Spacer(width=fl._find("welcome_content_padding_x")) with ui.VStack(): ui.Line(height=2, style_type_name_override="ThumbnailGrid.Separator") ui.Label("NEW", height=0, style_type_name_override="ThumbnailGrid.Title") ui.Spacer(height=10) ui.Spacer(width=fl._find("welcome_content_padding_x")) with ui.HStack(height=fl._find("welcome_open_thumbnail_size") + fl._find("welcome_open_lable_size") + 60): ui.Spacer(width=8) self._template_grid = TemplateGrid(on_selection_changed=self.__on_template_selected) ui.Spacer(width=8) # Recent files with ui.HStack(height=0): ui.Spacer(width=fl._find("welcome_content_padding_x")) with ui.VStack(): ui.Line(height=2, style_type_name_override="ThumbnailGrid.Separator") with ui.HStack(height=20): ui.Label("RECENT", width=0, style_type_name_override="ThumbnailGrid.Title") ui.Spacer() self._mode_image = ui.Image(name="grid", width=20, style_type_name_override="ThumbnailGrid.Mode", mouse_pressed_fn=lambda x, y, b,a: self.__toggle_thumbnail_model()) ui.Spacer(height=10) ui.Spacer(width=fl._find("welcome_content_padding_x")) self._recent_widget = RecentWidget(self.__on_recent_selected, self.__on_grid_mode) # Open widgets with ui.ZStack(height=26): ui.Rectangle(style_type_name_override="Stage.Separator") with ui.VStack(): ui.Spacer(height=2) with ui.HStack(spacing=2): self._checkpoint_blank = ui.Rectangle(style_type_name_override="Stage.Blank") self._checkpoint_frame = ui.Frame(build_fn=self.__build_checkpoints, visible=False) # Button size/style to be same as omni.kit.window.filepicker.FilePickerWidget ui.Button("Open File", width=117, style_type_name_override="Stage.Button", mouse_pressed_fn=lambda x, y, a, f:self.__open_file()) ui.Button("Close", width=117, style_type_name_override="Stage.Button", mouse_pressed_fn=lambda x, y, a, f:show_welcome_window(visible=False)) def __toggle_thumbnail_model(self): if self._mode_image.name == "grid": self._mode_image.name = "table" self._recent_widget.show_grid(False) else: self._mode_image.name = "grid" self._recent_widget.show_grid(True) def __build_checkpoints(self): try: import omni.kit.app manager = omni.kit.app.get_app().get_extension_manager() manager.set_extension_enabled_immediate("omni.kit.widget.versioning", True) from omni.kit.widget.versioning import CheckpointCombobox with ui.HStack(spacing=2): with ui.ZStack(content_clipping=True, width=0): ui.Rectangle(style_type_name_override="Stage.Blank") ui.Label("Checkpoints", width=0, style_type_name_override="Stage.Label") self._checkpoint_combobox = CheckpointCombobox( self._recent_widget.selected_url if self._recent_widget.selected_url else "", None, width=ui.Fraction(1), has_pre_spacer=False, popup_width=0, modal=True ) except Exception as e: carb.log_warn(f"Failed to create checkpoint combobox: {e}") self._checkpoint_combobox = None def __on_template_selected(self, item: Optional[ThumbnailItem]): if item: # Clear selection in recents self._recent_widget.selected_url = None # Hide checkpoint combobox self._checkpoint_frame.visible = False self._checkpoint_blank.visible = True def __on_recent_selected(self, item: Optional[ui.AbstractItem]): if item: # Clear selection in templates self._template_grid.selected = None if isinstance(item, ThumbnailItem): # Show checkpoint combobox if selected in recent grid self._checkpoint_frame.visible = bool(item) self._checkpoint_blank.visible = not bool(item) if item and self._checkpoint_combobox: self._checkpoint_combobox.url = item.url def __on_grid_mode(self, grid_mode: bool) -> None: # Show checkpoint combobox in grid mode and recent file selected if grid_mode: show_checkpoint = bool(self._recent_widget.selected_url) self._checkpoint_frame.visible = show_checkpoint self._checkpoint_blank.visible = not show_checkpoint else: self._checkpoint_frame.visible = False self._checkpoint_blank.visible = True def __open_file(self) -> None: selected = self._template_grid.selected if selected: carb.log_info(f"Open template: {selected.url}") selected.execute() else: self._recent_widget.open_selected(self._checkpoint_combobox.url if self._checkpoint_combobox else None)
6,253
Python
44.985294
189
0.58244
omniverse-code/kit/exts/omni.kit.welcome.open/omni/kit/welcome/open/style.py
from pathlib import Path import omni.ui as ui from omni.ui import color as cl from omni.ui import constant as fl CURRENT_PATH = Path(__file__).parent ICON_PATH = CURRENT_PATH.parent.parent.parent.parent.joinpath("icons") fl.welcome_open_thumbnail_size = 145 fl.welcome_open_lable_size = 30 cl.welcome_open_item_selected = cl.shade(cl("#77878A")) cl.welcome_open_label = cl.shade(cl("#9E9E9E")) OPEN_PAGE_STYLE = { "RadioButton": {"background_color": cl.transparent, "stack_direction": ui.Direction.LEFT_TO_RIGHT, "padding": 0, "margin": 0}, "RadioButton.Label": {"font_size": fl.welcome_title_font_size, "color": cl.welcome_label, "alignment": ui.Alignment.LEFT_CENTER}, "RadioButton.Label:checked": {"color": cl.welcome_label_selected}, "RadioButton:checked": {"background_color": cl.transparent}, "RadioButton:hovered": {"background_color": cl.transparent}, "RadioButton:pressed": {"background_color": cl.transparent}, "RadioButton.Image::STAGE": {"image_url": f"{ICON_PATH}/USD.svg"}, "RadioButton.Image::SAMPLES": {"image_url": f"{ICON_PATH}/image.svg"}, "RadioButton.Image::FILE": {"image_url": f"{ICON_PATH}/hdd.svg"}, "RadioButton.Image": {"color": cl.welcome_label, "alignment": ui.Alignment.RIGHT_CENTER}, "RadioButton.Image:checked": {"color": cl.welcome_label_selected}, "ThumbnailGrid.Separator": {"color": cl.welcome_window_background, "border_width": 1.5}, "ThumbnailGrid.Title": {"color": 0xFFCCCCCC, "font_size": fl.welcome_title_font_size}, "ThumbnailGrid.Mode": {"margin": 2}, "ThumbnailGrid.Mode::grid": {"image_url": f"{ICON_PATH}/thumbnail.svg"}, "ThumbnailGrid.Mode::table": {"image_url": f"{ICON_PATH}/list.svg"}, "ThumbnailGrid.Frame": { "background_color": cl.transparent, "secondary_color": 0xFF808080, "border_radius": 0, "scrollbar_size": 10, }, "ThumbnailGrid.Selection": { "background_color": cl.transparent, }, "ThumbnailGrid.Selection:selected": { "border_width": 1, "border_color": cl.welcome_open_item_selected, "border_radius": 0, }, "ThumbnailGrid.Item.Background": { "background_color": cl.transparent, }, "ThumbnailGrid.Item.Background:selected": { "background_color": 0xFF525252, }, "ThumbnailGrid.Item": { "margin_width": 2, "color": cl.welcome_label, }, "Template.Add": {"color": 0xFFFFFFFF}, "Template.Add:hovered": {"color": cl.welcome_label_selected}, "Template.Add:pressed": {"color": cl.welcome_label_selected}, "Template.Add:selected": {"color": cl.welcome_label_selected}, "Stage.Label": {"color": cl.welcome_open_label, "margin_width": 6}, "Stage.Button": { "background_color": 0xFF23211F, "selected_color": 0xFF8A8777, "color": cl.welcome_open_label, "margin": 0, "padding": 0 }, "Stage.Button:hovered": {"background_color": 0xFF3A3A3A}, "Stage.Button.Label": {"color": cl.welcome_open_label}, "Stage.Button.Label:disabled": {"color": 0xFF3A3A3A}, "Stage.Separator": {"background_color": cl.welcome_window_background}, "Stage.Blank": {"background_color": cl.welcome_content_background}, }
3,242
Python
41.116883
133
0.652067
omniverse-code/kit/exts/omni.kit.welcome.open/omni/kit/welcome/open/extension.py
from typing import Optional import omni.ext import omni.ui as ui from omni.kit.welcome.window import register_page from .open_widget import OpenWidget class OpenPageExtension(omni.ext.IExt): def on_startup(self, ext_id): self._widget: Optional[OpenWidget] = None self.__ext_name = omni.ext.get_extension_name(ext_id) register_page(self.__ext_name, self.build_ui) def on_shutdown(self): if self._widget: self._widget.destroy() self._widget = None def build_ui(self) -> None: self._widget = OpenWidget()
585
Python
23.416666
61
0.652991
omniverse-code/kit/exts/omni.kit.welcome.open/omni/kit/welcome/open/recent_widget.py
import asyncio import os from typing import Callable, List, Optional import carb.settings import omni.ui as ui from .thumbnail_grid import ThumbnailGrid, ThumbnailItem, ThumbnailModel SETTING_RECENT_FILES = "/persistent/app/file/recentFiles" class RecentItem(ThumbnailItem): """ Data item for recent file. """ def __init__(self, url: str): super().__init__(self.__get_thumbnail(url), url) def __get_thumbnail(self, url: str): file_name = os.path.basename(url) path = os.path.dirname(url) # Do not check if thumbnail image exists here, leave it to ThumbnailGrid return f"{path}/.thumbs/256x256/{file_name}.png" def execute(self, url: Optional[str] = None): from .open_action import run_open_action run_open_action("omni.kit.window.file", "open_stage", url if url else self.url) class RecentModel(ThumbnailModel): """ Data model for recent files. """ def __init__(self, recent_files: List[str]): super().__init__([]) self.refresh(recent_files) def refresh(self, recent_files: List[str]) -> None: self._items = [RecentItem(recent) for recent in recent_files] if recent_files else [] self._item_changed(None) class RecentWidget: """ Show recents grid and open widgets. """ def __init__(self, on_recent_changed_fn: Callable[[Optional[ui.AbstractItem]], None], on_grid_mode_fn: Callable[[bool], None]): self._settings = carb.settings.get_settings() self.__get_recent_history() self._grid_model = RecentModel(self.__recent_files) self._recent_table: Optional[RecentTable] = None self.__on_recent_selected_fn = on_recent_changed_fn self.__on_grid_mode_fn = on_grid_mode_fn self._build_ui() def destroy(self): self._subscription = None self._event_sub = None @property def selected_url(self) -> str: if self._grid_frame.visible: return self._recent_grid.selected.url if self._recent_grid.selected else "" else: return self._recent_table.selected @selected_url.setter def selected_url(self, url: str) -> None: if self._grid_frame.visible: self._recent_grid.select_url(url) else: self._recent_table.selected = url def clear_selection(self): if self._grid_frame.visible: self._recent_grid.selected = None else: self._recent_table.selected = None def show_grid(self, grid: bool) -> None: self._grid_frame.visible = grid self._table_frame.visible = not grid if grid: # Set grid selection from table if self._recent_table: self._recent_grid.select_url(self._recent_table.selected) else: # Set table selection from grid if self._recent_table: if self._recent_grid.selected: self._recent_table.selected = self._recent_grid.selected.url else: # Wait for widget create and set selection async def __delay_select(): await omni.kit.app.get_app().next_update_async() if self._recent_grid.selected: self._recent_table.selected = self._recent_grid.selected.url asyncio.ensure_future(__delay_select()) self.__on_grid_mode_fn(grid) def open_selected(self, checkpoint_url: Optional[str]) -> None: def __open_file(url): carb.log_info(f"Open recent file: {url}") from .open_action import run_open_action run_open_action("omni.kit.window.file", "open_stage", url) if self.selected_url: if self._grid_frame.visible: __open_file(checkpoint_url or self.selected_url) else: __open_file(self._recent_table.get_filename()) def _build_ui(self): with ui.ZStack(): self._grid_frame = ui.Frame(build_fn=self._build_grid_ui) self._table_frame = ui.Frame(build_fn=self._build_table_ui, visible=False) def _build_table_ui(self): try: from .recent_table import RecentTable self._recent_table = RecentTable(self.__recent_files, on_selection_changed_fn=self.__on_recent_selected_fn) except Exception as e: self._recent_table = None carb.log_error(f"Failed to create recent table: {e}") def _build_grid_ui(self): with ui.VStack(): # Recent grid with ui.HStack(): ui.Spacer(width=8) self._recent_grid = ThumbnailGrid(self._grid_model, on_selection_changed=self.__on_recent_selected_fn) ui.Spacer(width=8) def _on_change(self, item, event_type): if event_type == carb.settings.ChangeEventType.CHANGED: self.__recent_files = self._settings.get(SETTING_RECENT_FILES) self.__rebuild_recents() def __rebuild_recents_from_event(self) -> None: from omni.kit.helper.file_utils import get_latest_urls_from_event_queue, asset_types self.__recent_files = get_latest_urls_from_event_queue(self._max_recent_files, asset_type=asset_types.ASSET_TYPE_USD) if self._recent_table: self._recent_table.refresh(self.__recent_files) self._grid_model.refresh(self.__recent_files) def __get_recent_history(self): load_recents_from_event = self._settings.get("/exts/omni.kit.welcome.open/load_recent_from_event") if load_recents_from_event: self.__get_recent_from_event() else: self.__recent_files = self._settings.get(SETTING_RECENT_FILES) # If recent files changed, refresh self._subscription = omni.kit.app.SettingChangeSubscription(SETTING_RECENT_FILES, self._on_change) def __get_recent_from_event(self) -> None: import omni.kit.app manager = omni.kit.app.get_app().get_extension_manager() manager.set_extension_enabled_immediate("omni.kit.helper.file_utils", True) from omni.kit.helper.file_utils import get_latest_urls_from_event_queue, asset_types, FILE_EVENT_QUEUE_UPDATED self._max_recent_files = self._settings.get("exts/omni.kit.menu.file/maxRecentFiles") or 10 self.__recent_files = get_latest_urls_from_event_queue(self._max_recent_files, asset_type=asset_types.ASSET_TYPE_USD) event_stream = omni.kit.app.get_app().get_message_bus_event_stream() self._event_sub = event_stream.create_subscription_to_pop_by_type(FILE_EVENT_QUEUE_UPDATED, lambda _: self.__rebuild_recents_from_event())
6,736
Python
39.10119
146
0.614757
omniverse-code/kit/exts/omni.kit.welcome.open/omni/kit/welcome/open/open_action.py
# Copyright (c) 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. # __all__ = ["run_open_action"] import asyncio def run_open_action(extension_id: str, action_id: str, *args, **kwargs): import omni.kit.actions.core action_registry = omni.kit.actions.core.get_action_registry() # Setup the viewport (and UI first) action_registry.execute_action("omni.app.setup", "enable_viewport_rendering") # Finally hide the Welcome window from omni.kit.welcome.window import show_window as show_welcome_window show_welcome_window(visible=False, stage_opened=True) # Run the action which will open or create a Usd.Stage async def __execute_action(): import omni.kit.app # OM-90720: sometimes open stage will popup a prompt to ask if save current stage # But the prompt is a popup window which will hide immediately if the welcome window (modal) still there # As a result, the required stage will not be opened # So here wait a few frames to make sure welcome window is really closed for _ in range(4): await omni.kit.app.get_app().next_update_async() action_registry.execute_action(extension_id, action_id, *args, **kwargs) asyncio.ensure_future(__execute_action())
1,624
Python
45.42857
112
0.723522
omniverse-code/kit/exts/omni.kit.welcome.open/omni/kit/welcome/open/open_widget.py
from typing import Dict, Optional import carb import omni.ui as ui from omni.kit.welcome.window import show_window as show_welcome_window from omni.ui import constant as fl from .stage_tab import StageTab from .style import OPEN_PAGE_STYLE class OpenWidget: """ Widget for open page. """ def __init__(self): self.__tabs: Dict[str, callable] = { "STAGE": self.__build_stage, "SAMPLES": self.__build_sample, "FILE": self.__build_file, } self.__tab_frames: Dict[str, ui.Frame] = {} self.__stage_tab: Optional[StageTab] = None self._build_ui() def destroy(self): if self.__stage_tab: self.__stage_tab.destroy() self.__stage_tab = None def _build_ui(self): self._collection = ui.RadioCollection() with ui.ZStack(style=OPEN_PAGE_STYLE): # Background ui.Rectangle(style_type_name_override="Content") with ui.VStack(): # Tab buttons with ui.VStack(height=fl._find("welcome_page_title_height")): ui.Spacer() with ui.HStack(height=0): ui.Spacer() with ui.HStack(spacing=30): for tab in self.__tabs.keys(): ui.RadioButton(text=tab, width=0, spacing=8, image_width=24, image_height=24, name=tab, radio_collection=self._collection, clicked_fn=lambda t=tab: self._show_tab(t)) ui.Spacer() ui.Spacer() # Tab frames with ui.ZStack(): for tab in self.__tabs.keys(): self.__tab_frames[tab] = ui.Frame(build_fn=lambda t=tab: self.__tabs[t](), visible=tab == "STAGE") def _show_tab(self, name: str) -> None: for tab in self.__tabs.keys(): if tab == name: self.__tab_frames[name].visible = True else: self.__tab_frames[tab].visible = False def __build_stage(self): self.__stage_tab = StageTab() def __build_sample(self): try: import omni.kit.app manager = omni.kit.app.get_app().get_extension_manager() manager.set_extension_enabled_immediate("omni.kit.browser.sample", True) from omni.kit.browser.sample import get_instance as get_sample_instance from omni.kit.browser.sample.browser_widget import SampleTreeFolderBrowserWidget from omni.kit.browser.core import BrowserSearchBar # Remove options button class SampleWidget(SampleTreeFolderBrowserWidget): def _build_search_bar(self): self._search_bar = BrowserSearchBar(options_menu=None) # Hack to close welcome window after sample opened def __open_sample(item): from .open_action import run_open_action run_open_action("omni.kit.window.file", "open_stage", item.url) model = get_sample_instance().get_model() model.execute = __open_sample # Sample widget with ui.ZStack(): ui.Rectangle(style_type_name_override="Stage.Separator") with ui.VStack(): ui.Spacer(height=4) with ui.HStack(): ui.Spacer(width=2) self.__sample_widget = SampleWidget(model) # Open widgets with ui.ZStack(height=26): ui.Rectangle(style_type_name_override="Stage.Separator") with ui.VStack(): ui.Spacer(height=2) with ui.HStack(spacing=2): ui.Rectangle(style_type_name_override="Stage.Blank") # Button size/style to be same as omni.kit.window.filepicker.FilePickerWidget ui.Button("Open File", width=117, style_type_name_override="Stage.Button", mouse_pressed_fn=lambda x, y, a, f:self.__open_sample()) ui.Button("Close", width=117, style_type_name_override="Stage.Button", mouse_pressed_fn=lambda x, y, a, f:show_welcome_window(visible=False)) except Exception as e: carb.log_error(f"Failed to import sample browser widget: {e}") def __build_file(self): try: from omni.kit.window.filepicker import FilePickerWidget def __open_file(file_name, dir_name): from .open_action import run_open_action run_open_action("omni.kit.window.file", "open_stage", dir_name + file_name) with ui.ZStack(): ui.Rectangle(style_type_name_override="Stage.Separator") with ui.VStack(): ui.Spacer(height=2) with ui.HStack(): ui.Spacer(width=2) FilePickerWidget( "Welcome", enable_checkpoints=True, apply_button_label="Open File", cancel_button_label="Close", click_apply_handler=__open_file, click_cancel_handler=lambda f, d: show_welcome_window(visible=False), modal=True, ) except Exception as e: carb.log_error(f"Failed to import file picker widget: {e}") def __open_sample(self): selections = self.__sample_widget.detail_selection if selections: self.__sample_widget._browser_model.execute(selections[0]) show_welcome_window(visible=False)
5,849
Python
42.333333
198
0.526586
omniverse-code/kit/exts/omni.kit.welcome.open/omni/kit/welcome/open/recent_table.py
import os from typing import List, Optional import omni.client import omni.ui as ui from omni.kit.widget.filebrowser import LAYOUT_SINGLE_PANE_LIST, LISTVIEW_PANE, FileBrowserItem, FileBrowserModel from omni.kit.widget.filebrowser.model import FileBrowserItemFields from omni.kit.window.filepicker import FilePickerWidget class RecentTableModel(FileBrowserModel): def __init__(self, recent_files: List[str]): super().__init__() self.refresh(recent_files) def get_item_children(self, item: FileBrowserItem) -> [FileBrowserItem]: return self._items def refresh(self, recent_files: List[str]): if recent_files: self._items = [self.__create_file_item(url) for url in recent_files] else: self._items = [] self._item_changed(None) def __create_file_item(self, url: str) -> Optional[FileBrowserItem]: file_name = os.path.basename(url) result, entry = omni.client.stat(url) if result == omni.client.Result.OK: item = FileBrowserItem(url, FileBrowserItemFields(file_name, entry.modified_time, 0, 0), is_folder=False) item._models = (ui.SimpleStringModel(item.name), entry.modified_time, ui.SimpleStringModel("")) return item else: return None class RecentTable: def __init__(self, recent_files: List[str], on_selection_changed_fn: callable): self.__recent_files = recent_files self.__picker: Optional[FilePickerWidget] = None self.__on_selection_changed_fn = on_selection_changed_fn self._build_ui() @property def selected(self) -> str: if self.__picker: selections = self.__picker._view.get_selections(pane=LISTVIEW_PANE) if selections: return selections[0].path else: return "" else: return "" @selected.setter def selected(self, url: str) -> None: if self.__picker: if url: for item in self._model.get_item_children(None): if item.path == url: selections = [item] else: selections = [] self.__picker._view.set_selections(selections, pane=LISTVIEW_PANE) def refresh(self, recent_files: List[str]): self._model.refresh(recent_files) def get_filename(self) -> str: return self.__picker._api.get_filename() if self.__picker else "" def _build_ui(self): with ui.ZStack(): ui.Rectangle(style_type_name_override="Stage.Separator") with ui.VStack(): ui.Spacer(height=2) with ui.HStack(): self.__picker = FilePickerWidget( "Welcome", enable_tool_bar=False, layout=LAYOUT_SINGLE_PANE_LIST, show_grid_view=False, save_grid_view=False, enable_checkpoints=True, enable_zoombar=False, enable_file_bar=False, selection_changed_fn=self.__on_selection_changed_fn, ) self._model = RecentTableModel(self.__recent_files) self.__picker._view.show_model(self._model)
3,377
Python
35.717391
117
0.568256
omniverse-code/kit/exts/omni.kit.welcome.open/omni/kit/welcome/open/template_grid.py
import functools import locale from typing import List import omni.kit.stage_templates import omni.ui as ui from omni.kit.welcome.window import show_window from .style import ICON_PATH from .thumbnail_grid import ThumbnailGrid, ThumbnailItem, ThumbnailModel import asyncio class TemplateItem(ThumbnailItem): """ Data item for template. """ def __init__(self, template: list): # TODO: how to get template thumbnail? stage_name = template[0] super().__init__("", stage_name) def execute(self): from .open_action import run_open_action run_open_action("omni.kit.stage.templates", self.__get_action_name()) def __get_action_name(self): return "create_new_stage_" + self.url.lower().replace('-', '_').replace(' ', '_') class TemplateModel(ThumbnailModel): """ Data model for templates. """ def __init__(self): stage_templates = omni.kit.stage_templates.get_stage_template_list() template_items: List[ThumbnailItem] = [] def sort_cmp(template1, template2): return locale.strcoll(template1[0], template2[0]) for template_list in stage_templates: for template in sorted(template_list.items(), key=functools.cmp_to_key(sort_cmp)): template_items.append(TemplateItem(template)) super().__init__(template_items) class TemplateGrid(ThumbnailGrid): """ Template grid. """ def __init__(self, **kwargs): self._model = TemplateModel() super().__init__(self._model, **kwargs) def build_thumbnail(self, item: ThumbnailItem): padding = 5 with ui.ZStack(): super().build_thumbnail(item) with ui.VStack(): ui.Spacer() with ui.HStack(height=20): ui.Spacer() ui.Image( f"{ICON_PATH}/add_dark.svg", width=20, style_type_name_override="Template.Add", mouse_pressed_fn=lambda x, y, a, f, i=item: i.execute() ) ui.Spacer(width=padding) ui.Spacer(height=padding)
2,216
Python
29.791666
94
0.576715
omniverse-code/kit/exts/omni.kit.selection/config/extension.toml
[package] version = "0.1.0" category = "Internal" [dependencies] "omni.kit.commands" = {} "omni.ui" = {} "omni.usd" = {} [[python.module]] name = "omni.kit.selection"
169
TOML
13.166666
27
0.621302
omniverse-code/kit/exts/omni.kit.selection/omni/kit/selection/selection_actions.py
import omni.kit.actions.core def register_actions(extension_id): import omni.kit.commands action_registry = omni.kit.actions.core.get_action_registry() actions_tag = "Selection Actions" action_registry.register_action( extension_id, "all", lambda: omni.kit.commands.execute("SelectAll"), display_name="Select->All", description="Select all prims.", tag=actions_tag, ) action_registry.register_action( extension_id, "none", lambda: omni.kit.commands.execute("SelectNone"), display_name="Select->None", description="Deselect all prims.", tag=actions_tag, ) action_registry.register_action( extension_id, "invert", lambda: omni.kit.commands.execute("SelectInvert"), display_name="Select->Invert", description="Deselect all currently unselected prims, and select all currently unselected prims.", tag=actions_tag, ) action_registry.register_action( extension_id, "parent", lambda: omni.kit.commands.execute("SelectParentCommand"), display_name="Select->Parent", description="Select the parents of all currently selected prims.", tag=actions_tag, ) action_registry.register_action( extension_id, "leaf", lambda: omni.kit.commands.execute("SelectLeafCommand"), display_name="Select->Leaf", description="Select the leafs of all currently selected prims.", tag=actions_tag, ) action_registry.register_action( extension_id, "hierarchy", lambda: omni.kit.commands.execute("SelectHierarchyCommand"), display_name="Select->Hierarchy", description="Select the hierachies of all currently selected prims.", tag=actions_tag, ) action_registry.register_action( extension_id, "similar", lambda: omni.kit.commands.execute("SelectSimilarCommand"), display_name="Select->Similar", description="Select prims of the same type as any currently selected prim.", tag=actions_tag, ) action_registry.register_action( extension_id, "HideUnselected", lambda: omni.kit.commands.execute("HideUnselected"), display_name="Select->Hide Unselected", description="Hide Unselected Prims", tag=actions_tag, ) action_registry.register_action( extension_id, "UnhideAllPrims", lambda: omni.kit.commands.execute("UnhideAllPrims"), display_name="Select->Unhide All Prims", description="Unhide All Prims", tag=actions_tag, ) def deregister_actions(extension_id): action_registry = omni.kit.actions.core.get_action_registry() action_registry.deregister_all_actions_for_extension(extension_id)
2,880
Python
31.370786
106
0.639931
omniverse-code/kit/exts/omni.kit.selection/omni/kit/selection/__init__.py
from .selection import *
25
Python
11.999994
24
0.76
omniverse-code/kit/exts/omni.kit.selection/omni/kit/selection/selection.py
import omni.kit.commands from pxr import Usd, Sdf, UsdGeom, Gf, Tf, Trace, Kind from .selection_actions import register_actions, deregister_actions class SelectionExtension(omni.ext.IExt): def on_startup(self, ext_id): self._ext_name = omni.ext.get_extension_name(ext_id) register_actions(self._ext_name) def on_shutdown(self): deregister_actions(self._ext_name) class SelectAllCommand(omni.kit.commands.Command): """ Select all prims. Args: type (Union[str, None]): Specific type name. If it's None, it will select all prims. If it has type str with value "", it will select all prims without any type. Otherwise, it will select prims with that type. """ def __init__(self, type=None): self._type = type self._prev_selection = omni.usd.get_context().get_selection().get_selected_prim_paths() @Trace.TraceFunction def do(self): omni.usd.get_context().get_selection().select_all_prims(self._type) def undo(self): if self._prev_selection: omni.usd.get_context().get_selection().set_selected_prim_paths(self._prev_selection, True) else: omni.usd.get_context().get_selection().clear_selected_prim_paths() class SelectNoneCommand(omni.kit.commands.Command): def __init__(self): self._prev_selection = omni.usd.get_context().get_selection().get_selected_prim_paths() def do(self): omni.usd.get_context().get_selection().clear_selected_prim_paths() def undo(self): omni.usd.get_context().get_selection().set_selected_prim_paths(self._prev_selection, True) class SelectInvertCommand(omni.kit.commands.Command): def __init__(self): self._prev_selection = omni.usd.get_context().get_selection().get_selected_prim_paths() @Trace.TraceFunction def do(self): omni.usd.get_context().get_selection().set_selected_prim_paths(self._prev_selection, True) omni.usd.get_context().get_selection().select_inverted_prims() def undo(self): omni.usd.get_context().get_selection().set_selected_prim_paths(self._prev_selection, True) class HideUnselectedCommand(omni.kit.commands.Command): def get_parent_prims(self, stage, prim): parent_prims = set([]) while prim.GetParent(): parent_prims.add(prim.GetParent().GetPath()) prim = prim.GetParent() if stage.HasDefaultPrim() and stage.GetDefaultPrim() == prim: break return parent_prims def get_all_children(self, prim): children_list = set([]) queue = [prim] while len(queue) > 0: child_prim = queue.pop() for child in child_prim.GetAllChildren(): children_list.add(child.GetPath()) queue.append(child) return children_list def __init__(self): stage = omni.usd.get_context().get_stage() selection = omni.usd.get_context().get_selection().get_selected_prim_paths() # if selected path as children and none of the children are selected, then all the children are selected.. selected_prims = set([]) for prim_path in selection: sdf_prim_path = Sdf.Path(prim_path) prim = stage.GetPrimAtPath(sdf_prim_path) if prim: selected_prims.add(sdf_prim_path) selected_prims.update(self.get_all_children(prim)) ## exclude parent prims as visabillity is inherited all_parent_prims = set([]) for prim_path in selected_prims: prim = stage.GetPrimAtPath(prim_path) if prim: all_parent_prims.update(self.get_parent_prims(stage, prim)) selected_prims.update(all_parent_prims) all_prims = set([]) children_iterator = iter(stage.TraverseAll()) for prim in children_iterator: if omni.usd.is_hidden_type(prim): children_iterator.PruneChildren() continue all_prims.add(prim.GetPath()) self._invert_prims = [item for item in all_prims if item not in selected_prims] self._prev_visabillity = [] for prim_path in self._invert_prims: prim = stage.GetPrimAtPath(prim_path) if prim: if stage.HasDefaultPrim() and stage.GetDefaultPrim() == prim: continue imageable = UsdGeom.Imageable(prim) if imageable: self._prev_visabillity.append([prim, imageable.ComputeVisibility()]) @Trace.TraceFunction def do(self): stage = omni.usd.get_context().get_stage() for prim_path in self._invert_prims: prim = stage.GetPrimAtPath(prim_path) if prim: if stage.HasDefaultPrim() and stage.GetDefaultPrim() == prim: continue imageable = UsdGeom.Imageable(prim) if imageable: imageable.MakeInvisible() def undo(self): for prim, state in self._prev_visabillity: imageable = UsdGeom.Imageable(prim) if imageable: if state == UsdGeom.Tokens.invisible: imageable.MakeInvisible() else: imageable.MakeVisible() class SelectParentCommand(omni.kit.commands.Command): def __init__(self): self._prev_selection = omni.usd.get_context().get_selection().get_selected_prim_paths() def do(self): stage = omni.usd.get_context().get_stage() parent_prims = set() for prim_path in self._prev_selection: prim = stage.GetPrimAtPath(prim_path) if prim and prim.GetParent() is not None: parent_prims.add(prim.GetParent().GetPath().pathString) omni.usd.get_context().get_selection().set_selected_prim_paths(sorted(list(parent_prims)), True) def undo(self): omni.usd.get_context().get_selection().set_selected_prim_paths(self._prev_selection, True) class SelectLeafCommand(omni.kit.commands.Command): def __init__(self): self._prev_selection = omni.usd.get_context().get_selection().get_selected_prim_paths() def collect_leafs(self, prim, leaf_set): prim_children = prim.GetChildren() if not prim_children: leaf_set.add(prim.GetPath().pathString) else: for child in prim_children: self.collect_leafs(child, leaf_set) def do(self): stage = omni.usd.get_context().get_stage() leaf_prims = set() for prim_path in self._prev_selection: prim = stage.GetPrimAtPath(prim_path) self.collect_leafs(prim, leaf_prims) omni.usd.get_context().get_selection().set_selected_prim_paths(sorted(list(leaf_prims)), True) def undo(self): omni.usd.get_context().get_selection().set_selected_prim_paths(self._prev_selection, True) class SelectHierarchyCommand(omni.kit.commands.Command): def __init__(self): self._prev_selection = omni.usd.get_context().get_selection().get_selected_prim_paths() def collect_hierarchy(self, prim, hierarchy_set): hierarchy_set.add(prim.GetPath().pathString) prim_children = prim.GetChildren() for child in prim_children: self.collect_hierarchy(child, hierarchy_set) def do(self): stage = omni.usd.get_context().get_stage() heirarchy_prims = set() for prim_path in self._prev_selection: prim = stage.GetPrimAtPath(prim_path) self.collect_hierarchy(prim, heirarchy_prims) omni.usd.get_context().get_selection().set_selected_prim_paths(sorted(list(heirarchy_prims)), True) def undo(self): omni.usd.get_context().get_selection().set_selected_prim_paths(self._prev_selection, True) class SelectSimilarCommand(omni.kit.commands.Command): def __init__(self): self._prev_selection = omni.usd.get_context().get_selection().get_selected_prim_paths() def do(self): stage = omni.usd.get_context().get_stage() similar_prim_types = set() for prim_path in self._prev_selection: prim_type = stage.GetPrimAtPath(prim_path).GetTypeName() similar_prim_types.add(prim_type) omni.usd.get_context().get_selection().select_all_prims(sorted(list(similar_prim_types))) def undo(self): omni.usd.get_context().get_selection().set_selected_prim_paths(self._prev_selection, True) class SelectListCommand(omni.kit.commands.Command): def __init__(self, **kwargs): self._prev_selection = omni.usd.get_context().get_selection().get_selected_prim_paths() self._new_selection = [] if 'selection' in kwargs: self._new_selection = kwargs['selection'] def do(self): omni.usd.get_context().get_selection().set_selected_prim_paths(self._new_selection, True) def undo(self): omni.usd.get_context().get_selection().set_selected_prim_paths(self._prev_selection, True) class SelectKindCommand(omni.kit.commands.Command): def __init__(self, **kwargs): self._prev_selection = omni.usd.get_context().get_selection().get_selected_prim_paths() self._kind = "" if 'kind' in kwargs: self._kind = kwargs['kind'] @Trace.TraceFunction def do(self): selection = [] for prim in omni.usd.get_context().get_stage().TraverseAll(): model_api = Usd.ModelAPI(prim) if Kind.Registry.IsA(model_api.GetKind(), self._kind): selection.append(str(prim.GetPath())) omni.usd.get_context().get_selection().set_selected_prim_paths(selection, True) def undo(self): omni.usd.get_context().get_selection().set_selected_prim_paths(self._prev_selection, True)
9,914
Python
36.415094
114
0.620637
omniverse-code/kit/exts/omni.kit.selection/omni/kit/selection/tests/create_prims.py
import os import carb import carb.settings import omni.kit.commands from pxr import Usd, Sdf, UsdGeom, Gf, Tf, UsdShade, UsdLux def create_test_stage(): settings = carb.settings.get_settings() default_prim_name = settings.get("/persistent/app/stage/defaultPrimName") rootname = f"/{default_prim_name}" stage = omni.usd.get_context().get_stage() kit_folder = carb.tokens.get_tokens_interface().resolve("${kit}") omni_pbr_mtl = os.path.normpath(kit_folder + "/mdl/core/Base/OmniPBR.mdl") # create Looks folder omni.kit.commands.execute( "CreatePrim", prim_path="{}/Looks".format(rootname), prim_type="Scope", select_new_prim=False ) # create GroundMat material mtl_name = "GroundMat" mtl_path = omni.usd.get_stage_next_free_path( stage, "{}/Looks/{}".format(rootname, Tf.MakeValidIdentifier(mtl_name)), False ) omni.kit.commands.execute( "CreateMdlMaterialPrim", mtl_url=omni_pbr_mtl, mtl_name=mtl_name, mtl_path=mtl_path ) ground_mat_prim = stage.GetPrimAtPath(mtl_path) shader = UsdShade.Material(ground_mat_prim).ComputeSurfaceSource("mdl")[0] shader.SetSourceAssetSubIdentifier("OmniPBR", "mdl") omni.usd.create_material_input(ground_mat_prim, "reflection_roughness_constant", 0.36, Sdf.ValueTypeNames.Float) omni.usd.create_material_input(ground_mat_prim, "specular_level", 0.25, Sdf.ValueTypeNames.Float) omni.usd.create_material_input( ground_mat_prim, "diffuse_color_constant", Gf.Vec3f(0.08, 0.08, 0.08), Sdf.ValueTypeNames.Color3f ) omni.usd.create_material_input(ground_mat_prim, "diffuse_tint", Gf.Vec3f(1, 1, 1), Sdf.ValueTypeNames.Color3f) omni.usd.create_material_input(ground_mat_prim, "diffuse_tint", Gf.Vec3f(1, 1, 1), Sdf.ValueTypeNames.Color3f) omni.usd.create_material_input(ground_mat_prim, "metallic_constant", 0.0, Sdf.ValueTypeNames.Float) omni.usd.create_material_input(ground_mat_prim, "reflection_roughness_constant", 0.36, Sdf.ValueTypeNames.Float) # create BackSideMat mtl_name = "BackSideMat" backside_mtl_path = omni.usd.get_stage_next_free_path( stage, "{}/Looks/{}".format(rootname, Tf.MakeValidIdentifier(mtl_name)), False ) omni.kit.commands.execute( "CreateMdlMaterialPrim", mtl_url=omni_pbr_mtl, mtl_name=mtl_name, mtl_path=backside_mtl_path ) backside_mtl_prim = stage.GetPrimAtPath(backside_mtl_path) shader = UsdShade.Material(backside_mtl_prim).ComputeSurfaceSource("mdl")[0] shader.SetSourceAssetSubIdentifier("OmniPBR", "mdl") omni.usd.create_material_input( backside_mtl_prim, "diffuse_color_constant", Gf.Vec3f(0.11814344, 0.118142255, 0.118142255), Sdf.ValueTypeNames.Color3f, ) omni.usd.create_material_input(backside_mtl_prim, "reflection_roughness_constant", 0.27, Sdf.ValueTypeNames.Float) omni.usd.create_material_input(backside_mtl_prim, "specular_level", 0.163, Sdf.ValueTypeNames.Float) # create EmissiveMat mtl_name = "EmissiveMat" emissive_mtl_path = omni.usd.get_stage_next_free_path( stage, "{}/Looks/{}".format(rootname, Tf.MakeValidIdentifier(mtl_name)), False ) omni.kit.commands.execute( "CreateMdlMaterialPrim", mtl_url=omni_pbr_mtl, mtl_name=mtl_name, mtl_path=emissive_mtl_path ) emissive_mtl_prim = stage.GetPrimAtPath(emissive_mtl_path) shader = UsdShade.Material(emissive_mtl_prim).ComputeSurfaceSource("mdl")[0] shader.SetSourceAssetSubIdentifier("OmniPBR", "mdl") omni.usd.create_material_input( emissive_mtl_prim, "diffuse_color_constant", Gf.Vec3f(0, 0, 0), Sdf.ValueTypeNames.Color3f ) omni.usd.create_material_input(emissive_mtl_prim, "reflection_roughness_constant", 1, Sdf.ValueTypeNames.Float) omni.usd.create_material_input(emissive_mtl_prim, "specular_level", 0, Sdf.ValueTypeNames.Float) omni.usd.create_material_input(emissive_mtl_prim, "enable_emission", True, Sdf.ValueTypeNames.Bool) omni.usd.create_material_input(emissive_mtl_prim, "emissive_color", Gf.Vec3f(1, 1, 1), Sdf.ValueTypeNames.Color3f) omni.usd.create_material_input(emissive_mtl_prim, "emissive_intensity", 15000, Sdf.ValueTypeNames.Float) # create studiohemisphere hemisphere_path = omni.usd.get_stage_next_free_path(stage, "{}/studiohemisphere".format(rootname), False) omni.kit.commands.execute( "CreatePrim", prim_path=hemisphere_path, prim_type="Xform", select_new_prim=False, attributes={} ) hemisphere_prim = stage.GetPrimAtPath(hemisphere_path) UsdGeom.PrimvarsAPI(hemisphere_prim).CreatePrimvar("doNotCastShadows", Sdf.ValueTypeNames.Bool).Set(True) Usd.ModelAPI(hemisphere_prim).SetKind("group") # create sphere hemisphere_sphere_path = omni.usd.get_stage_next_free_path( stage, "{}/studiohemisphere/Sphere".format(rootname), False ) omni.kit.commands.execute( "CreatePrim", prim_path=hemisphere_sphere_path, prim_type="Sphere", select_new_prim=False, attributes={UsdGeom.Tokens.radius: 100}, ) hemisphere_prim = stage.GetPrimAtPath(hemisphere_sphere_path) Usd.ModelAPI(hemisphere_prim).SetKind("assembly") # set transform hemisphere_prim.CreateAttribute("xformOp:scale", Sdf.ValueTypeNames.Double3, False).Set(Gf.Vec3d(2500, 2500, 2500)) hemisphere_prim.CreateAttribute("xformOpOrder", Sdf.ValueTypeNames.String, False).Set(["xformOp:scale"]) UsdGeom.PrimvarsAPI(hemisphere_prim).CreatePrimvar("doNotCastShadows", Sdf.ValueTypeNames.Bool).Set(True) # bind material omni.kit.commands.execute( "BindMaterial", prim_path=hemisphere_sphere_path, material_path=mtl_path, strength=UsdShade.Tokens.strongerThanDescendants, ) # create floor hemisphere_floor_path = omni.usd.get_stage_next_free_path( stage, "{}/studiohemisphere/Floor".format(rootname), False ) omni.kit.commands.execute( "CreatePrim", prim_path=hemisphere_floor_path, prim_type="Cube", select_new_prim=False, attributes={UsdGeom.Tokens.size: 100}, ) hemisphere_floor_prim = stage.GetPrimAtPath(hemisphere_floor_path) # set transform hemisphere_floor_prim.CreateAttribute("xformOp:scale", Sdf.ValueTypeNames.Double3, False).Set( Gf.Vec3d(2500, 0.1, 2500) ) hemisphere_floor_prim.CreateAttribute("xformOpOrder", Sdf.ValueTypeNames.String, False).Set(["xformOp:scale"]) UsdGeom.PrimvarsAPI(hemisphere_floor_prim).CreatePrimvar("doNotCastShadows", Sdf.ValueTypeNames.Bool).Set(True) # bind material omni.kit.commands.execute( "BindMaterial", prim_path=hemisphere_floor_path, material_path=mtl_path, strength=UsdShade.Tokens.strongerThanDescendants, ) # create LightPivot_01 light_pivot1_path = omni.usd.get_stage_next_free_path(stage, "{}/LightPivot_01".format(rootname), False) omni.kit.commands.execute( "CreatePrim", prim_path=light_pivot1_path, prim_type="Xform", select_new_prim=False, attributes={} ) light_pivot1_prim = stage.GetPrimAtPath(light_pivot1_path) UsdGeom.PrimvarsAPI(light_pivot1_prim).CreatePrimvar("doNotCastShadows", Sdf.ValueTypeNames.Bool).Set(True) # set transform light_pivot1_prim.CreateAttribute("xformOp:translate", Sdf.ValueTypeNames.Double3, False).Set(Gf.Vec3d(0, 0, 0)) light_pivot1_prim.CreateAttribute("xformOp:rotateZYX", Sdf.ValueTypeNames.Double3, False).Set( Gf.Vec3d(-30.453436397207547, 16.954190666353664, 9.728788165428536) ) light_pivot1_prim.CreateAttribute("xformOp:scale", Sdf.ValueTypeNames.Double3, False).Set( Gf.Vec3d(0.9999999445969171, 1.000000574567198, 0.9999995086845976) ) light_pivot1_prim.CreateAttribute("xformOpOrder", Sdf.ValueTypeNames.String, False).Set( ["xformOp:translate", "xformOp:rotateZYX", "xformOp:scale"] ) # create AreaLight light_pivot1_al_path = omni.usd.get_stage_next_free_path( stage, "{}/LightPivot_01/AreaLight".format(rootname), False ) omni.kit.commands.execute( "CreatePrim", prim_path=light_pivot1_al_path, prim_type="Xform", select_new_prim=False, attributes={} ) light_pivot1_al_prim = stage.GetPrimAtPath(light_pivot1_al_path) UsdGeom.PrimvarsAPI(light_pivot1_al_prim).CreatePrimvar("doNotCastShadows", Sdf.ValueTypeNames.Bool).Set(True) # set transform light_pivot1_al_prim.CreateAttribute("xformOp:translate", Sdf.ValueTypeNames.Double3, False).Set( Gf.Vec3d(0, 0, 800) ) light_pivot1_al_prim.CreateAttribute("xformOp:rotateZYX", Sdf.ValueTypeNames.Double3, False).Set(Gf.Vec3d(0, 0, 0)) light_pivot1_al_prim.CreateAttribute("xformOp:scale", Sdf.ValueTypeNames.Double3, False).Set( Gf.Vec3d(4.5, 4.5, 4.5) ) light_pivot1_al_prim.CreateAttribute("xformOpOrder", Sdf.ValueTypeNames.String, False).Set( ["xformOp:translate", "xformOp:rotateZYX", "xformOp:scale"] ) # create AreaLight RectLight light_pivot1_alrl_path = omni.usd.get_stage_next_free_path( stage, "{}/LightPivot_01/AreaLight/RectLight".format(rootname), False ) omni.kit.commands.execute( "CreatePrim", prim_path=light_pivot1_alrl_path, prim_type="RectLight", select_new_prim=False, attributes={}, ) light_pivot1_alrl_prim = stage.GetPrimAtPath(light_pivot1_alrl_path) # set values # https://github.com/PixarAnimationStudios/USD/commit/b5d3809c943950cd3ff6be0467858a3297df0bb7 # https://github.com/PixarAnimationStudios/USD/commit/3738719d72e60fb78d1cd18100768a7dda7340a4 if hasattr(UsdLux.Tokens, 'inputsIntensity'): light_pivot1_alrl_prim.CreateAttribute(UsdLux.Tokens.inputsHeight, Sdf.ValueTypeNames.Float, False).Set(100) light_pivot1_alrl_prim.CreateAttribute(UsdLux.Tokens.inputsWidth, Sdf.ValueTypeNames.Float, False).Set(100) light_pivot1_alrl_prim.CreateAttribute(UsdLux.Tokens.inputsIntensity, Sdf.ValueTypeNames.Float, False).Set(15000) light_pivot1_alrl_prim.CreateAttribute(UsdLux.Tokens.inputsShapingConeAngle, Sdf.ValueTypeNames.Float, False).Set(180) else: light_pivot1_alrl_prim.CreateAttribute(UsdLux.Tokens.height, Sdf.ValueTypeNames.Float, False).Set(100) light_pivot1_alrl_prim.CreateAttribute(UsdLux.Tokens.width, Sdf.ValueTypeNames.Float, False).Set(100) light_pivot1_alrl_prim.CreateAttribute(UsdLux.Tokens.intensity, Sdf.ValueTypeNames.Float, False).Set(15000) light_pivot1_alrl_prim.CreateAttribute(UsdLux.Tokens.shapingConeAngle, Sdf.ValueTypeNames.Float, False).Set(180) # create AreaLight Backside backside_albs_path = omni.usd.get_stage_next_free_path( stage, "{}/LightPivot_01/AreaLight/Backside".format(rootname), False ) omni.kit.commands.execute( "CreatePrim", prim_path=backside_albs_path, prim_type="Cube", select_new_prim=False, attributes={UsdGeom.Tokens.size: 100, UsdGeom.Tokens.extent: [(-50, -50, -50), (50, 50, 50)]}, ) backside_albs_prim = stage.GetPrimAtPath(backside_albs_path) # set values backside_albs_prim.CreateAttribute("xformOp:translate", Sdf.ValueTypeNames.Double3, False).Set(Gf.Vec3d(0, 0, 1.1)) backside_albs_prim.CreateAttribute("xformOp:rotateZYX", Sdf.ValueTypeNames.Double3, False).Set(Gf.Vec3d(0, 0, 0)) backside_albs_prim.CreateAttribute("xformOp:scale", Sdf.ValueTypeNames.Double3, False).Set(Gf.Vec3d(1, 1, 0.02)) backside_albs_prim.CreateAttribute("xformOpOrder", Sdf.ValueTypeNames.String, False).Set( ["xformOp:translate", "xformOp:rotateZYX", "xformOp:scale"] ) UsdGeom.PrimvarsAPI(backside_albs_prim).CreatePrimvar("doNotCastShadows", Sdf.ValueTypeNames.Bool).Set(True) # bind material omni.kit.commands.execute( "BindMaterial", prim_path=backside_albs_path, material_path=backside_mtl_path, strength=UsdShade.Tokens.strongerThanDescendants, ) # create AreaLight EmissiveSurface backside_ales_path = omni.usd.get_stage_next_free_path( stage, "{}/LightPivot_01/AreaLight/EmissiveSurface".format(rootname), False ) omni.kit.commands.execute( "CreatePrim", prim_path=backside_ales_path, prim_type="Cube", select_new_prim=False, attributes={UsdGeom.Tokens.size: 100, UsdGeom.Tokens.extent: [(-50, -50, -50), (50, 50, 50)]}, ) backside_ales_prim = stage.GetPrimAtPath(backside_ales_path) # set values backside_ales_prim.CreateAttribute("xformOp:translate", Sdf.ValueTypeNames.Double3, False).Set( Gf.Vec3d(0, 0, 0.002) ) backside_ales_prim.CreateAttribute("xformOp:rotateZYX", Sdf.ValueTypeNames.Double3, False).Set(Gf.Vec3d(0, 0, 0)) backside_ales_prim.CreateAttribute("xformOp:scale", Sdf.ValueTypeNames.Double3, False).Set(Gf.Vec3d(1, 1, 0.02)) backside_ales_prim.CreateAttribute("xformOpOrder", Sdf.ValueTypeNames.String, False).Set( ["xformOp:translate", "xformOp:rotateZYX", "xformOp:scale"] ) UsdGeom.PrimvarsAPI(backside_ales_prim).CreatePrimvar("doNotCastShadows", Sdf.ValueTypeNames.Bool).Set(True) # bind material omni.kit.commands.execute( "BindMaterial", prim_path=backside_ales_path, material_path=emissive_mtl_path, strength=UsdShade.Tokens.strongerThanDescendants, ) # create LightPivot_02 light_pivot2_path = omni.usd.get_stage_next_free_path(stage, "{}/LightPivot_02".format(rootname), False) omni.kit.commands.execute( "CreatePrim", prim_path=light_pivot2_path, prim_type="Xform", select_new_prim=False, attributes={} ) light_pivot2_prim = stage.GetPrimAtPath(light_pivot2_path) UsdGeom.PrimvarsAPI(light_pivot2_prim).CreatePrimvar("doNotCastShadows", Sdf.ValueTypeNames.Bool).Set(True) # set transform light_pivot2_prim.CreateAttribute("xformOp:translate", Sdf.ValueTypeNames.Double3, False).Set(Gf.Vec3d(0, 0, 0)) light_pivot2_prim.CreateAttribute("xformOp:rotateZYX", Sdf.ValueTypeNames.Double3, False).Set( Gf.Vec3d(-149.8694695859529, 35.87684189578612, -18.78499937937383) ) light_pivot2_prim.CreateAttribute("xformOp:scale", Sdf.ValueTypeNames.Double3, False).Set( Gf.Vec3d(0.9999999347425043, 0.9999995656418647, 1.0000001493100235) ) light_pivot2_prim.CreateAttribute("xformOpOrder", Sdf.ValueTypeNames.String, False).Set( ["xformOp:translate", "xformOp:rotateZYX", "xformOp:scale"] ) # create AreaLight light_pivot2_al_path = omni.usd.get_stage_next_free_path( stage, "{}/LightPivot_02/AreaLight".format(rootname), False ) omni.kit.commands.execute( "CreatePrim", prim_path=light_pivot2_al_path, prim_type="Xform", select_new_prim=False, attributes={} ) light_pivot2_al_prim = stage.GetPrimAtPath(light_pivot2_al_path) UsdGeom.PrimvarsAPI(light_pivot2_al_prim).CreatePrimvar("doNotCastShadows", Sdf.ValueTypeNames.Bool).Set(True) # set transform light_pivot2_al_prim.CreateAttribute("xformOp:translate", Sdf.ValueTypeNames.Double3, False).Set( Gf.Vec3d(0, 0, 800) ) light_pivot2_al_prim.CreateAttribute("xformOp:rotateZYX", Sdf.ValueTypeNames.Double3, False).Set(Gf.Vec3d(0, 0, 0)) light_pivot2_al_prim.CreateAttribute("xformOp:scale", Sdf.ValueTypeNames.Double3, False).Set( Gf.Vec3d(1.5, 1.5, 1.5) ) light_pivot2_al_prim.CreateAttribute("xformOpOrder", Sdf.ValueTypeNames.String, False).Set( ["xformOp:translate", "xformOp:rotateZYX", "xformOp:scale"] ) # create AreaLight RectLight light_pivot2_alrl_path = omni.usd.get_stage_next_free_path( stage, "{}/LightPivot_02/AreaLight/RectLight".format(rootname), False ) omni.kit.commands.execute( "CreatePrim", prim_path=light_pivot2_alrl_path, prim_type="RectLight", select_new_prim=False, attributes={}, ) light_pivot2_alrl_prim = stage.GetPrimAtPath(light_pivot2_alrl_path) # set values # https://github.com/PixarAnimationStudios/USD/commit/b5d3809c943950cd3ff6be0467858a3297df0bb7 # https://github.com/PixarAnimationStudios/USD/commit/3738719d72e60fb78d1cd18100768a7dda7340a4 if hasattr(UsdLux.Tokens, 'inputsIntensity'): light_pivot2_alrl_prim.CreateAttribute(UsdLux.Tokens.inputsHeight, Sdf.ValueTypeNames.Float, False).Set(100) light_pivot2_alrl_prim.CreateAttribute(UsdLux.Tokens.inputsWidth, Sdf.ValueTypeNames.Float, False).Set(100) light_pivot2_alrl_prim.CreateAttribute(UsdLux.Tokens.inputsIntensity, Sdf.ValueTypeNames.Float, False).Set(55000) light_pivot2_alrl_prim.CreateAttribute(UsdLux.Tokens.inputsShapingConeAngle, Sdf.ValueTypeNames.Float, False).Set(180) else: light_pivot2_alrl_prim.CreateAttribute(UsdLux.Tokens.height, Sdf.ValueTypeNames.Float, False).Set(100) light_pivot2_alrl_prim.CreateAttribute(UsdLux.Tokens.width, Sdf.ValueTypeNames.Float, False).Set(100) light_pivot2_alrl_prim.CreateAttribute(UsdLux.Tokens.intensity, Sdf.ValueTypeNames.Float, False).Set(55000) light_pivot2_alrl_prim.CreateAttribute(UsdLux.Tokens.shapingConeAngle, Sdf.ValueTypeNames.Float, False).Set(180) # create AreaLight Backside backside_albs_path = omni.usd.get_stage_next_free_path( stage, "{}/LightPivot_02/AreaLight/Backside".format(rootname), False ) omni.kit.commands.execute( "CreatePrim", prim_path=backside_albs_path, prim_type="Cube", select_new_prim=False, attributes={UsdGeom.Tokens.size: 100, UsdGeom.Tokens.extent: [(-50, -50, -50), (50, 50, 50)]}, ) backside_albs_prim = stage.GetPrimAtPath(backside_albs_path) # set values backside_albs_prim.CreateAttribute("xformOp:translate", Sdf.ValueTypeNames.Double3, False).Set(Gf.Vec3d(0, 0, 1.1)) backside_albs_prim.CreateAttribute("xformOp:rotateZYX", Sdf.ValueTypeNames.Double3, False).Set(Gf.Vec3d(0, 0, 0)) backside_albs_prim.CreateAttribute("xformOp:scale", Sdf.ValueTypeNames.Double3, False).Set(Gf.Vec3d(1, 1, 0.02)) backside_albs_prim.CreateAttribute("xformOpOrder", Sdf.ValueTypeNames.String, False).Set( ["xformOp:translate", "xformOp:rotateZYX", "xformOp:scale"] ) UsdGeom.PrimvarsAPI(backside_albs_prim).CreatePrimvar("doNotCastShadows", Sdf.ValueTypeNames.Bool).Set(True) # bind material omni.kit.commands.execute( "BindMaterial", prim_path=backside_albs_path, material_path=backside_mtl_path, strength=UsdShade.Tokens.strongerThanDescendants, ) # create AreaLight EmissiveSurface backside_ales_path = omni.usd.get_stage_next_free_path( stage, "{}/LightPivot_02/AreaLight/EmissiveSurface".format(rootname), False ) omni.kit.commands.execute( "CreatePrim", prim_path=backside_ales_path, prim_type="Cube", select_new_prim=False, attributes={UsdGeom.Tokens.size: 100, UsdGeom.Tokens.extent: [(-50, -50, -50), (50, 50, 50)]}, ) backside_ales_prim = stage.GetPrimAtPath(backside_ales_path) # set values backside_ales_prim.CreateAttribute("xformOp:translate", Sdf.ValueTypeNames.Double3, False).Set( Gf.Vec3d(0, 0, 0.002) ) backside_ales_prim.CreateAttribute("xformOp:rotateZYX", Sdf.ValueTypeNames.Double3, False).Set(Gf.Vec3d(0, 0, 0)) backside_ales_prim.CreateAttribute("xformOp:scale", Sdf.ValueTypeNames.Double3, False).Set(Gf.Vec3d(1, 1, 0.02)) backside_ales_prim.CreateAttribute("xformOpOrder", Sdf.ValueTypeNames.String, False).Set( ["xformOp:translate", "xformOp:rotateZYX", "xformOp:scale"] ) UsdGeom.PrimvarsAPI(backside_ales_prim).CreatePrimvar("doNotCastShadows", Sdf.ValueTypeNames.Bool).Set(True) # bind material omni.kit.commands.execute( "BindMaterial", prim_path=backside_ales_path, material_path=emissive_mtl_path, strength=UsdShade.Tokens.strongerThanDescendants, )
20,064
Python
48.178921
126
0.707835
omniverse-code/kit/exts/omni.kit.selection/omni/kit/selection/tests/__init__.py
from .test_commands import * from .create_prims import *
57
Python
18.333327
28
0.754386
omniverse-code/kit/exts/omni.kit.selection/omni/kit/selection/tests/test_commands.py
import random import omni.kit.test import omni.kit.commands import omni.kit.undo from pxr import Usd, UsdGeom, Kind class TestCommands(omni.kit.test.AsyncTestCase): def check_visibillity(self, visible_set, invisible_set): context = omni.usd.get_context() stage = context.get_stage() for prim in stage.TraverseAll(): if prim and not prim.GetMetadata("hide_in_stage_window"): if stage.HasDefaultPrim() and stage.GetDefaultPrim() == prim: continue imageable = UsdGeom.Imageable(prim) if imageable: if imageable.ComputeVisibility() == UsdGeom.Tokens.invisible: self.assertTrue((prim.GetPath().pathString in invisible_set)) else: self.assertTrue((prim.GetPath().pathString in visible_set)) def get_parent_prims(self, prim): stage = omni.usd.get_context().get_stage() parent_prims = [] while prim.GetParent(): parent_prims.append(prim.GetParent().GetPath().pathString) prim = prim.GetParent() if stage.HasDefaultPrim() and stage.GetDefaultPrim() == prim: break return parent_prims def get_all_children(self, prim, child_list): for child in prim.GetAllChildren(): child_list.append(child.GetPath().pathString) self.get_all_children(child, child_list) def get_all_prims(self): all_prims = [] stage = omni.usd.get_context().get_stage() for prim in stage.TraverseAll(): if not prim.GetMetadata("hide_in_stage_window"): all_prims.append(prim.GetPath().pathString) return all_prims async def setUp(self): # Disable logging for the time of tests to avoid spewing errors await omni.usd.get_context().new_stage_async() omni.kit.selection.tests.create_test_stage() async def tearDown(self): pass async def test_command_select_all(self): context = omni.usd.get_context() selection = context.get_selection() stage = context.get_stage() all_root_prims = [] all_prims = [] material_prims = [] cube_prims = [] sphere_prims = [] children_iterator = iter(stage.TraverseAll()) for prim in children_iterator: all_root_prims.append(prim.GetPath().pathString) children_iterator.PruneChildren() for prim in stage.TraverseAll(): if prim.GetMetadata("hide_in_stage_window"): continue all_prims.append(prim.GetPath().pathString) if prim.GetTypeName() == "Material": material_prims.append(prim.GetPath().pathString) if prim.GetTypeName() == "Cube": cube_prims.append(prim.GetPath().pathString) if prim.GetTypeName() == "Sphere": sphere_prims.append(prim.GetPath().pathString) subset_count = int(len(all_prims) >> 1) subset_prims = random.sample(all_prims, subset_count) # SelectAllCommand Execute and undo selection.set_selected_prim_paths(subset_prims, True) omni.kit.commands.execute("SelectAll") self.assertListEqual(selection.get_selected_prim_paths(), all_root_prims) omni.kit.undo.undo() self.assertListEqual(selection.get_selected_prim_paths(), subset_prims) # SelectAllCommand "Material" Execute and undo selection.set_selected_prim_paths(subset_prims, True) omni.kit.commands.execute("SelectAll", type="Material") self.assertListEqual(selection.get_selected_prim_paths(), material_prims) omni.kit.undo.undo() self.assertListEqual(selection.get_selected_prim_paths(), subset_prims) # SelectAllCommand "Cube" Execute and undo selection.set_selected_prim_paths(subset_prims, True) omni.kit.commands.execute("SelectAll", type="Cube") self.assertListEqual(selection.get_selected_prim_paths(), cube_prims) omni.kit.undo.undo() self.assertListEqual(selection.get_selected_prim_paths(), subset_prims) # SelectAllCommand "Sphere" Execute and undo selection.set_selected_prim_paths(subset_prims, True) omni.kit.commands.execute("SelectAll", type="Sphere") self.assertListEqual(selection.get_selected_prim_paths(), sphere_prims) omni.kit.undo.undo() self.assertListEqual(selection.get_selected_prim_paths(), subset_prims) # SelectSimilarCommand: "Sphere" and "Cube" prim_paths = [sphere_prims[0], cube_prims[0]] selection.set_selected_prim_paths(prim_paths, True) omni.kit.commands.execute("SelectSimilar") all_prims = sphere_prims.copy() all_prims.extend(cube_prims) self.assertListEqual(selection.get_selected_prim_paths(), all_prims) omni.kit.undo.undo() self.assertListEqual(selection.get_selected_prim_paths(), prim_paths) async def test_command_select_none(self): context = omni.usd.get_context() selection = context.get_selection() stage = context.get_stage() all_prims = self.get_all_prims() subset_count = int(len(all_prims) >> 1) subset_prims = random.sample(all_prims, subset_count) inverse_prims = [item for item in all_prims if item not in subset_prims] # SelectNoneCommand Execute and undo selection.set_selected_prim_paths(subset_prims, True) omni.kit.commands.execute("SelectNone") self.assertListEqual(selection.get_selected_prim_paths(), []) omni.kit.undo.undo() self.assertListEqual(selection.get_selected_prim_paths(), subset_prims) async def test_command_select_invert(self): context = omni.usd.get_context() selection = context.get_selection() stage = context.get_stage() all_prims = [] for prim in stage.TraverseAll(): if not prim.GetMetadata("hide_in_stage_window") and stage.HasDefaultPrim() and not stage.GetDefaultPrim() == prim: all_prims.append(prim.GetPath().pathString) # if selected path as children and none of the children are selected, then all the children are selected.. subset_count = int(len(all_prims) >> 1) subset_prims = [] for prim_path in sorted(random.sample(all_prims, subset_count), reverse=True): prim = stage.GetPrimAtPath(prim_path) if prim: subset_prims.append(prim_path) child_list = [] self.get_all_children(prim, child_list) if not set(subset_prims).intersection(set(child_list)): subset_prims += child_list # SelectInvertCommand Execute and undo selection.set_selected_prim_paths(subset_prims, True) omni.kit.commands.execute("SelectInvert") self.assertListEqual(selection.get_selected_prim_paths(), ['/World']) omni.kit.undo.undo() self.assertListEqual(selection.get_selected_prim_paths(), subset_prims) async def test_command_hide_unselected(self): context = omni.usd.get_context() selection = context.get_selection() stage = context.get_stage() all_prims = self.get_all_prims() # if selected path as children and none of the children are selected, then all the children are selected.. subset_prims = set() for prim_path in sorted(random.sample(all_prims, 3), reverse=True): # we need to remove "/World" from the sampled result since it is the parent of all prims if prim_path == '/World': continue prim = stage.GetPrimAtPath(prim_path) if prim: subset_prims.add(prim_path) child_list = [] self.get_all_children(prim, child_list) subset_prims.update(child_list) # HideUnselectedCommand Execute and undo visible_prims = set() for prim_path in subset_prims: prim = stage.GetPrimAtPath(prim_path) if prim: visible_prims.add(prim.GetPath().pathString) visible_prims.update(self.get_parent_prims(prim)) invisible_prims = set([item for item in all_prims if item not in visible_prims]) selection.set_selected_prim_paths(list(subset_prims), True) omni.kit.commands.execute("HideUnselected") self.check_visibillity(visible_prims, invisible_prims) omni.kit.undo.undo() self.check_visibillity(all_prims, []) async def test_command_select_parent(self): context = omni.usd.get_context() selection = context.get_selection() stage = context.get_stage() all_prims = self.get_all_prims() subset_count = int(len(all_prims) >> 1) subset_prims = random.sample(all_prims, subset_count) parent_prims = set() for prim_path in subset_prims: prim = stage.GetPrimAtPath(prim_path) if prim and prim.GetParent() is not None: parent_prims.add(prim.GetParent().GetPath().pathString) parent_prims = list(parent_prims) selection.set_selected_prim_paths(subset_prims, True) omni.kit.commands.execute("SelectParent") self.assertListEqual(selection.get_selected_prim_paths(), sorted(parent_prims)) omni.kit.undo.undo() self.assertListEqual(selection.get_selected_prim_paths(), subset_prims) async def test_command_select_kind(self): context = omni.usd.get_context() selection = context.get_selection() stage = context.get_stage() all_prims = [] group_prims = [] for prim in stage.TraverseAll(): if Kind.Registry.IsA(Usd.ModelAPI(prim).GetKind(), "group"): group_prims.append(prim.GetPath().pathString) if not prim.GetMetadata("hide_in_stage_window"): all_prims.append(prim.GetPath().pathString) subset_count = int(len(all_prims) >> 1) subset_prims = random.sample(all_prims, subset_count) selection.set_selected_prim_paths(subset_prims, True) omni.kit.commands.execute("SelectKind", kind="group") self.assertListEqual(selection.get_selected_prim_paths(), sorted(group_prims)) omni.kit.undo.undo() self.assertListEqual(selection.get_selected_prim_paths(), subset_prims) async def test_command_select_hierarchy(self): context = omni.usd.get_context() selection = context.get_selection() selection.set_selected_prim_paths(['/World'], True) omni.kit.commands.execute("SelectHierarchy") self.assertListEqual(selection.get_selected_prim_paths(), sorted(self.get_all_prims())) omni.kit.undo.undo() self.assertListEqual(selection.get_selected_prim_paths(), ['/World']) async def test_command_select_list(self): context = omni.usd.get_context() selection = context.get_selection() all_prims = self.get_all_prims() subset_count = int(len(all_prims) >> 1) subset_prims = random.sample(all_prims, subset_count) selection.set_selected_prim_paths(['/World'], True) self.assertListEqual(selection.get_selected_prim_paths(), ['/World']) # with no kwargs it should clear the selection omni.kit.commands.execute("SelectList") self.assertListEqual(selection.get_selected_prim_paths(), []) omni.kit.undo.undo() self.assertListEqual(selection.get_selected_prim_paths(), ['/World']) # with kwarg it should swap the selection to the new list omni.kit.commands.execute("SelectList", selection=subset_prims) self.assertListEqual(sorted(selection.get_selected_prim_paths()), sorted(subset_prims)) omni.kit.undo.undo() self.assertListEqual(selection.get_selected_prim_paths(), ['/World']) async def test_command_select_leaf(self): context = omni.usd.get_context() selection = context.get_selection() stage = context.get_stage() selection.set_selected_prim_paths(['/World'], True) omni.kit.commands.execute("SelectLeaf") selected = selection.get_selected_prim_paths() for leaf in selected: self.assertFalse(stage.GetPrimAtPath(leaf).GetChildren()) omni.kit.undo.undo() self.assertListEqual(selection.get_selected_prim_paths(), ['/World'])
12,583
Python
41.948805
126
0.629739
omniverse-code/kit/exts/omni.kit.selection/docs/index.rst
omni.kit.selection ########################### Commands for selection of prims
80
reStructuredText
15.199997
31
0.5375
omniverse-code/kit/exts/omni.kit.widget.toolbar/omni/kit/widget/toolbar/simple_tool_button.py
# Copyright (c) 2020, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. # import omni.ui import weakref from .hotkey import Hotkey from .widget_group import WidgetGroup class SimpleToolButton(WidgetGroup): """ A helper class to create simple WidgetGroup that contains only one ToolButton. Args: name: Name of the ToolButton. tooltip: Tooltip of the ToolButton. icon_path: The icon to be used when button is not checked. icon_checked_path: The icon to be used when button is checked. hotkey: HotKey to toggle the button (optional). toggled_fn: Callback function when button is toggled. Signature: on_toggled(checked) (optional). model: Model for the ToolButton (optional). additional_style: Additional styling to apply to the ToolButton (optional). """ def __init__( self, name, tooltip, icon_path, icon_checked_path, hotkey=None, toggled_fn=None, model=None, additional_style=None, ): super().__init__() self._name = name self._tooltip = tooltip self._icon_path = icon_path self._icon_checked_path = icon_checked_path self._hotkey = hotkey self._toggled_fn = toggled_fn self._model = model self._additional_style = additional_style self._hotkey = None if hotkey: def on_hotkey_changed(hotkey: str): self._tool_button.tooltip = f"{self._tooltip} ({hotkey})" self._select_hotkey = Hotkey( f"{name}::hotkey", hotkey, lambda: self._on_hotkey(), lambda: self._tool_button.enabled and self._is_in_context(), on_hotkey_changed_fn=lambda hotkey: on_hotkey_changed(hotkey), ) def clean(self): super().clean() self._value_sub = None self._tool_button = None if self._select_hotkey: self._select_hotkey.clean() self._select_hotkey = None def get_style(self): style = { f"Button.Image::{self._name}": {"image_url": self._icon_path}, f"Button.Image::{self._name}:checked": {"image_url": self._icon_checked_path}, } if self._additional_style: style.update(self._additional_style) return style def create(self, default_size): def on_value_changed(model, widget): widget = widget() if widget is not None: if model.get_value_as_bool(): self._acquire_toolbar_context() else: self._release_toolbar_context() widget._toggled_fn(model.get_value_as_bool()) self._tool_button = omni.ui.ToolButton( name=self._name, model=self._model, tooltip=self._tooltip, width=default_size, height=default_size ) if self._toggled_fn is not None: self._value_sub = self._tool_button.model.subscribe_value_changed_fn( lambda model, widget=weakref.ref(self): on_value_changed(model, widget) ) # return a dictionary of name -> widget if you want to expose it to other widget_group return {self._name: self._tool_button} def get_tool_button(self): return self._tool_button def _on_hotkey(self): self._tool_button.model.set_value(not self._tool_button.model.get_value_as_bool())
3,858
Python
34.081818
110
0.604458
omniverse-code/kit/exts/omni.kit.widget.toolbar/omni/kit/widget/toolbar/widget_group.py
# Copyright (c) 2020, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. # import asyncio from abc import abstractmethod import omni.kit.widget.toolbar import omni.kit.app import omni.ui as ui from .context_menu import ContextMenuEvent class WidgetGroup: """ Base class to create a group of widgets on Toolbar """ def __init__(self): self._context = "" self._context_token = None self._show_menu_task = None self._toolbar_ext_path = ( omni.kit.app.get_app().get_extension_manager().get_extension_path_by_module("omni.kit.widget.toolbar") ) @abstractmethod def clean(self): """ Clean up function to be called before destorying the object. """ if self._context_token: self._release_toolbar_context() self._context_token = None self._context = "" if self._show_menu_task: # pragma: no cover self._show_menu_task.cancel() self._show_menu_task = None @abstractmethod def get_style(self) -> dict: """ Gets the style of all widgets defined in this Widgets group. """ pass # pragma: no cover (Abstract) @abstractmethod def create(self, default_size): """ Main function to creates widget. If you want to export widgets and allow external code to fetch and manipulate them, return a Dict[str, Widget] mapping from name to instance at the end of the function. """ pass # pragma: no cover (Abstract) def on_toolbar_context_changed(self, context: str): """ Called when toolbar's effective context has changed. Args: context: new toolbar context. """ pass def on_added(self, context): """ Called when widget is added to toolbar when calling Toolbar.add_widget Args: context: the context used to add widget when calling Toolbar.add_widget. """ self._context = context def on_removed(self): """ Called when widget is removed from toolbar when calling Toolbar.remove_widget """ pass def _acquire_toolbar_context(self): """ Request toolbar to switch to current widget's context. """ self._context_token = omni.kit.widget.toolbar.get_instance().acquire_toolbar_context(self._context) def _release_toolbar_context(self): """ Release the ownership of toolbar context and reset to default. If the ownership was preemptively taken by other owner, release does nothing. """ omni.kit.widget.toolbar.get_instance().release_toolbar_context(self._context_token) def _is_in_context(self): """ Checks if the Toolbar is in default context or owned by current widget's context. Override this function if you want to customize the behavior. Returns: True if toolbar is either in default context or owned by current widget. False otherwise. """ toolbar_context = omni.kit.widget.toolbar.get_instance().get_context() return toolbar_context == omni.kit.widget.toolbar.Toolbar.DEFAULT_CONTEXT or self._context == toolbar_context def _invoke_context_menu(self, button_id: str, min_menu_entries: int = 1): """ Function to invoke context menu. Args: button_id: button_id of the context menu to be invoked. min_menu_entries: minimal number of menu entries required for menu to be visible (default 1). """ event = ContextMenuEvent() event.payload["widget_name"] = button_id event.payload["min_menu_entries"] = min_menu_entries omni.kit.widget.toolbar.get_instance().context_menu.on_mouse_event(event) def _on_mouse_pressed(self, button, button_id: str, min_menu_entries: int = 2): """ Function to handle flyout menu. Either with LMB long press or RMB click. Args: button_id: button_id of the context menu to be invoked. min_menu_entries: minimal number of menu entries required for menu to be visible (default 1). """ self._acquire_toolbar_context() if button == 1: # Right click, show immediately self._invoke_context_menu(button_id, min_menu_entries) elif button == 0: # Schedule a task if hold LMB long enough self._show_menu_task = asyncio.ensure_future(self._schedule_show_menu(button_id)) def _on_mouse_released(self, button): if button == 0: if self._show_menu_task: self._show_menu_task.cancel() async def _schedule_show_menu(self, button_id: str, min_menu_entries: int = 2): await asyncio.sleep(0.3) self._invoke_context_menu(button_id, min_menu_entries) self._show_menu_task = None def _build_flyout_indicator( self, width, height, index: str, extension_id: str = "omni.kit.widget.toolbar", padding=7, min_menu_count=2 ): import carb import omni.kit.context_menu indicator_size = 3 with ui.Placer(offset_x=width - indicator_size - padding, offset_y=height - indicator_size - padding): indicator = ui.Image( f"{self._toolbar_ext_path}/data/icon/flyout_indicator_dark.svg", width=indicator_size, height=indicator_size, ) def on_menu_changed(evt: carb.events.IEvent): try: menu_list = omni.kit.context_menu.get_menu_dict(index, extension_id) # because we moved separated the widget from the window extension, we need to still grab the menu from # the window extension menu_list_backward_compatible = omni.kit.context_menu.get_menu_dict(index, "omni.kit.window.toolbar") if menu_list_backward_compatible and evt.payload.get("extension_id", None) == "omni.kit.window.toolbar": # pragma: no cover omni.kit.app.log_deprecation( 'Adding menu using "add_menu(menu, index, "omni.kit.window.toolbar")" is deprecated. ' 'Please use "add_menu(menu, index, "omni.kit.widget.toolbar")"' ) # TODO check the actual menu entry visibility with show_fn indicator.visible = len(menu_list + menu_list_backward_compatible) >= min_menu_count except AttributeError as exc: # pragma: no cover carb.log_warn(f"on_menu_changed error {exc}") # Check initial state on_menu_changed(None) event_stream = omni.kit.context_menu.get_menu_event_stream() return event_stream.create_subscription_to_pop(on_menu_changed)
7,173
Python
38.202186
176
0.625401
omniverse-code/kit/exts/omni.kit.widget.toolbar/omni/kit/widget/toolbar/commands.py
# Copyright (c) 2020, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. # import omni.timeline import omni.kit.commands class ToolbarPlayButtonClickedCommand(omni.kit.commands.Command): """ On clicked toolbar play button **Command**. """ def do(self): omni.timeline.get_timeline_interface().play() class ToolbarPauseButtonClickedCommand(omni.kit.commands.Command): """ On clicked toolbar pause button **Command**. """ def do(self): omni.timeline.get_timeline_interface().pause() class ToolbarStopButtonClickedCommand(omni.kit.commands.Command): """ On clicked toolbar stop button **Command**. """ def do(self): omni.timeline.get_timeline_interface().stop() class ToolbarPlayFilterCheckedCommand(omni.kit.commands.Command): """ Change settings depending on the status of play filter checkboxes **Command**. Args: path: Path to the setting to change. enabled: New value to change to. """ def __init__(self, setting_path, enabled): self._setting_path = setting_path self._enabled = enabled def do(self): omni.kit.commands.execute("ChangeSetting", path=self._setting_path, value=self._enabled) def undo(self): pass # pragma: no cover class ToolbarPlayFilterSelectAllCommand(omni.kit.commands.Command): # pragma: no cover """ Sets all play filter settings to True **Command**. Args: settings: Paths to the settings. """ def __init__(self, settings): self._settings = settings def do(self): for setting in self._settings: omni.kit.commands.execute("ChangeSetting", path=setting, value=True) def undo(self): pass omni.kit.commands.register_all_commands_in_module(__name__)
2,165
Python
26.075
96
0.684988
omniverse-code/kit/exts/omni.kit.widget.toolbar/omni/kit/widget/toolbar/extension.py
# Copyright (c) 2018-2020, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. # import carb import omni.ext from functools import lru_cache from pathlib import Path from .toolbar import Toolbar _toolbar_instance = None @lru_cache() def get_data_path() -> Path: manager = omni.kit.app.get_app().get_extension_manager() extension_path = manager.get_extension_path_by_module("omni.kit.widget.toolbar") return Path(extension_path).joinpath("data") def get_instance(): return _toolbar_instance class WidgetToolBarExtension(omni.ext.IExt): """omni.kit.widget.toolbar ext""" def on_startup(self, ext_id): global _toolbar_instance carb.log_info("[omni.kit.widget.toolbar] Startup") _toolbar_instance = Toolbar() def on_shutdown(self): carb.log_info("[omni.kit.widget.toolbar] Shutdown") global _toolbar_instance if _toolbar_instance: _toolbar_instance.destroy() _toolbar_instance = None
1,338
Python
29.431818
84
0.720478
omniverse-code/kit/exts/omni.kit.widget.toolbar/omni/kit/widget/toolbar/__init__.py
from .extension import * from .toolbar import * from omni.kit.widget.toolbar.simple_tool_button import * # backward compatible from .widget_group import * # backward compatible
179
Python
34.999993
79
0.776536
omniverse-code/kit/exts/omni.kit.widget.toolbar/omni/kit/widget/toolbar/context_menu.py
# Copyright (c) 2020, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. # import carb import omni.kit.context_menu from omni import ui class ContextMenuEvent: """The object comatible with ContextMenu""" def __init__(self): self.type = 0 self.payload = {} class ContextMenu: def on_mouse_event(self, event): # check its expected event if event.type != int(omni.kit.ui.MenuEventType.ACTIVATE): # pragma: no cover return # get context menu core functionality & check its enabled context_menu = omni.kit.context_menu.get_instance() if context_menu is None: # pragma: no cover carb.log_error("context_menu is disabled!") return # setup objects, this is passed to all functions objects = {} objects.update(event.payload) widget_name = objects.get("widget_name", None) menu_list = omni.kit.context_menu.get_menu_dict(widget_name, "omni.kit.widget.toolbar") # because we moved separated the widget from the window extension, we need to still grab the menu from # the window extension menu_list_backward_compatible = omni.kit.context_menu.get_menu_dict(widget_name, "omni.kit.window.toolbar") for menu_list_backward in menu_list_backward_compatible: # pragma: no cover if menu_list_backward not in menu_list: menu_list.append(menu_list_backward) # For some tool buttons, the context menu only shows if additional (>1) menu entries are added. min_menu_entries = event.payload.get("min_menu_entries", 0) # show menu context_menu.show_context_menu("toolbar", objects, menu_list, min_menu_entries, delegate=ui.MenuDelegate())
2,117
Python
38.962263
115
0.683987
omniverse-code/kit/exts/omni.kit.widget.toolbar/omni/kit/widget/toolbar/toolbar.py
# Copyright (c) 2020, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. # import asyncio import carb import carb.settings import omni.kit.app import omni.ui as ui import omni.usd from omni.ui import color as cl from typing import Callable from .builtin_tools.builtin_tools import BuiltinTools from .commands import * from .context_menu import * from .widget_group import WidgetGroup # backward compatible import typing if typing.TYPE_CHECKING: # pragma: no cover import weakref GRAB_ENABLED_SETTING_PATH = "/exts/omni.kit.widget.toolbar/Grab/enabled" # Any class derived from `omni.ext.IExt` in top level module (defined in `python.modules` of `extension.toml`) will be # instantiated when extension gets enabled and `on_startup(ext_id)` will be called. Later when extension gets disabled # on_shutdown() is called. class Toolbar: WINDOW_NAME = "Main ToolBar" DEFAULT_CONTEXT = "" DEFAULT_CONTEXT_TOKEN = 0 DEFAULT_SIZE = 38 # ext_id is current extension id. It can be used with extension manager to query additional information, like where # this extension is located on filesystem. def __init__(self): self._settings = carb.settings.get_settings() self.__root_frame = None self._toolbar_widget_groups = [] self._toolbar_widgets = {} self._toolbar_dirty = False self._axis = ui.ToolBarAxis.X self._rebuild_task = None self._grab_stack = None self._context_menu = ContextMenu() self._context_token_pool = 1 self._context = Toolbar.DEFAULT_CONTEXT self._context_token = Toolbar.DEFAULT_CONTEXT_TOKEN self._context_token_owner_count = 0 self.__init_shades() self._builtin_tools = BuiltinTools(self) def __init_shades(self): """Style colors""" cl.toolbar_button_background = cl.shade(0x0) cl.toolbar_button_background_checked = cl.shade(0xFF1F2123) cl.toolbar_button_background_pressed = cl.shade(0xFF4B4B4B) cl.toolbar_button_background_hovered = cl.shade(0xFF383838) @property def context_menu(self): return self._context_menu def destroy(self): if self._rebuild_task is not None: # pragma: no cover self._rebuild_task.cancel() self._toolbar_widgets = {} if self._builtin_tools: self._builtin_tools.destroy() self._builtin_tools = None self._toolbar_widget_groups = [] def add_widget(self, widget_group: "WidgetGroup", priority: int, context: str = ""): self._toolbar_widget_groups.append((priority, widget_group)) widget_group.on_added(context) self._set_toolbar_dirty() def remove_widget(self, widget_group: "WidgetGroup"): for widget in self._toolbar_widget_groups: if widget[1] == widget_group: self._toolbar_widget_groups.remove(widget) widget_group.on_removed() self._set_toolbar_dirty() break def get_widget(self, name: str): return self._toolbar_widgets.get(name, None) def acquire_toolbar_context(self, context: str): """ Request toolbar to switch to given context. It takes the context preemptively even if previous context owner has not release the context. Args: context (str): Context to switch to. Returns: A token to be used to release_toolbar_context """ if self._context == context: self._context_token_owner_count += 1 return self._context_token # preemptively take current context, regardless of previous owner/count self._context = context if context == Toolbar.DEFAULT_CONTEXT: self._context_token = Toolbar.DEFAULT_CONTEXT_TOKEN else: self._context_token_pool += 1 self._context_token = self._context_token_pool self._context_token_owner_count = 1 for widget in self._toolbar_widget_groups: widget[1].on_toolbar_context_changed(context) return self._context_token def release_toolbar_context(self, token: int): """ Request toolbar to release context associated with token. If token is expired (already released or context ownership taken by others), this function does nothing. Args: token (int): Context token to release. """ if token == self._context_token: self._context_token_owner_count -= 1 else: carb.log_info("Releasing expired context token, ignoring") return if self._context_token_owner_count <= 0: self._context = Toolbar.DEFAULT_CONTEXT self._context_token = Toolbar.DEFAULT_CONTEXT_TOKEN self._context_token_owner_count = 0 for widget in self._toolbar_widget_groups: widget[1].on_toolbar_context_changed(self._context) def get_context(self): return self._context def _set_toolbar_dirty(self): self._toolbar_dirty = True if self._rebuild_task is None: self._rebuild_task = asyncio.ensure_future(self._delayed_rebuild()) def set_axis(self, axis): self._axis = axis # delay rebuild so widgets added within one frame are rebuilt together @omni.usd.handle_exception async def _delayed_rebuild(self): await omni.kit.app.get_app().next_update_async() if self._toolbar_dirty: self.rebuild_toolbar() self._toolbar_dirty = False self._rebuild_task = None def rebuild_toolbar(self, root_frame=None): if root_frame: self.__root_frame = root_frame if not self.__root_frame: carb.log_warn("No root frame specified. Please specify a root frame for this widget") return axis = self._axis self._toolbar_widgets = {} self._toolbar_widget_groups.sort(key=lambda x: x[0]) # sort by priority with self.__root_frame: stack = None style = { "Button": {"background_color": cl.toolbar_button_background, "border_radius": 4, "margin": 2, "padding": 3}, "Button:checked": {"background_color": cl.toolbar_button_background_checked}, "Button:pressed": {"background_color": cl.toolbar_button_background_pressed}, "Button:hovered": {"background_color": cl.toolbar_button_background_hovered}, "Button.Image::disabled": {"color": 0x608A8777}, "Line::grab": {"color": 0xFF2E2E2E, "border_width": 2, "margin": 2}, "Line::separator": {"color": 0xFF555555}, "Tooltip": { "background_color": 0xFFC7F5FC, "color": 0xFF4B493B, "border_width": 1, "margin_width": 2, "margin_height": 1, "padding": 1, }, } for widget in self._toolbar_widget_groups: style.update(widget[1].get_style()) default_size = self.DEFAULT_SIZE if axis == ui.ToolBarAxis.X: stack = ui.HStack(style=style, height=default_size, width=ui.Percent(100)) else: stack = ui.VStack(style=style, height=ui.Percent(100), width=default_size) with stack: if self._settings.get(GRAB_ENABLED_SETTING_PATH): self._create_grab(axis) ui.Spacer(width=3, height=3) last_priority = None for widget in self._toolbar_widget_groups: this_priority = widget[0] if last_priority is not None and this_priority - last_priority >= 10: self._create_separator(axis) public_widgets = widget[1].create(default_size=default_size) if public_widgets is not None: self._toolbar_widgets.update(public_widgets) last_priority = this_priority def _create_separator(self, axis): if axis == ui.ToolBarAxis.X: ui.Line(width=1, name="separator", alignment=ui.Alignment.LEFT) else: ui.Line(height=1, name="separator", alignment=ui.Alignment.TOP) def subscribe_grab_mouse_pressed(self, function: Callable[[int, "weakref.ref"], None]): if self._grab_stack: self._grab_stack.set_mouse_pressed_fn(function) def _create_grab(self, axis): grab_area_size = 20 if axis == ui.ToolBarAxis.X: self._grab_stack = ui.HStack(width=grab_area_size) else: self._grab_stack = ui.VStack(height=grab_area_size) with self._grab_stack: if axis == ui.ToolBarAxis.X: ui.Spacer(width=5) ui.Line(name="grab", width=5, alignment=ui.Alignment.LEFT) ui.Line(name="grab", width=5, alignment=ui.Alignment.LEFT) ui.Line(name="grab", width=5, alignment=ui.Alignment.LEFT) ui.Spacer(width=3) else: ui.Spacer(height=5) ui.Line(name="grab", height=5, alignment=ui.Alignment.TOP) ui.Line(name="grab", height=5, alignment=ui.Alignment.TOP) ui.Line(name="grab", height=5, alignment=ui.Alignment.TOP) ui.Spacer(height=3) def add_custom_select_type(self, entry_name: str, selection_types: list): self._builtin_tools.add_custom_select_type(entry_name, selection_types) def remove_custom_select(self, entry_name): self._builtin_tools.remove_custom_select(entry_name)
10,132
Python
37.973077
124
0.606001
omniverse-code/kit/exts/omni.kit.widget.toolbar/omni/kit/widget/toolbar/hotkey.py
# 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. # from __future__ import annotations from typing import Callable import carb.events import carb.input import omni.appwindow import omni.kit.actions.core import omni.kit.app class Hotkey: def __init__( self, action_name: str, hotkey: carb.input.KeyboardInput, on_action_fn: Callable[[], None], hotkey_enabled_fn: Callable[[], None], modifiers: int = 0, on_hotkey_changed_fn: Callable[[str], None] = None, ): self._action_registry = omni.kit.actions.core.get_action_registry() self._settings = carb.settings.get_settings() self._action_name = action_name self._hotkey = hotkey self._modifiers = modifiers self._on_hotkey_changed_fn = on_hotkey_changed_fn self._registered_hotkey = None self._manager = omni.kit.app.get_app().get_extension_manager() self._extension_name = omni.ext.get_extension_name(self._manager.get_extension_id_by_module(__name__)) def action_trigger(): if not hotkey_enabled_fn(): return if on_action_fn: on_action_fn() # Register a test action that invokes a Python function. self._action = self._action_registry.register_action( self._extension_name, action_name, lambda *_: action_trigger(), display_name=action_name, tag="Toolbar", ) self._hooks = self._manager.subscribe_to_extension_enable( lambda _: self._register_hotkey(), lambda _: self._unregister_hotkey(), ext_name="omni.kit.hotkeys.core", hook_name=f"toolbar hotkey {action_name} listener", ) def clean(self): self._unregister_hotkey() self._action_registry.deregister_action(self._action) self._hooks = None self._on_hotkey_changed_fn = None def get_as_string(self, default:str): if self._registered_hotkey: return self._registered_hotkey.key_text return default def _on_hotkey_changed(self, event: carb.events.IEvent): from omni.kit.hotkeys.core import KeyCombination if ( event.payload["hotkey_ext_id"] == self._extension_name and event.payload["action_ext_id"] == self._extension_name and event.payload["action_id"] == self._action_name ): new_key = event.payload["key"] # refresh _registered_hotkey with newly registered key? hotkey_combo = KeyCombination(new_key) self._registered_hotkey = self._hotkey_registry.get_hotkey(self._extension_name, hotkey_combo) if self._on_hotkey_changed_fn: self._on_hotkey_changed_fn(new_key) def _register_hotkey(self): try: from omni.kit.hotkeys.core import HOTKEY_CHANGED_EVENT, KeyCombination, get_hotkey_registry self._hotkey_registry = get_hotkey_registry() hotkey_combo = KeyCombination(self._hotkey, self._modifiers) self._registered_hotkey = self._hotkey_registry.register_hotkey( self._extension_name, hotkey_combo, self._extension_name, self._action_name ) event_stream = omni.kit.app.get_app().get_message_bus_event_stream() self._change_event_sub = event_stream.create_subscription_to_pop_by_type( HOTKEY_CHANGED_EVENT, self._on_hotkey_changed ) except ImportError: # pragma: no cover pass def _unregister_hotkey(self): if not self._registered_hotkey or not self._hotkey_registry: return try: self._hotkey_registry.deregister_hotkey(self._registered_hotkey) self._registered_hotkey = None self._change_event_sub = None except Exception: # pragma: no cover pass
4,357
Python
34.430894
110
0.620151
omniverse-code/kit/exts/omni.kit.widget.toolbar/omni/kit/widget/toolbar/builtin_tools/play_button_group.py
# Copyright (c) 2020, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. # import carb.dictionary import carb.settings import omni.timeline import omni.ui as ui from carb.input import KeyboardInput as Key from omni.kit.commands import execute from omni.kit.widget.toolbar.hotkey import Hotkey from omni.kit.widget.toolbar.widget_group import WidgetGroup from .models.timeline_model import TimelinePlayPauseModel PLAY_TOOL_NAME = "Play" PAUSE_TOOL_NAME = "Pause" class PlayButtonGroup(WidgetGroup): PLAY_ANIMATIONS_SETTING = "/app/player/playAnimations" PLAY_AUDIO_SETTING = "/app/player/audio/enabled" PLAY_SIMULATIONS_SETTING = "/app/player/playSimulations" PLAY_COMPUTEGRAPH_SETTING = "/app/player/playComputegraph" all_settings_paths = [ PLAY_ANIMATIONS_SETTING, PLAY_AUDIO_SETTING, PLAY_SIMULATIONS_SETTING, PLAY_COMPUTEGRAPH_SETTING, ] def __init__(self): super().__init__() self._play_button = None self._play_hotkey = None self._stop_button = None self._settings = carb.settings.get_settings() self._dict = carb.dictionary.get_dictionary() self._timeline_play_pause_model = TimelinePlayPauseModel() self._timeline = omni.timeline.get_timeline_interface() self._settings.set_default_bool(self.PLAY_ANIMATIONS_SETTING, True) self._settings.set_default_bool(self.PLAY_AUDIO_SETTING, True) self._settings.set_default_bool(self.PLAY_SIMULATIONS_SETTING, True) self._settings.set_default_bool(self.PLAY_COMPUTEGRAPH_SETTING, True) stream = self._timeline.get_timeline_event_stream() self._sub = stream.create_subscription_to_pop(self._on_timeline_event) self._register_context_menu() self._show_menu_task = None self._visible = True def clean(self): super().clean() self._sub = None if self._timeline_play_pause_model: self._timeline_play_pause_model.clean() self._timeline_play_pause_model = None self._play_button = None self._stop_button = None self._animations_menu = None self._audio_menu = None self._simulations_menu = None self._compute_graph_menu = None self._play_filter_menu = None self._filter_menu = None self._sep_menu = None self._sep_menu2 = None self._select_all_menu = None if self._show_menu_task: # pragma: no cover self._show_menu_task.cancel() self._show_menu_task = None if self._play_hotkey: self._play_hotkey.clean() self._play_hotkey = None self._visible = True def get_style(self): style = { "Button.Image::play": {"image_url": "${glyphs}/toolbar_play.svg"}, "Button.Image::play:checked": {"image_url": "${glyphs}/toolbar_pause.svg"}, "Button.Image::stop": {"image_url": "${glyphs}/toolbar_stop.svg"}, } return style def create(self, default_size): # Build Play button self._play_button = ui.ToolButton( model=self._timeline_play_pause_model, name="play", tooltip=f"{PLAY_TOOL_NAME} ('Space')", width=default_size, height=default_size, mouse_pressed_fn=lambda x, y, b, _: self._on_mouse_pressed(b, "play"), mouse_released_fn=lambda x, y, b, _: self._on_mouse_released(b), checked=self._timeline_play_pause_model.get_value_as_bool(), ) def on_play_hotkey_changed(hotkey: str): if self._play_button: self._play_button.tooltip = f"{PLAY_TOOL_NAME} ({hotkey})" # Assign Play button Hotkey self._play_hotkey = Hotkey( "toolbar::play", Key.SPACE, lambda: self._timeline_play_pause_model.set_value(not self._timeline_play_pause_model.get_value_as_bool()), lambda: self._play_button is not None and self._play_button.enabled and self._is_in_context(), on_hotkey_changed_fn=lambda hotkey: on_play_hotkey_changed(hotkey), ) self._visible = True def on_stop_clicked(*_): self._acquire_toolbar_context() execute("ToolbarStopButtonClicked") self._stop_button = ui.Button( name="stop", tooltip="Stop", width=default_size, height=default_size, visible=False, clicked_fn=on_stop_clicked, ) return {"play": self._play_button, "stop": self._stop_button} def _on_setting_changed(self, item, event_type, menu_item): # pragma: no cover menu_item.checked = self._dict.get(item) def _on_timeline_event(self, e): if e.type == int(omni.timeline.TimelineEventType.PLAY): if self._play_button: self._play_button.set_tooltip(f"{PAUSE_TOOL_NAME} ({self._play_hotkey.get_as_string('Space')})") if self._stop_button: self._stop_button.visible = self._visible if e.type == int(omni.timeline.TimelineEventType.PAUSE): if self._play_button: self._play_button.set_tooltip(f"{PLAY_TOOL_NAME} ({self._play_hotkey.get_as_string('Space')})") if e.type == int(omni.timeline.TimelineEventType.STOP): if self._stop_button: self._stop_button.visible = False if self._play_button: self._play_button.set_tooltip(f"{PLAY_TOOL_NAME} ({self._play_hotkey.get_as_string('Space')})") if hasattr(omni.timeline.TimelineEventType, 'DIRECTOR_CHANGED') and\ e.type == int(omni.timeline.TimelineEventType.DIRECTOR_CHANGED): # pragma: no cover self._visible = not e.payload['hasDirector'] if self._stop_button: self._stop_button.visible = self._visible if self._play_button: self._play_button.visible = self._visible def _on_filter_changed(self, filter_setting, enabled): # pragma: no cover execute("ToolbarPlayFilterChecked", setting_path=filter_setting, enabled=enabled) def _select_all(self): # pragma: no cover execute("ToolbarPlayFilterSelectAll", settings=self.all_settings_paths) def _register_context_menu(self): context_menu = omni.kit.context_menu.get_instance() def is_button(objects: dict, button_name: str): # pragma: no cover return objects.get("widget_name", None) == button_name def create_menu_entry(name, setting_path): menu = { "name": name, "show_fn": [lambda object: is_button(object, "play")], "onclick_fn": lambda object: self._on_filter_changed( setting_path, not self._settings.get(setting_path) ), "checked_fn": lambda object: self._settings.get(setting_path), } return omni.kit.context_menu.add_menu(menu, "play", "omni.kit.widget.toolbar") def create_seperator(name=""): menu = { "name": name, "show_fn": [lambda object: is_button(object, "play")], } return omni.kit.context_menu.add_menu(menu, "play", "omni.kit.widget.toolbar") if context_menu: menu = { "name": "Filter", "show_fn": [lambda object: is_button(object, "play")], "enabled_fn": lambda object: False, } self._filter_menu = omni.kit.context_menu.add_menu(menu, "play", "omni.kit.widget.toolbar") self._sep_menu = create_seperator("sep/") self._animations_menu = create_menu_entry("Animation", self.PLAY_ANIMATIONS_SETTING) self._audio_menu = create_menu_entry("Audio", self.PLAY_AUDIO_SETTING) self._simulations_menu = create_menu_entry("Simulations", self.PLAY_SIMULATIONS_SETTING) self._compute_graph_menu = create_menu_entry("OmniGraph", self.PLAY_COMPUTEGRAPH_SETTING) self._sep_menu2 = create_seperator("sep2/") menu = { "name": "Select All", "show_fn": [lambda object: is_button(object, "play")], "onclick_fn": lambda object: self._select_all(), } self._select_all_menu = omni.kit.context_menu.add_menu(menu, "play", "omni.kit.widget.toolbar")
8,842
Python
40.32243
119
0.604275
omniverse-code/kit/exts/omni.kit.widget.toolbar/omni/kit/widget/toolbar/builtin_tools/builtin_tools.py
# Copyright (c) 2020, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. # import carb.dictionary import carb.settings from .select_button_group import SelectButtonGroup from .snap_button_group import LegacySnapButtonGroup from .transform_button_group import TransformButtonGroup from .play_button_group import PlayButtonGroup import typing if typing.TYPE_CHECKING: # pragma: no cover from ..toolbar import Toolbar SELECT_BUTTON_ENABLED_SETTING_PATH = "/exts/omni.kit.widget.toolbar/SelectionButton/enabled" TRANSFORM_BUTTON_ENABLED_SETTING_PATH = "/exts/omni.kit.widget.toolbar/TransformButton/enabled" PLAY_BUTTON_ENABLED_SETTING_PATH = "/exts/omni.kit.widget.toolbar/PlayButton/enabled" LEGACY_SNAP_BUTTON_ENABLED_SETTING_PATH_WINDOW = "/exts/omni.kit.window.toolbar/legacySnapButton/enabled" LEGACY_SNAP_BUTTON_ENABLED_SETTING_PATH_WIDGET = "/exts/omni.kit.widget.toolbar/legacySnapButton/enabled" class BuiltinTools: def __init__(self, toolbar: "Toolbar"): self._dict = carb.dictionary.get_dictionary() self._settings = carb.settings.get_settings() self._sub_window = self._settings.subscribe_to_node_change_events( LEGACY_SNAP_BUTTON_ENABLED_SETTING_PATH_WINDOW, self._on_legacy_snap_setting_changed_window ) self._toolbar = toolbar self._select_button_group = None if self._settings.get(SELECT_BUTTON_ENABLED_SETTING_PATH): self._select_button_group = SelectButtonGroup() toolbar.add_widget(self._select_button_group, 0) self._transform_button_group = None if self._settings.get(TRANSFORM_BUTTON_ENABLED_SETTING_PATH): self._transform_button_group = TransformButtonGroup() toolbar.add_widget(self._transform_button_group, 1) self._snap_button_group = None if self._settings.get(LEGACY_SNAP_BUTTON_ENABLED_SETTING_PATH_WIDGET): self._add_snap_button() self._play_button_group = None if self._settings.get(PLAY_BUTTON_ENABLED_SETTING_PATH): self._play_button_group = PlayButtonGroup() toolbar.add_widget(self._play_button_group, 21) self._sub_widget = self._settings.subscribe_to_node_change_events( LEGACY_SNAP_BUTTON_ENABLED_SETTING_PATH_WIDGET, self._on_legacy_snap_setting_changed ) def destroy(self): if self._select_button_group: self._toolbar.remove_widget(self._select_button_group) self._select_button_group.clean() self._select_button_group = None if self._transform_button_group: self._toolbar.remove_widget(self._transform_button_group) self._transform_button_group.clean() self._transform_button_group = None if self._snap_button_group: self._remove_snap_button() if self._play_button_group: self._toolbar.remove_widget(self._play_button_group) self._play_button_group.clean() self._play_button_group = None if self._sub_window: self._settings.unsubscribe_to_change_events(self._sub_window) self._sub_window = None if self._sub_widget: self._settings.unsubscribe_to_change_events(self._sub_widget) self._sub_widget = None def __del__(self): self.destroy() def _add_snap_button(self): self._snap_button_group = LegacySnapButtonGroup() self._toolbar.add_widget(self._snap_button_group, 11) def _remove_snap_button(self): self._toolbar.remove_widget(self._snap_button_group) self._snap_button_group.clean() self._snap_button_group = None def _on_legacy_snap_setting_changed_window(self, *args, **kwargs): """ If the old setting is set, we forward it into the new settings. """ enabled_legacy_snap = self._settings.get(LEGACY_SNAP_BUTTON_ENABLED_SETTING_PATH_WINDOW) if enabled_legacy_snap is not None: carb.log_warn( 'Deprecated, please use "/exts/omni.kit.widget.toolbar/legacySnapButton/enabled" setting' ) self._settings.set(LEGACY_SNAP_BUTTON_ENABLED_SETTING_PATH_WIDGET, enabled_legacy_snap) def _on_legacy_snap_setting_changed(self, *args, **kwargs): enabled_legacy_snap = self._settings.get(LEGACY_SNAP_BUTTON_ENABLED_SETTING_PATH_WIDGET) if self._snap_button_group is None and enabled_legacy_snap: self._add_snap_button() elif self._snap_button_group is not None and not enabled_legacy_snap: self._remove_snap_button() def add_custom_select_type(self, entry_name: str, selection_types: list): self._select_button_group.add_custom_select_type(entry_name, selection_types) def remove_custom_select(self, entry_name): self._select_button_group.remove_custom_select(entry_name)
5,263
Python
41.796748
105
0.67984
omniverse-code/kit/exts/omni.kit.widget.toolbar/omni/kit/widget/toolbar/builtin_tools/transform_button_group.py
# Copyright (c) 2020, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. # import carb.input import carb.dictionary import carb.settings import omni.kit.context_menu import omni.ui as ui from carb.input import KeyboardInput as Key from omni.kit.widget.toolbar.hotkey import Hotkey from omni.kit.widget.toolbar.widget_group import WidgetGroup from .models.transform_mode_model import LocalGlobalTransformModeModel, TransformModeModel MOVE_TOOL_NAME = "Move" ROTATE_TOOL_NAME = "Rotate" SCALE_TOOL_NAME = "Scale" class TransformButtonGroup(WidgetGroup): TRANSFORM_MOVE_MODE_SETTING = "/app/transform/moveMode" TRANSFORM_ROTATE_MODE_SETTING = "/app/transform/rotateMode" def __init__(self): super().__init__() self._input = carb.input.acquire_input_interface() self._settings = carb.settings.get_settings() self._settings.set_default_string(TransformModeModel.TRANSFORM_OP_SETTING, TransformModeModel.TRANSFORM_OP_MOVE) self._settings.set_default_string( self.TRANSFORM_MOVE_MODE_SETTING, LocalGlobalTransformModeModel.TRANSFORM_MODE_GLOBAL ) self._settings.set_default_string( self.TRANSFORM_ROTATE_MODE_SETTING, LocalGlobalTransformModeModel.TRANSFORM_MODE_GLOBAL ) self._move_op_model = LocalGlobalTransformModeModel( op=TransformModeModel.TRANSFORM_OP_MOVE, op_space_setting_path=self.TRANSFORM_MOVE_MODE_SETTING ) self._rotate_op_model = LocalGlobalTransformModeModel( op=TransformModeModel.TRANSFORM_OP_ROTATE, op_space_setting_path=self.TRANSFORM_ROTATE_MODE_SETTING ) self._scale_op_model = TransformModeModel(TransformModeModel.TRANSFORM_OP_SCALE) def on_hotkey_changed(hotkey: str, button, tool_name: str): button.tooltip = f"{tool_name} ({hotkey})" self._move_hotkey = Hotkey( "toolbar::move", Key.W, lambda: self._move_op_model.set_value(not self._move_op_model.get_value_as_bool()), lambda: self._move_button.enabled and self._is_in_context() and self._input.get_mouse_value(None, carb.input.MouseInput.RIGHT_BUTTON) == 0, # when RMB is down, it's possible viewport WASD navigation is going on, and don't trigger it if W is pressed on_hotkey_changed_fn=lambda hotkey: on_hotkey_changed(hotkey, self._move_button, MOVE_TOOL_NAME), ) self._rotate_hotkey = Hotkey( "toolbar::rotate", Key.E, lambda: self._rotate_op_model.set_value(not self._rotate_op_model.get_value_as_bool()), lambda: self._rotate_button.enabled and self._is_in_context() and self._input.get_mouse_value(None, carb.input.MouseInput.RIGHT_BUTTON) == 0, on_hotkey_changed_fn=lambda hotkey: on_hotkey_changed(hotkey, self._rotate_button, ROTATE_TOOL_NAME), ) self._scale_hotkey = Hotkey( "toolbar::scale", Key.R, lambda: self._scale_op_model.set_value(True), lambda: self._scale_button.enabled and self._is_in_context(), on_hotkey_changed_fn=lambda hotkey: on_hotkey_changed(hotkey, self._scale_button, SCALE_TOOL_NAME), ) self._register_context_menu() def get_style(self): style = { "Button.Image::move_op_global": {"image_url": "${glyphs}/toolbar_move_global.svg"}, "Button.Image::move_op_local": {"image_url": "${glyphs}/toolbar_move_local.svg"}, "Button.Image::rotate_op_global": {"image_url": "${glyphs}/toolbar_rotate_global.svg"}, "Button.Image::rotate_op_local": {"image_url": "${glyphs}/toolbar_rotate_local.svg"}, "Button.Image::scale_op": {"image_url": "${glyphs}/toolbar_scale.svg"}, } return style def create(self, default_size): self._sub_move, self._move_button = self._create_local_global_button( self._move_op_model, f"{MOVE_TOOL_NAME} ({self._move_hotkey.get_as_string('W')})", "move_op", self.TRANSFORM_MOVE_MODE_SETTING, "move_op_global", "move_op_local", default_size, ) self._sub_rotate, self._rotate_button = self._create_local_global_button( self._rotate_op_model, f"{ROTATE_TOOL_NAME} ({self._rotate_hotkey.get_as_string('E')})", "rotate_op", self.TRANSFORM_ROTATE_MODE_SETTING, "rotate_op_global", "rotate_op_local", default_size, ) self._scale_button = ui.ToolButton( model=self._scale_op_model, name="scale_op", tooltip=f"{SCALE_TOOL_NAME} ({self._scale_hotkey.get_as_string('R')})", width=default_size, height=default_size, mouse_pressed_fn=lambda *_: self._acquire_toolbar_context(), ) return {"move_op": self._move_button, "rotate_op": self._rotate_button, "scale_op": self._scale_button} def clean(self): super().clean() self._move_button = None self._rotate_button = None self._scale_button = None self._sub_move = None self._sub_rotate = None self._move_op_model.clean() self._move_op_model = None self._rotate_op_model.clean() self._rotate_op_model = None self._scale_op_model.clean() self._scale_op_model = None self._move_hotkey.clean() self._move_hotkey = None self._rotate_hotkey.clean() self._rotate_hotkey = None self._scale_hotkey.clean() self._scale_hotkey = None self._move_global_menu_entry = None self._move_local_menu_entry = None self._rotate_global_menu_entry = None self._rotate_local_menu_entry = None def _get_op_button_name(self, model, global_name, local_name): if model.get_op_space_mode() == LocalGlobalTransformModeModel.TRANSFORM_MODE_GLOBAL: return global_name else: # pragma: no cover return local_name def _create_local_global_button( self, op_model, tooltip, button_name, op_setting_path, global_name, local_name, default_size ): op_button = ui.ToolButton( name=self._get_op_button_name(op_model, global_name, local_name), model=op_model, tooltip=tooltip, width=default_size, height=default_size, mouse_pressed_fn=lambda x, y, b, _: self._on_mouse_pressed(b, button_name), mouse_released_fn=lambda x, y, b, _: self._on_mouse_released(b), checked=op_model.get_value_as_bool(), ) def on_op_button_value_change(model): op_button.name = self._get_op_button_name(model, global_name, local_name) return op_model.subscribe_value_changed_fn(on_op_button_value_change), op_button def _register_context_menu(self): context_menu = omni.kit.context_menu.get_instance() def is_button(objects: dict, button_name: str): # pragma: no cover return objects.get("widget_name", None) == button_name def on_mode(objects: dict, op_setting_path: str, desired_value): # pragma: no cover self._settings.set(op_setting_path, desired_value) def checked(objects: dict, op_setting_path: str, desired_value: str): # pragma: no cover return self._settings.get(op_setting_path) == desired_value if context_menu: menu = { "name": "Global (W)", "show_fn": [lambda object: is_button(object, "move_op")], "onclick_fn": lambda object: on_mode( object, self.TRANSFORM_MOVE_MODE_SETTING, LocalGlobalTransformModeModel.TRANSFORM_MODE_GLOBAL ), "checked_fn": lambda object: checked( object, self.TRANSFORM_MOVE_MODE_SETTING, LocalGlobalTransformModeModel.TRANSFORM_MODE_GLOBAL ), } self._move_global_menu_entry = omni.kit.context_menu.add_menu(menu, "move_op", "omni.kit.widget.toolbar") menu = { "name": "Local (W)", "show_fn": [lambda object: is_button(object, "move_op")], "onclick_fn": lambda object: on_mode( object, self.TRANSFORM_MOVE_MODE_SETTING, LocalGlobalTransformModeModel.TRANSFORM_MODE_LOCAL ), "checked_fn": lambda object: checked( object, self.TRANSFORM_MOVE_MODE_SETTING, LocalGlobalTransformModeModel.TRANSFORM_MODE_LOCAL ), } self._move_local_menu_entry = omni.kit.context_menu.add_menu(menu, "move_op", "omni.kit.widget.toolbar") menu = { "name": "Global (E)", "show_fn": [lambda object: is_button(object, "rotate_op")], "onclick_fn": lambda object: on_mode( object, self.TRANSFORM_ROTATE_MODE_SETTING, LocalGlobalTransformModeModel.TRANSFORM_MODE_GLOBAL ), "checked_fn": lambda object: checked( object, self.TRANSFORM_ROTATE_MODE_SETTING, LocalGlobalTransformModeModel.TRANSFORM_MODE_GLOBAL ), } self._rotate_global_menu_entry = omni.kit.context_menu.add_menu( menu, "rotate_op", "omni.kit.widget.toolbar" ) menu = { "name": "Local (E)", "show_fn": [lambda object: is_button(object, "rotate_op")], "onclick_fn": lambda object: on_mode( object, self.TRANSFORM_ROTATE_MODE_SETTING, LocalGlobalTransformModeModel.TRANSFORM_MODE_LOCAL ), "checked_fn": lambda object: checked( object, self.TRANSFORM_ROTATE_MODE_SETTING, LocalGlobalTransformModeModel.TRANSFORM_MODE_LOCAL ), } self._rotate_local_menu_entry = omni.kit.context_menu.add_menu(menu, "rotate_op", "omni.kit.widget.toolbar")
10,527
Python
43.8
127
0.605016
omniverse-code/kit/exts/omni.kit.widget.toolbar/omni/kit/widget/toolbar/builtin_tools/snap_button_group.py
# Copyright (c) 2020, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. # import carb.dictionary import carb.settings import omni.kit.context_menu import omni.ui as ui from omni.kit.widget.toolbar.widget_group import WidgetGroup from .models.setting_model import BoolSettingModel, FloatSettingModel class LegacySnapButtonGroup(WidgetGroup): SNAP_ENABLED_SETTING = "/app/viewport/snapEnabled" SNAP_MOVE_X_SETTING = "/persistent/app/viewport/stepMove/x" SNAP_MOVE_Y_SETTING = "/persistent/app/viewport/stepMove/y" SNAP_MOVE_Z_SETTING = "/persistent/app/viewport/stepMove/z" SNAP_ROTATE_SETTING = "/persistent/app/viewport/stepRotate" SNAP_SCALE_SETTING = "/persistent/app/viewport/stepScale" SNAP_TO_SURFACE_SETTING = "/persistent/app/viewport/snapToSurface" def __init__(self): super().__init__() self._settings = carb.settings.get_settings() self._settings.set_default_bool(self.SNAP_ENABLED_SETTING, False) self._settings.set_default_float(self.SNAP_MOVE_X_SETTING, 50.0) self._settings.set_default_float(self.SNAP_MOVE_Y_SETTING, 50.0) self._settings.set_default_float(self.SNAP_MOVE_Z_SETTING, 50.0) self._settings.set_default_float(self.SNAP_ROTATE_SETTING, 1.0) self._settings.set_default_float(self.SNAP_SCALE_SETTING, 1.0) self._dict = carb.dictionary.get_dictionary() self._snap_setting_model = BoolSettingModel(self.SNAP_ENABLED_SETTING, False) self._snap_move_x_settings_model = FloatSettingModel(self.SNAP_MOVE_X_SETTING) self._snap_move_y_settings_model = FloatSettingModel(self.SNAP_MOVE_Y_SETTING) self._snap_move_z_settings_model = FloatSettingModel(self.SNAP_MOVE_Z_SETTING) self._snap_rotate_settings_model = FloatSettingModel(self.SNAP_ROTATE_SETTING) self._snap_scale_settings_model = FloatSettingModel(self.SNAP_SCALE_SETTING) self._create_snap_increment_setting_window() self._register_context_menu() self._show_menu_task = None self._button = None def clean(self): super().clean() self._snap_setting_model.clean() self._snap_setting_model = None # workaround delayed toolbar rebuild after group is destroyed and access null model if self._button: self._button.model = ui.SimpleBoolModel() self._button = None self._snap_move_x_settings_model.clean() self._snap_move_x_settings_model = None self._snap_move_y_settings_model.clean() self._snap_move_y_settings_model = None self._snap_move_z_settings_model.clean() self._snap_move_z_settings_model = None self._snap_rotate_settings_model.clean() self._snap_rotate_settings_model = None self._snap_scale_settings_model.clean() self._snap_scale_settings_model = None self._snap_increment_setting_window = None self._snap_setting_menu = None self._snap_settings = None self._snap_to_increment_menu = None self._snap_to_face_menu = None if self._show_menu_task: # pragma: no cover self._show_menu_task.cancel() self._show_menu_task = None self._snap_settings_menu_entry = None self._snap_to_increment_menu_entry = None self._snap_to_face_menu_entry = None def get_style(self): style = {"Button.Image::snap": {"image_url": "${glyphs}/toolbar_snap.svg"}} return style def create(self, default_size): self._button = ui.ToolButton( model=self._snap_setting_model, name="snap", tooltip="Snap", width=default_size, height=default_size, mouse_pressed_fn=lambda x, y, b, _: self._on_mouse_pressed(b, "snap"), mouse_released_fn=lambda x, y, b, _: self._on_mouse_released(b), checked=self._snap_setting_model.get_value_as_bool(), ) return {"snap": self._button} def _on_snap_on_off(self, model): # pragma: no cover (Never called anywhere it seems) self._snap_settings.enabled = self._snap_setting_model.get_value_as_bool() def _on_snap_setting_change(self, item, event_type): # pragma: no cover (Never called anywhere it seems) snap_to_face = self._dict.get(item) self._snap_to_increment_menu.checked = not snap_to_face self._snap_to_face_menu.checked = snap_to_face self._snap_settings.enabled = not snap_to_face def _on_snap_setting_menu_clicked(self, snap_to_face): # pragma: no cover self._settings.set(self.SNAP_TO_SURFACE_SETTING, snap_to_face) def _on_show_snap_increment_setting_window(self): # pragma: no cover self._snap_increment_setting_window.visible = True def _create_snap_increment_setting_window(self): self._snap_increment_setting_window = ui.Window( "Snap Increment Settings Menu", width=400, height=0, flags=ui.WINDOW_FLAGS_NO_RESIZE | ui.WINDOW_FLAGS_NO_SCROLLBAR, visible=False, ) with self._snap_increment_setting_window.frame: with ui.VStack(spacing=8, height=0, name="frame_v_stack"): ui.Label("Snap Settings - Increments", enabled=False) ui.Separator() with ui.HStack(): with ui.HStack(width=120): ui.Label("Position", width=50) ui.Spacer() all_axis = ["X", "Y", "Z"] all_axis_model = { "X": self._snap_move_x_settings_model, "Y": self._snap_move_y_settings_model, "Z": self._snap_move_z_settings_model, } colors = {"X": 0xFF5555AA, "Y": 0xFF76A371, "Z": 0xFFA07D4F} for axis in all_axis: with ui.HStack(): with ui.ZStack(width=15): ui.Rectangle( width=15, height=20, style={ "background_color": colors[axis], "border_radius": 3, "corner_flag": ui.CornerFlag.LEFT, }, ) ui.Label(axis, alignment=ui.Alignment.CENTER) ui.FloatDrag(model=all_axis_model[axis], min=0, max=1000000, step=0.01) ui.Circle(width=20, radius=3.5, size_policy=ui.CircleSizePolicy.FIXED) with ui.HStack(): with ui.HStack(width=120): ui.Label("Rotation", width=50) ui.Spacer() ui.FloatDrag(model=self._snap_rotate_settings_model, min=0, max=1000000, step=0.01) with ui.HStack(): with ui.HStack(width=120): ui.Label("Scale", width=50) ui.Spacer() ui.FloatDrag(model=self._snap_scale_settings_model, min=0, max=1000000, step=0.01) def _register_context_menu(self): context_menu = omni.kit.context_menu.get_instance() def is_button(objects: dict, button_name: str): # pragma: no cover return objects.get("widget_name", None) == button_name if context_menu: menu = { "name": f"Snap Settings {ui.get_custom_glyph_code('${glyphs}/cog.svg')}", "show_fn": [lambda object: is_button(object, "snap")], "onclick_fn": lambda object: self._on_show_snap_increment_setting_window(), "enabled_fn": lambda object: not self._settings.get(self.SNAP_TO_SURFACE_SETTING), } self._snap_settings_menu_entry = omni.kit.context_menu.add_menu(menu, "snap", "omni.kit.widget.toolbar") menu = { "name": "Snap to Increment", "show_fn": [lambda object: is_button(object, "snap")], "onclick_fn": lambda object: self._on_snap_setting_menu_clicked(snap_to_face=False), "checked_fn": lambda object: not self._settings.get(self.SNAP_TO_SURFACE_SETTING), } self._snap_to_increment_menu_entry = omni.kit.context_menu.add_menu(menu, "snap", "omni.kit.widget.toolbar") menu = { "name": "Snap to Face", "show_fn": [lambda object: is_button(object, "snap")], "onclick_fn": lambda object: self._on_snap_setting_menu_clicked(snap_to_face=True), "checked_fn": lambda object: self._settings.get(self.SNAP_TO_SURFACE_SETTING), } self._snap_to_face_menu_entry = omni.kit.context_menu.add_menu(menu, "snap", "omni.kit.widget.toolbar")
9,363
Python
47.518134
120
0.583574
omniverse-code/kit/exts/omni.kit.widget.toolbar/omni/kit/widget/toolbar/builtin_tools/select_button_group.py
# Copyright (c) 2020, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. # import carb.input import omni.kit.context_menu import omni.ui as ui import pathlib from pxr import Kind from carb.input import KeyboardInput as Key from omni.kit.widget.toolbar.hotkey import Hotkey from omni.kit.widget.toolbar.widget_group import WidgetGroup from .models.select_mode_model import SelectModeModel from .models.select_no_kinds_model import SelectNoKindsModel from .models.select_include_ref_model import SelectIncludeRefModel from .models.transform_mode_model import TransformModeModel SELECT_PRIM_MODE_TOOL_NAME = "Prim" SELECT_MODEL_MODE_TOOL_NAME = "Model" SELECT_TOOL_NAME = "Select" LIGHT_TYPES = "type:CylinderLight;type:DiskLight;type:DistantLight;type:DomeLight;type:GeometryLight;type:Light;type:RectLight;type:SphereLight" EXTENSION_FOLDER_PATH = pathlib.Path( omni.kit.app.get_app().get_extension_manager().get_extension_path_by_module("omni.kit.widget.toolbar") ) SELECT_MODE_BUTTON_ENABLED_SETTING_PATH = "/exts/omni.kit.widget.toolbar/SelectionButton/SelectMode/enabled" class SelectButtonGroup(WidgetGroup): def __init__(self): super().__init__() self._input = carb.input.acquire_input_interface() self._select_mode_model = SelectModeModel() self._select_no_kinds_model = SelectNoKindsModel() self._select_include_ref_model = SelectIncludeRefModel() self._select_op_model = TransformModeModel(TransformModeModel.TRANSFORM_OP_SELECT) self._select_op_menu_entry = None self._custom_types = [] self._settings = carb.settings.get_settings() self._icon_path = str(EXTENSION_FOLDER_PATH / "data" / "icon") self._settings = carb.settings.get_settings() self._select_mode_button = None self._mode_hotkey = None if self._settings.get(SELECT_MODE_BUTTON_ENABLED_SETTING_PATH): def hotkey_change(): current_mode = self._select_mode_model.get_value_as_string() if current_mode == "models" or current_mode == "kind:model.ALL": self._select_mode_model.set_value("type:ALL") else: self._select_mode_model.set_value("kind:model.ALL") self._update_selection_mode_button() def on_select_mode_hotkey_changed(hotkey: str): self._select_mode_button.tooltip = self._get_select_mode_tooltip() self._mode_hotkey = Hotkey( "toolbar::select_mode", Key.T, hotkey_change, lambda: self._select_mode_button.enabled and self._is_in_context(), on_hotkey_changed_fn=on_select_mode_hotkey_changed, ) # only replace the tooltip part so that "Paint Select" registered from select brush can still have correct label def on_select_hotkey_changed(hotkey: str): self._select_op_button.tooltip = ( self._select_op_button.tooltip.rsplit("(", 1)[0] + f"({self._select_hotkey.get_as_string('Q')})" ) self._select_hotkey = Hotkey( "toolbar::select", Key.Q, lambda: self._select_op_button.model.set_value(True), lambda: self._select_op_button.enabled and self._is_in_context() and self._input.get_mouse_value(None, carb.input.MouseInput.RIGHT_BUTTON) == 0, on_hotkey_changed_fn=lambda hotkey: on_select_hotkey_changed(hotkey), ) self._sub_menu = [] self._register_context_menu() def get_style(self): style = { "Button.Image::select_mode": {"image_url": "${glyphs}/toolbar_select_prim.svg"}, "Button.Image::select_op_models": {"image_url": "${glyphs}/toolbar_select_models.svg"}, "Button.Image::select_op_prims": {"image_url": "${glyphs}/toolbar_select_prims.svg"}, "Button.Image::all_prim_types": {"image_url": f"{self._icon_path}/all_prim_types.svg"}, "Button.Image::meshes": {"image_url": f"{self._icon_path}/meshes.svg"}, "Button.Image::lights": {"image_url": f"{self._icon_path}/lights.svg"}, "Button.Image::cameras": {"image_url": f"{self._icon_path}/cameras.svg"}, "Button.Image::model_kinds": {"image_url": f"{self._icon_path}/model_kinds.svg"}, "Button.Image::assembly": {"image_url": f"{self._icon_path}/assembly.svg"}, "Button.Image::group": {"image_url": f"{self._icon_path}/group.svg"}, "Button.Image::component": {"image_url": f"{self._icon_path}/component.svg"}, "Button.Image::sub_component": {"image_url": f"{self._icon_path}/sub_component.svg"}, "Button.Image::payload_reference": {"image_url": f"{self._icon_path}/payload_reference.svg"}, "Button.Image::custom_kind": {"image_url": f"{self._icon_path}/custom_kind.svg"}, "Button.Image::custom_type": {"image_url": f"{self._icon_path}/custom_type.svg"}, } return style def create(self, default_size): def select_enabled(): # pragma: no cover (Unused, it's commened out below - I am just adding coverage! '^^) return True def on_select_mode_change(model): self._update_selection_mode_button() result = {} if self._settings.get(SELECT_MODE_BUTTON_ENABLED_SETTING_PATH): self._select_mode_button = ui.ToolButton( model=self._select_mode_model, name="select_mode", tooltip=self._get_select_mode_tooltip(), width=default_size, height=default_size, # checked=select_enabled, mouse_pressed_fn=lambda x, y, b, _: self._on_mouse_pressed(b, "select_mode"), mouse_released_fn=lambda x, y, b, _: self._on_mouse_released(b), ) self._model_changed_sub = self._select_mode_model.subscribe_value_changed_fn(on_select_mode_change) result["select_mode"] = self._select_mode_button with ui.ZStack(width=0, height=0): self._select_op_button = ui.ToolButton( model=self._select_op_model, name=self._get_select_op_button_name(self._select_mode_model), tooltip=self._get_select_tooltip(), width=default_size, height=default_size, checked=self._select_op_model.get_value_as_bool(), mouse_pressed_fn=lambda x, y, b, _: self._on_mouse_pressed(b, "select_op"), mouse_released_fn=lambda x, y, b, _: self._on_mouse_released(b), ) # Follow the pattern here (ZStack + _build_flyout_indicator) for other buttons if they want dynamic flyout indicator self._select_op_menu_sub = self._build_flyout_indicator(default_size, default_size, "select_op") result["select_op"] = self._select_op_button self._update_selection_mode_button() return result def clean(self): super().clean() self._select_mode_button = None self._select_op_button = None self._select_mode_model.clean() self._select_mode_model = None self._select_no_kinds_model.clean() self._select_no_kinds_model = None self._select_include_ref_model.clean() self._select_include_ref_model = None self._select_op_model.clean() self._select_op_model = None self._model_changed_sub = None if self._mode_hotkey: self._mode_hotkey.clean() self._mode_hotkey = None self._select_hotkey.clean() self._select_hotkey = None self._select_mode_menu_entry.release() self._select_mode_menu_entry = None if self._select_op_menu_entry: self._select_op_menu_entry.release() self._select_op_menu_entry = None self._select_op_menu_sub = None for menu in self._sub_menu: menu.release() self._sub_menu = [] def _get_select_op_button_name(self, model): return "select_op_prims" if model.get_value_as_bool() else "select_op_models" def _get_select_tooltip(self): return f"{SELECT_TOOL_NAME} ({self._select_hotkey.get_as_string('Q')})" def _get_select_mode_button_name(self): mode_name = { "type:ALL": "all_prim_types", "type:Mesh": "meshes", LIGHT_TYPES: "lights", "type:Camera": "cameras", "kind:model.ALL": "model_kinds", "kind:assembly": "assembly", "kind:group": "group", "kind:component": "component", "kind:subcomponent": "sub_component", "ref:reference;ref:payload": "custom_type", } mode = self._select_mode_model.get_value_as_string() if mode in mode_name: return mode_name[mode] else: # pragma: no cover if mode[:4] == "kind": return "custom_kind" else: return "custom_type" def _get_select_mode_tooltip(self): mode_data = { "type:ALL": "All Prim Types", "type:Mesh": "Meshes", LIGHT_TYPES: "Lights", "type:Camera": "Camera", "kind:model.ALL": "All Model Kinds", "kind:assembly": "Assembly", "kind:group": "Group", "kind:component": "Component", "kind:subcomponent": "Subcomponent", "ref:reference;ref:payload": "Subcomponent", } mode = self._select_mode_model.get_value_as_string() if mode in mode_data: tooltip = mode_data[mode] else: # pragma: no cover if mode[:4] == "kind": tooltip = "Custom Kind" else: tooltip = "Custom type" return tooltip + f" ({self._mode_hotkey.get_as_string('T')})" def _usd_kinds(self): return ["model", "assembly", "group", "component", "subcomponent"] def _enable_no_kinds_option(self, b): # pragma: no cover mode = self._select_mode_model.get_value_as_string() return mode[:4] == "kind" def _usd_kinds_display(self): # pragma: no cover return self._usd_kinds()[1:] def _plugin_kinds(self): all_kinds = set(Kind.Registry.GetAllKinds()) return all_kinds - set(self._usd_kinds()) def _create_selection_list(self, selections): results = "" delimiter = ";" first_selection = True for s in selections: if not first_selection: # pragma: no cover (This seemingly can never happen, since first_selection is initialized with True oO) first_selection = True else: results += delimiter results += s return results def _update_selection_mode_button(self): if self._select_mode_button: self._select_mode_button.name = self._get_select_mode_button_name() self._select_mode_button.tooltip = self._get_select_mode_tooltip() if self._select_op_button: self._select_op_button.name = self._get_select_op_button_name(self._select_mode_model) def _update_select_menu(self): for menu in self._sub_menu: menu.release() self._sub_menu = [] def create_menu_entry(name, value, add_hotkey=False): menu = { "name": name, "onclick_fn": lambda object: self._select_mode_model.set_value(value), "checked_fn": lambda object, name=name, value=value: self._select_mode_model.get_value_as_string() == value, "additional_kwargs": { "style": {"Menu.Item.CheckMark": {"image_url": omni.kit.context_menu.style.get_radio_mark_url()}} }, } if add_hotkey: menu["hotkey"] = (carb.input.KeyboardInput.T) return omni.kit.context_menu.add_menu(menu, "select_mode", "omni.kit.widget.toolbar") def create_header(header=""): menu = { "header": header, "name": "", } return omni.kit.context_menu.add_menu(menu, "select_mode", "omni.kit.widget.toolbar") self._sub_menu.append(create_header(header="Select by Type")) self._sub_menu.append(create_menu_entry("All Prim Types", "type:ALL", True)) self._sub_menu.append(create_menu_entry("Meshes", "type:Mesh")) self._sub_menu.append(create_menu_entry("Lights", LIGHT_TYPES)) self._sub_menu.append(create_menu_entry("Camera", "type:Camera")) if self._custom_types: for name, types in self._custom_types: self._sub_menu.append(create_menu_entry(name, types)) self._sub_menu.append(create_header(header="Select by Model Kind")) self._sub_menu.append(create_menu_entry("All Model Kinds", "kind:model.ALL")) self._sub_menu.append(create_menu_entry("Assembly", "kind:assembly")) self._sub_menu.append(create_menu_entry("Group", "kind:group")) self._sub_menu.append(create_menu_entry("Component", "kind:component")) self._sub_menu.append(create_menu_entry("Subcomponent", "kind:subcomponent")) plugin_kinds = self._plugin_kinds() if (len(plugin_kinds)) > 0: for k in plugin_kinds: # pragma: no cover self._sub_menu.append(create_menu_entry(str(k), str(key).capitalize(), f"kind:{k}")) self._sub_menu.append(create_header(header="")) menu = { "name": "Include Prims with no Kind", "onclick_fn": lambda object: self._select_no_kinds_model.set_value(not self._select_no_kinds_model.get_value_as_bool()), "checked_fn": lambda object: self._select_no_kinds_model.get_value_as_bool(), "enabled_fn": self._enable_no_kinds_option, } self._sub_menu.append(omni.kit.context_menu.add_menu(menu, "select_mode", "omni.kit.widget.toolbar")) menu = { "name": "Include References and Payloads", "onclick_fn": lambda object: self._select_include_ref_model.set_value(not self._select_include_ref_model.get_value_as_bool()), "checked_fn": lambda object: self._select_include_ref_model.get_value_as_bool(), "enabled_fn": self._enable_no_kinds_option, } self._sub_menu.append(omni.kit.context_menu.add_menu(menu, "select_mode", "omni.kit.widget.toolbar")) def _register_context_menu(self): context_menu = omni.kit.context_menu.get_instance() def is_button(objects: dict, button_name: str): # pragma: no cover return objects.get("widget_name", None) == button_name if context_menu: def on_clicked_select(): # pragma: no cover self._select_op_model.set_value(True) self._select_op_button.name = self._get_select_op_button_name(self._select_mode_model) self._select_op_button.set_tooltip(self._get_select_tooltip()) self._select_op_button.model = self._select_op_model menu = { "name": "Select", "show_fn": [lambda object: is_button(object, "select_op")], "onclick_fn": lambda object: on_clicked_select(), "checked_fn": lambda object: self._select_op_button.name == "select_op_prims" or self._select_op_button.name == "select_op_models", } self._select_mode_menu_entry = omni.kit.context_menu.add_menu(menu, "select_op", "omni.kit.widget.toolbar") if self._settings.get(SELECT_MODE_BUTTON_ENABLED_SETTING_PATH): menu = { "name": "Select Mode", "show_fn": [lambda object: is_button(object, "select_mode")], } self._select_op_menu_entry = omni.kit.context_menu.add_menu(menu, "select_mode", "omni.kit.widget.toolbar") self._update_select_menu() def add_custom_select_type(self, entry_name: str, selection_types: list): selection = [] for s in selection_types: selection.append(f"type:{s}") selection_string = self._create_selection_list(selection) self._custom_types.append((entry_name, selection_string)) self._update_select_menu() def remove_custom_select(self, entry_name): for index, (entry, selection_string) in enumerate(self._custom_types): if entry == entry_name: del self._custom_types[index] self._update_select_menu() return
17,097
Python
44.473404
144
0.592151