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
CesiumGS/cesium-omniverse/src/plugins/CesiumUsdSchemas/src/CesiumUsdSchemas/wrapTokens.cpp
// GENERATED FILE. DO NOT EDIT. #include <boost/python/class.hpp> #include ".//tokens.h" PXR_NAMESPACE_USING_DIRECTIVE namespace { // Helper to return a static token as a string. We wrap tokens as Python // strings and for some reason simply wrapping the token using def_readonly // bypasses to-Python conversion, leading to the error that there's no // Python type for the C++ TfToken type. So we wrap this functor instead. class _WrapStaticToken { public: _WrapStaticToken(const TfToken* token) : _token(token) { } std::string operator()() const { return _token->GetString(); } private: const TfToken* _token; }; template <typename T> void _AddToken(T& cls, const char* name, const TfToken& token) { cls.add_static_property(name, boost::python::make_function( _WrapStaticToken(&token), boost::python::return_value_policy< boost::python::return_by_value>(), boost::mpl::vector1<std::string>())); } } // anonymous void wrapCesiumTokens() { boost::python::class_<CesiumTokensType, boost::noncopyable> cls("Tokens", boost::python::no_init); _AddToken(cls, "cesiumAlpha", CesiumTokens->cesiumAlpha); _AddToken(cls, "cesiumAnchorAdjustOrientationForGlobeWhenMoving", CesiumTokens->cesiumAnchorAdjustOrientationForGlobeWhenMoving); _AddToken(cls, "cesiumAnchorDetectTransformChanges", CesiumTokens->cesiumAnchorDetectTransformChanges); _AddToken(cls, "cesiumAnchorGeoreferenceBinding", CesiumTokens->cesiumAnchorGeoreferenceBinding); _AddToken(cls, "cesiumAnchorHeight", CesiumTokens->cesiumAnchorHeight); _AddToken(cls, "cesiumAnchorLatitude", CesiumTokens->cesiumAnchorLatitude); _AddToken(cls, "cesiumAnchorLongitude", CesiumTokens->cesiumAnchorLongitude); _AddToken(cls, "cesiumAnchorPosition", CesiumTokens->cesiumAnchorPosition); _AddToken(cls, "cesiumBaseUrl", CesiumTokens->cesiumBaseUrl); _AddToken(cls, "cesiumCartographicPolygonBinding", CesiumTokens->cesiumCartographicPolygonBinding); _AddToken(cls, "cesiumCulledScreenSpaceError", CesiumTokens->cesiumCulledScreenSpaceError); _AddToken(cls, "cesiumDebugDisableGeometryPool", CesiumTokens->cesiumDebugDisableGeometryPool); _AddToken(cls, "cesiumDebugDisableGeoreferencing", CesiumTokens->cesiumDebugDisableGeoreferencing); _AddToken(cls, "cesiumDebugDisableMaterialPool", CesiumTokens->cesiumDebugDisableMaterialPool); _AddToken(cls, "cesiumDebugDisableMaterials", CesiumTokens->cesiumDebugDisableMaterials); _AddToken(cls, "cesiumDebugDisableTexturePool", CesiumTokens->cesiumDebugDisableTexturePool); _AddToken(cls, "cesiumDebugDisableTextures", CesiumTokens->cesiumDebugDisableTextures); _AddToken(cls, "cesiumDebugGeometryPoolInitialCapacity", CesiumTokens->cesiumDebugGeometryPoolInitialCapacity); _AddToken(cls, "cesiumDebugMaterialPoolInitialCapacity", CesiumTokens->cesiumDebugMaterialPoolInitialCapacity); _AddToken(cls, "cesiumDebugRandomColors", CesiumTokens->cesiumDebugRandomColors); _AddToken(cls, "cesiumDebugTexturePoolInitialCapacity", CesiumTokens->cesiumDebugTexturePoolInitialCapacity); _AddToken(cls, "cesiumDisplayName", CesiumTokens->cesiumDisplayName); _AddToken(cls, "cesiumEast", CesiumTokens->cesiumEast); _AddToken(cls, "cesiumEcefToUsdTransform", CesiumTokens->cesiumEcefToUsdTransform); _AddToken(cls, "cesiumEnableFogCulling", CesiumTokens->cesiumEnableFogCulling); _AddToken(cls, "cesiumEnableFrustumCulling", CesiumTokens->cesiumEnableFrustumCulling); _AddToken(cls, "cesiumEnforceCulledScreenSpaceError", CesiumTokens->cesiumEnforceCulledScreenSpaceError); _AddToken(cls, "cesiumExcludeSelectedTiles", CesiumTokens->cesiumExcludeSelectedTiles); _AddToken(cls, "cesiumForbidHoles", CesiumTokens->cesiumForbidHoles); _AddToken(cls, "cesiumFormat", CesiumTokens->cesiumFormat); _AddToken(cls, "cesiumGeoreferenceBinding", CesiumTokens->cesiumGeoreferenceBinding); _AddToken(cls, "cesiumGeoreferenceOriginHeight", CesiumTokens->cesiumGeoreferenceOriginHeight); _AddToken(cls, "cesiumGeoreferenceOriginLatitude", CesiumTokens->cesiumGeoreferenceOriginLatitude); _AddToken(cls, "cesiumGeoreferenceOriginLongitude", CesiumTokens->cesiumGeoreferenceOriginLongitude); _AddToken(cls, "cesiumInvertSelection", CesiumTokens->cesiumInvertSelection); _AddToken(cls, "cesiumIonAccessToken", CesiumTokens->cesiumIonAccessToken); _AddToken(cls, "cesiumIonAssetId", CesiumTokens->cesiumIonAssetId); _AddToken(cls, "cesiumIonServerApiUrl", CesiumTokens->cesiumIonServerApiUrl); _AddToken(cls, "cesiumIonServerApplicationId", CesiumTokens->cesiumIonServerApplicationId); _AddToken(cls, "cesiumIonServerBinding", CesiumTokens->cesiumIonServerBinding); _AddToken(cls, "cesiumIonServerUrl", CesiumTokens->cesiumIonServerUrl); _AddToken(cls, "cesiumLayer", CesiumTokens->cesiumLayer); _AddToken(cls, "cesiumLayers", CesiumTokens->cesiumLayers); _AddToken(cls, "cesiumLoadingDescendantLimit", CesiumTokens->cesiumLoadingDescendantLimit); _AddToken(cls, "cesiumMainThreadLoadingTimeLimit", CesiumTokens->cesiumMainThreadLoadingTimeLimit); _AddToken(cls, "cesiumMaximumCachedBytes", CesiumTokens->cesiumMaximumCachedBytes); _AddToken(cls, "cesiumMaximumLevel", CesiumTokens->cesiumMaximumLevel); _AddToken(cls, "cesiumMaximumScreenSpaceError", CesiumTokens->cesiumMaximumScreenSpaceError); _AddToken(cls, "cesiumMaximumSimultaneousTileLoads", CesiumTokens->cesiumMaximumSimultaneousTileLoads); _AddToken(cls, "cesiumMaximumTextureSize", CesiumTokens->cesiumMaximumTextureSize); _AddToken(cls, "cesiumMaximumZoomLevel", CesiumTokens->cesiumMaximumZoomLevel); _AddToken(cls, "cesiumMinimumLevel", CesiumTokens->cesiumMinimumLevel); _AddToken(cls, "cesiumMinimumZoomLevel", CesiumTokens->cesiumMinimumZoomLevel); _AddToken(cls, "cesiumNorth", CesiumTokens->cesiumNorth); _AddToken(cls, "cesiumOverlayRenderMethod", CesiumTokens->cesiumOverlayRenderMethod); _AddToken(cls, "cesiumPreloadAncestors", CesiumTokens->cesiumPreloadAncestors); _AddToken(cls, "cesiumPreloadSiblings", CesiumTokens->cesiumPreloadSiblings); _AddToken(cls, "cesiumProjectDefaultIonAccessToken", CesiumTokens->cesiumProjectDefaultIonAccessToken); _AddToken(cls, "cesiumProjectDefaultIonAccessTokenId", CesiumTokens->cesiumProjectDefaultIonAccessTokenId); _AddToken(cls, "cesiumRasterOverlayBinding", CesiumTokens->cesiumRasterOverlayBinding); _AddToken(cls, "cesiumRootTilesX", CesiumTokens->cesiumRootTilesX); _AddToken(cls, "cesiumRootTilesY", CesiumTokens->cesiumRootTilesY); _AddToken(cls, "cesiumSelectedIonServer", CesiumTokens->cesiumSelectedIonServer); _AddToken(cls, "cesiumShowCreditsOnScreen", CesiumTokens->cesiumShowCreditsOnScreen); _AddToken(cls, "cesiumSmoothNormals", CesiumTokens->cesiumSmoothNormals); _AddToken(cls, "cesiumSourceType", CesiumTokens->cesiumSourceType); _AddToken(cls, "cesiumSouth", CesiumTokens->cesiumSouth); _AddToken(cls, "cesiumSpecifyTileMatrixSetLabels", CesiumTokens->cesiumSpecifyTileMatrixSetLabels); _AddToken(cls, "cesiumSpecifyTilingScheme", CesiumTokens->cesiumSpecifyTilingScheme); _AddToken(cls, "cesiumSpecifyZoomLevels", CesiumTokens->cesiumSpecifyZoomLevels); _AddToken(cls, "cesiumStyle", CesiumTokens->cesiumStyle); _AddToken(cls, "cesiumSubTileCacheBytes", CesiumTokens->cesiumSubTileCacheBytes); _AddToken(cls, "cesiumSuspendUpdate", CesiumTokens->cesiumSuspendUpdate); _AddToken(cls, "cesiumTileHeight", CesiumTokens->cesiumTileHeight); _AddToken(cls, "cesiumTileMatrixSetId", CesiumTokens->cesiumTileMatrixSetId); _AddToken(cls, "cesiumTileMatrixSetLabelPrefix", CesiumTokens->cesiumTileMatrixSetLabelPrefix); _AddToken(cls, "cesiumTileMatrixSetLabels", CesiumTokens->cesiumTileMatrixSetLabels); _AddToken(cls, "cesiumTileWidth", CesiumTokens->cesiumTileWidth); _AddToken(cls, "cesiumUrl", CesiumTokens->cesiumUrl); _AddToken(cls, "cesiumUseWebMercatorProjection", CesiumTokens->cesiumUseWebMercatorProjection); _AddToken(cls, "cesiumWest", CesiumTokens->cesiumWest); _AddToken(cls, "clip", CesiumTokens->clip); _AddToken(cls, "ion", CesiumTokens->ion); _AddToken(cls, "overlay", CesiumTokens->overlay); _AddToken(cls, "url", CesiumTokens->url); }
8,498
C++
64.376923
133
0.772182
CesiumGS/cesium-omniverse/src/plugins/CesiumUsdSchemas/src/CesiumUsdSchemas/ionServer.h
#ifndef CESIUMUSDSCHEMAS_GENERATED_IONSERVER_H #define CESIUMUSDSCHEMAS_GENERATED_IONSERVER_H /// \file CesiumUsdSchemas/ionServer.h #include "pxr/pxr.h" #include ".//api.h" #include "pxr/usd/usd/typed.h" #include "pxr/usd/usd/prim.h" #include "pxr/usd/usd/stage.h" #include ".//tokens.h" #include "pxr/base/vt/value.h" #include "pxr/base/gf/vec3d.h" #include "pxr/base/gf/vec3f.h" #include "pxr/base/gf/matrix4d.h" #include "pxr/base/tf/token.h" #include "pxr/base/tf/type.h" PXR_NAMESPACE_OPEN_SCOPE class SdfAssetPath; // -------------------------------------------------------------------------- // // CESIUMIONSERVERPRIM // // -------------------------------------------------------------------------- // /// \class CesiumIonServer /// /// Stores metadata related to Cesium ion server connections for tilesets. /// class CesiumIonServer : public UsdTyped { public: /// Compile time constant representing what kind of schema this class is. /// /// \sa UsdSchemaKind static const UsdSchemaKind schemaKind = UsdSchemaKind::ConcreteTyped; /// Construct a CesiumIonServer on UsdPrim \p prim . /// Equivalent to CesiumIonServer::Get(prim.GetStage(), prim.GetPath()) /// for a \em valid \p prim, but will not immediately throw an error for /// an invalid \p prim explicit CesiumIonServer(const UsdPrim& prim=UsdPrim()) : UsdTyped(prim) { } /// Construct a CesiumIonServer on the prim held by \p schemaObj . /// Should be preferred over CesiumIonServer(schemaObj.GetPrim()), /// as it preserves SchemaBase state. explicit CesiumIonServer(const UsdSchemaBase& schemaObj) : UsdTyped(schemaObj) { } /// Destructor. CESIUMUSDSCHEMAS_API virtual ~CesiumIonServer(); /// Return a vector of names of all pre-declared attributes for this schema /// class and all its ancestor classes. Does not include attributes that /// may be authored by custom/extended methods of the schemas involved. CESIUMUSDSCHEMAS_API static const TfTokenVector & GetSchemaAttributeNames(bool includeInherited=true); /// Return a CesiumIonServer holding the prim adhering to this /// schema at \p path on \p stage. If no prim exists at \p path on /// \p stage, or if the prim at that path does not adhere to this schema, /// return an invalid schema object. This is shorthand for the following: /// /// \code /// CesiumIonServer(stage->GetPrimAtPath(path)); /// \endcode /// CESIUMUSDSCHEMAS_API static CesiumIonServer Get(const UsdStagePtr &stage, const SdfPath &path); /// Attempt to ensure a \a UsdPrim adhering to this schema at \p path /// is defined (according to UsdPrim::IsDefined()) on this stage. /// /// If a prim adhering to this schema at \p path is already defined on this /// stage, return that prim. Otherwise author an \a SdfPrimSpec with /// \a specifier == \a SdfSpecifierDef and this schema's prim type name for /// the prim at \p path at the current EditTarget. Author \a SdfPrimSpec s /// with \p specifier == \a SdfSpecifierDef and empty typeName at the /// current EditTarget for any nonexistent, or existing but not \a Defined /// ancestors. /// /// The given \a path must be an absolute prim path that does not contain /// any variant selections. /// /// If it is impossible to author any of the necessary PrimSpecs, (for /// example, in case \a path cannot map to the current UsdEditTarget's /// namespace) issue an error and return an invalid \a UsdPrim. /// /// Note that this method may return a defined prim whose typeName does not /// specify this schema class, in case a stronger typeName opinion overrides /// the opinion at the current EditTarget. /// CESIUMUSDSCHEMAS_API static CesiumIonServer Define(const UsdStagePtr &stage, const SdfPath &path); protected: /// Returns the kind of schema this class belongs to. /// /// \sa UsdSchemaKind CESIUMUSDSCHEMAS_API UsdSchemaKind _GetSchemaKind() const override; private: // needs to invoke _GetStaticTfType. friend class UsdSchemaRegistry; CESIUMUSDSCHEMAS_API static const TfType &_GetStaticTfType(); static bool _IsTypedSchema(); // override SchemaBase virtuals. CESIUMUSDSCHEMAS_API const TfType &_GetTfType() const override; public: // --------------------------------------------------------------------- // // DISPLAYNAME // --------------------------------------------------------------------- // /// The name to display for this server. /// /// | || /// | -- | -- | /// | Declaration | `string cesium:displayName` | /// | C++ Type | std::string | /// | \ref Usd_Datatypes "Usd Type" | SdfValueTypeNames->String | CESIUMUSDSCHEMAS_API UsdAttribute GetDisplayNameAttr() const; /// See GetDisplayNameAttr(), and also /// \ref Usd_Create_Or_Get_Property for when to use Get vs Create. /// If specified, author \p defaultValue as the attribute's default, /// sparsely (when it makes sense to do so) if \p writeSparsely is \c true - /// the default for \p writeSparsely is \c false. CESIUMUSDSCHEMAS_API UsdAttribute CreateDisplayNameAttr(VtValue const &defaultValue = VtValue(), bool writeSparsely=false) const; public: // --------------------------------------------------------------------- // // IONSERVERURL // --------------------------------------------------------------------- // /// The base URL for the Cesium ion Server. /// /// | || /// | -- | -- | /// | Declaration | `string cesium:ionServerUrl` | /// | C++ Type | std::string | /// | \ref Usd_Datatypes "Usd Type" | SdfValueTypeNames->String | CESIUMUSDSCHEMAS_API UsdAttribute GetIonServerUrlAttr() const; /// See GetIonServerUrlAttr(), and also /// \ref Usd_Create_Or_Get_Property for when to use Get vs Create. /// If specified, author \p defaultValue as the attribute's default, /// sparsely (when it makes sense to do so) if \p writeSparsely is \c true - /// the default for \p writeSparsely is \c false. CESIUMUSDSCHEMAS_API UsdAttribute CreateIonServerUrlAttr(VtValue const &defaultValue = VtValue(), bool writeSparsely=false) const; public: // --------------------------------------------------------------------- // // IONSERVERAPIURL // --------------------------------------------------------------------- // /// The base URL for the Cesium ion Server API. /// /// | || /// | -- | -- | /// | Declaration | `string cesium:ionServerApiUrl` | /// | C++ Type | std::string | /// | \ref Usd_Datatypes "Usd Type" | SdfValueTypeNames->String | CESIUMUSDSCHEMAS_API UsdAttribute GetIonServerApiUrlAttr() const; /// See GetIonServerApiUrlAttr(), and also /// \ref Usd_Create_Or_Get_Property for when to use Get vs Create. /// If specified, author \p defaultValue as the attribute's default, /// sparsely (when it makes sense to do so) if \p writeSparsely is \c true - /// the default for \p writeSparsely is \c false. CESIUMUSDSCHEMAS_API UsdAttribute CreateIonServerApiUrlAttr(VtValue const &defaultValue = VtValue(), bool writeSparsely=false) const; public: // --------------------------------------------------------------------- // // IONSERVERAPPLICATIONID // --------------------------------------------------------------------- // /// The application ID for the Cesium ion Server connection. /// /// | || /// | -- | -- | /// | Declaration | `int64 cesium:ionServerApplicationId` | /// | C++ Type | int64_t | /// | \ref Usd_Datatypes "Usd Type" | SdfValueTypeNames->Int64 | CESIUMUSDSCHEMAS_API UsdAttribute GetIonServerApplicationIdAttr() const; /// See GetIonServerApplicationIdAttr(), and also /// \ref Usd_Create_Or_Get_Property for when to use Get vs Create. /// If specified, author \p defaultValue as the attribute's default, /// sparsely (when it makes sense to do so) if \p writeSparsely is \c true - /// the default for \p writeSparsely is \c false. CESIUMUSDSCHEMAS_API UsdAttribute CreateIonServerApplicationIdAttr(VtValue const &defaultValue = VtValue(), bool writeSparsely=false) const; public: // --------------------------------------------------------------------- // // PROJECTDEFAULTIONACCESSTOKEN // --------------------------------------------------------------------- // /// A string representing the token for accessing Cesium ion assets. /// /// | || /// | -- | -- | /// | Declaration | `string cesium:projectDefaultIonAccessToken = ""` | /// | C++ Type | std::string | /// | \ref Usd_Datatypes "Usd Type" | SdfValueTypeNames->String | CESIUMUSDSCHEMAS_API UsdAttribute GetProjectDefaultIonAccessTokenAttr() const; /// See GetProjectDefaultIonAccessTokenAttr(), and also /// \ref Usd_Create_Or_Get_Property for when to use Get vs Create. /// If specified, author \p defaultValue as the attribute's default, /// sparsely (when it makes sense to do so) if \p writeSparsely is \c true - /// the default for \p writeSparsely is \c false. CESIUMUSDSCHEMAS_API UsdAttribute CreateProjectDefaultIonAccessTokenAttr(VtValue const &defaultValue = VtValue(), bool writeSparsely=false) const; public: // --------------------------------------------------------------------- // // PROJECTDEFAULTIONACCESSTOKENID // --------------------------------------------------------------------- // /// A string representing the token ID for accessing Cesium ion assets. /// /// | || /// | -- | -- | /// | Declaration | `string cesium:projectDefaultIonAccessTokenId = ""` | /// | C++ Type | std::string | /// | \ref Usd_Datatypes "Usd Type" | SdfValueTypeNames->String | CESIUMUSDSCHEMAS_API UsdAttribute GetProjectDefaultIonAccessTokenIdAttr() const; /// See GetProjectDefaultIonAccessTokenIdAttr(), and also /// \ref Usd_Create_Or_Get_Property for when to use Get vs Create. /// If specified, author \p defaultValue as the attribute's default, /// sparsely (when it makes sense to do so) if \p writeSparsely is \c true - /// the default for \p writeSparsely is \c false. CESIUMUSDSCHEMAS_API UsdAttribute CreateProjectDefaultIonAccessTokenIdAttr(VtValue const &defaultValue = VtValue(), bool writeSparsely=false) const; public: // ===================================================================== // // Feel free to add custom code below this line, it will be preserved by // the code generator. // // Just remember to: // - Close the class declaration with }; // - Close the namespace with PXR_NAMESPACE_CLOSE_SCOPE // - Close the include guard with #endif // ===================================================================== // // --(BEGIN CUSTOM CODE)-- }; PXR_NAMESPACE_CLOSE_SCOPE #endif
11,156
C
39.423913
131
0.594299
CesiumGS/cesium-omniverse/src/plugins/CesiumUsdSchemas/src/CesiumUsdSchemas/wrapData.cpp
#include ".//data.h" #include "pxr/usd/usd/schemaBase.h" #include "pxr/usd/sdf/primSpec.h" #include "pxr/usd/usd/pyConversions.h" #include "pxr/base/tf/pyContainerConversions.h" #include "pxr/base/tf/pyResultConversions.h" #include "pxr/base/tf/pyUtils.h" #include "pxr/base/tf/wrapTypeHelpers.h" #include <boost/python.hpp> #include <string> using namespace boost::python; PXR_NAMESPACE_USING_DIRECTIVE namespace { #define WRAP_CUSTOM \ template <class Cls> static void _CustomWrapCode(Cls &_class) // fwd decl. WRAP_CUSTOM; static UsdAttribute _CreateDebugDisableMaterialsAttr(CesiumData &self, object defaultVal, bool writeSparsely) { return self.CreateDebugDisableMaterialsAttr( UsdPythonToSdfType(defaultVal, SdfValueTypeNames->Bool), writeSparsely); } static UsdAttribute _CreateDebugDisableTexturesAttr(CesiumData &self, object defaultVal, bool writeSparsely) { return self.CreateDebugDisableTexturesAttr( UsdPythonToSdfType(defaultVal, SdfValueTypeNames->Bool), writeSparsely); } static UsdAttribute _CreateDebugDisableGeometryPoolAttr(CesiumData &self, object defaultVal, bool writeSparsely) { return self.CreateDebugDisableGeometryPoolAttr( UsdPythonToSdfType(defaultVal, SdfValueTypeNames->Bool), writeSparsely); } static UsdAttribute _CreateDebugDisableMaterialPoolAttr(CesiumData &self, object defaultVal, bool writeSparsely) { return self.CreateDebugDisableMaterialPoolAttr( UsdPythonToSdfType(defaultVal, SdfValueTypeNames->Bool), writeSparsely); } static UsdAttribute _CreateDebugDisableTexturePoolAttr(CesiumData &self, object defaultVal, bool writeSparsely) { return self.CreateDebugDisableTexturePoolAttr( UsdPythonToSdfType(defaultVal, SdfValueTypeNames->Bool), writeSparsely); } static UsdAttribute _CreateDebugGeometryPoolInitialCapacityAttr(CesiumData &self, object defaultVal, bool writeSparsely) { return self.CreateDebugGeometryPoolInitialCapacityAttr( UsdPythonToSdfType(defaultVal, SdfValueTypeNames->UInt64), writeSparsely); } static UsdAttribute _CreateDebugMaterialPoolInitialCapacityAttr(CesiumData &self, object defaultVal, bool writeSparsely) { return self.CreateDebugMaterialPoolInitialCapacityAttr( UsdPythonToSdfType(defaultVal, SdfValueTypeNames->UInt64), writeSparsely); } static UsdAttribute _CreateDebugTexturePoolInitialCapacityAttr(CesiumData &self, object defaultVal, bool writeSparsely) { return self.CreateDebugTexturePoolInitialCapacityAttr( UsdPythonToSdfType(defaultVal, SdfValueTypeNames->UInt64), writeSparsely); } static UsdAttribute _CreateDebugRandomColorsAttr(CesiumData &self, object defaultVal, bool writeSparsely) { return self.CreateDebugRandomColorsAttr( UsdPythonToSdfType(defaultVal, SdfValueTypeNames->Bool), writeSparsely); } static UsdAttribute _CreateDebugDisableGeoreferencingAttr(CesiumData &self, object defaultVal, bool writeSparsely) { return self.CreateDebugDisableGeoreferencingAttr( UsdPythonToSdfType(defaultVal, SdfValueTypeNames->Bool), writeSparsely); } static std::string _Repr(const CesiumData &self) { std::string primRepr = TfPyRepr(self.GetPrim()); return TfStringPrintf( "CesiumUsdSchemas.Data(%s)", primRepr.c_str()); } } // anonymous namespace void wrapCesiumData() { typedef CesiumData This; class_<This, bases<UsdTyped> > cls("Data"); cls .def(init<UsdPrim>(arg("prim"))) .def(init<UsdSchemaBase const&>(arg("schemaObj"))) .def(TfTypePythonClass()) .def("Get", &This::Get, (arg("stage"), arg("path"))) .staticmethod("Get") .def("Define", &This::Define, (arg("stage"), arg("path"))) .staticmethod("Define") .def("GetSchemaAttributeNames", &This::GetSchemaAttributeNames, arg("includeInherited")=true, return_value_policy<TfPySequenceToList>()) .staticmethod("GetSchemaAttributeNames") .def("_GetStaticTfType", (TfType const &(*)()) TfType::Find<This>, return_value_policy<return_by_value>()) .staticmethod("_GetStaticTfType") .def(!self) .def("GetDebugDisableMaterialsAttr", &This::GetDebugDisableMaterialsAttr) .def("CreateDebugDisableMaterialsAttr", &_CreateDebugDisableMaterialsAttr, (arg("defaultValue")=object(), arg("writeSparsely")=false)) .def("GetDebugDisableTexturesAttr", &This::GetDebugDisableTexturesAttr) .def("CreateDebugDisableTexturesAttr", &_CreateDebugDisableTexturesAttr, (arg("defaultValue")=object(), arg("writeSparsely")=false)) .def("GetDebugDisableGeometryPoolAttr", &This::GetDebugDisableGeometryPoolAttr) .def("CreateDebugDisableGeometryPoolAttr", &_CreateDebugDisableGeometryPoolAttr, (arg("defaultValue")=object(), arg("writeSparsely")=false)) .def("GetDebugDisableMaterialPoolAttr", &This::GetDebugDisableMaterialPoolAttr) .def("CreateDebugDisableMaterialPoolAttr", &_CreateDebugDisableMaterialPoolAttr, (arg("defaultValue")=object(), arg("writeSparsely")=false)) .def("GetDebugDisableTexturePoolAttr", &This::GetDebugDisableTexturePoolAttr) .def("CreateDebugDisableTexturePoolAttr", &_CreateDebugDisableTexturePoolAttr, (arg("defaultValue")=object(), arg("writeSparsely")=false)) .def("GetDebugGeometryPoolInitialCapacityAttr", &This::GetDebugGeometryPoolInitialCapacityAttr) .def("CreateDebugGeometryPoolInitialCapacityAttr", &_CreateDebugGeometryPoolInitialCapacityAttr, (arg("defaultValue")=object(), arg("writeSparsely")=false)) .def("GetDebugMaterialPoolInitialCapacityAttr", &This::GetDebugMaterialPoolInitialCapacityAttr) .def("CreateDebugMaterialPoolInitialCapacityAttr", &_CreateDebugMaterialPoolInitialCapacityAttr, (arg("defaultValue")=object(), arg("writeSparsely")=false)) .def("GetDebugTexturePoolInitialCapacityAttr", &This::GetDebugTexturePoolInitialCapacityAttr) .def("CreateDebugTexturePoolInitialCapacityAttr", &_CreateDebugTexturePoolInitialCapacityAttr, (arg("defaultValue")=object(), arg("writeSparsely")=false)) .def("GetDebugRandomColorsAttr", &This::GetDebugRandomColorsAttr) .def("CreateDebugRandomColorsAttr", &_CreateDebugRandomColorsAttr, (arg("defaultValue")=object(), arg("writeSparsely")=false)) .def("GetDebugDisableGeoreferencingAttr", &This::GetDebugDisableGeoreferencingAttr) .def("CreateDebugDisableGeoreferencingAttr", &_CreateDebugDisableGeoreferencingAttr, (arg("defaultValue")=object(), arg("writeSparsely")=false)) .def("GetSelectedIonServerRel", &This::GetSelectedIonServerRel) .def("CreateSelectedIonServerRel", &This::CreateSelectedIonServerRel) .def("__repr__", ::_Repr) ; _CustomWrapCode(cls); } // ===================================================================== // // Feel free to add custom code below this line, it will be preserved by // the code generator. The entry point for your custom code should look // minimally like the following: // // WRAP_CUSTOM { // _class // .def("MyCustomMethod", ...) // ; // } // // Of course any other ancillary or support code may be provided. // // Just remember to wrap code in the appropriate delimiters: // 'namespace {', '}'. // // ===================================================================== // // --(BEGIN CUSTOM CODE)-- namespace { WRAP_CUSTOM { } }
8,609
C++
33.858299
82
0.630503
CesiumGS/cesium-omniverse/src/plugins/CesiumUsdSchemas/src/CesiumUsdSchemas/polygonRasterOverlay.cpp
#include ".//polygonRasterOverlay.h" #include "pxr/usd/usd/schemaRegistry.h" #include "pxr/usd/usd/typed.h" #include "pxr/usd/sdf/types.h" #include "pxr/usd/sdf/assetPath.h" PXR_NAMESPACE_OPEN_SCOPE // Register the schema with the TfType system. TF_REGISTRY_FUNCTION(TfType) { TfType::Define<CesiumPolygonRasterOverlay, TfType::Bases< CesiumRasterOverlay > >(); // Register the usd prim typename as an alias under UsdSchemaBase. This // enables one to call // TfType::Find<UsdSchemaBase>().FindDerivedByName("CesiumPolygonRasterOverlayPrim") // to find TfType<CesiumPolygonRasterOverlay>, which is how IsA queries are // answered. TfType::AddAlias<UsdSchemaBase, CesiumPolygonRasterOverlay>("CesiumPolygonRasterOverlayPrim"); } /* virtual */ CesiumPolygonRasterOverlay::~CesiumPolygonRasterOverlay() { } /* static */ CesiumPolygonRasterOverlay CesiumPolygonRasterOverlay::Get(const UsdStagePtr &stage, const SdfPath &path) { if (!stage) { TF_CODING_ERROR("Invalid stage"); return CesiumPolygonRasterOverlay(); } return CesiumPolygonRasterOverlay(stage->GetPrimAtPath(path)); } /* static */ CesiumPolygonRasterOverlay CesiumPolygonRasterOverlay::Define( const UsdStagePtr &stage, const SdfPath &path) { static TfToken usdPrimTypeName("CesiumPolygonRasterOverlayPrim"); if (!stage) { TF_CODING_ERROR("Invalid stage"); return CesiumPolygonRasterOverlay(); } return CesiumPolygonRasterOverlay( stage->DefinePrim(path, usdPrimTypeName)); } /* virtual */ UsdSchemaKind CesiumPolygonRasterOverlay::_GetSchemaKind() const { return CesiumPolygonRasterOverlay::schemaKind; } /* static */ const TfType & CesiumPolygonRasterOverlay::_GetStaticTfType() { static TfType tfType = TfType::Find<CesiumPolygonRasterOverlay>(); return tfType; } /* static */ bool CesiumPolygonRasterOverlay::_IsTypedSchema() { static bool isTyped = _GetStaticTfType().IsA<UsdTyped>(); return isTyped; } /* virtual */ const TfType & CesiumPolygonRasterOverlay::_GetTfType() const { return _GetStaticTfType(); } UsdAttribute CesiumPolygonRasterOverlay::GetInvertSelectionAttr() const { return GetPrim().GetAttribute(CesiumTokens->cesiumInvertSelection); } UsdAttribute CesiumPolygonRasterOverlay::CreateInvertSelectionAttr(VtValue const &defaultValue, bool writeSparsely) const { return UsdSchemaBase::_CreateAttr(CesiumTokens->cesiumInvertSelection, SdfValueTypeNames->Bool, /* custom = */ false, SdfVariabilityVarying, defaultValue, writeSparsely); } UsdAttribute CesiumPolygonRasterOverlay::GetExcludeSelectedTilesAttr() const { return GetPrim().GetAttribute(CesiumTokens->cesiumExcludeSelectedTiles); } UsdAttribute CesiumPolygonRasterOverlay::CreateExcludeSelectedTilesAttr(VtValue const &defaultValue, bool writeSparsely) const { return UsdSchemaBase::_CreateAttr(CesiumTokens->cesiumExcludeSelectedTiles, SdfValueTypeNames->Bool, /* custom = */ false, SdfVariabilityVarying, defaultValue, writeSparsely); } UsdAttribute CesiumPolygonRasterOverlay::GetCesiumOverlayRenderMethodAttr() const { return GetPrim().GetAttribute(CesiumTokens->cesiumOverlayRenderMethod); } UsdAttribute CesiumPolygonRasterOverlay::CreateCesiumOverlayRenderMethodAttr(VtValue const &defaultValue, bool writeSparsely) const { return UsdSchemaBase::_CreateAttr(CesiumTokens->cesiumOverlayRenderMethod, SdfValueTypeNames->Token, /* custom = */ false, SdfVariabilityUniform, defaultValue, writeSparsely); } UsdRelationship CesiumPolygonRasterOverlay::GetCartographicPolygonBindingRel() const { return GetPrim().GetRelationship(CesiumTokens->cesiumCartographicPolygonBinding); } UsdRelationship CesiumPolygonRasterOverlay::CreateCartographicPolygonBindingRel() const { return GetPrim().CreateRelationship(CesiumTokens->cesiumCartographicPolygonBinding, /* custom = */ false); } namespace { static inline TfTokenVector _ConcatenateAttributeNames(const TfTokenVector& left,const TfTokenVector& right) { TfTokenVector result; result.reserve(left.size() + right.size()); result.insert(result.end(), left.begin(), left.end()); result.insert(result.end(), right.begin(), right.end()); return result; } } /*static*/ const TfTokenVector& CesiumPolygonRasterOverlay::GetSchemaAttributeNames(bool includeInherited) { static TfTokenVector localNames = { CesiumTokens->cesiumInvertSelection, CesiumTokens->cesiumExcludeSelectedTiles, CesiumTokens->cesiumOverlayRenderMethod, }; static TfTokenVector allNames = _ConcatenateAttributeNames( CesiumRasterOverlay::GetSchemaAttributeNames(true), localNames); if (includeInherited) return allNames; else return localNames; } PXR_NAMESPACE_CLOSE_SCOPE // ===================================================================== // // Feel free to add custom code below this line. It will be preserved by // the code generator. // // Just remember to wrap code in the appropriate delimiters: // 'PXR_NAMESPACE_OPEN_SCOPE', 'PXR_NAMESPACE_CLOSE_SCOPE'. // ===================================================================== // // --(BEGIN CUSTOM CODE)--
5,592
C++
28.592592
118
0.690808
CesiumGS/cesium-omniverse/src/plugins/CesiumUsdSchemas/src/CesiumUsdSchemas/tokens.cpp
#include ".//tokens.h" PXR_NAMESPACE_OPEN_SCOPE CesiumTokensType::CesiumTokensType() : cesiumAlpha("cesium:alpha", TfToken::Immortal), cesiumAnchorAdjustOrientationForGlobeWhenMoving("cesium:anchor:adjustOrientationForGlobeWhenMoving", TfToken::Immortal), cesiumAnchorDetectTransformChanges("cesium:anchor:detectTransformChanges", TfToken::Immortal), cesiumAnchorGeoreferenceBinding("cesium:anchor:georeferenceBinding", TfToken::Immortal), cesiumAnchorHeight("cesium:anchor:height", TfToken::Immortal), cesiumAnchorLatitude("cesium:anchor:latitude", TfToken::Immortal), cesiumAnchorLongitude("cesium:anchor:longitude", TfToken::Immortal), cesiumAnchorPosition("cesium:anchor:position", TfToken::Immortal), cesiumBaseUrl("cesium:baseUrl", TfToken::Immortal), cesiumCartographicPolygonBinding("cesium:cartographicPolygonBinding", TfToken::Immortal), cesiumCulledScreenSpaceError("cesium:culledScreenSpaceError", TfToken::Immortal), cesiumDebugDisableGeometryPool("cesium:debug:disableGeometryPool", TfToken::Immortal), cesiumDebugDisableGeoreferencing("cesium:debug:disableGeoreferencing", TfToken::Immortal), cesiumDebugDisableMaterialPool("cesium:debug:disableMaterialPool", TfToken::Immortal), cesiumDebugDisableMaterials("cesium:debug:disableMaterials", TfToken::Immortal), cesiumDebugDisableTexturePool("cesium:debug:disableTexturePool", TfToken::Immortal), cesiumDebugDisableTextures("cesium:debug:disableTextures", TfToken::Immortal), cesiumDebugGeometryPoolInitialCapacity("cesium:debug:geometryPoolInitialCapacity", TfToken::Immortal), cesiumDebugMaterialPoolInitialCapacity("cesium:debug:materialPoolInitialCapacity", TfToken::Immortal), cesiumDebugRandomColors("cesium:debug:randomColors", TfToken::Immortal), cesiumDebugTexturePoolInitialCapacity("cesium:debug:texturePoolInitialCapacity", TfToken::Immortal), cesiumDisplayName("cesium:displayName", TfToken::Immortal), cesiumEast("cesium:east", TfToken::Immortal), cesiumEcefToUsdTransform("cesium:ecefToUsdTransform", TfToken::Immortal), cesiumEnableFogCulling("cesium:enableFogCulling", TfToken::Immortal), cesiumEnableFrustumCulling("cesium:enableFrustumCulling", TfToken::Immortal), cesiumEnforceCulledScreenSpaceError("cesium:enforceCulledScreenSpaceError", TfToken::Immortal), cesiumExcludeSelectedTiles("cesium:excludeSelectedTiles", TfToken::Immortal), cesiumForbidHoles("cesium:forbidHoles", TfToken::Immortal), cesiumFormat("cesium:format", TfToken::Immortal), cesiumGeoreferenceBinding("cesium:georeferenceBinding", TfToken::Immortal), cesiumGeoreferenceOriginHeight("cesium:georeferenceOrigin:height", TfToken::Immortal), cesiumGeoreferenceOriginLatitude("cesium:georeferenceOrigin:latitude", TfToken::Immortal), cesiumGeoreferenceOriginLongitude("cesium:georeferenceOrigin:longitude", TfToken::Immortal), cesiumInvertSelection("cesium:invertSelection", TfToken::Immortal), cesiumIonAccessToken("cesium:ionAccessToken", TfToken::Immortal), cesiumIonAssetId("cesium:ionAssetId", TfToken::Immortal), cesiumIonServerApiUrl("cesium:ionServerApiUrl", TfToken::Immortal), cesiumIonServerApplicationId("cesium:ionServerApplicationId", TfToken::Immortal), cesiumIonServerBinding("cesium:ionServerBinding", TfToken::Immortal), cesiumIonServerUrl("cesium:ionServerUrl", TfToken::Immortal), cesiumLayer("cesium:layer", TfToken::Immortal), cesiumLayers("cesium:layers", TfToken::Immortal), cesiumLoadingDescendantLimit("cesium:loadingDescendantLimit", TfToken::Immortal), cesiumMainThreadLoadingTimeLimit("cesium:mainThreadLoadingTimeLimit", TfToken::Immortal), cesiumMaximumCachedBytes("cesium:maximumCachedBytes", TfToken::Immortal), cesiumMaximumLevel("cesium:maximumLevel", TfToken::Immortal), cesiumMaximumScreenSpaceError("cesium:maximumScreenSpaceError", TfToken::Immortal), cesiumMaximumSimultaneousTileLoads("cesium:maximumSimultaneousTileLoads", TfToken::Immortal), cesiumMaximumTextureSize("cesium:maximumTextureSize", TfToken::Immortal), cesiumMaximumZoomLevel("cesium:maximumZoomLevel", TfToken::Immortal), cesiumMinimumLevel("cesium:minimumLevel", TfToken::Immortal), cesiumMinimumZoomLevel("cesium:minimumZoomLevel", TfToken::Immortal), cesiumNorth("cesium:north", TfToken::Immortal), cesiumOverlayRenderMethod("cesium:overlayRenderMethod", TfToken::Immortal), cesiumPreloadAncestors("cesium:preloadAncestors", TfToken::Immortal), cesiumPreloadSiblings("cesium:preloadSiblings", TfToken::Immortal), cesiumProjectDefaultIonAccessToken("cesium:projectDefaultIonAccessToken", TfToken::Immortal), cesiumProjectDefaultIonAccessTokenId("cesium:projectDefaultIonAccessTokenId", TfToken::Immortal), cesiumRasterOverlayBinding("cesium:rasterOverlayBinding", TfToken::Immortal), cesiumRootTilesX("cesium:rootTilesX", TfToken::Immortal), cesiumRootTilesY("cesium:rootTilesY", TfToken::Immortal), cesiumSelectedIonServer("cesium:selectedIonServer", TfToken::Immortal), cesiumShowCreditsOnScreen("cesium:showCreditsOnScreen", TfToken::Immortal), cesiumSmoothNormals("cesium:smoothNormals", TfToken::Immortal), cesiumSourceType("cesium:sourceType", TfToken::Immortal), cesiumSouth("cesium:south", TfToken::Immortal), cesiumSpecifyTileMatrixSetLabels("cesium:specifyTileMatrixSetLabels", TfToken::Immortal), cesiumSpecifyTilingScheme("cesium:specifyTilingScheme", TfToken::Immortal), cesiumSpecifyZoomLevels("cesium:specifyZoomLevels", TfToken::Immortal), cesiumStyle("cesium:style", TfToken::Immortal), cesiumSubTileCacheBytes("cesium:subTileCacheBytes", TfToken::Immortal), cesiumSuspendUpdate("cesium:suspendUpdate", TfToken::Immortal), cesiumTileHeight("cesium:tileHeight", TfToken::Immortal), cesiumTileMatrixSetId("cesium:tileMatrixSetId", TfToken::Immortal), cesiumTileMatrixSetLabelPrefix("cesium:tileMatrixSetLabelPrefix", TfToken::Immortal), cesiumTileMatrixSetLabels("cesium:tileMatrixSetLabels", TfToken::Immortal), cesiumTileWidth("cesium:tileWidth", TfToken::Immortal), cesiumUrl("cesium:url", TfToken::Immortal), cesiumUseWebMercatorProjection("cesium:useWebMercatorProjection", TfToken::Immortal), cesiumWest("cesium:west", TfToken::Immortal), clip("clip", TfToken::Immortal), ion("ion", TfToken::Immortal), overlay("overlay", TfToken::Immortal), url("url", TfToken::Immortal), allTokens({ cesiumAlpha, cesiumAnchorAdjustOrientationForGlobeWhenMoving, cesiumAnchorDetectTransformChanges, cesiumAnchorGeoreferenceBinding, cesiumAnchorHeight, cesiumAnchorLatitude, cesiumAnchorLongitude, cesiumAnchorPosition, cesiumBaseUrl, cesiumCartographicPolygonBinding, cesiumCulledScreenSpaceError, cesiumDebugDisableGeometryPool, cesiumDebugDisableGeoreferencing, cesiumDebugDisableMaterialPool, cesiumDebugDisableMaterials, cesiumDebugDisableTexturePool, cesiumDebugDisableTextures, cesiumDebugGeometryPoolInitialCapacity, cesiumDebugMaterialPoolInitialCapacity, cesiumDebugRandomColors, cesiumDebugTexturePoolInitialCapacity, cesiumDisplayName, cesiumEast, cesiumEcefToUsdTransform, cesiumEnableFogCulling, cesiumEnableFrustumCulling, cesiumEnforceCulledScreenSpaceError, cesiumExcludeSelectedTiles, cesiumForbidHoles, cesiumFormat, cesiumGeoreferenceBinding, cesiumGeoreferenceOriginHeight, cesiumGeoreferenceOriginLatitude, cesiumGeoreferenceOriginLongitude, cesiumInvertSelection, cesiumIonAccessToken, cesiumIonAssetId, cesiumIonServerApiUrl, cesiumIonServerApplicationId, cesiumIonServerBinding, cesiumIonServerUrl, cesiumLayer, cesiumLayers, cesiumLoadingDescendantLimit, cesiumMainThreadLoadingTimeLimit, cesiumMaximumCachedBytes, cesiumMaximumLevel, cesiumMaximumScreenSpaceError, cesiumMaximumSimultaneousTileLoads, cesiumMaximumTextureSize, cesiumMaximumZoomLevel, cesiumMinimumLevel, cesiumMinimumZoomLevel, cesiumNorth, cesiumOverlayRenderMethod, cesiumPreloadAncestors, cesiumPreloadSiblings, cesiumProjectDefaultIonAccessToken, cesiumProjectDefaultIonAccessTokenId, cesiumRasterOverlayBinding, cesiumRootTilesX, cesiumRootTilesY, cesiumSelectedIonServer, cesiumShowCreditsOnScreen, cesiumSmoothNormals, cesiumSourceType, cesiumSouth, cesiumSpecifyTileMatrixSetLabels, cesiumSpecifyTilingScheme, cesiumSpecifyZoomLevels, cesiumStyle, cesiumSubTileCacheBytes, cesiumSuspendUpdate, cesiumTileHeight, cesiumTileMatrixSetId, cesiumTileMatrixSetLabelPrefix, cesiumTileMatrixSetLabels, cesiumTileWidth, cesiumUrl, cesiumUseWebMercatorProjection, cesiumWest, clip, ion, overlay, url }) { } TfStaticData<CesiumTokensType> CesiumTokens; PXR_NAMESPACE_CLOSE_SCOPE
9,367
C++
49.913043
124
0.766094
CesiumGS/cesium-omniverse/src/plugins/CesiumUsdSchemas/src/CesiumUsdSchemas/moduleDeps.cpp
#include "pxr/pxr.h" #include "pxr/base/tf/registryManager.h" #include "pxr/base/tf/scriptModuleLoader.h" #include "pxr/base/tf/token.h" #include <vector> PXR_NAMESPACE_OPEN_SCOPE TF_REGISTRY_FUNCTION(TfScriptModuleLoader) { // List of direct dependencies for this library. const std::vector<TfToken> reqs = { TfToken("sdf"), TfToken("tf"), TfToken("usd"), TfToken("vt"), TfToken("usdGeom"), }; TfScriptModuleLoader::GetInstance(). RegisterLibrary(TfToken("CesiumUsdSchemas"), TfToken("cesium.usd.plugins.CesiumUsdSchemas"), reqs); } PXR_NAMESPACE_CLOSE_SCOPE
628
C++
25.208332
107
0.675159
CesiumGS/cesium-omniverse/src/public/CesiumOmniverse.cpp
#define CARB_EXPORTS #include "cesium/omniverse/CesiumOmniverse.h" #include "cesium/omniverse/AssetRegistry.h" #include "cesium/omniverse/CesiumIonServerManager.h" #include "cesium/omniverse/CesiumIonSession.h" #include "cesium/omniverse/Context.h" #include "cesium/omniverse/FabricUtil.h" #include "cesium/omniverse/OmniData.h" #include "cesium/omniverse/OmniIonServer.h" #include "cesium/omniverse/OmniTileset.h" #include "cesium/omniverse/UsdUtil.h" #include "cesium/omniverse/Viewport.h" #include <CesiumGeospatial/Cartographic.h> #include <CesiumUtility/CreditSystem.h> #include <carb/PluginUtils.h> #include <omni/fabric/IFabric.h> #include <omni/kit/IApp.h> #include <gsl/span> namespace cesium::omniverse { class CesiumOmniversePlugin final : public ICesiumOmniverseInterface { protected: void onStartup(const char* cesiumExtensionLocation) noexcept override { _pContext = std::make_unique<Context>(cesiumExtensionLocation); } void onShutdown() noexcept override { _pContext = nullptr; } void reloadTileset(const char* tilesetPath) noexcept override { const auto pTileset = _pContext->getAssetRegistry().getTileset(pxr::SdfPath(tilesetPath)); if (pTileset) { pTileset->reload(); } } void onUpdateFrame(const ViewportApi* viewports, uint64_t count, bool waitForLoadingTiles) noexcept override { const auto span = gsl::span<const Viewport>(reinterpret_cast<const Viewport*>(viewports), count); _pContext->onUpdateFrame(span, waitForLoadingTiles); } void onUsdStageChanged(long stageId) noexcept override { _pContext->onUsdStageChanged(stageId); } void connectToIon() noexcept override { _pContext->getCesiumIonServerManager().connectToIon(); } std::optional<std::shared_ptr<CesiumIonSession>> getSession() noexcept override { return _pContext->getCesiumIonServerManager().getCurrentIonSession(); } std::string getServerPath() noexcept override { const auto pIonServer = _pContext->getCesiumIonServerManager().getCurrentIonServer(); if (!pIonServer) { return ""; } return pIonServer->getPath().GetString(); } std::vector<std::shared_ptr<CesiumIonSession>> getSessions() noexcept override { const auto& ionServers = _pContext->getAssetRegistry().getIonServers(); std::vector<std::shared_ptr<CesiumIonSession>> result; result.reserve(ionServers.size()); for (const auto& pIonServer : ionServers) { result.push_back(pIonServer->getSession()); } return result; } std::vector<std::string> getServerPaths() noexcept override { const auto& ionServers = _pContext->getAssetRegistry().getIonServers(); std::vector<std::string> result; result.reserve(ionServers.size()); for (const auto& pIonServer : ionServers) { result.push_back(pIonServer->getPath().GetString()); } return result; } SetDefaultTokenResult getSetDefaultTokenResult() noexcept override { return _pContext->getCesiumIonServerManager().getSetDefaultTokenResult(); } bool isDefaultTokenSet() noexcept override { return _pContext->getCesiumIonServerManager().isDefaultTokenSet(); } void createToken(const char* name) noexcept override { _pContext->getCesiumIonServerManager().createToken(name); } void selectToken(const char* id, const char* token) noexcept override { CesiumIonClient::Token t{id, "", token}; _pContext->getCesiumIonServerManager().selectToken(t); } void specifyToken(const char* token) noexcept override { _pContext->getCesiumIonServerManager().specifyToken(token); } std::optional<AssetTroubleshootingDetails> getAssetTroubleshootingDetails() noexcept override { return _pContext->getCesiumIonServerManager().getAssetTroubleshootingDetails(); } std::optional<TokenTroubleshootingDetails> getAssetTokenTroubleshootingDetails() noexcept override { return _pContext->getCesiumIonServerManager().getAssetTokenTroubleshootingDetails(); } std::optional<TokenTroubleshootingDetails> getDefaultTokenTroubleshootingDetails() noexcept override { return _pContext->getCesiumIonServerManager().getDefaultTokenTroubleshootingDetails(); } void updateTroubleshootingDetails( const char* tilesetPath, int64_t tilesetIonAssetId, uint64_t tokenEventId, uint64_t assetEventId) noexcept override { return _pContext->getCesiumIonServerManager().updateTroubleshootingDetails( pxr::SdfPath(tilesetPath), tilesetIonAssetId, tokenEventId, assetEventId); } void updateTroubleshootingDetails( const char* tilesetPath, int64_t tilesetIonAssetId, int64_t rasterOverlayIonAssetId, uint64_t tokenEventId, uint64_t assetEventId) noexcept override { return _pContext->getCesiumIonServerManager().updateTroubleshootingDetails( pxr::SdfPath(tilesetPath), tilesetIonAssetId, rasterOverlayIonAssetId, tokenEventId, assetEventId); } std::string printFabricStage() noexcept override { return FabricUtil::printFabricStage(_pContext->getFabricStage()); } RenderStatistics getRenderStatistics() noexcept override { return _pContext->getRenderStatistics(); } bool creditsAvailable() noexcept override { return _pContext->getCreditSystem()->getCreditsToShowThisFrame().size() > 0; } std::vector<std::pair<std::string, bool>> getCredits() noexcept override { const auto& pCreditSystem = _pContext->getCreditSystem(); const auto& credits = pCreditSystem->getCreditsToShowThisFrame(); std::vector<std::pair<std::string, bool>> result; result.reserve(credits.size()); for (const auto& item : credits) { const auto showOnScreen = pCreditSystem->shouldBeShownOnScreen(item); result.emplace_back(pCreditSystem->getHtml(item), showOnScreen); } return result; } void creditsStartNextFrame() noexcept override { return _pContext->getCreditSystem()->startNextFrame(); } bool isTracingEnabled() noexcept override { #if CESIUM_TRACING_ENABLED return true; #else return false; #endif } void clearAccessorCache() override { _pContext->clearAccessorCache(); } private: std::unique_ptr<Context> _pContext; }; } // namespace cesium::omniverse const struct carb::PluginImplDesc pluginImplDesc = { "cesium.omniverse.plugin", "Cesium Omniverse Carbonite Plugin.", "Cesium", carb::PluginHotReload::eDisabled, "dev"}; #ifdef CESIUM_OMNI_CLANG #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wgnu-zero-variadic-macro-arguments" #endif CARB_PLUGIN_IMPL(pluginImplDesc, cesium::omniverse::CesiumOmniversePlugin) CARB_PLUGIN_IMPL_DEPS(omni::fabric::IFabric, omni::kit::IApp, carb::settings::ISettings) #ifdef CESIUM_OMNI_CLANG #pragma clang diagnostic pop #endif void fillInterface([[maybe_unused]] cesium::omniverse::CesiumOmniversePlugin& iface) {}
7,245
C++
32.391705
114
0.704348
CesiumGS/cesium-omniverse/exts/cesium.powertools/cesium/powertools/extension.py
from functools import partial import asyncio from typing import Optional, List import logging import omni.ext import omni.ui as ui import omni.kit.ui from .powertools_window import CesiumPowertoolsWindow from cesium.omniverse.utils import wait_n_frames, dock_window_async from cesium.omniverse.install import WheelInfo, WheelInstaller class CesiumPowertoolsExtension(omni.ext.IExt): def __init__(self): super().__init__() self._logger = logging.getLogger(__name__) self._powertools_window: Optional[CesiumPowertoolsWindow] = None self._install_py_dependencies() def on_startup(self): self._logger.info("Starting Cesium Power Tools...") self._setup_menus() self._show_and_dock_startup_windows() def on_shutdown(self): self._destroy_powertools_window() def _setup_menus(self): ui.Workspace.set_show_window_fn( CesiumPowertoolsWindow.WINDOW_NAME, partial(self._show_powertools_window, None) ) editor_menu = omni.kit.ui.get_editor_menu() if editor_menu: editor_menu.add_item( CesiumPowertoolsWindow.MENU_PATH, self._show_powertools_window, toggle=True, value=True ) def _show_and_dock_startup_windows(self): ui.Workspace.show_window(CesiumPowertoolsWindow.WINDOW_NAME) asyncio.ensure_future(dock_window_async(self._powertools_window, target="Property")) def _destroy_powertools_window(self): if self._powertools_window is not None: self._powertools_window.destroy() self._powertools_window = None async def _destroy_window_async(self, path): # Wait one frame, this is due to the one frame defer in Window::_moveToMainOSWindow() await wait_n_frames(1) if path is CesiumPowertoolsWindow.MENU_PATH: self._destroy_powertools_window() def _visibility_changed_fn(self, path, visible): editor_menu = omni.kit.ui.get_editor_menu() if editor_menu: editor_menu.set_value(path, visible) if not visible: asyncio.ensure_future(self._destroy_window_async(path)) def _show_powertools_window(self, _menu, value): if value: self._powertools_window = CesiumPowertoolsWindow(width=300, height=400) self._powertools_window.set_visibility_changed_fn( partial(self._visibility_changed_fn, CesiumPowertoolsWindow.MENU_PATH) ) elif self._powertools_window is not None: self._powertools_window.visible = False def _install_py_dependencies(self): vendor_wheels: List[WheelInfo] = [ WheelInfo( module="pyproj", windows_whl="pyproj-3.6.0-cp310-cp310-win_amd64.whl", linux_x64_whl="pyproj-3.6.0-cp310-cp310-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", linux_aarch_whl="pyproj-3.6.0-cp310-cp310-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", ) ] for w in vendor_wheels: installer = WheelInstaller(w, extension_module="cesium.powertools") if not installer.install(): self._logger.error(f"Could not install wheel for {w.module}")
3,271
Python
34.565217
108
0.646897
CesiumGS/cesium-omniverse/exts/cesium.powertools/cesium/powertools/__init__.py
from .extension import * # noqa: F401 F403
44
Python
21.499989
43
0.704545
CesiumGS/cesium-omniverse/exts/cesium.powertools/cesium/powertools/powertools_window.py
import logging import omni.ui as ui from typing import Callable, Optional, List from cesium.omniverse.ui import CesiumOmniverseDebugWindow from .georefhelper.georef_helper_window import CesiumGeorefHelperWindow from .utils import ( extend_far_plane, save_carb_settings, save_fabric_stage, set_sunstudy_from_georef, ) import os from functools import partial from .benchmarking.load_timer_window import CesiumLoadTimerWindow powertools_extension_location = os.path.join(os.path.dirname(__file__), "../../") class PowertoolsAction: def __init__(self, title: str, action: Callable): self._title = title self._action = action self._button: Optional[ui.Button] = None def destroy(self): if self._button is not None: self._button.destroy() self._button = None def button(self): if self._button is None: self._button = ui.Button(self._title, height=0, clicked_fn=self._action) return self._button class CesiumPowertoolsWindow(ui.Window): WINDOW_NAME = "Cesium Power Tools" MENU_PATH = f"Window/Cesium/{WINDOW_NAME}" def __init__(self, **kwargs): super().__init__(CesiumPowertoolsWindow.WINDOW_NAME, **kwargs) self._logger = logging.getLogger(__name__) # You do not necessarily need to create an action function in this window class. If you have a function # in another window or class, you can absolutely call that instead from here. self._actions: List[PowertoolsAction] = [ PowertoolsAction("Open Cesium Debugging Window", CesiumOmniverseDebugWindow.show_window), PowertoolsAction("Open Cesium Georeference Helper Window", CesiumGeorefHelperWindow.create_window), PowertoolsAction("Open Cesium Load Timer Window", CesiumLoadTimerWindow.create_window), PowertoolsAction("Extend Far Plane", extend_far_plane), PowertoolsAction("Save Carb Settings", partial(save_carb_settings, powertools_extension_location)), PowertoolsAction("Save Fabric Stage", partial(save_fabric_stage, powertools_extension_location)), PowertoolsAction("Set Sun Study from Georef", set_sunstudy_from_georef), ] self.frame.set_build_fn(self._build_fn) def destroy(self) -> None: for action in self._actions: action.destroy() self._actions.clear() super().destroy() def _build_fn(self): with ui.ScrollingFrame(): with ui.VStack(spacing=4): for action in self._actions: action.button()
2,623
Python
35.444444
111
0.666794
CesiumGS/cesium-omniverse/exts/cesium.powertools/cesium/powertools/benchmarking/load_timer_window.py
import logging import omni.ui as ui import carb.events import omni.kit.app as app from typing import List from cesium.omniverse.ui.models.space_delimited_number_model import SpaceDelimitedNumberModel from cesium.omniverse.utils.cesium_interface import CesiumInterfaceManager from datetime import datetime from cesium.omniverse.usdUtils import get_tileset_paths class CesiumLoadTimerWindow(ui.Window): WINDOW_NAME = "Cesium Load Timer" _logger: logging.Logger _last_tiles_loading_worker = 0 def __init__(self, **kwargs): super().__init__(CesiumLoadTimerWindow.WINDOW_NAME, **kwargs) self._logger = logging.getLogger(__name__) self._timer_active = False self._tiles_loading_worker_model: SpaceDelimitedNumberModel = SpaceDelimitedNumberModel(0) self._load_time_seconds_model: SpaceDelimitedNumberModel = SpaceDelimitedNumberModel(0) self._past_results_model: ui.SimpleStringModel = ui.SimpleStringModel("") self._subscriptions: List[carb.events.ISubscription] = [] self._setup_subscriptions() # Set the function that is called to build widgets when the window is visible self.frame.set_build_fn(self._build_fn) self.set_visibility_changed_fn(self._visibility_changed_fn) def destroy(self): self._remove_subscriptions() super().destroy() def __del__(self): self.destroy() def _visibility_changed_fn(self, visible): if not visible: self._remove_subscriptions() def _setup_subscriptions(self): update_stream = app.get_app().get_update_event_stream() self._subscriptions.append( update_stream.create_subscription_to_pop(self._on_update_frame, name="on_update_frame") ) def _remove_subscriptions(self): for subscription in self._subscriptions: subscription.unsubscribe() self._subscriptions.clear() def _on_update_frame(self, _e: carb.events.IEvent): if not self.visible or not self._timer_active: return with CesiumInterfaceManager() as interface: render_statistics = interface.get_render_statistics() # Loading worker count has changed from last frame, so update the timer if render_statistics.tiles_loading_worker != self._last_tiles_loading_worker: # Register a new end-time and calculate the total elapsed time in seconds self._end_time = datetime.now() time_elapsed = self._end_time - self._start_time self._load_time_seconds_model.set_value(time_elapsed.total_seconds()) # If 30 sucessive frames with zero tiles loading occurs, we assume loading has finished if render_statistics.tiles_loading_worker == 0: self._zero_counter += 1 if self._zero_counter >= 30: self._end_load_timer() # Cancel the timer after 30 successful 0 tile frames else: self._zero_counter = 0 # Store the number of tile workers for use in the next update cycle self._last_tiles_loading_worker = render_statistics.tiles_loading_worker self._tiles_loading_worker_model.set_value(render_statistics.tiles_loading_worker) def _start_load_timer(self): self._start_time = datetime.now() self._end_time = datetime.now() self._timer_active = True self._zero_counter = 0 with CesiumInterfaceManager() as interface: tileset_paths = get_tileset_paths() for tileset_path in tileset_paths: interface.reload_tileset(tileset_path) def _end_load_timer(self): self._timer_active = False result_str = f"{self._load_time_seconds_model}\n" + self._past_results_model.get_value_as_string() self._past_results_model.set_value(result_str) @staticmethod def create_window(): return CesiumLoadTimerWindow(width=300, height=370) def _build_fn(self): """Builds out the UI""" with ui.VStack(spacing=4): ui.Label( "This tool records the amount of time taken to reload all tilesets in the stage", word_wrap=True, ) def reload_all_tilesets(): self._start_load_timer() ui.Button("Reload all Tilesets", height=20, clicked_fn=reload_all_tilesets) ui.Label( "The timer automatically completes when no tiles are queued to load for 30 successive frames", word_wrap=True, ) for label, model in [ ("Tiles loading (worker)", self._tiles_loading_worker_model), ("Load time (s)", self._load_time_seconds_model), ]: with ui.HStack(height=0): ui.Label(label, height=0) ui.StringField(model=model, height=0, read_only=True) ui.Label("Past results:", height=0) ui.StringField(model=self._past_results_model, multiline=True, height=150)
5,135
Python
36.764706
110
0.627653
CesiumGS/cesium-omniverse/exts/cesium.powertools/cesium/powertools/georefhelper/georef_helper_window.py
import logging import omni.ui as ui import omni.usd from .proj import epsg_to_ecef, epsg_to_wgs84, get_crs_name_from_epsg import math from cesium.omniverse.utils.custom_fields import string_field_with_label, int_field_with_label, float_field_with_label from pxr import Sdf class CesiumGeorefHelperWindow(ui.Window): WINDOW_NAME = "Cesium Georeference Helper" _logger: logging.Logger def __init__(self, **kwargs): super().__init__(CesiumGeorefHelperWindow.WINDOW_NAME, **kwargs) self._logger = logging.getLogger(__name__) # Set the function that is called to build widgets when the window is visible self.frame.set_build_fn(self._build_fn) def destroy(self): # It will destroy all the children super().destroy() def __del__(self): self.destroy() @staticmethod def create_window(): return CesiumGeorefHelperWindow(width=250, height=600) def _convert_coordinates(self): # Get the CRS and check if it is valid, adjust UI values accordingly crs = get_crs_name_from_epsg(self._epsg_model.get_value_as_int()) if crs is None: self._epsg_name_model.set_value("Invalid EPSG Code") self._wgs84_latitude_model.set_value(math.nan) self._wgs84_longitude_model.set_value(math.nan) self._wgs84_height_model.set_value(math.nan) self._ecef_x_model.set_value(math.nan) self._ecef_y_model.set_value(math.nan) self._ecef_z_model.set_value(math.nan) return self._epsg_name_model.set_value(crs) # Convert coords to WGS84 and set in UI wgs84_coords = epsg_to_wgs84( self._epsg_model.as_string, self._easting_model.as_float, self._northing_model.as_float, self._elevation_model.as_float, ) self._wgs84_latitude_model.set_value(wgs84_coords[0]) self._wgs84_longitude_model.set_value(wgs84_coords[1]) self._wgs84_height_model.set_value(wgs84_coords[2]) # Convert coords to ECEF and set in UI ecef_coords = epsg_to_ecef( self._epsg_model.as_string, self._easting_model.as_float, self._northing_model.as_float, self._elevation_model.as_float, ) self._ecef_x_model.set_value(ecef_coords[0]) self._ecef_y_model.set_value(ecef_coords[1]) self._ecef_z_model.set_value(ecef_coords[2]) def _set_georeference_prim(self): if math.isnan(self._wgs84_latitude_model.get_value_as_float()): self._logger.warning("Cannot set CesiumGeoreference to NaN") return stage = omni.usd.get_context().get_stage() cesium_prim = stage.GetPrimAtPath("/CesiumGeoreference") cesium_prim.GetAttribute("cesium:georeferenceOrigin:latitude").Set( self._wgs84_latitude_model.get_value_as_float() ) cesium_prim.GetAttribute("cesium:georeferenceOrigin:longitude").Set( self._wgs84_longitude_model.get_value_as_float() ) cesium_prim.GetAttribute("cesium:georeferenceOrigin:height").Set( self._wgs84_height_model.get_value_as_float() ) @staticmethod def set_georef_from_environment(): stage = omni.usd.get_context().get_stage() environment_prim = stage.GetPrimAtPath("/Environment") cesium_prim = stage.GetPrimAtPath("/CesiumGeoreference") lat_attr = environment_prim.GetAttribute("location:latitude") long_attr = environment_prim.GetAttribute("location:longitude") if lat_attr and long_attr: cesium_prim.GetAttribute("cesium:georeferenceOrigin:latitude").Set(lat_attr.Get()) cesium_prim.GetAttribute("cesium:georeferenceOrigin:longitude").Set(long_attr.Get()) cesium_prim.GetAttribute("cesium:georeferenceOrigin:height").Set(0.0) else: logger = logging.getLogger(__name__) logger.warning( "Cannot set CesiumGeoreference as environment prim does not have latitude or longitude attributes" ) @staticmethod def set_georef_from_anchor(): logger = logging.getLogger(__name__) stage = omni.usd.get_context().get_stage() cesium_prim = stage.GetPrimAtPath("/CesiumGeoreference") if not cesium_prim.IsValid(): logger.error("No CesiumGeoreference found") return selection = omni.usd.get_context().get_selection().get_selected_prim_paths() for prim_path in selection: prim = stage.GetPrimAtPath(prim_path) latitude = prim.GetAttribute("cesium:anchor:latitude").Get() longitude = prim.GetAttribute("cesium:anchor:longitude").Get() height = prim.GetAttribute("cesium:anchor:height").Get() if latitude is not None and longitude is not None and height is not None: cesium_prim.GetAttribute("cesium:georeferenceOrigin:latitude").Set(latitude) cesium_prim.GetAttribute("cesium:georeferenceOrigin:longitude").Set(longitude) cesium_prim.GetAttribute("cesium:georeferenceOrigin:height").Set(height) return logger.error("Please select a prim with a globe anchor") def _build_fn(self): """Builds out the UI buttons and their handlers.""" with ui.VStack(spacing=4): label_style = {"Label": {"font_size": 16}} ui.Label( "Enter coordinates in any EPSG CRS to convert them to ECEF and WGS84", word_wrap=True, style=label_style, ) ui.Spacer(height=10) ui.Label("Your Project Details:", style=label_style) # TODO: Precision issues to resolve def on_coordinate_update(event): self._convert_coordinates() # Define the SimpleValueModels for the UI self._epsg_model = ui.SimpleIntModel(28356) self._epsg_name_model = ui.SimpleStringModel("") self._easting_model = ui.SimpleFloatModel(503000.0) self._northing_model = ui.SimpleFloatModel(6950000.0) self._elevation_model = ui.SimpleFloatModel(0.0) # Add the value changed callbacks self._epsg_model.add_value_changed_fn(on_coordinate_update) self._easting_model.add_value_changed_fn(on_coordinate_update) self._northing_model.add_value_changed_fn(on_coordinate_update) self._elevation_model.add_value_changed_fn(on_coordinate_update) # TODO: Make EPSG an autocomplete field int_field_with_label("EPSG Code", model=self._epsg_model) string_field_with_label("EPSG Name", model=self._epsg_name_model, enabled=False) float_field_with_label("Easting / X", model=self._easting_model) float_field_with_label("Northing / Y", model=self._northing_model) float_field_with_label("Elevation / Z", model=self._elevation_model) ui.Spacer(height=10) # TODO: It would be nice to be able to copy these fields, or potentially have two way editing ui.Label("WGS84 Results:", style=label_style) self._wgs84_latitude_model = ui.SimpleFloatModel(0.0) self._wgs84_longitude_model = ui.SimpleFloatModel(0.0) self._wgs84_height_model = ui.SimpleFloatModel(0.0) float_field_with_label("Latitude", model=self._wgs84_latitude_model, enabled=False) float_field_with_label("Longitude", model=self._wgs84_longitude_model, enabled=False) float_field_with_label("Elevation", model=self._wgs84_height_model, enabled=False) ui.Spacer(height=10) ui.Label("ECEF Results:", style=label_style) self._ecef_x_model = ui.SimpleFloatModel(0.0) self._ecef_y_model = ui.SimpleFloatModel(0.0) self._ecef_z_model = ui.SimpleFloatModel(0.0) float_field_with_label("X", model=self._ecef_x_model, enabled=False) float_field_with_label("Y", model=self._ecef_y_model, enabled=False) float_field_with_label("Z", model=self._ecef_z_model, enabled=False) ui.Button("Set Georeference from EPSG", height=20, clicked_fn=self._set_georeference_prim) ui.Button( "Set Georeference from Environment Prim", height=20, clicked_fn=self.set_georef_from_environment ) ui.Button("Set Georef from Selected Anchor", height=20, clicked_fn=self.set_georef_from_anchor) # Do the first conversion self._convert_coordinates()
8,726
Python
41.15942
118
0.628467
CesiumGS/cesium-omniverse/exts/cesium.powertools/cesium/powertools/georefhelper/proj.py
ECEF_EPSG = 4978 WGS84_EPSG = 4979 def get_crs_name_from_epsg(epsg_code): import pyproj try: return pyproj.crs.CRS.from_epsg(epsg_code).name except pyproj.exceptions.CRSError: return None def epsg_to_epsg(from_epsg, to_epsg, x, y, z): import pyproj from_crs = pyproj.crs.CRS.from_epsg(from_epsg) to_crs = pyproj.crs.CRS.from_epsg(to_epsg) # Define the from and to coordinate systems transformer = pyproj.Transformer.from_crs(from_crs, to_crs) # Convert ECEF coordinates to longitude, latitude, and height lat, lon, height = transformer.transform(x, y, z) return lat, lon, height def epsg_to_wgs84(from_epsg, x, y, z): return epsg_to_epsg(from_epsg, WGS84_EPSG, x, y, z) def epsg_to_ecef(from_epsg, x, y, z): return epsg_to_epsg(from_epsg, ECEF_EPSG, x, y, z) def ecef_to_wgs84(x, y, z): return epsg_to_epsg(ECEF_EPSG, WGS84_EPSG, x, y, z) def wgs84_to_ecef(x, y, z): return epsg_to_epsg(WGS84_EPSG, ECEF_EPSG, x, y, z)
1,012
Python
22.558139
65
0.658103
CesiumGS/cesium-omniverse/exts/cesium.powertools/cesium/powertools/utils/__init__.py
from .utils import * # noqa: F401 F403
40
Python
19.49999
39
0.675
CesiumGS/cesium-omniverse/exts/cesium.powertools/cesium/powertools/utils/utils.py
import logging import omni.usd from omni.kit.viewport.utility import get_active_viewport from pxr import Gf, UsdGeom, Sdf import json import carb.settings import os from cesium.omniverse.utils.cesium_interface import CesiumInterfaceManager from asyncio import ensure_future # Modified version of ScopedEdit in _build_viewport_cameras in omni.kit.widget.viewport class ScopedEdit: def __init__(self, stage): self.__stage = stage edit_target = stage.GetEditTarget() edit_layer = edit_target.GetLayer() self.__edit_layer = stage.GetSessionLayer() self.__was_editable = self.__edit_layer.permissionToEdit if not self.__was_editable: self.__edit_layer.SetPermissionToEdit(True) if self.__edit_layer != edit_layer: stage.SetEditTarget(self.__edit_layer) self.__edit_target = edit_target else: self.__edit_target = None def __del__(self): if self.__edit_layer and not self.__was_editable: self.__edit_layer.SetPermissionToEdit(False) self.__edit_layer = None if self.__edit_target: self.__stage.SetEditTarget(self.__edit_target) self.__edit_target = None def extend_far_plane(): stage = omni.usd.get_context().get_stage() viewport = get_active_viewport() camera_path = viewport.get_active_camera() camera = UsdGeom.Camera.Get(stage, camera_path) assert camera.GetPrim().IsValid() scoped_edit = ScopedEdit(stage) # noqa: F841 camera.GetClippingRangeAttr().Set(Gf.Vec2f(1.0, 10000000000.0)) def save_carb_settings(powertools_extension_location: str): carb_settings_path = os.path.join(powertools_extension_location, "carb_settings.txt") with open(carb_settings_path, "w") as fh: fh.write(json.dumps(carb.settings.get_settings().get("/"), indent=2)) def save_fabric_stage(powertools_extension_location: str): with CesiumInterfaceManager() as interface: fabric_stage_path = os.path.join(powertools_extension_location, "fabric_stage.txt") with open(fabric_stage_path, "w") as fh: fh.write(interface.print_fabric_stage()) # Helper function to search for an attribute on a prim, or create it if not present def get_or_create_attribute(prim, name, type): attribute = prim.GetAttribute(name) if not attribute: attribute = prim.CreateAttribute(name, type) return attribute def set_sunstudy_from_georef(): stage = omni.usd.get_context().get_stage() environment_prim = stage.GetPrimAtPath("/Environment") cesium_prim = stage.GetPrimAtPath("/CesiumGeoreference") lat_attr = get_or_create_attribute(environment_prim, "location:latitude", Sdf.ValueTypeNames.Float) lat_attr.Set(cesium_prim.GetAttribute("cesium:georeferenceOrigin:latitude").Get()) long_attr = get_or_create_attribute(environment_prim, "location:longitude", Sdf.ValueTypeNames.Float) long_attr.Set(cesium_prim.GetAttribute("cesium:georeferenceOrigin:longitude").Get()) north_attr = get_or_create_attribute(environment_prim, "location:north_orientation", Sdf.ValueTypeNames.Float) north_attr.Set(90.0) # Always set to 90, otherwise the sun is at the wrong angle
3,243
Python
37.164705
114
0.69411
CesiumGS/cesium-omniverse/exts/cesium.powertools/doc/README.md
# Cesium for Omniverse Power Tools This extension provides supporting features and tools that may be useful while developing apps and stages using Cesium for Omniverse, but are provided **on an entirely your milage may vary** basis. All of these tools are considered experimental. If you like a particular tool in this extension, and would like to see it moved to the main Cesium for Omniverse extension, please [feel free to let us know on the Cesium for Omniverse forums](https://community.cesium.com/c/cesium-for-omniverse/14). ## Current Features ### Open Cesium Debugging Window Easier and quicker way for opening the Cesium Debugging window. ## License Apache 2.0 (http://www.apache.org/licenses/LICENSE-2.0.html). Cesium for Omniverse is free for both commercial and non-commercial use.
800
Markdown
56.214282
495
0.78875
CesiumGS/cesium-omniverse/exts/cesium.powertools/config/extension.toml
[package] version = "0.1.0" category = "simulation" feature = false app = false title = "Cesium for Omniverse Power Tools" description = "Additional experimental helper features for Cesium for Omniverse." authors = "Cesium GS Inc." repository = "https://github.com/CesiumGS/cesium-omniverse" keywords = [ "cesium", "omniverse", "geospatial", "3D Tiles", "glTF", "globe", "earth", "simulation", ] # Paths are relative to the extension folder readme = "doc/README.md" icon = "doc/resources/icon.png" [dependencies] "cesium.omniverse" = {} [[python.module]] name = "cesium.powertools" [python.pipapi] archiveDirs = ["vendor"]
659
TOML
18.999999
81
0.681335
CesiumGS/cesium-omniverse/exts/cesium.usd.plugins/cesium/usd/__init__.py
from .plugins import * # noqa: F401 F403
42
Python
20.49999
41
0.690476
CesiumGS/cesium-omniverse/exts/cesium.usd.plugins/cesium/usd/plugins/__init__.py
import os # noqa: F401 from pxr import Plug pluginsRoot = os.path.join(os.path.dirname(__file__), "../../../plugins") cesiumUsdSchemasPath = pluginsRoot + "/CesiumUsdSchemas/resources" Plug.Registry().RegisterPlugins(cesiumUsdSchemasPath) plugin = Plug.Registry().GetPluginWithName("CesiumUsdSchemas") if plugin: plugin.Load() else: print("Cannot find plugin")
372
Python
27.692306
73
0.739247
CesiumGS/cesium-omniverse/exts/cesium.usd.plugins/cesium/usd/plugins/CesiumUsdSchemas/__init__.py
from . import _CesiumUsdSchemas from pxr import Tf Tf.PrepareModule(_CesiumUsdSchemas, locals()) del Tf try: import __DOC __DOC.Execute(locals()) del __DOC except Exception: try: import __tmpDoc __tmpDoc.Execute(locals()) del __tmpDoc except Exception: pass
314
Python
14.749999
45
0.617834
CesiumGS/cesium-omniverse/exts/cesium.usd.plugins/cesium/usd/plugins/CesiumUsdSchemas/__init__.pyi
from typing import Any, ClassVar import Boost.Python import pxr.Usd import pxr.UsdGeom __MFB_FULL_PACKAGE_NAME: str class Data(pxr.Usd.Typed): __instance_size__: ClassVar[int] = ... @classmethod def __init__(cls, *args, **kwargs) -> None: ... @classmethod def CreateDebugDisableGeometryPoolAttr(cls, *args, **kwargs) -> Any: ... @classmethod def CreateDebugDisableGeoreferencingAttr(cls, *args, **kwargs) -> Any: ... @classmethod def CreateDebugDisableMaterialPoolAttr(cls, *args, **kwargs) -> Any: ... @classmethod def CreateDebugDisableMaterialsAttr(cls, *args, **kwargs) -> Any: ... @classmethod def CreateDebugDisableTexturePoolAttr(cls, *args, **kwargs) -> Any: ... @classmethod def CreateDebugDisableTexturesAttr(cls, *args, **kwargs) -> Any: ... @classmethod def CreateDebugGeometryPoolInitialCapacityAttr(cls, *args, **kwargs) -> Any: ... @classmethod def CreateDebugMaterialPoolInitialCapacityAttr(cls, *args, **kwargs) -> Any: ... @classmethod def CreateDebugRandomColorsAttr(cls, *args, **kwargs) -> Any: ... @classmethod def CreateDebugTexturePoolInitialCapacityAttr(cls, *args, **kwargs) -> Any: ... @classmethod def CreateSelectedIonServerRel(cls, *args, **kwargs) -> Any: ... @classmethod def Define(cls, *args, **kwargs) -> Any: ... @classmethod def Get(cls, *args, **kwargs) -> Any: ... @classmethod def GetDebugDisableGeometryPoolAttr(cls, *args, **kwargs) -> Any: ... @classmethod def GetDebugDisableGeoreferencingAttr(cls, *args, **kwargs) -> Any: ... @classmethod def GetDebugDisableMaterialPoolAttr(cls, *args, **kwargs) -> Any: ... @classmethod def GetDebugDisableMaterialsAttr(cls, *args, **kwargs) -> Any: ... @classmethod def GetDebugDisableTexturePoolAttr(cls, *args, **kwargs) -> Any: ... @classmethod def GetDebugDisableTexturesAttr(cls, *args, **kwargs) -> Any: ... @classmethod def GetDebugGeometryPoolInitialCapacityAttr(cls, *args, **kwargs) -> Any: ... @classmethod def GetDebugMaterialPoolInitialCapacityAttr(cls, *args, **kwargs) -> Any: ... @classmethod def GetDebugRandomColorsAttr(cls, *args, **kwargs) -> Any: ... @classmethod def GetDebugTexturePoolInitialCapacityAttr(cls, *args, **kwargs) -> Any: ... @classmethod def GetSchemaAttributeNames(cls, *args, **kwargs) -> Any: ... @classmethod def GetSelectedIonServerRel(cls, *args, **kwargs) -> Any: ... @classmethod def _GetStaticTfType(cls, *args, **kwargs) -> Any: ... @classmethod def __bool__(cls) -> bool: ... @classmethod def __reduce__(cls) -> Any: ... class Georeference(pxr.Usd.Typed): __instance_size__: ClassVar[int] = ... @classmethod def __init__(cls, *args, **kwargs) -> None: ... @classmethod def CreateGeoreferenceOriginHeightAttr(cls, *args, **kwargs) -> Any: ... @classmethod def CreateGeoreferenceOriginLatitudeAttr(cls, *args, **kwargs) -> Any: ... @classmethod def CreateGeoreferenceOriginLongitudeAttr(cls, *args, **kwargs) -> Any: ... @classmethod def Define(cls, *args, **kwargs) -> Any: ... @classmethod def Get(cls, *args, **kwargs) -> Any: ... @classmethod def GetGeoreferenceOriginHeightAttr(cls, *args, **kwargs) -> Any: ... @classmethod def GetGeoreferenceOriginLatitudeAttr(cls, *args, **kwargs) -> Any: ... @classmethod def GetGeoreferenceOriginLongitudeAttr(cls, *args, **kwargs) -> Any: ... @classmethod def GetSchemaAttributeNames(cls, *args, **kwargs) -> Any: ... @classmethod def _GetStaticTfType(cls, *args, **kwargs) -> Any: ... @classmethod def __bool__(cls) -> bool: ... @classmethod def __reduce__(cls) -> Any: ... class GlobeAnchorAPI(pxr.Usd.APISchemaBase): __instance_size__: ClassVar[int] = ... @classmethod def __init__(cls, *args, **kwargs) -> None: ... @classmethod def Apply(cls, *args, **kwargs) -> Any: ... @classmethod def CanApply(cls, *args, **kwargs) -> Any: ... @classmethod def CreateAdjustOrientationForGlobeWhenMovingAttr(cls, *args, **kwargs) -> Any: ... @classmethod def CreateAnchorHeightAttr(cls, *args, **kwargs) -> Any: ... @classmethod def CreateAnchorLatitudeAttr(cls, *args, **kwargs) -> Any: ... @classmethod def CreateAnchorLongitudeAttr(cls, *args, **kwargs) -> Any: ... @classmethod def CreateDetectTransformChangesAttr(cls, *args, **kwargs) -> Any: ... @classmethod def CreateGeoreferenceBindingRel(cls, *args, **kwargs) -> Any: ... @classmethod def CreatePositionAttr(cls, *args, **kwargs) -> Any: ... @classmethod def Get(cls, *args, **kwargs) -> Any: ... @classmethod def GetAdjustOrientationForGlobeWhenMovingAttr(cls, *args, **kwargs) -> Any: ... @classmethod def GetAnchorHeightAttr(cls, *args, **kwargs) -> Any: ... @classmethod def GetAnchorLatitudeAttr(cls, *args, **kwargs) -> Any: ... @classmethod def GetAnchorLongitudeAttr(cls, *args, **kwargs) -> Any: ... @classmethod def GetDetectTransformChangesAttr(cls, *args, **kwargs) -> Any: ... @classmethod def GetGeoreferenceBindingRel(cls, *args, **kwargs) -> Any: ... @classmethod def GetPositionAttr(cls, *args, **kwargs) -> Any: ... @classmethod def GetSchemaAttributeNames(cls, *args, **kwargs) -> Any: ... @classmethod def _GetStaticTfType(cls, *args, **kwargs) -> Any: ... @classmethod def __bool__(cls) -> bool: ... @classmethod def __reduce__(cls) -> Any: ... class IonRasterOverlay(RasterOverlay): __instance_size__: ClassVar[int] = ... @classmethod def __init__(cls, *args, **kwargs) -> None: ... @classmethod def CreateIonAccessTokenAttr(cls, *args, **kwargs) -> Any: ... @classmethod def CreateIonAssetIdAttr(cls, *args, **kwargs) -> Any: ... @classmethod def CreateIonServerBindingRel(cls, *args, **kwargs) -> Any: ... @classmethod def Define(cls, *args, **kwargs) -> Any: ... @classmethod def Get(cls, *args, **kwargs) -> Any: ... @classmethod def GetIonAccessTokenAttr(cls, *args, **kwargs) -> Any: ... @classmethod def GetIonAssetIdAttr(cls, *args, **kwargs) -> Any: ... @classmethod def GetIonServerBindingRel(cls, *args, **kwargs) -> Any: ... @classmethod def GetSchemaAttributeNames(cls, *args, **kwargs) -> Any: ... @classmethod def _GetStaticTfType(cls, *args, **kwargs) -> Any: ... @classmethod def __bool__(cls) -> bool: ... @classmethod def __reduce__(cls) -> Any: ... class IonServer(pxr.Usd.Typed): __instance_size__: ClassVar[int] = ... @classmethod def __init__(cls, *args, **kwargs) -> None: ... @classmethod def CreateDisplayNameAttr(cls, *args, **kwargs) -> Any: ... @classmethod def CreateIonServerApiUrlAttr(cls, *args, **kwargs) -> Any: ... @classmethod def CreateIonServerApplicationIdAttr(cls, *args, **kwargs) -> Any: ... @classmethod def CreateIonServerUrlAttr(cls, *args, **kwargs) -> Any: ... @classmethod def CreateProjectDefaultIonAccessTokenAttr(cls, *args, **kwargs) -> Any: ... @classmethod def CreateProjectDefaultIonAccessTokenIdAttr(cls, *args, **kwargs) -> Any: ... @classmethod def Define(cls, *args, **kwargs) -> Any: ... @classmethod def Get(cls, *args, **kwargs) -> Any: ... @classmethod def GetDisplayNameAttr(cls, *args, **kwargs) -> Any: ... @classmethod def GetIonServerApiUrlAttr(cls, *args, **kwargs) -> Any: ... @classmethod def GetIonServerApplicationIdAttr(cls, *args, **kwargs) -> Any: ... @classmethod def GetIonServerUrlAttr(cls, *args, **kwargs) -> Any: ... @classmethod def GetProjectDefaultIonAccessTokenAttr(cls, *args, **kwargs) -> Any: ... @classmethod def GetProjectDefaultIonAccessTokenIdAttr(cls, *args, **kwargs) -> Any: ... @classmethod def GetSchemaAttributeNames(cls, *args, **kwargs) -> Any: ... @classmethod def _GetStaticTfType(cls, *args, **kwargs) -> Any: ... @classmethod def __bool__(cls) -> bool: ... @classmethod def __reduce__(cls) -> Any: ... class PolygonRasterOverlay(RasterOverlay): __instance_size__: ClassVar[int] = ... @classmethod def __init__(cls, *args, **kwargs) -> None: ... @classmethod def CreateCartographicPolygonBindingRel(cls, *args, **kwargs) -> Any: ... @classmethod def CreateCesiumOverlayRenderMethodAttr(cls, *args, **kwargs) -> Any: ... @classmethod def CreateInvertSelectionAttr(cls, *args, **kwargs) -> Any: ... @classmethod def Define(cls, *args, **kwargs) -> Any: ... @classmethod def Get(cls, *args, **kwargs) -> Any: ... @classmethod def GetCartographicPolygonBindingRel(cls, *args, **kwargs) -> Any: ... @classmethod def GetCesiumOverlayRenderMethodAttr(cls, *args, **kwargs) -> Any: ... @classmethod def GetInvertSelectionAttr(cls, *args, **kwargs) -> Any: ... @classmethod def GetSchemaAttributeNames(cls, *args, **kwargs) -> Any: ... @classmethod def _GetStaticTfType(cls, *args, **kwargs) -> Any: ... @classmethod def __bool__(cls) -> bool: ... @classmethod def __reduce__(cls) -> Any: ... class RasterOverlay(pxr.Usd.Typed): __instance_size__: ClassVar[int] = ... @classmethod def __init__(cls, *args, **kwargs) -> None: ... @classmethod def CreateAlphaAttr(cls, *args, **kwargs) -> Any: ... @classmethod def CreateMaximumScreenSpaceErrorAttr(cls, *args, **kwargs) -> Any: ... @classmethod def CreateMaximumSimultaneousTileLoadsAttr(cls, *args, **kwargs) -> Any: ... @classmethod def CreateMaximumTextureSizeAttr(cls, *args, **kwargs) -> Any: ... @classmethod def CreateOverlayRenderMethodAttr(cls, *args, **kwargs) -> Any: ... @classmethod def CreateShowCreditsOnScreenAttr(cls, *args, **kwargs) -> Any: ... @classmethod def CreateSubTileCacheBytesAttr(cls, *args, **kwargs) -> Any: ... @classmethod def Get(cls, *args, **kwargs) -> Any: ... @classmethod def GetAlphaAttr(cls, *args, **kwargs) -> Any: ... @classmethod def GetMaximumScreenSpaceErrorAttr(cls, *args, **kwargs) -> Any: ... @classmethod def GetMaximumSimultaneousTileLoadsAttr(cls, *args, **kwargs) -> Any: ... @classmethod def GetMaximumTextureSizeAttr(cls, *args, **kwargs) -> Any: ... @classmethod def GetOverlayRenderMethodAttr(cls, *args, **kwargs) -> Any: ... @classmethod def GetSchemaAttributeNames(cls, *args, **kwargs) -> Any: ... @classmethod def GetShowCreditsOnScreenAttr(cls, *args, **kwargs) -> Any: ... @classmethod def GetSubTileCacheBytesAttr(cls, *args, **kwargs) -> Any: ... @classmethod def _GetStaticTfType(cls, *args, **kwargs) -> Any: ... @classmethod def __bool__(cls) -> bool: ... @classmethod def __reduce__(cls) -> Any: ... class Session(pxr.Usd.Typed): __instance_size__: ClassVar[int] = ... @classmethod def __init__(cls, *args, **kwargs) -> None: ... @classmethod def CreateEcefToUsdTransformAttr(cls, *args, **kwargs) -> Any: ... @classmethod def Define(cls, *args, **kwargs) -> Any: ... @classmethod def Get(cls, *args, **kwargs) -> Any: ... @classmethod def GetEcefToUsdTransformAttr(cls, *args, **kwargs) -> Any: ... @classmethod def GetSchemaAttributeNames(cls, *args, **kwargs) -> Any: ... @classmethod def _GetStaticTfType(cls, *args, **kwargs) -> Any: ... @classmethod def __bool__(cls) -> bool: ... @classmethod def __reduce__(cls) -> Any: ... class TileMapServiceRasterOverlay(RasterOverlay): __instance_size__: ClassVar[int] = ... @classmethod def __init__(cls, *args, **kwargs) -> None: ... @classmethod def CreateMaximumZoomLevelAttr(cls, *args, **kwargs) -> Any: ... @classmethod def CreateMinimumZoomLevelAttr(cls, *args, **kwargs) -> Any: ... @classmethod def CreateSpecifyZoomLevelsAttr(cls, *args, **kwargs) -> Any: ... @classmethod def CreateUrlAttr(cls, *args, **kwargs) -> Any: ... @classmethod def Define(cls, *args, **kwargs) -> Any: ... @classmethod def Get(cls, *args, **kwargs) -> Any: ... @classmethod def GetMaximumZoomLevelAttr(cls, *args, **kwargs) -> Any: ... @classmethod def GetMinimumZoomLevelAttr(cls, *args, **kwargs) -> Any: ... @classmethod def GetSchemaAttributeNames(cls, *args, **kwargs) -> Any: ... @classmethod def GetSpecifyZoomLevelsAttr(cls, *args, **kwargs) -> Any: ... @classmethod def GetUrlAttr(cls, *args, **kwargs) -> Any: ... @classmethod def _GetStaticTfType(cls, *args, **kwargs) -> Any: ... @classmethod def __bool__(cls) -> bool: ... @classmethod def __reduce__(cls) -> Any: ... class Tileset(pxr.UsdGeom.Gprim): __instance_size__: ClassVar[int] = ... @classmethod def __init__(cls, *args, **kwargs) -> None: ... @classmethod def CreateCulledScreenSpaceErrorAttr(cls, *args, **kwargs) -> Any: ... @classmethod def CreateEnableFogCullingAttr(cls, *args, **kwargs) -> Any: ... @classmethod def CreateEnableFrustumCullingAttr(cls, *args, **kwargs) -> Any: ... @classmethod def CreateEnforceCulledScreenSpaceErrorAttr(cls, *args, **kwargs) -> Any: ... @classmethod def CreateForbidHolesAttr(cls, *args, **kwargs) -> Any: ... @classmethod def CreateGeoreferenceBindingRel(cls, *args, **kwargs) -> Any: ... @classmethod def CreateIonAccessTokenAttr(cls, *args, **kwargs) -> Any: ... @classmethod def CreateIonAssetIdAttr(cls, *args, **kwargs) -> Any: ... @classmethod def CreateIonServerBindingRel(cls, *args, **kwargs) -> Any: ... @classmethod def CreateLoadingDescendantLimitAttr(cls, *args, **kwargs) -> Any: ... @classmethod def CreateMainThreadLoadingTimeLimitAttr(cls, *args, **kwargs) -> Any: ... @classmethod def CreateMaximumCachedBytesAttr(cls, *args, **kwargs) -> Any: ... @classmethod def CreateMaximumScreenSpaceErrorAttr(cls, *args, **kwargs) -> Any: ... @classmethod def CreateMaximumSimultaneousTileLoadsAttr(cls, *args, **kwargs) -> Any: ... @classmethod def CreatePreloadAncestorsAttr(cls, *args, **kwargs) -> Any: ... @classmethod def CreatePreloadSiblingsAttr(cls, *args, **kwargs) -> Any: ... @classmethod def CreateRasterOverlayBindingRel(cls, *args, **kwargs) -> Any: ... @classmethod def CreateShowCreditsOnScreenAttr(cls, *args, **kwargs) -> Any: ... @classmethod def CreateSmoothNormalsAttr(cls, *args, **kwargs) -> Any: ... @classmethod def CreateSourceTypeAttr(cls, *args, **kwargs) -> Any: ... @classmethod def CreateSuspendUpdateAttr(cls, *args, **kwargs) -> Any: ... @classmethod def CreateUrlAttr(cls, *args, **kwargs) -> Any: ... @classmethod def Define(cls, *args, **kwargs) -> Any: ... @classmethod def Get(cls, *args, **kwargs) -> Any: ... @classmethod def GetCulledScreenSpaceErrorAttr(cls, *args, **kwargs) -> Any: ... @classmethod def GetEnableFogCullingAttr(cls, *args, **kwargs) -> Any: ... @classmethod def GetEnableFrustumCullingAttr(cls, *args, **kwargs) -> Any: ... @classmethod def GetEnforceCulledScreenSpaceErrorAttr(cls, *args, **kwargs) -> Any: ... @classmethod def GetForbidHolesAttr(cls, *args, **kwargs) -> Any: ... @classmethod def GetGeoreferenceBindingRel(cls, *args, **kwargs) -> Any: ... @classmethod def GetIonAccessTokenAttr(cls, *args, **kwargs) -> Any: ... @classmethod def GetIonAssetIdAttr(cls, *args, **kwargs) -> Any: ... @classmethod def GetIonServerBindingRel(cls, *args, **kwargs) -> Any: ... @classmethod def GetLoadingDescendantLimitAttr(cls, *args, **kwargs) -> Any: ... @classmethod def GetMainThreadLoadingTimeLimitAttr(cls, *args, **kwargs) -> Any: ... @classmethod def GetMaximumCachedBytesAttr(cls, *args, **kwargs) -> Any: ... @classmethod def GetMaximumScreenSpaceErrorAttr(cls, *args, **kwargs) -> Any: ... @classmethod def GetMaximumSimultaneousTileLoadsAttr(cls, *args, **kwargs) -> Any: ... @classmethod def GetPreloadAncestorsAttr(cls, *args, **kwargs) -> Any: ... @classmethod def GetPreloadSiblingsAttr(cls, *args, **kwargs) -> Any: ... @classmethod def GetRasterOverlayBindingRel(cls, *args, **kwargs) -> Any: ... @classmethod def GetSchemaAttributeNames(cls, *args, **kwargs) -> Any: ... @classmethod def GetShowCreditsOnScreenAttr(cls, *args, **kwargs) -> Any: ... @classmethod def GetSmoothNormalsAttr(cls, *args, **kwargs) -> Any: ... @classmethod def GetSourceTypeAttr(cls, *args, **kwargs) -> Any: ... @classmethod def GetSuspendUpdateAttr(cls, *args, **kwargs) -> Any: ... @classmethod def GetUrlAttr(cls, *args, **kwargs) -> Any: ... @classmethod def _GetStaticTfType(cls, *args, **kwargs) -> Any: ... @classmethod def __bool__(cls) -> bool: ... @classmethod def __reduce__(cls) -> Any: ... class Tokens(Boost.Python.instance): @classmethod def __init__(cls, *args, **kwargs) -> None: ... @classmethod def __reduce__(cls) -> Any: ... @property def cesiumAlpha(self) -> Any: ... @property def cesiumAnchorAdjustOrientationForGlobeWhenMoving(self) -> Any: ... @property def cesiumAnchorDetectTransformChanges(self) -> Any: ... @property def cesiumAnchorGeoreferenceBinding(self) -> Any: ... @property def cesiumAnchorHeight(self) -> Any: ... @property def cesiumAnchorLatitude(self) -> Any: ... @property def cesiumAnchorLongitude(self) -> Any: ... @property def cesiumAnchorPosition(self) -> Any: ... @property def cesiumBaseUrl(self) -> Any: ... @property def cesiumCartographicPolygonBinding(self) -> Any: ... @property def cesiumCulledScreenSpaceError(self) -> Any: ... @property def cesiumDebugDisableGeometryPool(self) -> Any: ... @property def cesiumDebugDisableGeoreferencing(self) -> Any: ... @property def cesiumDebugDisableMaterialPool(self) -> Any: ... @property def cesiumDebugDisableMaterials(self) -> Any: ... @property def cesiumDebugDisableTexturePool(self) -> Any: ... @property def cesiumDebugDisableTextures(self) -> Any: ... @property def cesiumDebugGeometryPoolInitialCapacity(self) -> Any: ... @property def cesiumDebugMaterialPoolInitialCapacity(self) -> Any: ... @property def cesiumDebugRandomColors(self) -> Any: ... @property def cesiumDebugTexturePoolInitialCapacity(self) -> Any: ... @property def cesiumDisplayName(self) -> Any: ... @property def cesiumEast(self) -> Any: ... @property def cesiumEcefToUsdTransform(self) -> Any: ... @property def cesiumEnableFogCulling(self) -> Any: ... @property def cesiumEnableFrustumCulling(self) -> Any: ... @property def cesiumEnforceCulledScreenSpaceError(self) -> Any: ... @property def cesiumForbidHoles(self) -> Any: ... @property def cesiumFormat(self) -> Any: ... @property def cesiumGeoreferenceBinding(self) -> Any: ... @property def cesiumGeoreferenceOriginHeight(self) -> Any: ... @property def cesiumGeoreferenceOriginLatitude(self) -> Any: ... @property def cesiumGeoreferenceOriginLongitude(self) -> Any: ... @property def cesiumInvertSelection(self) -> Any: ... @property def cesiumIonAccessToken(self) -> Any: ... @property def cesiumIonAssetId(self) -> Any: ... @property def cesiumIonServerApiUrl(self) -> Any: ... @property def cesiumIonServerApplicationId(self) -> Any: ... @property def cesiumIonServerBinding(self) -> Any: ... @property def cesiumIonServerUrl(self) -> Any: ... @property def cesiumLayer(self) -> Any: ... @property def cesiumLayers(self) -> Any: ... @property def cesiumLoadingDescendantLimit(self) -> Any: ... @property def cesiumMainThreadLoadingTimeLimit(self) -> Any: ... @property def cesiumMaximumCachedBytes(self) -> Any: ... @property def cesiumMaximumLevel(self) -> Any: ... @property def cesiumMaximumScreenSpaceError(self) -> Any: ... @property def cesiumMaximumSimultaneousTileLoads(self) -> Any: ... @property def cesiumMaximumTextureSize(self) -> Any: ... @property def cesiumMaximumZoomLevel(self) -> Any: ... @property def cesiumMinimumLevel(self) -> Any: ... @property def cesiumMinimumZoomLevel(self) -> Any: ... @property def cesiumNorth(self) -> Any: ... @property def cesiumOverlayRenderMethod(self) -> Any: ... @property def cesiumPreloadAncestors(self) -> Any: ... @property def cesiumPreloadSiblings(self) -> Any: ... @property def cesiumProjectDefaultIonAccessToken(self) -> Any: ... @property def cesiumProjectDefaultIonAccessTokenId(self) -> Any: ... @property def cesiumRasterOverlayBinding(self) -> Any: ... @property def cesiumRootTilesX(self) -> Any: ... @property def cesiumRootTilesY(self) -> Any: ... @property def cesiumSelectedIonServer(self) -> Any: ... @property def cesiumShowCreditsOnScreen(self) -> Any: ... @property def cesiumSmoothNormals(self) -> Any: ... @property def cesiumSourceType(self) -> Any: ... @property def cesiumSouth(self) -> Any: ... @property def cesiumSpecifyTileMatrixSetLabels(self) -> Any: ... @property def cesiumSpecifyTilingScheme(self) -> Any: ... @property def cesiumSpecifyZoomLevels(self) -> Any: ... @property def cesiumStyle(self) -> Any: ... @property def cesiumSubTileCacheBytes(self) -> Any: ... @property def cesiumSuspendUpdate(self) -> Any: ... @property def cesiumTileHeight(self) -> Any: ... @property def cesiumTileMatrixSetId(self) -> Any: ... @property def cesiumTileMatrixSetLabelPrefix(self) -> Any: ... @property def cesiumTileMatrixSetLabels(self) -> Any: ... @property def cesiumTileWidth(self) -> Any: ... @property def cesiumUrl(self) -> Any: ... @property def cesiumUseWebMercatorProjection(self) -> Any: ... @property def cesiumWest(self) -> Any: ... @property def clip(self) -> Any: ... @property def ion(self) -> Any: ... @property def overlay(self) -> Any: ... @property def url(self) -> Any: ... class WebMapServiceRasterOverlay(RasterOverlay): __instance_size__: ClassVar[int] = ... @classmethod def __init__(cls, *args, **kwargs) -> None: ... @classmethod def CreateBaseUrlAttr(cls, *args, **kwargs) -> Any: ... @classmethod def CreateLayersAttr(cls, *args, **kwargs) -> Any: ... @classmethod def CreateMaximumLevelAttr(cls, *args, **kwargs) -> Any: ... @classmethod def CreateMinimumLevelAttr(cls, *args, **kwargs) -> Any: ... @classmethod def CreateTileHeightAttr(cls, *args, **kwargs) -> Any: ... @classmethod def CreateTileWidthAttr(cls, *args, **kwargs) -> Any: ... @classmethod def Define(cls, *args, **kwargs) -> Any: ... @classmethod def Get(cls, *args, **kwargs) -> Any: ... @classmethod def GetBaseUrlAttr(cls, *args, **kwargs) -> Any: ... @classmethod def GetLayersAttr(cls, *args, **kwargs) -> Any: ... @classmethod def GetMaximumLevelAttr(cls, *args, **kwargs) -> Any: ... @classmethod def GetMinimumLevelAttr(cls, *args, **kwargs) -> Any: ... @classmethod def GetSchemaAttributeNames(cls, *args, **kwargs) -> Any: ... @classmethod def GetTileHeightAttr(cls, *args, **kwargs) -> Any: ... @classmethod def GetTileWidthAttr(cls, *args, **kwargs) -> Any: ... @classmethod def _GetStaticTfType(cls, *args, **kwargs) -> Any: ... @classmethod def __bool__(cls) -> bool: ... @classmethod def __reduce__(cls) -> Any: ... class WebMapTileServiceRasterOverlay(RasterOverlay): __instance_size__: ClassVar[int] = ... @classmethod def __init__(cls, *args, **kwargs) -> None: ... @classmethod def CreateEastAttr(cls, *args, **kwargs) -> Any: ... @classmethod def CreateFormatAttr(cls, *args, **kwargs) -> Any: ... @classmethod def CreateLayerAttr(cls, *args, **kwargs) -> Any: ... @classmethod def CreateMaximumZoomLevelAttr(cls, *args, **kwargs) -> Any: ... @classmethod def CreateMinimumZoomLevelAttr(cls, *args, **kwargs) -> Any: ... @classmethod def CreateNorthAttr(cls, *args, **kwargs) -> Any: ... @classmethod def CreateRootTilesXAttr(cls, *args, **kwargs) -> Any: ... @classmethod def CreateRootTilesYAttr(cls, *args, **kwargs) -> Any: ... @classmethod def CreateSouthAttr(cls, *args, **kwargs) -> Any: ... @classmethod def CreateSpecifyTileMatrixSetLabelsAttr(cls, *args, **kwargs) -> Any: ... @classmethod def CreateSpecifyTilingSchemeAttr(cls, *args, **kwargs) -> Any: ... @classmethod def CreateSpecifyZoomLevelsAttr(cls, *args, **kwargs) -> Any: ... @classmethod def CreateStyleAttr(cls, *args, **kwargs) -> Any: ... @classmethod def CreateTileMatrixSetIdAttr(cls, *args, **kwargs) -> Any: ... @classmethod def CreateTileMatrixSetLabelPrefixAttr(cls, *args, **kwargs) -> Any: ... @classmethod def CreateTileMatrixSetLabelsAttr(cls, *args, **kwargs) -> Any: ... @classmethod def CreateUrlAttr(cls, *args, **kwargs) -> Any: ... @classmethod def CreateUseWebMercatorProjectionAttr(cls, *args, **kwargs) -> Any: ... @classmethod def CreateWestAttr(cls, *args, **kwargs) -> Any: ... @classmethod def Define(cls, *args, **kwargs) -> Any: ... @classmethod def Get(cls, *args, **kwargs) -> Any: ... @classmethod def GetEastAttr(cls, *args, **kwargs) -> Any: ... @classmethod def GetFormatAttr(cls, *args, **kwargs) -> Any: ... @classmethod def GetLayerAttr(cls, *args, **kwargs) -> Any: ... @classmethod def GetMaximumZoomLevelAttr(cls, *args, **kwargs) -> Any: ... @classmethod def GetMinimumZoomLevelAttr(cls, *args, **kwargs) -> Any: ... @classmethod def GetNorthAttr(cls, *args, **kwargs) -> Any: ... @classmethod def GetRootTilesXAttr(cls, *args, **kwargs) -> Any: ... @classmethod def GetRootTilesYAttr(cls, *args, **kwargs) -> Any: ... @classmethod def GetSchemaAttributeNames(cls, *args, **kwargs) -> Any: ... @classmethod def GetSouthAttr(cls, *args, **kwargs) -> Any: ... @classmethod def GetSpecifyTileMatrixSetLabelsAttr(cls, *args, **kwargs) -> Any: ... @classmethod def GetSpecifyTilingSchemeAttr(cls, *args, **kwargs) -> Any: ... @classmethod def GetSpecifyZoomLevelsAttr(cls, *args, **kwargs) -> Any: ... @classmethod def GetStyleAttr(cls, *args, **kwargs) -> Any: ... @classmethod def GetTileMatrixSetIdAttr(cls, *args, **kwargs) -> Any: ... @classmethod def GetTileMatrixSetLabelPrefixAttr(cls, *args, **kwargs) -> Any: ... @classmethod def GetTileMatrixSetLabelsAttr(cls, *args, **kwargs) -> Any: ... @classmethod def GetUrlAttr(cls, *args, **kwargs) -> Any: ... @classmethod def GetUseWebMercatorProjectionAttr(cls, *args, **kwargs) -> Any: ... @classmethod def GetWestAttr(cls, *args, **kwargs) -> Any: ... @classmethod def _GetStaticTfType(cls, *args, **kwargs) -> Any: ... @classmethod def __bool__(cls) -> bool: ... @classmethod def __reduce__(cls) -> Any: ... class _CanApplyResult(Boost.Python.instance): __instance_size__: ClassVar[int] = ... @classmethod def __init__(cls, *args, **kwargs) -> None: ... @classmethod def __bool__(cls) -> bool: ... @classmethod def __eq__(cls, other) -> bool: ... @classmethod def __getitem__(cls, index) -> Any: ... @classmethod def __ne__(cls, other) -> bool: ... @classmethod def __reduce__(cls) -> Any: ... @property def whyNot(self) -> Any: ...
28,367
unknown
35.793774
87
0.62608
CesiumGS/cesium-omniverse/exts/cesium.usd.plugins/doc/README.md
# Cesium for Omniverse USD Plugins Supporting package for Cesium for Omniverse containing Cesium's USD plugins and schemas.
125
Markdown
30.499992
88
0.824
CesiumGS/cesium-omniverse/exts/cesium.usd.plugins/config/extension.toml
[core] # Load after omni.usd.libs (-1000) and before omni.usd (0) # See https://docs.omniverse.nvidia.com/py/kit/docs/guide/usd_schema.html order = -100 [package] version = "0.4.0" category = "simulation" feature = false app = false title = "Cesium for Omniverse USD Plugins" description = "Supporting USD Plugins for Cesium for Omniverse" authors = "Cesium GS Inc." repository = "https://github.com/CesiumGS/cesium-omniverse" keywords = [ "cesium", "omniverse", "geospatial", "3D Tiles", "glTF", "globe", "earth", "simulation", ] toggleable = false # Paths are relative to the extension folder changelog = "doc/CHANGES.md" readme = "doc/README.md" preview_image = "doc/images/preview.jpg" icon = "doc/images/icon.png" [package.target] kit = ["105.1"] [package.writeTarget] kit = true python = false # Which extensions this extension depends on [dependencies] "omni.usd.libs" = {} # Main python module this extension provides, it will be publicly available as "import cesium.usd.plugins" [[python.module]] name = "cesium.usd.plugins" [[native.library]] path = "bin/${lib_prefix}CesiumUsdSchemas${lib_ext}"
1,145
TOML
21.92
106
0.702183
CesiumGS/cesium-omniverse/exts/cesium.omniverse.cpp.tests/cesium/omniverse/cpp/tests/extension.py
import os import omni.ext import omni.usd import omni.kit.ui import omni.kit.app from .bindings import acquire_cesium_omniverse_tests_interface, release_cesium_omniverse_tests_interface class CesiumOmniverseCppTestsExtension(omni.ext.IExt): def __init__(self): super().__init__() self.tests_set_up = False self.frames_since_stage_opened = 0 self.frame_count_delta = 0 self.frames_between_setup_and_tests = 15 def on_startup(self): print("Starting Cesium Tests Extension...") global tests_interface tests_interface = acquire_cesium_omniverse_tests_interface() tests_interface.on_startup(os.path.join(os.path.dirname(__file__), "../../../../../cesium.omniverse")) update_stream = omni.kit.app.get_app().get_update_event_stream() # To ensure the tests only run after the stage has been opened, we # attach a handler to an event that occurs every frame. That handler # checks if the stage has opened, runs once, then detaches itself self._run_once_sub = update_stream.create_subscription_to_pop( self.run_once_after_stage_opens, name="Run once after stage opens" ) print("Started Cesium Tests Extension.") def run_once_after_stage_opens(self, _): # wait until the USD stage is fully set up if omni.usd.get_context().get_stage_state() == omni.usd.StageState.OPENED: # set up tests on one frame, then run the tests on the next frame # note we can't use wait_n_frames here as this is a subscribed function # so it cannot be async if not self.tests_set_up: self.tests_set_up = True print("Beginning Cesium Tests Extension tests") stageId = omni.usd.get_context().get_stage_id() tests_interface.set_up_tests(stageId) self.frame_count_delta = 1 elif self.frames_since_stage_opened >= self.frames_between_setup_and_tests: # unsubscribe so there's no way the next frame triggers another run self._run_once_sub.unsubscribe() tests_interface.run_all_tests() print("Cesium Tests Extension tests complete") self.frames_since_stage_opened += self.frame_count_delta def on_shutdown(self): print("Stopping Cesium Tests Extension...") tests_interface.on_shutdown() release_cesium_omniverse_tests_interface(tests_interface) print("Stopped Cesium Tests Extension.")
2,571
Python
41.163934
110
0.639051
CesiumGS/cesium-omniverse/exts/cesium.omniverse.cpp.tests/cesium/omniverse/cpp/tests/bindings/__init__.py
from .CesiumOmniverseCppTestsPythonBindings import * # noqa: F401 F403
72
Python
35.499982
71
0.819444
CesiumGS/cesium-omniverse/exts/cesium.omniverse.cpp.tests/cesium/omniverse/cpp/tests/bindings/CesiumOmniverseCppTestsPythonBindings.pyi
class ICesiumOmniverseCppTestsInterface: def __init__(self, *args, **kwargs) -> None: ... def on_shutdown(self) -> None: ... def on_startup(self, arg0: str) -> None: ... def run_all_tests(self) -> None: ... def set_up_tests(self, arg0: int) -> None: ... def acquire_cesium_omniverse_tests_interface( plugin_name: str = ..., library_path: str = ... ) -> ICesiumOmniverseCppTestsInterface: ... def release_cesium_omniverse_tests_interface(arg0: ICesiumOmniverseCppTestsInterface) -> None: ...
516
unknown
42.08333
98
0.658915
CesiumGS/cesium-omniverse/exts/cesium.omniverse.cpp.tests/doc/README.md
# Cesium for Omniverse Tests Extension This extension is designed to run tests against the Cesium for Omniverse Extension. ## License Apache 2.0 (http://www.apache.org/licenses/LICENSE-2.0.html). Cesium for Omniverse is free for both commercial and non-commercial use.
272
Markdown
33.124996
134
0.786765
CesiumGS/cesium-omniverse/exts/cesium.omniverse.cpp.tests/config/extension.toml
[package] version = "0.1.0" category = "simulation" feature = false app = false title = "Cesium for Omniverse Tests" description = "An extention to run tests against Cesium for Omniverse." authors = "Cesium GS Inc." repository = "https://github.com/CesiumGS/cesium-omniverse" keywords = [ "cesium", "omniverse", "geospatial", "3D Tiles", "glTF", "globe", "earth", "simulation", "test", ] # Paths are relative to the extension folder readme = "doc/README.md" preview_image = "doc/resources/icon.png" icon = "doc/resources/icon.png" [package.target] kit = ["105.*"] # Which extensions this extension depends on [dependencies] "cesium.usd.plugins" = {} "usdrt.scenegraph" = {} # Main python module this extension provides, it will be publicly available as "import cesium.omniverse" [[python.module]] name = "cesium.omniverse.cpp.tests" [[native.plugin]] path = "bin/cesium.omniverse.cpp.tests.plugin"
939
TOML
21.926829
104
0.693291
CesiumGS/cesium-omniverse/exts/cesium.omniverse/cesium/omniverse/extension.py
from .bindings import acquire_cesium_omniverse_interface, release_cesium_omniverse_interface, Viewport from .ui.add_menu_controller import CesiumAddMenuController from .install import perform_vendor_install from .utils import wait_n_frames, dock_window_async, perform_action_after_n_frames_async from .usdUtils import ( add_tileset_ion, add_raster_overlay_ion, add_cartographic_polygon, get_or_create_cesium_data, get_or_create_cesium_georeference, ) from .ui.asset_window import CesiumOmniverseAssetWindow from .ui.debug_window import CesiumOmniverseDebugWindow from .ui.main_window import CesiumOmniverseMainWindow from .ui.settings_window import CesiumOmniverseSettingsWindow from .ui.credits_viewport_frame import CesiumCreditsViewportFrame from .ui.fabric_modal import CesiumFabricModal from .models import AssetToAdd, RasterOverlayToAdd from .ui import CesiumAttributesWidgetController import asyncio from functools import partial import logging import carb.events import carb.settings as omni_settings import omni.ext import omni.kit.app as omni_app import omni.kit.ui import omni.kit.pipapi from omni.kit.viewport.window import get_viewport_window_instances import omni.ui as ui import omni.usd import os from typing import List, Optional, Callable from .ui.credits_viewport_controller import CreditsViewportController from cesium.usd.plugins.CesiumUsdSchemas import Data as CesiumData, IonServer as CesiumIonServer from omni.kit.capture.viewport import CaptureExtension CESIUM_DATA_PRIM_PATH = "/Cesium" cesium_extension_location = os.path.join(os.path.dirname(__file__), "../../") class CesiumOmniverseExtension(omni.ext.IExt): @staticmethod def _set_menu(path, value): # Set the menu to create this window on and off editor_menu = omni.kit.ui.get_editor_menu() if editor_menu: editor_menu.set_value(path, value) def __init__(self) -> None: super().__init__() self._main_window: Optional[CesiumOmniverseMainWindow] = None self._asset_window: Optional[CesiumOmniverseAssetWindow] = None self._debug_window: Optional[CesiumOmniverseDebugWindow] = None self._settings_window: Optional[CesiumOmniverseSettingsWindow] = None self._credits_viewport_frames: List[CesiumCreditsViewportFrame] = [] self._on_stage_subscription: Optional[carb.events.ISubscription] = None self._on_update_subscription: Optional[carb.events.ISubscription] = None self._show_asset_window_subscription: Optional[carb.events.ISubscription] = None self._token_set_subscription: Optional[carb.events.ISubscription] = None self._add_ion_asset_subscription: Optional[carb.events.ISubscription] = None self._add_blank_asset_subscription: Optional[carb.events.ISubscription] = None self._add_raster_overlay_subscription: Optional[carb.events.ISubscription] = None self._add_cartographic_polygon_subscription: Optional[carb.events.ISubscription] = None self._assets_to_add_after_token_set: List[AssetToAdd] = [] self._raster_overlay_to_add_after_token_set: List[RasterOverlayToAdd] = [] self._adding_assets = False self._attributes_widget_controller: Optional[CesiumAttributesWidgetController] = None self._credits_viewport_controller: Optional[CreditsViewportController] = None self._add_menu_controller: Optional[CesiumAddMenuController] = None self._logger: logging.Logger = logging.getLogger(__name__) self._menus = [] self._num_credits_viewport_frames: int = 0 self._capture_instance = None perform_vendor_install() def on_startup(self): # The ability to show up the window if the system requires it. We use it in QuickLayout. ui.Workspace.set_show_window_fn(CesiumOmniverseMainWindow.WINDOW_NAME, partial(self.show_main_window, None)) ui.Workspace.set_show_window_fn( CesiumOmniverseAssetWindow.WINDOW_NAME, partial(self.show_assets_window, None) ) ui.Workspace.set_show_window_fn(CesiumOmniverseDebugWindow.WINDOW_NAME, partial(self.show_debug_window, None)) ui.Workspace.set_show_window_fn( CesiumOmniverseSettingsWindow.WINDOW_NAME, partial(self.show_settings_window, None) ) settings = omni_settings.get_settings() show_on_startup = settings.get_as_bool("/exts/cesium.omniverse/showOnStartup") self._add_to_menu(CesiumOmniverseMainWindow.MENU_PATH, self.show_main_window, show_on_startup) self._add_to_menu(CesiumOmniverseAssetWindow.MENU_PATH, self.show_assets_window, False) self._add_to_menu(CesiumOmniverseDebugWindow.MENU_PATH, self.show_debug_window, False) self._add_to_menu(CesiumOmniverseSettingsWindow.MENU_PATH, self.show_settings_window, False) self._logger.info("CesiumOmniverse startup") # Acquire the Cesium Omniverse interface. global _cesium_omniverse_interface _cesium_omniverse_interface = acquire_cesium_omniverse_interface() _cesium_omniverse_interface.on_startup(cesium_extension_location) settings.set("/rtx/hydra/TBNFrameMode", 1) # Allow material graph to find cesium mdl exports mdl_custom_paths_name = "materialConfig/searchPaths/custom" mdl_user_allow_list_name = "materialConfig/materialGraph/userAllowList" mdl_renderer_custom_paths_name = "/renderer/mdl/searchPaths/custom" cesium_mdl_search_path = os.path.join(cesium_extension_location, "mdl") cesium_mdl_name = "cesium.mdl" mdl_custom_paths = settings.get(mdl_custom_paths_name) or [] mdl_user_allow_list = settings.get(mdl_user_allow_list_name) or [] mdl_custom_paths.append(cesium_mdl_search_path) mdl_user_allow_list.append(cesium_mdl_name) mdl_renderer_custom_paths = settings.get_as_string(mdl_renderer_custom_paths_name) mdl_renderer_custom_paths_sep = "" if mdl_renderer_custom_paths == "" else ";" mdl_renderer_custom_paths = mdl_renderer_custom_paths + mdl_renderer_custom_paths_sep + cesium_mdl_search_path settings.set_string_array(mdl_custom_paths_name, mdl_custom_paths) settings.set_string_array(mdl_user_allow_list_name, mdl_user_allow_list) settings.set_string(mdl_renderer_custom_paths_name, mdl_renderer_custom_paths) # Show the window. It will call `self.show_window` if show_on_startup: asyncio.ensure_future(perform_action_after_n_frames_async(15, CesiumOmniverseExtension._open_window)) self._credits_viewport_controller = CreditsViewportController(_cesium_omniverse_interface) self._add_menu_controller = CesiumAddMenuController(_cesium_omniverse_interface) # Subscribe to stage event stream usd_context = omni.usd.get_context() if usd_context.get_stage_state() == omni.usd.StageState.OPENED: _cesium_omniverse_interface.on_stage_change(usd_context.get_stage_id()) self._on_stage_subscription = usd_context.get_stage_event_stream().create_subscription_to_pop( self._on_stage_event, name="cesium.omniverse.ON_STAGE_EVENT" ) self._on_update_subscription = ( omni_app.get_app() .get_update_event_stream() .create_subscription_to_pop(self._on_update_frame, name="cesium.omniverse.extension.ON_UPDATE_FRAME") ) bus = omni_app.get_app().get_message_bus_event_stream() show_asset_window_event = carb.events.type_from_string("cesium.omniverse.SHOW_ASSET_WINDOW") self._show_asset_window_subscription = bus.create_subscription_to_pop_by_type( show_asset_window_event, self._on_show_asset_window_event ) token_set_event = carb.events.type_from_string("cesium.omniverse.SET_DEFAULT_TOKEN_SUCCESS") self._token_set_subscription = bus.create_subscription_to_pop_by_type(token_set_event, self._on_token_set) add_ion_asset_event = carb.events.type_from_string("cesium.omniverse.ADD_ION_ASSET") self._add_ion_asset_subscription = bus.create_subscription_to_pop_by_type( add_ion_asset_event, self._on_add_ion_asset_event ) add_blank_asset_event = carb.events.type_from_string("cesium.omniverse.ADD_BLANK_ASSET") self._add_blank_asset_subscription = bus.create_subscription_to_pop_by_type( add_blank_asset_event, self._on_add_blank_asset_event ) add_cartographic_polygon_event = carb.events.type_from_string("cesium.omniverse.ADD_CARTOGRAPHIC_POLYGON") self._add_cartographic_polygon_subscription = bus.create_subscription_to_pop_by_type( add_cartographic_polygon_event, self._on_add_cartographic_polygon_event ) add_raster_overlay_event = carb.events.type_from_string("cesium.omniverse.ADD_RASTER_OVERLAY") self._add_raster_overlay_subscription = bus.create_subscription_to_pop_by_type( add_raster_overlay_event, self._on_add_raster_overlay_to_tileset ) self._capture_instance = CaptureExtension.get_instance() def on_shutdown(self): self._menus.clear() if self._main_window is not None: self._main_window.destroy() self._main_window = None if self._asset_window is not None: self._asset_window.destroy() self._asset_window = None if self._debug_window is not None: self._debug_window.destroy() self._debug_window = None if self._settings_window is not None: self._settings_window.destroy() self._settings_window = None if self._credits_viewport_controller is not None: self._credits_viewport_controller.destroy() self._credits_viewport_controller = None # Deregister the function that shows the window from omni.ui ui.Workspace.set_show_window_fn(CesiumOmniverseMainWindow.WINDOW_NAME, None) ui.Workspace.set_show_window_fn(CesiumOmniverseAssetWindow.WINDOW_NAME, None) ui.Workspace.set_show_window_fn(CesiumOmniverseDebugWindow.WINDOW_NAME, None) ui.Workspace.set_show_window_fn(CesiumOmniverseSettingsWindow.WINDOW_NAME, None) if self._on_stage_subscription is not None: self._on_stage_subscription.unsubscribe() self._on_stage_subscription = None if self._on_update_subscription is not None: self._on_update_subscription.unsubscribe() self._on_update_subscription = None if self._token_set_subscription is not None: self._token_set_subscription.unsubscribe() self._token_set_subscription = None if self._add_ion_asset_subscription is not None: self._add_ion_asset_subscription.unsubscribe() self._add_ion_asset_subscription = None if self._add_blank_asset_subscription is not None: self._add_blank_asset_subscription.unsubscribe() self._add_blank_asset_subscription = None if self._add_raster_overlay_subscription is not None: self._add_raster_overlay_subscription.unsubscribe() self._add_raster_overlay_subscription = None if self._add_cartographic_polygon_subscription is not None: self._add_cartographic_polygon_subscription.unsubscribe() self._add_cartographic_polygon_subscription = None if self._show_asset_window_subscription is not None: self._show_asset_window_subscription.unsubscribe() self._show_asset_window_subscription = None if self._attributes_widget_controller is not None: self._attributes_widget_controller.destroy() self._attributes_widget_controller = None if self._add_menu_controller is not None: self._add_menu_controller.destroy() self._add_menu_controller = None self._capture_instance = None self._destroy_credits_viewport_frames() self._logger.info("CesiumOmniverse shutdown") # Release the Cesium Omniverse interface. _cesium_omniverse_interface.on_shutdown() release_cesium_omniverse_interface(_cesium_omniverse_interface) def _on_update_frame(self, _): if omni.usd.get_context().get_stage_state() != omni.usd.StageState.OPENED: return viewports = [] for instance in get_viewport_window_instances(): viewport_api = instance.viewport_api viewport = Viewport() viewport.viewMatrix = viewport_api.view viewport.projMatrix = viewport_api.projection viewport.width = float(viewport_api.resolution[0]) viewport.height = float(viewport_api.resolution[1]) viewports.append(viewport) if len(viewports) != self._num_credits_viewport_frames: self._setup_credits_viewport_frames() self._num_credits_viewport_frames = len(viewports) wait_for_loading_tiles = ( self._capture_instance.progress.capture_status == omni.kit.capture.viewport.CaptureStatus.CAPTURING ) _cesium_omniverse_interface.on_update_frame(viewports, wait_for_loading_tiles) def _on_stage_event(self, event): if _cesium_omniverse_interface is None: return if event.type == int(omni.usd.StageEventType.OPENED): _cesium_omniverse_interface.on_stage_change(omni.usd.get_context().get_stage_id()) self._attributes_widget_controller = CesiumAttributesWidgetController(_cesium_omniverse_interface) # Show Fabric modal if Fabric is disabled. fabric_enabled = omni_settings.get_settings().get_as_bool("/app/useFabricSceneDelegate") if not fabric_enabled: asyncio.ensure_future(perform_action_after_n_frames_async(15, CesiumOmniverseExtension._open_modal)) get_or_create_cesium_data() get_or_create_cesium_georeference() self._setup_ion_server_prims() elif event.type == int(omni.usd.StageEventType.CLOSED): _cesium_omniverse_interface.on_stage_change(0) if self._attributes_widget_controller is not None: self._attributes_widget_controller.destroy() self._attributes_widget_controller = None def _on_show_asset_window_event(self, _): self.do_show_assets_window() def _on_token_set(self, _: carb.events.IEvent): if self._adding_assets: return self._adding_assets = True for asset in self._assets_to_add_after_token_set: self._add_ion_assets(asset) self._assets_to_add_after_token_set.clear() for raster_overlay in self._raster_overlay_to_add_after_token_set: self._add_raster_overlay_to_tileset(raster_overlay) self._raster_overlay_to_add_after_token_set.clear() self._adding_assets = False def _on_add_ion_asset_event(self, event: carb.events.IEvent): asset_to_add = AssetToAdd.from_event(event) self._add_ion_assets(asset_to_add) def _on_add_blank_asset_event(self, event: carb.events.IEvent): asset_to_add = AssetToAdd.from_event(event) self._add_ion_assets(asset_to_add, skip_ion_checks=True) def _on_add_cartographic_polygon_event(self, event: carb.events.IEvent): self._add_cartographic_polygon_assets() def _add_ion_assets(self, asset_to_add: Optional[AssetToAdd], skip_ion_checks=False): if asset_to_add is None: self._logger.warning("Insufficient information to add asset.") return if not skip_ion_checks: session = _cesium_omniverse_interface.get_session() if not session.is_connected(): self._logger.warning("Must be logged in to add ion asset.") return if not _cesium_omniverse_interface.is_default_token_set(): bus = omni_app.get_app().get_message_bus_event_stream() show_token_window_event = carb.events.type_from_string("cesium.omniverse.SHOW_TOKEN_WINDOW") bus.push(show_token_window_event) self._assets_to_add_after_token_set.append(asset_to_add) return if asset_to_add.raster_overlay_name is not None and asset_to_add.raster_overlay_ion_asset_id is not None: tileset_path = add_tileset_ion(asset_to_add.tileset_name, asset_to_add.tileset_ion_asset_id) add_raster_overlay_ion( tileset_path, asset_to_add.raster_overlay_name, asset_to_add.raster_overlay_ion_asset_id ) else: tileset_path = add_tileset_ion(asset_to_add.tileset_name, asset_to_add.tileset_ion_asset_id) if tileset_path == "": self._logger.warning("Error adding tileset and raster overlay to stage") def _add_cartographic_polygon_assets(self): add_cartographic_polygon() def _on_add_raster_overlay_to_tileset(self, event: carb.events.IEvent): raster_overlay_to_add = RasterOverlayToAdd.from_event(event) if raster_overlay_to_add is None: self._logger.warning("Insufficient information to add raster overlay.") self._add_raster_overlay_to_tileset(raster_overlay_to_add) def _add_raster_overlay_to_tileset(self, raster_overlay_to_add: RasterOverlayToAdd): session = _cesium_omniverse_interface.get_session() if not session.is_connected(): self._logger.warning("Must be logged in to add ion asset.") return if not _cesium_omniverse_interface.is_default_token_set(): bus = omni_app.get_app().get_message_bus_event_stream() show_token_window_event = carb.events.type_from_string("cesium.omniverse.SHOW_TOKEN_WINDOW") bus.push(show_token_window_event) self._raster_overlay_to_add_after_token_set.append(raster_overlay_to_add) return add_raster_overlay_ion( raster_overlay_to_add.tileset_path, raster_overlay_to_add.raster_overlay_name, raster_overlay_to_add.raster_overlay_ion_asset_id, ) _cesium_omniverse_interface.reload_tileset(raster_overlay_to_add.tileset_path) def _add_to_menu(self, path, callback: Callable[[bool], None], show_on_startup): editor_menu = omni.kit.ui.get_editor_menu() if editor_menu: self._menus.append(editor_menu.add_item(path, callback, toggle=True, value=show_on_startup)) async def _destroy_window_async(self, path): # Wait one frame, this is due to the one frame defer in Window::_moveToMainOSWindow() await wait_n_frames(1) if path is CesiumOmniverseMainWindow.MENU_PATH: if self._main_window is not None: self._main_window.destroy() self._main_window = None elif path is CesiumOmniverseAssetWindow.MENU_PATH: if self._asset_window is not None: self._asset_window.destroy() self._asset_window = None elif path is CesiumOmniverseDebugWindow.MENU_PATH: if self._debug_window is not None: self._debug_window.destroy() self._debug_window = None elif path is CesiumOmniverseSettingsWindow.MENU_PATH: if self._settings_window is not None: self._settings_window.destroy() self._settings_window = None def _visibility_changed_fn(self, path, visible): # Called when the user pressed "X" self._set_menu(path, visible) if not visible: # Destroy the window, since we are creating new window in show_window asyncio.ensure_future(self._destroy_window_async(path)) def show_main_window(self, _menu, value): if _cesium_omniverse_interface is None: logging.error("Cesium Omniverse Interface is not set.") return if value: self._main_window = CesiumOmniverseMainWindow(_cesium_omniverse_interface, width=300, height=400) self._main_window.set_visibility_changed_fn( partial(self._visibility_changed_fn, CesiumOmniverseMainWindow.MENU_PATH) ) asyncio.ensure_future(dock_window_async(self._main_window)) elif self._main_window is not None: self._main_window.visible = False def do_show_assets_window(self): if self._asset_window: self._asset_window.focus() return self._asset_window = CesiumOmniverseAssetWindow(_cesium_omniverse_interface, width=700, height=300) self._asset_window.set_visibility_changed_fn( partial(self._visibility_changed_fn, CesiumOmniverseAssetWindow.MENU_PATH) ) asyncio.ensure_future(dock_window_async(self._asset_window, "Content")) def show_assets_window(self, _menu, value): if _cesium_omniverse_interface is None: logging.error("Cesium Omniverse Interface is not set.") return if value: self.do_show_assets_window() elif self._asset_window is not None: self._asset_window.visible = False def show_debug_window(self, _menu, value): if _cesium_omniverse_interface is None: logging.error("Cesium Omniverse Interface is not set.") return if value: self._debug_window = CesiumOmniverseDebugWindow( _cesium_omniverse_interface, CesiumOmniverseDebugWindow.WINDOW_NAME, width=300, height=365 ) self._debug_window.set_visibility_changed_fn( partial(self._visibility_changed_fn, CesiumOmniverseDebugWindow.MENU_PATH) ) asyncio.ensure_future(dock_window_async(self._debug_window)) elif self._debug_window is not None: self._debug_window.visible = False def show_settings_window(self, _menu, value): if _cesium_omniverse_interface is None: logging.error("Cesium Omniverse Interface is not set.") return if value: self._settings_window = CesiumOmniverseSettingsWindow( _cesium_omniverse_interface, CesiumOmniverseSettingsWindow.WINDOW_NAME, width=300, height=365 ) self._settings_window.set_visibility_changed_fn( partial(self._visibility_changed_fn, CesiumOmniverseSettingsWindow.MENU_PATH) ) asyncio.ensure_future(dock_window_async(self._settings_window)) elif self._settings_window is not None: self._settings_window.visible = False def _setup_credits_viewport_frames(self): self._destroy_credits_viewport_frames() self._credits_viewport_frames = [ CesiumCreditsViewportFrame(_cesium_omniverse_interface, i) for i in get_viewport_window_instances() ] if self._credits_viewport_controller is not None: self._credits_viewport_controller.broadcast_credits() def _destroy_credits_viewport_frames(self): for credits_viewport_frame in self._credits_viewport_frames: credits_viewport_frame.destroy() self._credits_viewport_frames.clear() @staticmethod def _open_window(): ui.Workspace.show_window(CesiumOmniverseMainWindow.WINDOW_NAME) @staticmethod def _open_modal(): CesiumFabricModal() def _setup_ion_server_prims(self): # TODO: Move a lot of this to usdUtils.py stage = omni.usd.get_context().get_stage() server_prims: List[CesiumIonServer] = [x for x in stage.Traverse() if x.IsA(CesiumIonServer)] if len(server_prims) < 1: # If we have no ion server prims, lets add a default one for the official ion servers. path = "/CesiumServers/IonOfficial" prim: CesiumIonServer = CesiumIonServer.Define(stage, path) prim.GetDisplayNameAttr().Set("ion.cesium.com") prim.GetIonServerUrlAttr().Set("https://ion.cesium.com/") prim.GetIonServerApiUrlAttr().Set("https://api.cesium.com/") prim.GetIonServerApplicationIdAttr().Set(413) data_prim: CesiumData = CesiumData.Get(stage, CESIUM_DATA_PRIM_PATH) data_prim.GetSelectedIonServerRel().AddTarget(path)
24,467
Python
44.227357
118
0.666285
CesiumGS/cesium-omniverse/exts/cesium.omniverse/cesium/omniverse/__init__.py
from .extension import * # noqa: F401 F403 F405 from .utils import * # noqa: F401 F403 F405 from .usdUtils import * # noqa: F401 F403 F405 from .ui import * # noqa: F401 F403 F405
184
Python
35.999993
48
0.695652
CesiumGS/cesium-omniverse/exts/cesium.omniverse/cesium/omniverse/usdUtils/usdUtils.py
import omni.usd import re from pxr import Sdf from typing import List, Optional from pxr import UsdGeom from cesium.usd.plugins.CesiumUsdSchemas import ( Data as CesiumData, Tileset as CesiumTileset, IonRasterOverlay as CesiumIonRasterOverlay, Georeference as CesiumGeoreference, GlobeAnchorAPI as CesiumGlobeAnchorAPI, Tokens as CesiumTokens, ) CESIUM_DATA_PRIM_PATH = "/Cesium" CESIUM_GEOREFERENCE_PRIM_PATH = "/CesiumGeoreference" def get_safe_name(name: str) -> str: return re.sub("[\\W]+", "_", name) def get_or_create_cesium_data() -> CesiumData: stage = omni.usd.get_context().get_stage() path = CESIUM_DATA_PRIM_PATH prim = stage.GetPrimAtPath(path) if prim.IsValid(): return CesiumData.Get(stage, path) return CesiumData.Define(stage, path) def get_or_create_cesium_georeference() -> CesiumGeoreference: stage = omni.usd.get_context().get_stage() georeference_paths = get_georeference_paths() if len(georeference_paths) < 1: return CesiumGeoreference.Define(stage, CESIUM_GEOREFERENCE_PRIM_PATH) return CesiumGeoreference.Get(stage, georeference_paths[0]) def add_tileset_ion(name: str, asset_id: int, token: str = "") -> str: stage = omni.usd.get_context().get_stage() safe_name = get_safe_name(name) if not safe_name.startswith("/"): safe_name = "/" + safe_name # get_stage_next_free_path will increment the path name if there is a collision tileset_path = omni.usd.get_stage_next_free_path(stage, safe_name, False) tileset = CesiumTileset.Define(stage, tileset_path) tileset.GetIonAssetIdAttr().Set(asset_id) tileset.GetIonAccessTokenAttr().Set(token) tileset.GetSourceTypeAttr().Set(CesiumTokens.ion) georeference = get_or_create_cesium_georeference() georeference_path = georeference.GetPath().pathString tileset.GetGeoreferenceBindingRel().AddTarget(georeference_path) server_prim_path = get_path_to_current_ion_server() if server_prim_path != "": tileset.GetIonServerBindingRel().AddTarget(server_prim_path) return tileset_path def add_raster_overlay_ion(tileset_path: str, name: str, asset_id: int, token: str = "") -> str: stage = omni.usd.get_context().get_stage() safe_name = get_safe_name(name) raster_overlay_path = Sdf.Path(tileset_path).AppendPath(safe_name).pathString # get_stage_next_free_path will increment the path name if there is a collision raster_overlay_path = omni.usd.get_stage_next_free_path(stage, raster_overlay_path, False) raster_overlay = CesiumIonRasterOverlay.Define(stage, raster_overlay_path) tileset_prim = CesiumTileset.Get(stage, tileset_path) tileset_prim.GetRasterOverlayBindingRel().AddTarget(raster_overlay_path) raster_overlay.GetIonAssetIdAttr().Set(asset_id) raster_overlay.GetIonAccessTokenAttr().Set(token) server_prim_path = get_path_to_current_ion_server() if server_prim_path != "": raster_overlay.GetIonServerBindingRel().AddTarget(server_prim_path) return raster_overlay_path def add_cartographic_polygon() -> str: stage = omni.usd.get_context().get_stage() name = "cartographic_polygon" cartographic_polygon_path = Sdf.Path("/CesiumCartographicPolygons").AppendPath(name).pathString cartographic_polygon_path = omni.usd.get_stage_next_free_path(stage, cartographic_polygon_path, False) basis_curves = UsdGeom.BasisCurves.Define(stage, cartographic_polygon_path) basis_curves.GetTypeAttr().Set("linear") basis_curves.GetWrapAttr().Set("periodic") # Set curve to have 10m edge lengths curve_size = 10 / UsdGeom.GetStageMetersPerUnit(stage) basis_curves.GetPointsAttr().Set( [ (-curve_size, 0, -curve_size), (-curve_size, 0, curve_size), (curve_size, 0, curve_size), (curve_size, 0, -curve_size), ] ) basis_curves.GetCurveVertexCountsAttr().Set([4]) # Set curve to a 0.5m width curve_width = 0.5 / UsdGeom.GetStageMetersPerUnit(stage) basis_curves.GetWidthsAttr().Set([curve_width, curve_width, curve_width, curve_width]) add_globe_anchor_to_prim(cartographic_polygon_path) return cartographic_polygon_path def is_tileset(path: str) -> bool: stage = omni.usd.get_context().get_stage() prim = stage.GetPrimAtPath(path) return prim.IsA(CesiumTileset) def remove_tileset(path: str) -> None: stage = omni.usd.get_context().get_stage() stage.RemovePrim(path) def get_path_to_current_ion_server() -> Optional[str]: data = get_or_create_cesium_data() rel = data.GetSelectedIonServerRel() targets = rel.GetForwardedTargets() if len(targets) < 1: return None return targets[0].pathString def set_path_to_current_ion_server(path: str) -> None: data = get_or_create_cesium_data() rel = data.GetSelectedIonServerRel() # This check helps avoid sending unnecessary USD notifications # See https://github.com/CesiumGS/cesium-omniverse/issues/640 if get_path_to_current_ion_server() != path: rel.SetTargets([path]) def get_tileset_paths() -> List[str]: stage = omni.usd.get_context().get_stage() paths = [x.GetPath().pathString for x in stage.Traverse() if x.IsA(CesiumTileset)] return paths def get_georeference_paths() -> List[str]: stage = omni.usd.get_context().get_stage() paths = [x.GetPath().pathString for x in stage.Traverse() if x.IsA(CesiumGeoreference)] return paths def add_globe_anchor_to_prim(path: str) -> CesiumGlobeAnchorAPI: stage = omni.usd.get_context().get_stage() prim = stage.GetPrimAtPath(path) georeference_path = get_or_create_cesium_georeference().GetPath().pathString globe_anchor = CesiumGlobeAnchorAPI.Apply(prim) globe_anchor.GetGeoreferenceBindingRel().AddTarget(georeference_path) return globe_anchor
5,914
Python
30.972973
106
0.701048
CesiumGS/cesium-omniverse/exts/cesium.omniverse/cesium/omniverse/usdUtils/__init__.py
from .usdUtils import * # noqa: F401 F403
43
Python
20.99999
42
0.697674
CesiumGS/cesium-omniverse/exts/cesium.omniverse/cesium/omniverse/install/wheel_installer.py
from dataclasses import dataclass import logging from pathlib import Path import platform import omni.kit.app as app import omni.kit.pipapi from ..utils.utils import str_is_empty_or_none @dataclass class WheelInfo: """ Data class containing the module and wheel file names for each platform. """ module: str windows_whl: str linux_x64_whl: str linux_aarch_whl: str class WheelInstaller: """ Class for installing wheel files bundled with the extension. """ def __init__(self, info: WheelInfo, extension_module="cesium.omniverse"): """ Creates a new instance of a wheel installer for installing a python package. :param info: A WheelInfo data class containing the information for wheel installation. :param extension_module: The full module for the extension, if a different extension is using this class. :raises ValueError: If any arguments are null or empty strings. """ self._logger = logging.getLogger(__name__) if ( str_is_empty_or_none(info.windows_whl) or str_is_empty_or_none(info.linux_x64_whl) or str_is_empty_or_none(info.linux_aarch_whl) ): raise ValueError(f"One or more wheels is missing for {info.module}.") self._info = info manager = app.get_app().get_extension_manager() ext_id = manager.get_extension_id_by_module(extension_module) self._vendor_directory_path = Path(manager.get_extension_path(ext_id)).joinpath("vendor") def install(self) -> bool: """ Installs the correct wheel for the current platform. :return: ``True`` if the installation was successful. """ if platform.system() == "Windows": return self._perform_install(self._info.windows_whl) else: machine = platform.machine() if machine.startswith("arm") or machine.startswith("aarch"): return self._perform_install(self._info.linux_aarch_whl) return self._perform_install(self._info.linux_x64_whl) def _perform_install(self, wheel_file_name: str) -> bool: """ Performs the actual installation of the wheel file. :param wheel_file_name: The file name of the wheel to install. :return: ``True`` if the installation was successful. """ path = self._vendor_directory_path.joinpath(wheel_file_name) return omni.kit.pipapi.install( package=str(path), module=self._info.module, use_online_index=False, ignore_cache=True, ignore_import_check=False, )
2,682
Python
30.940476
113
0.631991
CesiumGS/cesium-omniverse/exts/cesium.omniverse/cesium/omniverse/install/vendor_install.py
import logging from typing import List from .wheel_installer import WheelInfo, WheelInstaller def perform_vendor_install(): logger = logging.getLogger(__name__) # Only vendor wheels for the main Cesium Omniverse extension should be placed here. # This action needs to be mirrored for each extension. vendor_wheels: List[WheelInfo] = [ WheelInfo( module="lxml", windows_whl="lxml-4.9.2-cp310-cp310-win_amd64.whl", linux_x64_whl=( "lxml-4.9.2-cp310-cp310-manylinux_2_17_x86_64.manylinux2014_x86_64.manylinux_2_24_x86_64.whl" ), linux_aarch_whl=( "lxml-4.9.2-cp310-cp310-manylinux_2_17_aarch64.manylinux2014_aarch64.manylinux_2_24_aarch64.whl" ), ) ] for w in vendor_wheels: installer = WheelInstaller(w) if not installer.install(): logger.error(f"Could not install wheel for {w.module}")
964
Python
32.275861
112
0.623444
CesiumGS/cesium-omniverse/exts/cesium.omniverse/cesium/omniverse/install/__init__.py
from .wheel_installer import WheelInfo, WheelInstaller # noqa: F401 F403 from .vendor_install import perform_vendor_install # noqa: F401 F403
144
Python
47.333318
73
0.791667
CesiumGS/cesium-omniverse/exts/cesium.omniverse/cesium/omniverse/ui/asset_details_widget.py
from typing import Optional import carb.events import omni.kit.app as app import omni.ui as ui import omni.usd as usd from ..bindings import ICesiumOmniverseInterface from .models import IonAssetItem from ..models import AssetToAdd, RasterOverlayToAdd from .styles import CesiumOmniverseUiStyles from ..usdUtils import is_tileset, get_tileset_paths class CesiumAssetDetailsWidget(ui.ScrollingFrame): def __init__( self, cesium_omniverse_interface: ICesiumOmniverseInterface, asset: Optional[IonAssetItem] = None, **kwargs ): super().__init__(**kwargs) self._cesium_omniverse_interface = cesium_omniverse_interface self.style = CesiumOmniverseUiStyles.asset_detail_frame self._name = asset.name.as_string if asset else "" self._id = asset.id.as_int if asset else 0 self._description = asset.description.as_string if asset else "" self._attribution = asset.attribution.as_string if asset else "" self._asset_type = asset.type.as_string if asset else "" self._name_label: Optional[ui.Label] = None self._id_label: Optional[ui.Label] = None self._description_label: Optional[ui.Label] = None self._attribution_label: Optional[ui.Label] = None self.set_build_fn(self._build_fn) def __del__(self): self.destroy() def destroy(self) -> None: if self._name_label is not None: self._name_label.destroy() if self._id_label is not None: self._id_label.destroy() if self._description_label is not None: self._description_label.destroy() if self._attribution_label is not None: self._attribution_label.destroy() def update_selection(self, asset: Optional[IonAssetItem]): self._name = asset.name.as_string if asset else "" self._id = asset.id.as_int if asset else 0 self._description = asset.description.as_string if asset else "" self._attribution = asset.attribution.as_string if asset else "" self._asset_type = asset.type.as_string if asset else "" self.rebuild() def _should_be_visible(self): return self._name != "" or self._id != 0 or self._description != "" or self._attribution != "" def _add_overlay_with_tileset(self): asset_to_add = AssetToAdd("Cesium World Terrain", 1, self._name, self._id) add_asset_event = carb.events.type_from_string("cesium.omniverse.ADD_ION_ASSET") app.get_app().get_message_bus_event_stream().push(add_asset_event, payload=asset_to_add.to_dict()) def _add_tileset_button_clicked(self): asset_to_add = AssetToAdd(self._name, self._id) add_asset_event = carb.events.type_from_string("cesium.omniverse.ADD_ION_ASSET") app.get_app().get_message_bus_event_stream().push(add_asset_event, payload=asset_to_add.to_dict()) def _add_raster_overlay_button_clicked(self): context = usd.get_context() selection = context.get_selection().get_selected_prim_paths() tileset_path: Optional[str] = None if len(selection) > 0 and is_tileset(context.get_stage().GetPrimAtPath(selection[0])): tileset_path = selection[0] if tileset_path is None: all_tileset_paths = get_tileset_paths() if len(all_tileset_paths) > 0: tileset_path = all_tileset_paths[0] else: self._add_overlay_with_tileset() return raster_overlay_to_add = RasterOverlayToAdd(tileset_path, self._id, self._name) add_raster_overlay_event = carb.events.type_from_string("cesium.omniverse.ADD_RASTER_OVERLAY") app.get_app().get_message_bus_event_stream().push( add_raster_overlay_event, payload=raster_overlay_to_add.to_dict() ) def _build_fn(self): with self: if self._should_be_visible(): with ui.VStack(spacing=20): with ui.VStack(spacing=5): ui.Label( self._name, style=CesiumOmniverseUiStyles.asset_detail_name_label, height=0, word_wrap=True, ) ui.Label( f"(ID: {self._id})", style=CesiumOmniverseUiStyles.asset_detail_id_label, height=0, word_wrap=True, ) with ui.HStack(spacing=0, height=0): ui.Spacer(height=0) if self._asset_type == "3DTILES" or self._asset_type == "TERRAIN": ui.Button( "Add to Stage", width=0, height=0, style=CesiumOmniverseUiStyles.blue_button_style, clicked_fn=self._add_tileset_button_clicked, ) elif self._asset_type == "RASTER_OVERLAY": ui.Button( "Use as Terrain Tileset Base Layer", width=0, height=0, style=CesiumOmniverseUiStyles.blue_button_style, clicked_fn=self._add_raster_overlay_button_clicked, ) else: # Skipping adding a button for things we cannot add for now. pass ui.Spacer(height=0) with ui.VStack(spacing=5): ui.Label("Description", style=CesiumOmniverseUiStyles.asset_detail_header_label, height=0) ui.Label(self._description, word_wrap=True, alignment=ui.Alignment.TOP, height=0) with ui.VStack(spacing=5): ui.Label("Attribution", style=CesiumOmniverseUiStyles.asset_detail_header_label, height=0) ui.Label(self._attribution, word_wrap=True, alignment=ui.Alignment.TOP, height=0) else: ui.Spacer()
6,333
Python
42.682758
115
0.552503
CesiumGS/cesium-omniverse/exts/cesium.omniverse/cesium/omniverse/ui/debug_window.py
import logging from typing import Optional import omni.ui as ui from .statistics_widget import CesiumOmniverseStatisticsWidget from ..bindings import ICesiumOmniverseInterface from ..usdUtils import remove_tileset, get_tileset_paths class CesiumOmniverseDebugWindow(ui.Window): WINDOW_NAME = "Cesium Debugging" MENU_PATH = f"Window/Cesium/{WINDOW_NAME}" _logger: logging.Logger _cesium_omniverse_interface: Optional[ICesiumOmniverseInterface] = None def __init__(self, cesium_omniverse_interface: ICesiumOmniverseInterface, title: str, **kwargs): super().__init__(title, **kwargs) self._logger = logging.getLogger(__name__) self._cesium_omniverse_interface = cesium_omniverse_interface self._statistics_widget: Optional[CesiumOmniverseStatisticsWidget] = None # Set the function that is called to build widgets when the window is visible self.frame.set_build_fn(self._build_fn) def destroy(self): if self._statistics_widget is not None: self._statistics_widget.destroy() self._statistics_widget = None # It will destroy all the children super().destroy() def __del__(self): self.destroy() @staticmethod def show_window(): ui.Workspace.show_window(CesiumOmniverseDebugWindow.WINDOW_NAME) def _build_fn(self): """Builds out the UI buttons and their handlers.""" def remove_all_tilesets(): """Removes all tilesets from the stage.""" tileset_paths = get_tileset_paths() for tileset_path in tileset_paths: remove_tileset(tileset_path) def reload_all_tilesets(): """Reloads all tilesets.""" tileset_paths = get_tileset_paths() for tileset_path in tileset_paths: self._cesium_omniverse_interface.reload_tileset(tileset_path) with ui.VStack(spacing=10): with ui.VStack(): ui.Button("Remove all Tilesets", height=20, clicked_fn=remove_all_tilesets) ui.Button("Reload all Tilesets", height=20, clicked_fn=reload_all_tilesets) self._statistics_widget = CesiumOmniverseStatisticsWidget(self._cesium_omniverse_interface)
2,270
Python
33.938461
103
0.659912
CesiumGS/cesium-omniverse/exts/cesium.omniverse/cesium/omniverse/ui/uri_image.py
import urllib.request from io import BytesIO from PIL import Image import omni.ui as ui class CesiumUriImage: """A wrapper around an ui.ImageProvider that provides a clean way to load images from URIs or base64 encoded data strings.""" def __init__(self, src: str, padding=0, height=None, **kwargs): style_type = kwargs.pop("style_type_name_override", self.__class__.__name__) name = kwargs.pop("name", "") with ui.ZStack(height=0, width=0): # This is copied from uri_image.py since we seem to blow the stack if we nest any deeper when rendering. data = urllib.request.urlopen(src).read() img_data = BytesIO(data) image = Image.open(img_data) if image.mode != "RGBA": image = image.convert("RGBA") pixels = list(image.getdata()) provider = ui.ByteImageProvider() provider.set_bytes_data(pixels, [image.size[0], image.size[1]]) if height is None: width = image.size[0] height = image.size[1] else: # If the user is explicitely setting the height of the image, we need to calc an appropriate width width = image.size[0] * (height / image.size[1]) # Add padding for all sides height += padding * 2 width += padding * 2 self._image = ui.ImageWithProvider( provider, width=width, height=height, fill_policy=ui.IwpFillPolicy.IWP_PRESERVE_ASPECT_FIT, style={"alignment": ui.Alignment.CENTER, "margin": padding}, style_type_name_override=style_type, name=name, ) def get_image(self): return self._image
1,823
Python
36.224489
117
0.563357
CesiumGS/cesium-omniverse/exts/cesium.omniverse/cesium/omniverse/ui/styles.py
from omni.ui import Alignment, color as cl, Direction class CesiumOmniverseUiStyles: intro_label_style = { "font_size": 16, } troubleshooter_header_style = { "font_size": 18, } attribution_header_style = { "font_size": 18, } quick_add_section_label = { "font_size": 20, "margin": 5, } quick_add_button = {"Button.Label": {"font_size": 16}} blue_button_style = { "Button": { "background_color": cl("#4BA1CA"), "padding": 12, }, "Button.Label": { "color": cl("#FFF"), "font_size": 16, }, "Button:hovered": { "background_color": cl("#3C81A2"), }, "Button:pressed": {"background_color": cl("#2D6179")}, } top_bar_button_style = { "Button": {"padding": 10.0, "stack_direction": Direction.TOP_TO_BOTTOM}, "Button.Image": { "alignment": Alignment.CENTER, }, "Button.Label": {"alignment": Alignment.CENTER_BOTTOM}, "Button.Image:disabled": {"color": cl("#808080")}, "Button.Label:disabled": {"color": cl("#808080")}, } asset_detail_frame = {"ScrollingFrame": {"background_color": cl("#1F2123"), "padding": 10}} asset_detail_name_label = {"font_size": 22} asset_detail_header_label = {"font_size": 18} asset_detail_id_label = {"font_size": 14} asset_detail_content_label = {"font_size": 16}
1,483
Python
24.586206
95
0.527984
CesiumGS/cesium-omniverse/exts/cesium.omniverse/cesium/omniverse/ui/credits_parser.py
import logging import omni.ui as ui import webbrowser from dataclasses import dataclass from functools import partial from typing import Optional, List, Tuple from .uri_image import CesiumUriImage from .image_button import CesiumImageButton @dataclass class ParsedCredit: text: Optional[str] = None image_uri: Optional[str] = None link: Optional[str] = None class CesiumCreditsParser: """Takes in a credits array and outputs the elements necessary to show the credits. Should be embedded in a VStack or HStack.""" def _parse_element(self, element, link: Optional[str] = None) -> List[ParsedCredit]: results = [] tag = element.tag if tag == "html" or tag == "body": for child in element.iterchildren(): results.extend(self._parse_element(child, link)) elif tag == "a": # TODO: We probably need to do some sanitization of the href. link = element.attrib["href"] text = "".join(element.itertext()) if text != "": results.append(ParsedCredit(text=text, link=link)) for child in element.iterchildren(): results.extend(self._parse_element(child, link)) elif tag == "img": src = element.attrib["src"] if link is None: results.append(ParsedCredit(image_uri=src)) else: results.append(ParsedCredit(image_uri=src, link=link)) elif tag == "span" or tag == "div": for child in element.iterchildren(): results.extend(self._parse_element(child, link)) # Sometimes divs or spans have text. text = "".join(element.itertext()) if text: results.append(ParsedCredit(text=text)) else: text = "".join(element.itertext()) if link is None: results.append(ParsedCredit(text=text)) else: results.append(ParsedCredit(text=text, link=link)) return results def _parse_credits( self, asset_credits: List[Tuple[str, bool]], should_show_on_screen: bool, perform_fallback=False ) -> List[ParsedCredit]: results = [] try: from lxml import etree parser = etree.HTMLParser() for credit, show_on_screen in asset_credits: if credit == "" or show_on_screen is not should_show_on_screen: continue if credit[0] == "<": try: doc = etree.fromstring(credit, parser) results.extend(self._parse_element(doc)) continue except etree.XMLSyntaxError as err: self._logger.info(err) results.append(ParsedCredit(text=credit)) except Exception as e: self._logger.debug(e) if perform_fallback: self._logger.warning("Performing credits fallback.") for credit, _ in asset_credits: results.append(ParsedCredit(text=credit)) return results @staticmethod def _button_clicked(link: str): webbrowser.open_new_tab(link) def _build_ui_elements(self, parsed_credits: List[ParsedCredit], label_alignment: ui.Alignment): for parsed_credit in parsed_credits: # VStack + Spacer pushes our content to the bottom of the Stack to account for varying heights with ui.VStack(spacing=0, width=0): ui.Spacer() if parsed_credit.image_uri is not None: if parsed_credit.link is not None: CesiumImageButton( src=parsed_credit.image_uri, padding=4, height=28, clicked_fn=partial(self._button_clicked, parsed_credit.link), ) else: CesiumUriImage(src=parsed_credit.image_uri, padding=4, height=28) elif parsed_credit.text is not None: if parsed_credit.link is not None: ui.Button( parsed_credit.text, clicked_fn=partial(self._button_clicked, parsed_credit.link), height=0, width=0, ) else: ui.Label(parsed_credit.text, height=0, word_wrap=True, alignment=label_alignment) def _build_ui(self, parsed_credits: List[ParsedCredit], combine_labels: bool, label_alignment: ui.Alignment): if combine_labels: label_strings = [] other_credits = [] for credit in parsed_credits: if credit.text is not None and credit.link is None: label_strings.append(credit.text) else: other_credits.append(credit) label_strings_combined = " - ".join(label_strings) # Add the label even if the string is empty. The label will expand to fill the parent HStack # which acts like a spacer that right-aligns the image and button elements. Eventually we # should find a different solution here. # VStack + Spacer pushes our content to the bottom of the Stack to account for varying heights with ui.VStack(spacing=0): ui.Spacer() ui.Label(label_strings_combined, height=0, word_wrap=True, alignment=label_alignment) self._build_ui_elements(other_credits, label_alignment) else: self._build_ui_elements(parsed_credits, label_alignment) # There is a builtin name called credits, which is why this argument is called asset_credits. def __init__( self, asset_credits: List[Tuple[str, bool]], should_show_on_screen: bool, perform_fallback=False, combine_labels=False, label_alignment=ui.Alignment.LEFT, ): self._logger = logging.getLogger(__name__) parsed_credits = self._parse_credits(asset_credits, should_show_on_screen, perform_fallback) self._build_ui(parsed_credits, combine_labels, label_alignment)
6,390
Python
38.450617
113
0.56025
CesiumGS/cesium-omniverse/exts/cesium.omniverse/cesium/omniverse/ui/quick_add_widget.py
import logging import carb.events import omni.kit.app as app import omni.ui as ui import omni.usd from typing import List, Optional from ..bindings import ICesiumOmniverseInterface from ..models import AssetToAdd from .styles import CesiumOmniverseUiStyles from cesium.usd.plugins.CesiumUsdSchemas import IonServer as CesiumIonServer LABEL_HEIGHT = 24 BUTTON_HEIGHT = 40 class CesiumOmniverseQuickAddWidget(ui.Frame): def __init__(self, cesium_omniverse_interface: ICesiumOmniverseInterface, **kwargs): self._logger = logging.getLogger(__name__) self._cesium_omniverse_interface = cesium_omniverse_interface self._ion_quick_add_frame: Optional[ui.Frame] = None self._subscriptions: List[carb.events.ISubscription] = [] self._setup_subscriptions() super().__init__(build_fn=self._build_ui, **kwargs) def destroy(self) -> None: for subscription in self._subscriptions: subscription.unsubscribe() self._subscriptions.clear() def _setup_subscriptions(self): update_stream = app.get_app().get_update_event_stream() self._subscriptions.append( update_stream.create_subscription_to_pop(self._on_update_frame, name="on_update_frame") ) def _on_update_frame(self, _: carb.events.IEvent): if self._ion_quick_add_frame is None: return if omni.usd.get_context().get_stage_state() != omni.usd.StageState.OPENED: return session = self._cesium_omniverse_interface.get_session() if session is not None: stage = omni.usd.get_context().get_stage() current_server_path = self._cesium_omniverse_interface.get_server_path() current_server = CesiumIonServer.Get(stage, current_server_path) current_server_url = current_server.GetIonServerUrlAttr().Get() # Temporary workaround to only show quick add assets for official ion server # until quick add route is implemented self._ion_quick_add_frame.visible = ( session.is_connected() and current_server_url == "https://ion.cesium.com/" ) @staticmethod def _add_blank_button_clicked(): asset_to_add = AssetToAdd("Cesium Tileset", 0) add_blank_asset_event = carb.events.type_from_string("cesium.omniverse.ADD_BLANK_ASSET") app.get_app().get_message_bus_event_stream().push(add_blank_asset_event, payload=asset_to_add.to_dict()) @staticmethod def _add_cartographic_polygon_button_clicked(): add_cartographic_polygon_event = carb.events.type_from_string("cesium.omniverse.ADD_CARTOGRAPHIC_POLYGON") app.get_app().get_message_bus_event_stream().push(add_cartographic_polygon_event, payload={}) def _photorealistic_tiles_button_clicked(self): self._add_ion_assets(AssetToAdd("Google Photorealistic 3D Tiles", 2275207)) def _cwt_bing_maps_button_clicked(self): self._add_ion_assets(AssetToAdd("Cesium World Terrain", 1, "Bing Maps Aerial imagery", 2)) def _cwt_bing_maps_labels_button_clicked(self): self._add_ion_assets(AssetToAdd("Cesium World Terrain", 1, "Bing Maps Aerial with Labels imagery", 3)) def _cwt_bing_maps_roads_button_clicked(self): self._add_ion_assets(AssetToAdd("Cesium World Terrain", 1, "Bing Maps Road imagery", 4)) def _cwt_sentinel_button_clicked(self): self._add_ion_assets(AssetToAdd("Cesium World Terrain", 1, "Sentinel-2 imagery", 3954)) def _cesium_osm_buildings_clicked(self): self._add_ion_assets(AssetToAdd("Cesium OSM Buildings", 96188)) @staticmethod def _add_ion_assets(asset_to_add: AssetToAdd): add_asset_event = carb.events.type_from_string("cesium.omniverse.ADD_ION_ASSET") app.get_app().get_message_bus_event_stream().push(add_asset_event, payload=asset_to_add.to_dict()) def _build_ui(self): with self: with ui.VStack(spacing=10): with ui.VStack(spacing=5): ui.Label( "Quick Add Basic Assets", style=CesiumOmniverseUiStyles.quick_add_section_label, height=LABEL_HEIGHT, ) ui.Button( "Blank 3D Tiles Tileset", style=CesiumOmniverseUiStyles.quick_add_button, clicked_fn=self._add_blank_button_clicked, height=BUTTON_HEIGHT, ) ui.Button( "Cesium Cartographic Polygon", style=CesiumOmniverseUiStyles.quick_add_button, clicked_fn=self._add_cartographic_polygon_button_clicked, height=BUTTON_HEIGHT, ) self._ion_quick_add_frame = ui.Frame(visible=False, height=0) with self._ion_quick_add_frame: with ui.VStack(spacing=5): ui.Label( "Quick Add Cesium ion Assets", style=CesiumOmniverseUiStyles.quick_add_section_label, height=LABEL_HEIGHT, ) ui.Button( "Google Photorealistic 3D Tiles", style=CesiumOmniverseUiStyles.quick_add_button, height=BUTTON_HEIGHT, clicked_fn=self._photorealistic_tiles_button_clicked, ) ui.Button( "Cesium World Terrain + Bing Maps Aerial imagery", style=CesiumOmniverseUiStyles.quick_add_button, height=BUTTON_HEIGHT, clicked_fn=self._cwt_bing_maps_button_clicked, ) ui.Button( "Cesium World Terrain + Bing Maps with Labels imagery", style=CesiumOmniverseUiStyles.quick_add_button, height=BUTTON_HEIGHT, clicked_fn=self._cwt_bing_maps_labels_button_clicked, ) ui.Button( "Cesium World Terrain + Bing Maps Road imagery", style=CesiumOmniverseUiStyles.quick_add_button, height=BUTTON_HEIGHT, clicked_fn=self._cwt_bing_maps_roads_button_clicked, ) ui.Button( "Cesium World Terrain + Sentinel-2 imagery", style=CesiumOmniverseUiStyles.quick_add_button, height=BUTTON_HEIGHT, clicked_fn=self._cwt_sentinel_button_clicked, ) ui.Button( "Cesium OSM Buildings", style=CesiumOmniverseUiStyles.quick_add_button, height=BUTTON_HEIGHT, clicked_fn=self._cesium_osm_buildings_clicked, )
7,293
Python
44.874214
114
0.56232
CesiumGS/cesium-omniverse/exts/cesium.omniverse/cesium/omniverse/ui/troubleshooter_window.py
import logging import carb.events import omni.kit.app as app import omni.ui as ui import webbrowser from typing import List, Optional from ..bindings import ICesiumOmniverseInterface from .pass_fail_widget import CesiumPassFailWidget from .styles import CesiumOmniverseUiStyles class CesiumTroubleshooterWindow(ui.Window): WINDOW_BASE_NAME = "Token Troubleshooting" def __init__( self, cesium_omniverse_interface: ICesiumOmniverseInterface, name: str, tileset_path: str, tileset_ion_asset_id: int, raster_overlay_ion_asset_id: int, message: str, **kwargs, ): window_name = f"{CesiumTroubleshooterWindow.WINDOW_BASE_NAME} - {name}" super().__init__(window_name, **kwargs) self._cesium_omniverse_interface = cesium_omniverse_interface self._logger = logging.getLogger(__name__) self._name = name self._tileset_path = tileset_path self._tileset_ion_asset_id = tileset_ion_asset_id self.raster_overlay_ion_asset_id = raster_overlay_ion_asset_id ion_id = raster_overlay_ion_asset_id if raster_overlay_ion_asset_id > 0 else tileset_ion_asset_id self._message = ( f"{name} tried to access Cesium ion for asset id {ion_id}, but it didn't work, probably " + "due to a problem with the access token. This panel will help you fix it!" ) self.height = 400 self.width = 700 self.padding_x = 12 self.padding_y = 12 self._token_details_event_type = carb.events.type_from_string("cesium.omniverse.TOKEN_DETAILS_READY") self._asset_details_event_type = carb.events.type_from_string("cesium.omniverse.ASSET_DETAILS_READY") self._default_token_stack: Optional[ui.VStack] = None self._default_token_is_valid_widget: Optional[CesiumPassFailWidget] = None self._default_token_has_access_widget: Optional[CesiumPassFailWidget] = None self._default_token_associated_to_account_widget: Optional[CesiumPassFailWidget] = None self._asset_token_stack: Optional[ui.VStack] = None self._asset_token_is_valid_widget: Optional[CesiumPassFailWidget] = None self._asset_token_has_access_widget: Optional[CesiumPassFailWidget] = None self._asset_token_associated_to_account_widget: Optional[CesiumPassFailWidget] = None self._asset_on_account_widget: Optional[CesiumPassFailWidget] = None self._subscriptions: List[carb.events.ISubscription] = [] self._setup_subscriptions() if raster_overlay_ion_asset_id > 0: self._cesium_omniverse_interface.update_troubleshooting_details( tileset_path, tileset_ion_asset_id, raster_overlay_ion_asset_id, self._token_details_event_type, self._asset_details_event_type, ) else: self._cesium_omniverse_interface.update_troubleshooting_details( tileset_path, tileset_ion_asset_id, self._token_details_event_type, self._asset_details_event_type ) self.frame.set_build_fn(self._build_ui) def __del__(self): self.destroy() def destroy(self): for subscription in self._subscriptions: subscription.unsubscribe() self._subscriptions = None def _setup_subscriptions(self): bus = app.get_app().get_message_bus_event_stream() self._subscriptions.append( bus.create_subscription_to_pop_by_type( self._token_details_event_type, self._on_token_details_ready, name="cesium.omniverse.TOKEN_DETAILS_READY", ) ) self._subscriptions.append( bus.create_subscription_to_pop_by_type( self._asset_details_event_type, self._on_asset_details_ready, name="cesium.omniverse.ASSET_DETAILS_READY", ) ) def _on_token_details_ready(self, _e: carb.events.IEvent): self._logger.info("Received token details event.") default_token_details = self._cesium_omniverse_interface.get_default_token_troubleshooting_details() if self._default_token_stack is not None: self._default_token_stack.visible = default_token_details.show_details if self._default_token_is_valid_widget is not None: self._default_token_is_valid_widget.passed = default_token_details.is_valid if self._default_token_has_access_widget is not None: self._default_token_has_access_widget.passed = default_token_details.allows_access_to_asset if self._default_token_associated_to_account_widget is not None: self._default_token_associated_to_account_widget.passed = ( default_token_details.associated_with_user_account ) asset_token_details = self._cesium_omniverse_interface.get_asset_token_troubleshooting_details() if self._asset_token_stack is not None: self._asset_token_stack.visible = asset_token_details.show_details if self._asset_token_is_valid_widget is not None: self._asset_token_is_valid_widget.passed = asset_token_details.is_valid if self._asset_token_has_access_widget is not None: self._asset_token_has_access_widget.passed = asset_token_details.allows_access_to_asset if self._asset_token_associated_to_account_widget is not None: self._asset_token_associated_to_account_widget.passed = asset_token_details.associated_with_user_account def _on_asset_details_ready(self, _e: carb.events.IEvent): asset_details = self._cesium_omniverse_interface.get_asset_troubleshooting_details() if self._asset_on_account_widget is not None: self._asset_on_account_widget.passed = asset_details.asset_exists_in_user_account @staticmethod def _on_open_ion_button_clicked(): webbrowser.open("https://ion.cesium.com") def _build_ui(self): with ui.VStack(spacing=10): ui.Label(self._message, height=54, word_wrap=True) with ui.VGrid(spacing=10, column_count=2): self._asset_token_stack = ui.VStack(spacing=5, visible=False) with self._asset_token_stack: ui.Label( f"{self._name}'s Access Token", height=16, style=CesiumOmniverseUiStyles.troubleshooter_header_style, ) with ui.HStack(height=16, spacing=10): self._asset_token_is_valid_widget = CesiumPassFailWidget() ui.Label("Is a valid Cesium ion Token") with ui.HStack(height=16, spacing=10): self._asset_token_has_access_widget = CesiumPassFailWidget() ui.Label("Allows access to this asset") with ui.HStack(height=16, spacing=10): self._asset_token_associated_to_account_widget = CesiumPassFailWidget() ui.Label("Is associated with your user account") self._default_token_stack = ui.VStack(spacing=5, visible=False) with self._default_token_stack: ui.Label( "Project Default Access Token", height=16, style=CesiumOmniverseUiStyles.troubleshooter_header_style, ) with ui.HStack(height=16, spacing=10): self._default_token_is_valid_widget = CesiumPassFailWidget() ui.Label("Is a valid Cesium ion Token") with ui.HStack(height=16, spacing=10): self._default_token_has_access_widget = CesiumPassFailWidget() ui.Label("Allows access to this asset") with ui.HStack(height=16, spacing=10): self._default_token_associated_to_account_widget = CesiumPassFailWidget() ui.Label("Is associated with your user account") with ui.VStack(spacing=5): ui.Label("Asset", height=16, style=CesiumOmniverseUiStyles.troubleshooter_header_style) with ui.HStack(height=16, spacing=10): self._asset_on_account_widget = CesiumPassFailWidget() ui.Label("Asset ID exists in your user account") ui.Spacer() ui.Button( "Open Cesium ion on the Web", alignment=ui.Alignment.CENTER, height=36, style=CesiumOmniverseUiStyles.blue_button_style, clicked_fn=self._on_open_ion_button_clicked, )
8,910
Python
43.778894
116
0.609091
CesiumGS/cesium-omniverse/exts/cesium.omniverse/cesium/omniverse/ui/sign_in_widget.py
import logging import carb.events import omni.kit.app as app import omni.ui as ui import omni.kit.clipboard as clipboard import webbrowser from pathlib import Path from typing import List, Optional from ..bindings import ICesiumOmniverseInterface from .styles import CesiumOmniverseUiStyles class CesiumOmniverseSignInWidget(ui.Frame): def __init__(self, cesium_omniverse_interface: ICesiumOmniverseInterface, **kwargs): manager = app.get_app().get_extension_manager() ext_id = manager.get_extension_id_by_module("cesium.omniverse") self._logger = logging.getLogger(__name__) self._images_path = Path(manager.get_extension_path(ext_id)).joinpath("images") self._cesium_omniverse_interface = cesium_omniverse_interface self._connect_button: Optional[ui.Button] = None self._waiting_message_frame: Optional[ui.Frame] = None self._authorize_url_field: Optional[ui.StringField] = None self._subscriptions: List[carb.events.ISubscription] = [] self._setup_subscriptions() super().__init__(build_fn=self._build_ui, **kwargs) def destroy(self): for subscription in self._subscriptions: subscription.unsubscribe() self._subscriptions.clear() def _setup_subscriptions(self): update_stream = app.get_app().get_update_event_stream() self._subscriptions.append( update_stream.create_subscription_to_pop(self._on_update_frame, name="on_update_frame") ) def _on_update_frame(self, _e: carb.events.IEvent): if not self.visible: return session = self._cesium_omniverse_interface.get_session() if session is not None and self._waiting_message_frame is not None: self._waiting_message_frame.visible = session.is_connecting() if session.is_connecting(): authorize_url = session.get_authorize_url() if self._authorize_url_field.model.get_value_as_string() != authorize_url: self._authorize_url_field.model.set_value(authorize_url) webbrowser.open(authorize_url) def _build_ui(self): with self: with ui.VStack(alignment=ui.Alignment.CENTER_TOP, spacing=ui.Length(20, ui.UnitType.PIXEL)): ui.Spacer(height=0) ui.Image( f"{self._images_path}/placeholder_logo.png", alignment=ui.Alignment.CENTER, fill_policy=ui.FillPolicy.PRESERVE_ASPECT_FIT, height=140, ) with ui.HStack(height=0): ui.Spacer() ui.Label( "Access global high-resolution 3D content, including photogrammetry, " "terrain, imagery, and buildings. Bring your own data for tiling, hosting, " "and streaming to Omniverse.", alignment=ui.Alignment.CENTER, style=CesiumOmniverseUiStyles.intro_label_style, width=ui.Length(80, ui.UnitType.PERCENT), word_wrap=True, ) ui.Spacer() with ui.HStack(height=0): ui.Spacer() self._connect_button = ui.Button( "Connect to Cesium ion", alignment=ui.Alignment.CENTER, height=ui.Length(36, ui.UnitType.PIXEL), width=ui.Length(180, ui.UnitType.PIXEL), style=CesiumOmniverseUiStyles.blue_button_style, clicked_fn=self._connect_button_clicked, ) ui.Spacer() self._waiting_message_frame = ui.Frame(visible=False, height=0) with self._waiting_message_frame: with ui.VStack(spacing=10): ui.Label("Waiting for you to sign into Cesium ion with your web browser...") ui.Button("Open web browser again", clicked_fn=self._open_web_browser_again_clicked) ui.Label("Or copy the URL below into your web browser.") with ui.HStack(): self._authorize_url_field = ui.StringField(read_only=True) self._authorize_url_field.model.set_value("https://cesium.com") ui.Button("Copy to Clipboard", clicked_fn=self._copy_to_clipboard_clicked) ui.Spacer(height=10) def _connect_button_clicked(self) -> None: self._cesium_omniverse_interface.connect_to_ion() def _open_web_browser_again_clicked(self) -> None: webbrowser.open(self._authorize_url_field.model.get_value_as_string()) def _copy_to_clipboard_clicked(self) -> None: if self._authorize_url_field is not None: clipboard.copy(self._authorize_url_field.model.get_value_as_string())
5,049
Python
44.909091
108
0.579719
CesiumGS/cesium-omniverse/exts/cesium.omniverse/cesium/omniverse/ui/main_window.py
from ..bindings import ICesiumOmniverseInterface, CesiumIonSession import logging import carb.events import omni.kit.app as app import omni.ui as ui import webbrowser from pathlib import Path from typing import List, Optional from .quick_add_widget import CesiumOmniverseQuickAddWidget from .sign_in_widget import CesiumOmniverseSignInWidget from .profile_widget import CesiumOmniverseProfileWidget from .token_window import CesiumOmniverseTokenWindow from .troubleshooter_window import CesiumTroubleshooterWindow from .asset_window import CesiumOmniverseAssetWindow from .styles import CesiumOmniverseUiStyles HELP_URL = "https://community.cesium.com/c/cesium-for-omniverse" LEARN_URL = "https://cesium.com/learn/omniverse/" UPLOAD_URL = "https://ion.cesium.com/addasset" class CesiumOmniverseMainWindow(ui.Window): """ The main window for working with Cesium for Omniverse. Docked in the same area as "Stage". """ WINDOW_NAME = "Cesium" MENU_PATH = f"Window/Cesium/{WINDOW_NAME}" def __init__(self, cesium_omniverse_interface: ICesiumOmniverseInterface, **kwargs): super().__init__(CesiumOmniverseMainWindow.WINDOW_NAME, **kwargs) manager = app.get_app().get_extension_manager() ext_id = manager.get_extension_id_by_module("cesium.omniverse") self._cesium_omniverse_interface = cesium_omniverse_interface self._logger = logging.getLogger(__name__) self._icon_path = Path(manager.get_extension_path(ext_id)).joinpath("images") # Buttons aren't created until the build function is called. self._add_button: Optional[ui.Button] = None self._upload_button: Optional[ui.Button] = None self._token_button: Optional[ui.Button] = None self._learn_button: Optional[ui.Button] = None self._help_button: Optional[ui.Button] = None self._sign_out_button: Optional[ui.Button] = None self._quick_add_widget: Optional[CesiumOmniverseQuickAddWidget] = None self._sign_in_widget: Optional[CesiumOmniverseSignInWidget] = None self._profile_widget: Optional[CesiumOmniverseProfileWidget] = None self._troubleshooter_window: Optional[CesiumTroubleshooterWindow] = None self._asset_window: Optional[CesiumOmniverseAssetWindow] = None self._subscriptions: List[carb.events.ISubscription] = [] self._setup_subscriptions() self.frame.set_build_fn(self._build_fn) def destroy(self) -> None: for subscription in self._subscriptions: subscription.unsubscribe() if self._sign_in_widget is not None: self._sign_in_widget.destroy() self._sign_in_widget = None if self._profile_widget is not None: self._profile_widget.destroy() self._profile_widget = None if self._quick_add_widget is not None: self._quick_add_widget.destroy() self._quick_add_widget = None if self._troubleshooter_window is not None: self._troubleshooter_window.destroy() self._troubleshooter_window = None super().destroy() def __del__(self): self.destroy() def _setup_subscriptions(self): update_stream = app.get_app().get_update_event_stream() bus = app.get_app().get_message_bus_event_stream() self._subscriptions.append( update_stream.create_subscription_to_pop(self._on_update_frame, name="on_update_frame") ) assets_updated_event = carb.events.type_from_string("cesium.omniverse.ASSETS_UPDATED") self._subscriptions.append( bus.create_subscription_to_pop_by_type( assets_updated_event, self._on_assets_updated, name="assets_updated" ) ) connection_updated_event = carb.events.type_from_string("cesium.omniverse.CONNECTION_UPDATED") self._subscriptions.append( bus.create_subscription_to_pop_by_type( connection_updated_event, self._on_connection_updated, name="connection_updated" ) ) profile_updated_event = carb.events.type_from_string("cesium.omniverse.PROFILE_UPDATED") self._subscriptions.append( bus.create_subscription_to_pop_by_type( profile_updated_event, self._on_profile_updated, name="profile_updated" ) ) tokens_updated_event = carb.events.type_from_string("cesium.omniverse.TOKENS_UPDATED") self._subscriptions.append( bus.create_subscription_to_pop_by_type( tokens_updated_event, self._on_tokens_updated, name="tokens_updated" ) ) show_token_window_event = carb.events.type_from_string("cesium.omniverse.SHOW_TOKEN_WINDOW") self._subscriptions.append( bus.create_subscription_to_pop_by_type( show_token_window_event, self._on_show_token_window, name="cesium.omniverse.SHOW_TOKEN_WINDOW" ) ) show_troubleshooter_event = carb.events.type_from_string("cesium.omniverse.SHOW_TROUBLESHOOTER") self._subscriptions.append( bus.create_subscription_to_pop_by_type( show_troubleshooter_event, self._on_show_troubleshooter_window, name="cesium.omniverse.SHOW_TROUBLESHOOTER", ) ) def _on_update_frame(self, _e: carb.events.IEvent): session: CesiumIonSession = self._cesium_omniverse_interface.get_session() if session is not None and self._sign_in_widget is not None: # Since this goes across the pybind barrier, just grab it once. is_connected = session.is_connected() self._sign_in_widget.visible = not is_connected self._set_top_bar_button_status(is_connected) def _on_assets_updated(self, _e: carb.events.IEvent): self._logger.info("Received ion Assets updated event.") def _on_connection_updated(self, _e: carb.events.IEvent): self._logger.info("Received ion Connection updated event.") def _on_profile_updated(self, _e: carb.events.IEvent): self._logger.info("Received ion Profile updated event.") def _on_tokens_updated(self, _e: carb.events.IEvent): self._logger.info("Received ion Tokens updated event.") def _on_show_token_window(self, _e: carb.events.IEvent): self._show_token_window() def _on_show_troubleshooter_window(self, _e: carb.events.IEvent): tileset_path = _e.payload["tilesetPath"] tileset_ion_asset_id = _e.payload["tilesetIonAssetId"] raster_overlay_ion_asset_id = _e.payload["rasterOverlayIonAssetId"] message = _e.payload["message"] name = _e.payload["rasterOverlayName"] if _e.payload["rasterOverlayName"] else _e.payload["tilesetName"] if self._troubleshooter_window: self._troubleshooter_window.destroy() self._troubleshooter_window = None self._troubleshooter_window = CesiumTroubleshooterWindow( self._cesium_omniverse_interface, name, tileset_path, tileset_ion_asset_id, raster_overlay_ion_asset_id, message, ) def _set_top_bar_button_status(self, enabled: bool): self._add_button.enabled = enabled self._upload_button.enabled = enabled self._sign_out_button.enabled = enabled def _build_fn(self): """Builds all UI components.""" with ui.VStack(spacing=0): button_style = CesiumOmniverseUiStyles.top_bar_button_style self._profile_widget = CesiumOmniverseProfileWidget(self._cesium_omniverse_interface, height=20) with ui.HStack(height=ui.Length(80, ui.UnitType.PIXEL)): self._add_button = ui.Button( "Add", image_url=f"{self._icon_path}/FontAwesome/plus-solid.png", style=button_style, clicked_fn=self._add_button_clicked, enabled=False, ) self._upload_button = ui.Button( "Upload", image_url=f"{self._icon_path}/FontAwesome/cloud-upload-alt-solid.png", style=button_style, clicked_fn=self._upload_button_clicked, enabled=False, ) self._token_button = ui.Button( "Token", image_url=f"{self._icon_path}/FontAwesome/key-solid.png", style=button_style, clicked_fn=self._token_button_clicked, ) self._learn_button = ui.Button( "Learn", image_url=f"{self._icon_path}/FontAwesome/book-reader-solid.png", style=button_style, clicked_fn=self._learn_button_clicked, ) self._help_button = ui.Button( "Help", image_url=f"{self._icon_path}/FontAwesome/hands-helping-solid.png", style=button_style, clicked_fn=self._help_button_clicked, ) self._sign_out_button = ui.Button( "Sign Out", image_url=f"{self._icon_path}/FontAwesome/sign-out-alt-solid.png", # style=button_style, style=button_style, clicked_fn=self._sign_out_button_clicked, enabled=False, ) with ui.ScrollingFrame(): with ui.VStack(spacing=0): self._quick_add_widget = CesiumOmniverseQuickAddWidget(self._cesium_omniverse_interface) self._sign_in_widget = CesiumOmniverseSignInWidget( self._cesium_omniverse_interface, visible=False ) def _add_button_clicked(self) -> None: if not self._add_button or not self._add_button.enabled: return show_asset_window_event = carb.events.type_from_string("cesium.omniverse.SHOW_ASSET_WINDOW") app.get_app().get_message_bus_event_stream().push(show_asset_window_event) def _upload_button_clicked(self) -> None: if not self._upload_button or not self._upload_button.enabled: return webbrowser.open_new_tab(UPLOAD_URL) def _token_button_clicked(self) -> None: if not self._token_button: return self._show_token_window() def _learn_button_clicked(self) -> None: if not self._learn_button: return webbrowser.open_new_tab(LEARN_URL) def _help_button_clicked(self) -> None: if not self._help_button: return webbrowser.open_new_tab(HELP_URL) def _sign_out_button_clicked(self) -> None: if not self._sign_out_button or not self._sign_out_button.enabled: return session = self._cesium_omniverse_interface.get_session() if session is not None: session.disconnect() self._set_top_bar_button_status(False) def _show_token_window(self): self._cesium_omniverse_interface.get_session().refresh_tokens() CesiumOmniverseTokenWindow(self._cesium_omniverse_interface)
11,391
Python
38.97193
112
0.61452
CesiumGS/cesium-omniverse/exts/cesium.omniverse/cesium/omniverse/ui/settings_window.py
import logging import carb.settings from typing import Optional import omni.ui as ui from ..bindings import ICesiumOmniverseInterface from cesium.omniverse.utils.custom_fields import int_field_with_label class CesiumOmniverseSettingsWindow(ui.Window): WINDOW_NAME = "Cesium Settings" MENU_PATH = f"Window/Cesium/{WINDOW_NAME}" _logger: logging.Logger _cesium_omniverse_interface: Optional[ICesiumOmniverseInterface] = None def __init__(self, cesium_omniverse_interface: ICesiumOmniverseInterface, title: str, **kwargs): super().__init__(title, **kwargs) self._logger = logging.getLogger(__name__) self._cesium_omniverse_interface = cesium_omniverse_interface self._cache_items_setting = "/persistent/exts/cesium.omniverse/maxCacheItems" # Set the function that is called to build widgets when the window is visible self.frame.set_build_fn(self._build_fn) def destroy(self): # It will destroy all the children super().destroy() def __del__(self): self.destroy() @staticmethod def show_window(): ui.Workspace.show_window(CesiumOmniverseSettingsWindow.WINDOW_NAME) def _build_fn(self): """Builds out the UI buttons and their handlers.""" def set_cache_parameters(): newval = self._cache_items_model.get_value_as_int() carb.settings.get_settings().set(self._cache_items_setting, newval) def clear_cache(): self._cesium_omniverse_interface.clear_accessor_cache() with ui.VStack(spacing=4): cache_items = carb.settings.get_settings().get(self._cache_items_setting) self._cache_items_model = ui.SimpleIntModel(cache_items) int_field_with_label("Maximum cache items", model=self._cache_items_model) ui.Button("Set cache parameters (requires restart)", height=20, clicked_fn=set_cache_parameters) ui.Button("Clear cache", height=20, clicked_fn=clear_cache)
2,009
Python
36.924528
108
0.678447
CesiumGS/cesium-omniverse/exts/cesium.omniverse/cesium/omniverse/ui/credits_viewport_frame.py
import logging import carb.events import omni.kit.app as app import omni.ui as ui from typing import List, Optional, Tuple from ..bindings import ICesiumOmniverseInterface from .credits_parser import CesiumCreditsParser from .credits_window import CesiumOmniverseCreditsWindow import json from .events import EVENT_CREDITS_CHANGED class CesiumCreditsViewportFrame: def __init__(self, cesium_omniverse_interface: ICesiumOmniverseInterface, instance): self._logger = logging.getLogger(__name__) self._cesium_omniverse_interface = cesium_omniverse_interface self._credits_viewport_frame = instance.get_frame("cesium.omniverse.viewport.ION_CREDITS") self._credits_window: Optional[CesiumOmniverseCreditsWindow] = None self._data_attribution_button: Optional[ui.Button] = None self._on_credits_changed_event = EVENT_CREDITS_CHANGED self._subscriptions: List[carb.events.ISubscription] = [] self._setup_subscriptions() self._credits: List[Tuple[str, bool]] = [] self._new_credits: List[Tuple[str, bool]] = [] self._build_fn() def getFrame(self): return self._credits_viewport_frame def __del__(self): self.destroy() def destroy(self): for subscription in self._subscriptions: subscription.unsubscribe() self._subscriptions.clear() if self._credits_window is not None: self._credits_window.destroy() self._credits_window = None def _setup_subscriptions(self): update_stream = app.get_app().get_update_event_stream() self._subscriptions.append( update_stream.create_subscription_to_pop( self._on_update_frame, name="cesium.omniverse.viewport.ON_UPDATE_FRAME" ) ) message_bus = app.get_app().get_message_bus_event_stream() self._subscriptions.append( message_bus.create_subscription_to_pop_by_type(EVENT_CREDITS_CHANGED, self._on_credits_changed) ) def _on_update_frame(self, _e: carb.events.IEvent): if self._data_attribution_button is None: return if self._new_credits != self._credits: self._credits.clear() self._credits.extend(self._new_credits) self._build_fn() has_offscreen_credits = False for _, show_on_screen in self._new_credits: if not show_on_screen: has_offscreen_credits = True if has_offscreen_credits != self._data_attribution_button.visible: if has_offscreen_credits: self._logger.info("Show Data Attribution") else: self._logger.info("Hide Data Attribution") self._data_attribution_button.visible = has_offscreen_credits def _on_data_attribution_button_clicked(self): self._credits_window = CesiumOmniverseCreditsWindow(self._cesium_omniverse_interface, self._credits) def _build_fn(self): with self._credits_viewport_frame: with ui.VStack(): ui.Spacer() with ui.HStack(height=0): # Prevent credits from overlapping the axis display ui.Spacer(width=100) with ui.HStack(height=0, spacing=4): CesiumCreditsParser( self._credits, should_show_on_screen=True, combine_labels=True, label_alignment=ui.Alignment.RIGHT, ) # VStack + Spacer pushes our content to the bottom of the Stack to account for varying heights with ui.VStack(spacing=0, width=0): ui.Spacer() self._data_attribution_button = ui.Button( "Data Attribution", visible=False, width=0, height=0, clicked_fn=self._on_data_attribution_button_clicked, ) def _on_credits_changed(self, _e: carb.events.IEvent): credits_json = _e.payload["credits"] credits = json.loads(credits_json) if credits is not None: self._new_credits = credits
4,373
Python
36.706896
114
0.586783
CesiumGS/cesium-omniverse/exts/cesium.omniverse/cesium/omniverse/ui/__init__.py
from .styles import CesiumOmniverseUiStyles # noqa: F401 from .quick_add_widget import CesiumOmniverseQuickAddWidget # noqa: F401 from .sign_in_widget import CesiumOmniverseSignInWidget # noqa: F401 from .profile_widget import CesiumOmniverseProfileWidget # noqa: F401 from .token_window import CesiumOmniverseTokenWindow # noqa: F401 from .main_window import CesiumOmniverseMainWindow # noqa: F401 from .asset_window import CesiumOmniverseAssetWindow # noqa: F401 from .debug_window import CesiumOmniverseDebugWindow # noqa: F401 from .attributes_widget_controller import CesiumAttributesWidgetController # noqa: F401 from .fabric_modal import CesiumFabricModal # noqa: F401 from .credits_window import CesiumOmniverseCreditsWindow # noqa: F401 from .credits_viewport_frame import CesiumCreditsViewportFrame # noqa: F401 from .credits_parser import CesiumCreditsParser # noqa: F401 from .search_field_widget import CesiumSearchFieldWidget # noqa: F401 from .statistics_widget import CesiumOmniverseStatisticsWidget # noqa: F401 from .models import * # noqa: F401 F403 from .credits_viewport_controller import CreditsViewportController # noqa: F401 from .add_menu_controller import CesiumAddMenuController # noqa: F401
1,237
Python
64.157891
88
0.819725
CesiumGS/cesium-omniverse/exts/cesium.omniverse/cesium/omniverse/ui/search_field_widget.py
from typing import Callable, List, Optional import carb.events import omni.ui as ui from omni.ui import color as cl class CesiumSearchFieldWidget(ui.Frame): def __init__( self, callback_fn: Callable[[ui.AbstractValueModel], None], default_value="", font_size=14, **kwargs ): self._callback_fn = callback_fn self._search_value = ui.SimpleStringModel(default_value) self._font_size = font_size self._clear_button_stack: Optional[ui.Stack] = None self._subscriptions: List[carb.Subscription] = [] self._setup_subscriptions() super().__init__(build_fn=self._build_fn, **kwargs) def destroy(self): super().destroy() @property def search_value(self) -> str: return self._search_value.get_value_as_string() @search_value.setter def search_value(self, value: str): self._search_value.set_value(value) self._set_clear_button_visibility() def _update_visibility(self, _e): self._set_clear_button_visibility() def _setup_subscriptions(self): self._subscriptions.append(self._search_value.subscribe_value_changed_fn(self._callback_fn)) self._subscriptions.append(self._search_value.subscribe_value_changed_fn(self._update_visibility)) def _on_clear_click(self): self._search_value.set_value("") self._set_clear_button_visibility() def _set_clear_button_visibility(self): self._clear_button_stack.visible = self._search_value.as_string != "" def _build_fn(self): with self: with ui.ZStack(height=0): ui.Rectangle(style={"background_color": cl("#1F2123"), "border_radius": 3}) with ui.HStack(alignment=ui.Alignment.CENTER): image_size = self._font_size * 2 ui.Image( "resources/glyphs/menu_search.svg", width=image_size, height=image_size, style={"margin": 4}, ) with ui.VStack(): ui.Spacer() ui.StringField( model=self._search_value, height=self._font_size, style={"font_size": self._font_size} ) ui.Spacer() self._clear_button_stack = ui.VStack(width=0, visible=False) with self._clear_button_stack: ui.Spacer() ui.Button( image_url="resources/icons/Close.png", width=0, height=0, image_width=self._font_size, image_height=self._font_size, style={"margin": 4, "background_color": cl("#1F2123")}, clicked_fn=self._on_clear_click, opaque_for_mouse_events=True, ) ui.Spacer()
3,077
Python
37.962025
114
0.521287
CesiumGS/cesium-omniverse/exts/cesium.omniverse/cesium/omniverse/ui/credits_window.py
import logging import omni.kit.app as app import omni.ui as ui from pathlib import Path from typing import List, Tuple from .credits_parser import CesiumCreditsParser from ..bindings import ICesiumOmniverseInterface from .styles import CesiumOmniverseUiStyles class CesiumOmniverseCreditsWindow(ui.Window): WINDOW_NAME = "Data Attribution" # There is a builtin name called credits, which is why this argument is called asset_credits. def __init__( self, cesium_omniverse_interface: ICesiumOmniverseInterface, asset_credits: List[Tuple[str, bool]], **kwargs ): super().__init__(CesiumOmniverseCreditsWindow.WINDOW_NAME, **kwargs) manager = app.get_app().get_extension_manager() ext_id = manager.get_extension_id_by_module("cesium.omniverse") self._cesium_omniverse_interface = cesium_omniverse_interface self._logger = logging.getLogger(__name__) self._images_path = Path(manager.get_extension_path(ext_id)).joinpath("images") self.height = 500 self.width = 400 self.padding_x = 12 self.padding_y = 12 self._credits = asset_credits self.frame.set_build_fn(self._build_ui) def __del__(self): self.destroy() def destroy(self): super().destroy() def _build_ui(self): with ui.VStack(spacing=5): ui.Label("Data Provided By:", height=0, style=CesiumOmniverseUiStyles.attribution_header_style) CesiumCreditsParser(self._credits, should_show_on_screen=False, perform_fallback=True)
1,566
Python
31.645833
116
0.683269
CesiumGS/cesium-omniverse/exts/cesium.omniverse/cesium/omniverse/ui/pass_fail_widget.py
from pathlib import Path import carb.events import omni.kit.app as app import omni.ui as ui from typing import List class CesiumPassFailWidget(ui.Frame): def __init__(self, passed=False, **kwargs): self._passed_model = ui.SimpleBoolModel(passed) manager = app.get_app().get_extension_manager() ext_id = manager.get_extension_id_by_module("cesium.omniverse") self._icon_path = Path(manager.get_extension_path(ext_id)).joinpath("images") self._subscriptions: List[carb.Subscription] = [] self._setup_subscriptions() super().__init__(build_fn=self._build_ui, **kwargs) def __del__(self): self.destroy() def destroy(self): for subscription in self._subscriptions: subscription.unsubscribe() self._subscriptions.clear() @property def passed(self) -> bool: return self._passed_model.get_value_as_bool() @passed.setter def passed(self, value: bool): self._passed_model.set_value(value) def _setup_subscriptions(self): self._subscriptions.append(self._passed_model.subscribe_value_changed_fn(lambda _e: self.rebuild())) def _build_ui(self): with self: with ui.VStack(width=16, height=16): path_root = f"{self._icon_path}/FontAwesome" icon = ( f"{path_root}/check-solid.svg" if self._passed_model.get_value_as_bool() else f"{path_root}/times-solid.svg" ) ui.Image( icon, fill_policy=ui.FillPolicy.PRESERVE_ASPECT_FIT, alignment=ui.Alignment.CENTER_BOTTOM, width=16, height=16, )
1,794
Python
30.491228
108
0.572464
CesiumGS/cesium-omniverse/exts/cesium.omniverse/cesium/omniverse/ui/events.py
from carb.events import type_from_string # Event base path. Do not use directly outside of events.py _EVENT_BASE = "cesium.omniverse.event" # Signals the credits have changed. Currently, this only triggers when the displayed # credits are changed. It is possible for the credit payload that shows under # the "Data Attribution" button to change, but this event will not fire for that. EVENT_CREDITS_CHANGED = type_from_string(f"{_EVENT_BASE}.viewport.CREDITS_CHANGED")
471
Python
46.199995
84
0.779193
CesiumGS/cesium-omniverse/exts/cesium.omniverse/cesium/omniverse/ui/attributes_widget_controller.py
import logging import omni.kit.window.property from .attributes import ( CesiumDataSchemaAttributesWidget, CesiumGeoreferenceSchemaAttributesWidget, CesiumTilesetAttributesWidget, CesiumGlobeAnchorAttributesWidget, CesiumIonServerAttributesWidget, CesiumIonRasterOverlayAttributesWidget, CesiumPolygonRasterOverlayAttributesWidget, CesiumTileMapServiceRasterOverlayAttributesWidget, CesiumWebMapServiceRasterOverlayAttributesWidget, CesiumWebMapTileServiceRasterOverlayAttributesWidget, ) from ..bindings import ICesiumOmniverseInterface class CesiumAttributesWidgetController: """ This is designed as a helpful function for separating out the registration and unregistration of Cesium's attributes widgets. """ def __init__(self, _cesium_omniverse_interface: ICesiumOmniverseInterface): self._cesium_omniverse_interface = _cesium_omniverse_interface self._logger = logging.getLogger(__name__) self._register_data_attributes_widget() self._register_georeference_attributes_widget() self._register_tileset_attributes_widget() self._register_global_anchor_attributes_widget() self._register_ion_server_attributes_widget() self._register_ion_raster_overlay_attributes_widget() self._register_polygon_raster_overlay_attributes_widget() self._register_tile_map_service_raster_overlay_attributes_widget() self._register_web_map_service_raster_overlay_attributes_widget() self._register_web_map_tile_service_raster_overlay_attributes_widget() def destroy(self): self._unregister_data_attributes_widget() self._unregister_georeference_attributes_widget() self._unregister_tileset_attributes_widget() self._unregister_global_anchor_attributes_widget() self._unregister_ion_server_attributes_widget() self._unregister_ion_raster_overlay_attributes_widget() self._unregister_polygon_raster_overlay_attributes_widget() self._unregister_tile_map_service_raster_overlay_attributes_widget() self._unregister_web_map_service_raster_overlay_attributes_widget() self._unregister_web_map_tile_service_raster_overlay_attributes_widget() @staticmethod def _register_data_attributes_widget(): window = omni.kit.window.property.get_window() if window is not None: window.register_widget("prim", "cesiumData", CesiumDataSchemaAttributesWidget()) @staticmethod def _unregister_data_attributes_widget(): window = omni.kit.window.property.get_window() if window is not None: window.unregister_widget("prim", "cesiumData") @staticmethod def _register_georeference_attributes_widget(): window = omni.kit.window.property.get_window() if window is not None: window.register_widget("prim", "cesiumGeoreference", CesiumGeoreferenceSchemaAttributesWidget()) @staticmethod def _unregister_georeference_attributes_widget(): window = omni.kit.window.property.get_window() if window is not None: window.unregister_widget("prim", "cesiumGeoreference") def _register_tileset_attributes_widget(self): window = omni.kit.window.property.get_window() if window is not None: window.register_widget( "prim", "cesiumTileset", CesiumTilesetAttributesWidget(self._cesium_omniverse_interface) ) @staticmethod def _unregister_tileset_attributes_widget(): window = omni.kit.window.property.get_window() if window is not None: window.unregister_widget("prim", "cesiumTileset") @staticmethod def _register_ion_raster_overlay_attributes_widget(): window = omni.kit.window.property.get_window() if window is not None: window.register_widget("prim", "cesiumIonRasterOverlay", CesiumIonRasterOverlayAttributesWidget()) @staticmethod def _unregister_ion_raster_overlay_attributes_widget(): window = omni.kit.window.property.get_window() if window is not None: window.unregister_widget("prim", "cesiumIonRasterOverlay") @staticmethod def _register_polygon_raster_overlay_attributes_widget(): window = omni.kit.window.property.get_window() if window is not None: window.register_widget("prim", "cesiumPolygonRasterOverlay", CesiumPolygonRasterOverlayAttributesWidget()) @staticmethod def _unregister_polygon_raster_overlay_attributes_widget(): window = omni.kit.window.property.get_window() if window is not None: window.unregister_widget("prim", "cesiumPolygonRasterOverlay") @staticmethod def _register_web_map_service_raster_overlay_attributes_widget(): window = omni.kit.window.property.get_window() if window is not None: window.register_widget( "prim", "cesiumWebMapServiceRasterOverlay", CesiumWebMapServiceRasterOverlayAttributesWidget() ) @staticmethod def _register_tile_map_service_raster_overlay_attributes_widget(): window = omni.kit.window.property.get_window() if window is not None: window.register_widget( "prim", "cesiumTileMapServiceRasterOverlay", CesiumTileMapServiceRasterOverlayAttributesWidget() ) @staticmethod def _register_web_map_tile_service_raster_overlay_attributes_widget(): window = omni.kit.window.property.get_window() if window is not None: window.register_widget( "prim", "cesiumWebMapTileServiceRasterOverlay", CesiumWebMapTileServiceRasterOverlayAttributesWidget() ) @staticmethod def _unregister_web_map_service_raster_overlay_attributes_widget(): window = omni.kit.window.property.get_window() if window is not None: window.unregister_widget("prim", "cesiumWebMapServiceRasterOverlay") @staticmethod def _unregister_tile_map_service_raster_overlay_attributes_widget(): window = omni.kit.window.property.get_window() if window is not None: window.unregister_widget("prim", "cesiumTileMapServiceRasterOverlay") @staticmethod def _unregister_web_map_tile_service_raster_overlay_attributes_widget(): window = omni.kit.window.property.get_window() if window is not None: window.unregister_widget("prim", "cesiumWebMapTileServiceRasterOverlay") def _register_global_anchor_attributes_widget(self): window = omni.kit.window.property.get_window() if window is not None: window.register_widget( "prim", "cesiumGlobeAnchorAPI", CesiumGlobeAnchorAttributesWidget(self._cesium_omniverse_interface) ) @staticmethod def _unregister_global_anchor_attributes_widget(): window = omni.kit.window.property.get_window() if window is not None: window.unregister_widget("prim", "cesiumGlobalAnchorAPI") def _register_ion_server_attributes_widget(self): window = omni.kit.window.property.get_window() if window is not None: window.register_widget( "prim", "cesiumIonServer", CesiumIonServerAttributesWidget(self._cesium_omniverse_interface) ) @staticmethod def _unregister_ion_server_attributes_widget(): window = omni.kit.window.property.get_window() if window is not None: window.unregister_widget("prim", "cesiumIonServer")
7,625
Python
41.603352
118
0.694164
CesiumGS/cesium-omniverse/exts/cesium.omniverse/cesium/omniverse/ui/statistics_widget.py
import logging import carb.events import omni.kit.app as app import omni.ui as ui from typing import List from ..bindings import ICesiumOmniverseInterface from .models.space_delimited_number_model import SpaceDelimitedNumberModel from .models.human_readable_bytes_model import HumanReadableBytesModel MATERIALS_CAPACITY_TEXT = "Materials capacity" MATERIALS_LOADED_TEXT = "Materials loaded" GEOMETRIES_CAPACITY_TEXT = "Geometries capacity" GEOMETRIES_LOADED_TEXT = "Geometries loaded" GEOMETRIES_RENDERED_TEXT = "Geometries rendered" TRIANGLES_LOADED_TEXT = "Triangles loaded" TRIANGLES_RENDERED_TEXT = "Triangles rendered" TILESET_CACHED_BYTES_TEXT = "Tileset cached bytes" TILESET_CACHED_BYTES_HUMAN_READABLE_TEXT = "Tileset cached bytes (Human-readable)" TILES_VISITED_TEXT = "Tiles visited" CULLED_TILES_VISITED_TEXT = "Culled tiles visited" TILES_RENDERED_TEXT = "Tiles rendered" TILES_CULLED_TEXT = "Tiles culled" MAX_DEPTH_VISITED_TEXT = "Max depth visited" TILES_LOADING_WORKER_TEXT = "Tiles loading (worker)" TILES_LOADING_MAIN_TEXT = "Tiles loading (main)" TILES_LOADED_TEXT = "Tiles loaded" class CesiumOmniverseStatisticsWidget(ui.Frame): """ Widget that displays statistics about the scene. """ def __init__(self, cesium_omniverse_interface: ICesiumOmniverseInterface, **kwargs): super().__init__(build_fn=self._build_fn, **kwargs) self._logger = logging.getLogger(__name__) self._cesium_omniverse_interface = cesium_omniverse_interface self._materials_capacity_model: SpaceDelimitedNumberModel = SpaceDelimitedNumberModel(0) self._materials_loaded_model: SpaceDelimitedNumberModel = SpaceDelimitedNumberModel(0) self._geometries_capacity_model: SpaceDelimitedNumberModel = SpaceDelimitedNumberModel(0) self._geometries_loaded_model: SpaceDelimitedNumberModel = SpaceDelimitedNumberModel(0) self._geometries_rendered_model: SpaceDelimitedNumberModel = SpaceDelimitedNumberModel(0) self._triangles_loaded_model: SpaceDelimitedNumberModel = SpaceDelimitedNumberModel(0) self._triangles_rendered_model: SpaceDelimitedNumberModel = SpaceDelimitedNumberModel(0) self._tileset_cached_bytes_model: SpaceDelimitedNumberModel = SpaceDelimitedNumberModel(0) self._tileset_cached_bytes_human_readable_model: HumanReadableBytesModel = HumanReadableBytesModel(0) self._tiles_visited_model: SpaceDelimitedNumberModel = SpaceDelimitedNumberModel(0) self._culled_tiles_visited_model: SpaceDelimitedNumberModel = SpaceDelimitedNumberModel(0) self._tiles_rendered_model: SpaceDelimitedNumberModel = SpaceDelimitedNumberModel(0) self._tiles_culled_model: SpaceDelimitedNumberModel = SpaceDelimitedNumberModel(0) self._max_depth_visited_model: SpaceDelimitedNumberModel = SpaceDelimitedNumberModel(0) self._tiles_loading_worker_model: SpaceDelimitedNumberModel = SpaceDelimitedNumberModel(0) self._tiles_loading_main_model: SpaceDelimitedNumberModel = SpaceDelimitedNumberModel(0) self._tiles_loaded_model: SpaceDelimitedNumberModel = SpaceDelimitedNumberModel(0) self._subscriptions: List[carb.events.ISubscription] = [] self._setup_subscriptions() def __del__(self): self.destroy() def destroy(self): for subscription in self._subscriptions: subscription.unsubscribe() self._subscriptions.clear() super().destroy() def _setup_subscriptions(self): update_stream = app.get_app().get_update_event_stream() self._subscriptions.append( update_stream.create_subscription_to_pop(self._on_update_frame, name="on_update_frame") ) def _on_update_frame(self, _e: carb.events.IEvent): if not self.visible: return render_statistics = self._cesium_omniverse_interface.get_render_statistics() self._materials_capacity_model.set_value(render_statistics.materials_capacity) self._materials_loaded_model.set_value(render_statistics.materials_loaded) self._geometries_capacity_model.set_value(render_statistics.geometries_capacity) self._geometries_loaded_model.set_value(render_statistics.geometries_loaded) self._geometries_rendered_model.set_value(render_statistics.geometries_rendered) self._triangles_loaded_model.set_value(render_statistics.triangles_loaded) self._triangles_rendered_model.set_value(render_statistics.triangles_rendered) self._tileset_cached_bytes_model.set_value(render_statistics.tileset_cached_bytes) self._tileset_cached_bytes_human_readable_model.set_value(render_statistics.tileset_cached_bytes) self._tiles_visited_model.set_value(render_statistics.tiles_visited) self._culled_tiles_visited_model.set_value(render_statistics.culled_tiles_visited) self._tiles_rendered_model.set_value(render_statistics.tiles_rendered) self._tiles_culled_model.set_value(render_statistics.tiles_culled) self._max_depth_visited_model.set_value(render_statistics.max_depth_visited) self._tiles_loading_worker_model.set_value(render_statistics.tiles_loading_worker) self._tiles_loading_main_model.set_value(render_statistics.tiles_loading_main) self._tiles_loaded_model.set_value(render_statistics.tiles_loaded) def _build_fn(self): """Builds all UI components.""" with ui.VStack(spacing=4): with ui.HStack(height=16): ui.Label("Statistics", height=0) ui.Spacer() for label, model in [ (MATERIALS_CAPACITY_TEXT, self._materials_capacity_model), (MATERIALS_LOADED_TEXT, self._materials_loaded_model), (GEOMETRIES_CAPACITY_TEXT, self._geometries_capacity_model), (GEOMETRIES_LOADED_TEXT, self._geometries_loaded_model), (GEOMETRIES_RENDERED_TEXT, self._geometries_rendered_model), (TRIANGLES_LOADED_TEXT, self._triangles_loaded_model), (TRIANGLES_RENDERED_TEXT, self._triangles_rendered_model), (TILESET_CACHED_BYTES_TEXT, self._tileset_cached_bytes_model), (TILESET_CACHED_BYTES_HUMAN_READABLE_TEXT, self._tileset_cached_bytes_human_readable_model), (TILES_VISITED_TEXT, self._tiles_visited_model), (CULLED_TILES_VISITED_TEXT, self._culled_tiles_visited_model), (TILES_RENDERED_TEXT, self._tiles_rendered_model), (TILES_CULLED_TEXT, self._tiles_culled_model), (MAX_DEPTH_VISITED_TEXT, self._max_depth_visited_model), (TILES_LOADING_WORKER_TEXT, self._tiles_loading_worker_model), (TILES_LOADING_MAIN_TEXT, self._tiles_loading_main_model), (TILES_LOADED_TEXT, self._tiles_loaded_model), ]: with ui.HStack(height=0): ui.Label(label, height=0) ui.StringField(model=model, height=0, read_only=True)
7,064
Python
52.931297
109
0.708097
CesiumGS/cesium-omniverse/exts/cesium.omniverse/cesium/omniverse/ui/token_window.py
import logging import carb.events import omni.kit.app as app import omni.ui as ui import omni.usd from pathlib import Path from enum import Enum from typing import List, Optional from ..bindings import ICesiumOmniverseInterface, Token from .styles import CesiumOmniverseUiStyles from cesium.usd.plugins.CesiumUsdSchemas import IonServer as CesiumIonServer from ..usdUtils import get_path_to_current_ion_server SELECT_TOKEN_TEXT = ( "Cesium for Omniverse embeds a Cesium ion token in your stage in order to allow it " "to access the assets you add. Select the Cesium ion token to use." ) CREATE_NEW_LABEL_TEXT = "Create a new token" USE_EXISTING_LABEL_TEXT = "Use an existing token" SPECIFY_TOKEN_LABEL_TEXT = "Specify a token" CREATE_NEW_FIELD_LABEL_TEXT = "Name" USE_EXISTING_FIELD_LABEL_TEXT = "Token" SPECIFY_TOKEN_FIELD_LABEL_TEXT = "Token" SELECT_BUTTON_TEXT = "Use as Project Default Token" DEFAULT_TOKEN_PLACEHOLDER_BASE = "{0} (Created by Cesium For Omniverse)" OUTER_SPACING = 10 CHECKBOX_WIDTH = 20 INNER_HEIGHT = 20 FIELD_SPACING = 8 FIELD_LABEL_WIDTH = 40 class TokenOptionEnum(Enum): CREATE_NEW = 1 USE_EXISTING = 2 SPECIFY_TOKEN = 3 class UseExistingComboItem(ui.AbstractItem): def __init__(self, token: Token): super().__init__() self.id = ui.SimpleStringModel(token.id) self.name = ui.SimpleStringModel(token.name) self.token = ui.SimpleStringModel(token.token) def __str__(self): return f"{self.id.get_value_as_string()}:{self.name.get_value_as_string()}:{self.token.get_value_as_string()}" class UseExistingComboModel(ui.AbstractItemModel): def __init__(self, item_list): super().__init__() self._logger = logging.getLogger(__name__) self._current_index = ui.SimpleIntModel(0) self._current_index.add_value_changed_fn(lambda index_model: self._item_changed(None)) self._items = [UseExistingComboItem(text) for text in item_list] def replace_all_items(self, items: List[str]): self._items.clear() self._items = [UseExistingComboItem(text) for text in items] self._current_index.set_value(0) self._item_changed(None) def append_child_item(self, parent_item: ui.AbstractItem, model: str): self._items.append(UseExistingComboItem(model)) self._item_changed(None) def get_item_children(self, item=None): return self._items def get_item_value_model(self, item: UseExistingComboItem = None, column_id: int = 0): if item is None: return self._current_index return item.name def get_current_selection(self): if len(self._items) < 1: return None return self._items[self._current_index.get_value_as_int()] class CesiumOmniverseTokenWindow(ui.Window): WINDOW_NAME = "Select Cesium ion Token" def __init__(self, cesium_omniverse_interface: ICesiumOmniverseInterface, **kwargs): super().__init__(CesiumOmniverseTokenWindow.WINDOW_NAME, **kwargs) self._cesium_omniverse_interface = cesium_omniverse_interface self._logger = logging.getLogger(__name__) self.height = 400 self.width = 600 self.padding_x = 12 self.padding_y = 12 session = self._cesium_omniverse_interface.get_session() self._is_connected: bool = session.is_connected() if self._is_connected: self._selected_option = TokenOptionEnum.CREATE_NEW else: self._selected_option = TokenOptionEnum.SPECIFY_TOKEN self._create_new_radio_button_model = ui.SimpleBoolModel(self._is_connected) self._create_new_radio_button_model.add_value_changed_fn( lambda m: self._radio_button_changed(m, TokenOptionEnum.CREATE_NEW) ) self._use_existing_radio_button_model = ui.SimpleBoolModel(False) self._use_existing_radio_button_model.add_value_changed_fn( lambda m: self._radio_button_changed(m, TokenOptionEnum.USE_EXISTING) ) self._specify_token_radio_button_model = ui.SimpleBoolModel(not self._is_connected) self._specify_token_radio_button_model.add_value_changed_fn( lambda m: self._radio_button_changed(m, TokenOptionEnum.SPECIFY_TOKEN) ) self._use_existing_combo_box: Optional[ui.ComboBox] = None stage = omni.usd.get_context().get_stage() root_identifier = stage.GetRootLayer().identifier # In the event that the stage has been saved and the root layer identifier is a file path then we want to # grab just the final bit of that. if not root_identifier.startswith("anon:"): try: root_identifier = Path(root_identifier).name except NotImplementedError as e: self._logger.warning( f"Unknown stage identifier type. Passed {root_identifier} to Path. Exception: {e}" ) self._create_new_field_model = ui.SimpleStringModel(DEFAULT_TOKEN_PLACEHOLDER_BASE.format(root_identifier)) self._use_existing_combo_model = UseExistingComboModel([]) server_prim_path = get_path_to_current_ion_server() server_prim = CesiumIonServer.Get(stage, server_prim_path) if server_prim.GetPrim().IsValid(): current_token = server_prim.GetProjectDefaultIonAccessTokenAttr().Get() self._specify_token_field_model = ui.SimpleStringModel(current_token if current_token is not None else "") else: self._specify_token_field_model = ui.SimpleStringModel() self._reload_next_frame = False # _handle_select_result is different from most subscriptions. We delete it when we are done, so it is separate # from the subscriptions array. self._handle_select_result_sub: Optional[carb.events.ISubscription] = None self._subscriptions: List[carb.events.ISubscription] = [] self._setup_subscriptions() self.frame.set_build_fn(self._build_ui) def __del__(self): self.destroy() def destroy(self): for subscription in self._subscriptions: subscription.unsubscribe() self._subscriptions.clear() if self._handle_select_result_sub is not None: self._handle_select_result_sub.unsubscribe() self._handle_select_result_sub = None super().destroy() def _setup_subscriptions(self): update_stream = app.get_app().get_update_event_stream() self._subscriptions.append( update_stream.create_subscription_to_pop(self._on_update_frame, name="on_update_frame") ) def _on_update_frame(self, _e: carb.events.IEvent): session = self._cesium_omniverse_interface.get_session() if self._reload_next_frame and session.is_token_list_loaded(): token_list = session.get_tokens() self._use_existing_combo_model.replace_all_items(token_list) if self._use_existing_combo_box: self._use_existing_combo_box.enabled = True self._reload_next_frame = False elif session.is_loading_token_list(): if self._use_existing_combo_box: self._use_existing_combo_box.enabled = False self._reload_next_frame = True def _select_button_clicked(self): bus = app.get_app().get_message_bus_event_stream() completed_event = carb.events.type_from_string("cesium.omniverse.SET_DEFAULT_PROJECT_TOKEN_COMPLETE") self._handle_select_result_sub = bus.create_subscription_to_pop_by_type( completed_event, self._handle_select_result, name="cesium.omniverse.HANDLE_SELECT_TOKEN_RESULT" ) if self._selected_option is TokenOptionEnum.CREATE_NEW: self._create_token() elif self._selected_option is TokenOptionEnum.USE_EXISTING: self._use_existing_token() elif self._selected_option is TokenOptionEnum.SPECIFY_TOKEN: self._specify_token() def _handle_select_result(self, _e: carb.events.IEvent): # We probably need to put some better error handling here in the future. result = self._cesium_omniverse_interface.get_set_default_token_result() if result.code != 0: self._logger.warning(f"Error when trying to set token: {result.message}") bus = app.get_app().get_message_bus_event_stream() success_event = carb.events.type_from_string("cesium.omniverse.SET_DEFAULT_TOKEN_SUCCESS") bus.push(success_event) self.visible = False self.destroy() def _create_token(self): name = self._create_new_field_model.get_value_as_string().strip() if name != "": self._cesium_omniverse_interface.create_token(name) def _use_existing_token(self): token = self._use_existing_combo_model.get_current_selection() if token is not None: self._cesium_omniverse_interface.select_token( token.id.get_value_as_string(), token.token.get_value_as_string() ) def _specify_token(self): token = self._specify_token_field_model.get_value_as_string().strip() if token != "": self._cesium_omniverse_interface.specify_token(token) def _radio_button_changed(self, model, selected: TokenOptionEnum): if not model.get_value_as_bool(): self._reselect_if_none_selected(selected) return self._selected_option = selected if self._selected_option is TokenOptionEnum.CREATE_NEW: self._create_new_radio_button_model.set_value(True) self._use_existing_radio_button_model.set_value(False) self._specify_token_radio_button_model.set_value(False) elif self._selected_option is TokenOptionEnum.USE_EXISTING: self._create_new_radio_button_model.set_value(False) self._use_existing_radio_button_model.set_value(True) self._specify_token_radio_button_model.set_value(False) elif self._selected_option is TokenOptionEnum.SPECIFY_TOKEN: self._create_new_radio_button_model.set_value(False) self._use_existing_radio_button_model.set_value(False) self._specify_token_radio_button_model.set_value(True) def _reselect_if_none_selected(self, selected): """ Reselect the checkbox in our "radio buttons" if none are selected. This is necessary because Omniverse has us using checkboxes to make a radio button rather than a proper radio button. """ if ( not self._create_new_radio_button_model.get_value_as_bool() and not self._use_existing_radio_button_model.get_value_as_bool() and not self._specify_token_radio_button_model.get_value_as_bool() ): if selected is TokenOptionEnum.CREATE_NEW: self._create_new_radio_button_model.set_value(True) elif selected is TokenOptionEnum.USE_EXISTING: self._use_existing_radio_button_model.set_value(True) elif selected is TokenOptionEnum.SPECIFY_TOKEN: self._specify_token_radio_button_model.set_value(True) @staticmethod def _build_field( label_text: str, field_label_text: str, checkbox_model: ui.SimpleBoolModel, string_field_model: ui.SimpleStringModel, visible=True, ): with ui.HStack(spacing=OUTER_SPACING, visible=visible): ui.CheckBox(checkbox_model, width=CHECKBOX_WIDTH) with ui.VStack(height=INNER_HEIGHT, spacing=FIELD_SPACING): ui.Label(label_text) with ui.HStack(): ui.Label(field_label_text, width=FIELD_LABEL_WIDTH) ui.StringField(string_field_model) def _build_ui(self): with ui.VStack(spacing=10): ui.Label(SELECT_TOKEN_TEXT, height=40, word_wrap=True) self._build_field( CREATE_NEW_LABEL_TEXT, CREATE_NEW_FIELD_LABEL_TEXT, self._create_new_radio_button_model, self._create_new_field_model, self._is_connected, ) with ui.HStack(spacing=OUTER_SPACING, visible=self._is_connected): ui.CheckBox(self._use_existing_radio_button_model, width=CHECKBOX_WIDTH) with ui.VStack(height=20, spacing=FIELD_SPACING): ui.Label(USE_EXISTING_LABEL_TEXT) with ui.HStack(): ui.Label(USE_EXISTING_FIELD_LABEL_TEXT, width=FIELD_LABEL_WIDTH) self._use_existing_combo_box = ui.ComboBox(self._use_existing_combo_model) self._build_field( SPECIFY_TOKEN_LABEL_TEXT, SPECIFY_TOKEN_FIELD_LABEL_TEXT, self._specify_token_radio_button_model, self._specify_token_field_model, ) ui.Button( SELECT_BUTTON_TEXT, alignment=ui.Alignment.CENTER, height=36, style=CesiumOmniverseUiStyles.blue_button_style, clicked_fn=self._select_button_clicked, )
13,286
Python
40.009259
118
0.638717
CesiumGS/cesium-omniverse/exts/cesium.omniverse/cesium/omniverse/ui/profile_widget.py
import omni.usd import logging import carb.events import omni.kit.app as app import omni.ui as ui from typing import List, Optional from ..bindings import ICesiumOmniverseInterface, CesiumIonSession from enum import Enum from cesium.usd.plugins.CesiumUsdSchemas import IonServer as CesiumIonServer from ..usdUtils import set_path_to_current_ion_server class SessionState(Enum): NOT_CONNECTED = 1 LOADING = 2 CONNECTED = 3 def get_session_state(session: CesiumIonSession) -> SessionState: if session.is_profile_loaded(): return SessionState.CONNECTED elif session.is_loading_profile(): return SessionState.LOADING else: return SessionState.NOT_CONNECTED def get_profile_id(session: CesiumIonSession) -> Optional[int]: if session.is_profile_loaded(): profile = session.get_profile() return profile.id return None class SessionComboItem(ui.AbstractItem): def __init__(self, session: CesiumIonSession, server: CesiumIonServer): super().__init__() session_state = get_session_state(session) prefix = "" suffix = "" if session_state == SessionState.NOT_CONNECTED: suffix += " (not connected)" elif session_state == SessionState.LOADING: suffix += " (loading profile...)" elif session_state == SessionState.CONNECTED: prefix += session.get_profile().username prefix += " @ " # Get the display name from the server prim. If that's empty, use the prim path. server_name = server.GetDisplayNameAttr().Get() if server_name == "": server_name = server.GetPath() self.text = ui.SimpleStringModel(f"{prefix}{server_name}{suffix}") self.server = server class SessionComboModel(ui.AbstractItemModel): def __init__(self): super().__init__() self._logger = logging.getLogger(__name__) self._current_index = ui.SimpleIntModel(0) self._current_index.add_value_changed_fn(lambda index_model: self._item_changed(None)) self._items = [] def replace_all_items( self, sessions: List[CesiumIonSession], servers: List[CesiumIonServer], current_server: CesiumIonServer ): self._items.clear() self._items = [SessionComboItem(session, server) for session, server in zip(sessions, servers)] current_index = 0 for index, server in enumerate(servers): if server.GetPath() == current_server.GetPath(): current_index = index break self._current_index.set_value(current_index) self._item_changed(None) def get_item_children(self, item=None): return self._items def get_item_value_model(self, item: SessionComboItem = None, column_id: int = 0): if item is None: return self._current_index return item.text def get_current_selection(self): if len(self._items) < 1: return None return self._items[self._current_index.get_value_as_int()] class CesiumOmniverseProfileWidget(ui.Frame): def __init__(self, cesium_omniverse_interface: ICesiumOmniverseInterface, **kwargs): self._logger = logging.getLogger(__name__) self._cesium_omniverse_interface = cesium_omniverse_interface self._profile_ids: List[int] = [] self._session_states: List[SessionState] = [] self._server_paths: List[str] = [] self._server_names: List[str] = [] self._sessions_combo_box: Optional[ui.ComboBox] = None self._sessions_combo_model = SessionComboModel() self._sessions_combo_model.add_item_changed_fn(self._on_item_changed) self._subscriptions: List[carb.events.ISubscription] = [] self._setup_subscriptions() super().__init__(build_fn=self._build_ui, **kwargs) def destroy(self) -> None: for subscription in self._subscriptions: subscription.unsubscribe() self._subscriptions.clear() def _setup_subscriptions(self): update_stream = app.get_app().get_update_event_stream() self._subscriptions.append( update_stream.create_subscription_to_pop(self._on_update_frame, name="on_update_frame") ) def _on_item_changed(self, item_model, item): item = self._sessions_combo_model.get_current_selection() if item is not None: server_path = item.server.GetPath() set_path_to_current_ion_server(server_path) def _on_update_frame(self, _e: carb.events.IEvent): if omni.usd.get_context().get_stage_state() != omni.usd.StageState.OPENED: return stage = omni.usd.get_context().get_stage() sessions = self._cesium_omniverse_interface.get_sessions() server_paths = self._cesium_omniverse_interface.get_server_paths() servers = [CesiumIonServer.Get(stage, server_path) for server_path in server_paths] server_names = [server.GetDisplayNameAttr().Get() for server in servers] current_server_path = self._cesium_omniverse_interface.get_server_path() current_server = CesiumIonServer.Get(stage, current_server_path) profile_ids = [] session_states = [] for session in sessions: profile_id = get_profile_id(session) session_state = get_session_state(session) if session.is_connected() and not session.is_profile_loaded(): session.refresh_profile() profile_ids.append(profile_id) session_states.append(session_state) if ( profile_ids != self._profile_ids or session_states != self._session_states or server_paths != self._server_paths or server_names != self._server_names ): self._logger.info("Rebuilding profile widget") self._profile_ids = profile_ids self._session_states = session_states self._server_paths = server_paths self._server_names = server_names self._sessions_combo_model.replace_all_items(sessions, servers, current_server) self.rebuild() def _build_ui(self): self._sessions_combo_box = ui.ComboBox(self._sessions_combo_model)
6,315
Python
33.703297
111
0.634363
CesiumGS/cesium-omniverse/exts/cesium.omniverse/cesium/omniverse/ui/add_menu_controller.py
from functools import partial import logging import omni.kit.context_menu from omni.kit.property.usd import PrimPathWidget, PrimSelectionPayload from omni.kit.window.property import get_window as get_property_window import omni.usd from pxr import Sdf, Tf, UsdGeom from cesium.usd.plugins.CesiumUsdSchemas import ( Tileset as CesiumTileset, PolygonRasterOverlay as CesiumPolygonRasterOverlay, IonRasterOverlay as CesiumIonRasterOverlay, WebMapServiceRasterOverlay as CesiumWebMapServiceRasterOverlay, TileMapServiceRasterOverlay as CesiumTileMapServiceRasterOverlay, WebMapTileServiceRasterOverlay as CesiumWebMapTileServiceRasterOverlay, ) from ..usdUtils import add_globe_anchor_to_prim from ..bindings import ICesiumOmniverseInterface class CesiumAddMenuController: def __init__(self, cesium_omniverse_interface: ICesiumOmniverseInterface): self._logger = logging.getLogger(__name__) self._cesium_omniverse_interface = cesium_omniverse_interface context_menu = omni.kit.context_menu.get_instance() if context_menu is None: self._logger.error("Cannot add Cesium options to Add menu when context_menu is disabled.") return self._items_added = [ PrimPathWidget.add_button_menu_entry( "Cesium/Globe Anchor", show_fn=partial(self._show_add_globe_anchor, context_menu=context_menu, usd_type=UsdGeom.Xformable), onclick_fn=self._add_globe_anchor_api, ), PrimPathWidget.add_button_menu_entry( "Cesium/Ion Raster Overlay", show_fn=partial(self._show_add_raster_overlay, context_menu=context_menu, usd_type=CesiumTileset), onclick_fn=self._add_ion_raster_overlay, ), PrimPathWidget.add_button_menu_entry( "Cesium/Polygon Raster Overlay", show_fn=partial(self._show_add_raster_overlay, context_menu=context_menu, usd_type=CesiumTileset), onclick_fn=self._add_polygon_raster_overlay, ), PrimPathWidget.add_button_menu_entry( "Cesium/Web Map Service Raster Overlay", show_fn=partial(self._show_add_raster_overlay, context_menu=context_menu, usd_type=CesiumTileset), onclick_fn=self._add_web_map_service_raster_overlay, ), PrimPathWidget.add_button_menu_entry( "Cesium/Tile Map Service Raster Overlay", show_fn=partial(self._show_add_raster_overlay, context_menu=context_menu, usd_type=CesiumTileset), onclick_fn=self._add_tile_map_service_raster_overlay, ), PrimPathWidget.add_button_menu_entry( "Cesium/Web Map Tile Service Raster Overlay", show_fn=partial(self._show_add_raster_overlay, context_menu=context_menu, usd_type=CesiumTileset), onclick_fn=self._add_web_map_tile_service_raster_overlay, ), ] def destroy(self): for item in self._items_added: PrimPathWidget.remove_button_menu_entry(item) self._items_added.clear() def _add_globe_anchor_api(self, payload: PrimSelectionPayload): for path in payload: add_globe_anchor_to_prim(path) get_property_window().request_rebuild() def _add_ion_raster_overlay(self, payload: PrimSelectionPayload): stage = omni.usd.get_context().get_stage() for path in payload: child_path = Sdf.Path(path).AppendPath("ion_raster_overlay") ion_raster_overlay_path: str = omni.usd.get_stage_next_free_path(stage, child_path, False) CesiumIonRasterOverlay.Define(stage, ion_raster_overlay_path) tileset_prim = CesiumTileset.Get(stage, path) tileset_prim.GetRasterOverlayBindingRel().AddTarget(ion_raster_overlay_path) get_property_window().request_rebuild() def _add_polygon_raster_overlay(self, payload: PrimSelectionPayload): stage = omni.usd.get_context().get_stage() for path in payload: child_path = Sdf.Path(path).AppendPath("polygon_raster_overlay") polygon_raster_overlay_path: str = omni.usd.get_stage_next_free_path(stage, child_path, False) CesiumPolygonRasterOverlay.Define(stage, polygon_raster_overlay_path) tileset_prim = CesiumTileset.Get(stage, path) tileset_prim.GetRasterOverlayBindingRel().AddTarget(polygon_raster_overlay_path) get_property_window().request_rebuild() def _add_web_map_service_raster_overlay(self, payload: PrimSelectionPayload): stage = omni.usd.get_context().get_stage() for path in payload: child_path = Sdf.Path(path).AppendPath("web_map_service_raster_overlay") raster_overlay_path: str = omni.usd.get_stage_next_free_path(stage, child_path, False) CesiumWebMapServiceRasterOverlay.Define(stage, raster_overlay_path) tileset_prim = CesiumTileset.Get(stage, path) tileset_prim.GetRasterOverlayBindingRel().AddTarget(raster_overlay_path) get_property_window().request_rebuild() def _add_tile_map_service_raster_overlay(self, payload: PrimSelectionPayload): stage = omni.usd.get_context().get_stage() for path in payload: child_path = Sdf.Path(path).AppendPath("tile_map_service_raster_overlay") raster_overlay_path: str = omni.usd.get_stage_next_free_path(stage, child_path, False) CesiumTileMapServiceRasterOverlay.Define(stage, raster_overlay_path) tileset_prim = CesiumTileset.Get(stage, path) tileset_prim.GetRasterOverlayBindingRel().AddTarget(raster_overlay_path) get_property_window().request_rebuild() def _add_web_map_tile_service_raster_overlay(self, payload: PrimSelectionPayload): stage = omni.usd.get_context().get_stage() for path in payload: child_path = Sdf.Path(path).AppendPath("web_map_tile_service_raster_overlay") raster_overlay_path: str = omni.usd.get_stage_next_free_path(stage, child_path, False) CesiumWebMapTileServiceRasterOverlay.Define(stage, raster_overlay_path) tileset_prim = CesiumTileset.Get(stage, path) tileset_prim.GetRasterOverlayBindingRel().AddTarget(raster_overlay_path) get_property_window().request_rebuild() @staticmethod def _show_add_globe_anchor(objects: dict, context_menu: omni.kit.context_menu, usd_type: Tf.Type) -> bool: return context_menu.prim_is_type(objects, type=usd_type) @staticmethod def _show_add_raster_overlay(objects: dict, context_menu: omni.kit.context_menu, usd_type: Tf.Type) -> bool: return context_menu.prim_is_type(objects, type=usd_type)
6,877
Python
51.907692
116
0.671514
CesiumGS/cesium-omniverse/exts/cesium.omniverse/cesium/omniverse/ui/image_button.py
import urllib.request from io import BytesIO from PIL import Image import omni.ui as ui class CesiumImageButton: """A button with an image from a URL or base64 encoded string. Based off of Nvidia's ButtonWithProvider sample.""" def __init__(self, src: str, button_type=ui.Button, padding=0, height=None, **kwargs): style_type = kwargs.pop("style_type_name_override", self.__class__.__name__) name = kwargs.pop("name", "") with ui.ZStack(height=0, width=0): # This is copied from uri_image.py since we seem to blow the stack if we nest any deeper when rendering. data = urllib.request.urlopen(src).read() img_data = BytesIO(data) image = Image.open(img_data) if image.mode != "RGBA": image = image.convert("RGBA") pixels = list(image.getdata()) provider = ui.ByteImageProvider() provider.set_bytes_data(pixels, [image.size[0], image.size[1]]) if height is None: width = image.size[0] height = image.size[1] else: # If the user is explicitely setting the height of the button, we need to calc an appropriate width width = image.size[0] * (height / image.size[1]) # Add padding for all sides height += padding * 2 width += padding * 2 # The styles here are very specific to this stuff so they shouldn't be included # in the CesiumOmniverseUiStyles class. self._button = button_type( text=" ", # Workaround Buttons without text do not expand vertically style_type_name_override=style_type, name=name, width=width, height=height, style={ "border_radius": 6, "background_color": ui.color.transparent, "color": ui.color.transparent, ":hovered": {"background_color": ui.color("#9E9E9E")}, }, **kwargs, ) self._image = ui.ImageWithProvider( provider, width=width, height=height, fill_policy=ui.IwpFillPolicy.IWP_PRESERVE_ASPECT_FIT, style={"alignment": ui.Alignment.CENTER, "margin": padding}, style_type_name_override=style_type, name=name, ) def get_image(self): return self._image def __getattr__(self, attr): return getattr(self._button, attr) def __setattr__(self, attr, value): if attr == "_image" or attr == "_button": super().__setattr__(attr, value) else: self._button.__setattr__(attr, value)
2,834
Python
37.31081
118
0.538109
CesiumGS/cesium-omniverse/exts/cesium.omniverse/cesium/omniverse/ui/credits_viewport_controller.py
from .credits_parser import CesiumCreditsParser, ParsedCredit from typing import List, Optional, Tuple import logging import carb.events import omni.kit.app as app from ..bindings import ICesiumOmniverseInterface import omni.ui as ui import omni.kit.app import json from carb.events import IEventStream from .events import EVENT_CREDITS_CHANGED class CreditsViewportController: def __init__(self, cesium_omniverse_interface: ICesiumOmniverseInterface): self._cesium_omniverse_interface = cesium_omniverse_interface self._logger: Optional[logging.Logger] = logging.getLogger(__name__) self._parsed_credits: List[ParsedCredit] = [] self._credits: List[Tuple[str, bool]] = [] self._subscriptions: List[carb.events.ISubscription] = [] self._setup_update_subscription() self._message_bus: IEventStream = omni.kit.app.get_app().get_message_bus_event_stream() self._EVENT_CREDITS_CHANGED: int = EVENT_CREDITS_CHANGED def __del__(self): self.destroy() def destroy(self): for subscription in self._subscriptions: subscription.unsubscribe() self._subscriptions.clear() def _setup_update_subscription(self): update_stream = app.get_app().get_update_event_stream() self._subscriptions.append( update_stream.create_subscription_to_pop( self._on_update_frame, name="cesium.omniverse.viewport.ON_UPDATE_FRAME" ) ) def _on_update_frame(self, _e: carb.events.IEvent): if self._cesium_omniverse_interface is None: return new_credits = self._cesium_omniverse_interface.get_credits() # cheap test if new_credits != self._credits: self._credits.clear() self._credits.extend(new_credits) # deep test credits_parser = CesiumCreditsParser( new_credits, should_show_on_screen=True, combine_labels=True, label_alignment=ui.Alignment.RIGHT, ) new_parsed_credits = credits_parser._parse_credits(new_credits, True, False) if new_parsed_credits != self._parsed_credits: self._parsed_credits = new_parsed_credits self.broadcast_credits() self._cesium_omniverse_interface.credits_start_next_frame() def broadcast_credits(self): my_payload = json.dumps(self._credits) self._message_bus.push(self._EVENT_CREDITS_CHANGED, payload={"credits": my_payload})
2,567
Python
36.217391
95
0.64589
CesiumGS/cesium-omniverse/exts/cesium.omniverse/cesium/omniverse/ui/fabric_modal.py
import carb.settings import omni.ui as ui import omni.kit.window.file class CesiumFabricModal(ui.Window): def __init__(self): window_flags = ui.WINDOW_FLAGS_NO_RESIZE window_flags |= ui.WINDOW_FLAGS_NO_SCROLLBAR window_flags |= ui.WINDOW_FLAGS_MODAL window_flags |= ui.WINDOW_FLAGS_NO_CLOSE window_flags |= ui.WINDOW_FLAGS_NO_COLLAPSE super().__init__("Enable Fabric", height=200, width=300, flags=window_flags) self.frame.set_build_fn(self._build_fn) def _on_yes_click(self): carb.settings.get_settings().set_bool("/app/useFabricSceneDelegate", True) carb.settings.get_settings().set_bool("/app/usdrt/scene_delegate/enableProxyCubes", False) carb.settings.get_settings().set_bool("/app/usdrt/scene_delegate/geometryStreaming/enabled", False) carb.settings.get_settings().set_bool("/omnihydra/parallelHydraSprimSync", False) omni.kit.window.file.new() self.visible = False def _on_no_click(self): self.visible = False def _build_fn(self): with ui.VStack(height=0, spacing=10): ui.Label( "The Omniverse Fabric Scene Delegate is currently disabled. Cesium for Omniverse requires the " "Fabric Scene Delegate to be enabled to function.", word_wrap=True, ) ui.Label("Would you like to enable the Fabric Scene Delegate and create a new stage?", word_wrap=True) ui.Button("Yes", clicked_fn=self._on_yes_click) ui.Button("No", clicked_fn=self._on_no_click)
1,601
Python
40.076922
114
0.643348
CesiumGS/cesium-omniverse/exts/cesium.omniverse/cesium/omniverse/ui/asset_window.py
import logging from typing import cast, List, Optional import carb.events import omni.kit.app as app import omni.ui as ui from .asset_details_widget import CesiumAssetDetailsWidget from .search_field_widget import CesiumSearchFieldWidget from .models import IonAssets, IonAssetItem, IonAssetDelegate from .styles import CesiumOmniverseUiStyles from ..bindings import ICesiumOmniverseInterface class CesiumOmniverseAssetWindow(ui.Window): """ The asset list window for Cesium for Omniverse. Docked in the same area as "Assets". """ WINDOW_NAME = "Cesium Assets" MENU_PATH = f"Window/Cesium/{WINDOW_NAME}" def __init__(self, cesium_omniverse_interface: ICesiumOmniverseInterface, **kwargs): super().__init__(CesiumOmniverseAssetWindow.WINDOW_NAME, **kwargs) self._cesium_omniverse_interface = cesium_omniverse_interface self._logger = logging.getLogger(__name__) self._assets = IonAssets() self._assets_delegate = IonAssetDelegate() self._refresh_button: Optional[ui.Button] = None self._asset_tree_view: Optional[ui.TreeView] = None self._asset_details_widget: Optional[CesiumAssetDetailsWidget] = None self._search_field_widget: Optional[CesiumSearchFieldWidget] = None self._subscriptions: List[carb.events.ISubscription] = [] self._setup_subscriptions() self.frame.set_build_fn(self._build_fn) self._refresh_list() self.focus() def __del__(self): self.destroy() def destroy(self): if self._refresh_button is not None: self._refresh_button.destroy() self._refresh_button = None if self._asset_tree_view is not None: self._asset_tree_view.destroy() self._asset_tree_view = None if self._asset_details_widget is not None: self._asset_details_widget.destroy() self._asset_details_widget = None if self._search_field_widget is not None: self._search_field_widget.destroy() self._search_field_widget = None for subscription in self._subscriptions: subscription.unsubscribe() self._subscriptions.clear() super().destroy() def _setup_subscriptions(self): bus = app.get_app().get_message_bus_event_stream() assets_updated_event = carb.events.type_from_string("cesium.omniverse.ASSETS_UPDATED") self._subscriptions.append( bus.create_subscription_to_pop_by_type( assets_updated_event, self._on_assets_updated, name="cesium.omniverse.asset_window.assets_updated" ) ) def _refresh_list(self): session = self._cesium_omniverse_interface.get_session() if session is not None: self._logger.info("Cesium ion Assets refreshing.") session.refresh_assets() if self._search_field_widget is not None: self._search_field_widget.search_value = "" def _on_assets_updated(self, _e: carb.events.IEvent): session = self._cesium_omniverse_interface.get_session() if session is not None: self._logger.info("Cesium ion Assets refreshed.") self._assets.replace_items( [ IonAssetItem( item.asset_id, item.name, item.description, item.attribution, item.asset_type, item.date_added ) for item in session.get_assets().items ] ) def _refresh_button_clicked(self): self._refresh_list() self._selection_changed([]) def _selection_changed(self, items: List[ui.AbstractItem]): if len(items) > 0: item = cast(IonAssetItem, items.pop()) else: item = None self._asset_details_widget.update_selection(item) def _search_value_changed(self, _e): if self._search_field_widget is None: return self._assets.filter_items(self._search_field_widget.search_value) def _build_fn(self): """Builds all UI components.""" with ui.VStack(spacing=5): with ui.HStack(height=30): self._refresh_button = ui.Button( "Refresh", alignment=ui.Alignment.CENTER, width=80, style=CesiumOmniverseUiStyles.blue_button_style, clicked_fn=self._refresh_button_clicked, ) ui.Spacer() with ui.VStack(width=0): ui.Spacer() self._search_field_widget = CesiumSearchFieldWidget( self._search_value_changed, width=320, height=32 ) with ui.HStack(spacing=5): with ui.ScrollingFrame( style_type_name_override="TreeView", style={"Field": {"background_color": 0xFF000000}}, width=ui.Length(2, ui.UnitType.FRACTION), ): self._asset_tree_view = ui.TreeView( self._assets, delegate=self._assets_delegate, root_visible=False, header_visible=True, style={"TreeView.Item": {"margin": 4}}, ) self._asset_tree_view.set_selection_changed_fn(self._selection_changed) self._asset_details_widget = CesiumAssetDetailsWidget( self._cesium_omniverse_interface, width=ui.Length(1, ui.UnitType.FRACTION) )
5,691
Python
35.72258
118
0.582499
CesiumGS/cesium-omniverse/exts/cesium.omniverse/cesium/omniverse/ui/attributes/web_map_tile_service_raster_overlay_attributes_widget.py
import logging import omni.kit.window.property import omni.usd import omni.ui from omni.kit.property.usd.custom_layout_helper import CustomLayoutFrame, CustomLayoutGroup, CustomLayoutProperty from omni.kit.property.usd.usd_property_widget import SchemaPropertiesWidget from cesium.usd.plugins.CesiumUsdSchemas import ( WebMapTileServiceRasterOverlay as CesiumWebMapTileServiceRasterOverlay, ) from .cesium_properties_widget_builder import build_slider, build_common_raster_overlay_properties class CesiumWebMapTileServiceRasterOverlayAttributesWidget(SchemaPropertiesWidget): def __init__(self): super().__init__( "Cesium Web Map Service Raster Overlay Settings", CesiumWebMapTileServiceRasterOverlay, include_inherited=True, ) self._logger = logging.getLogger(__name__) self._stage = omni.usd.get_context().get_stage() def clean(self): super().clean() def _on_usd_changed(self, notice, stage): window = omni.kit.window.property.get_window() window.request_rebuild() def _customize_props_layout(self, props): frame = CustomLayoutFrame(hide_extra=True) prim_path = self._payload.get_paths()[0] webMapTileServiceRasterOverlay = CesiumWebMapTileServiceRasterOverlay.Get(self._stage, prim_path) specify_zoom_levels = webMapTileServiceRasterOverlay.GetSpecifyZoomLevelsAttr().Get() specify_tile_matrix_set_labels = webMapTileServiceRasterOverlay.GetSpecifyTileMatrixSetLabelsAttr().Get() specify_tiling_scheme = webMapTileServiceRasterOverlay.GetSpecifyTilingSchemeAttr().Get() with frame: with CustomLayoutGroup("WMTS Settings"): CustomLayoutProperty("cesium:url") CustomLayoutProperty("cesium:layer") CustomLayoutProperty("cesium:style") CustomLayoutProperty("cesium:format") with CustomLayoutGroup("Tiling Matrix Set Settings", collapsed=False): CustomLayoutProperty("cesium:tileMatrixSetId") CustomLayoutProperty("cesium:specifyTileMatrixSetLabels") if specify_tile_matrix_set_labels: CustomLayoutProperty("cesium:tileMatrixSetLabels") else: CustomLayoutProperty("cesium:tileMatrixSetLabelPrefix") CustomLayoutProperty("cesium:useWebMercatorProjection") with CustomLayoutGroup("Tiling Scheme Settings", collapsed=False): CustomLayoutProperty("cesium:specifyTilingScheme") if specify_tiling_scheme: CustomLayoutProperty("cesium:rootTilesX") CustomLayoutProperty("cesium:rootTilesY") CustomLayoutProperty("cesium:west") CustomLayoutProperty("cesium:east") CustomLayoutProperty("cesium:south") CustomLayoutProperty("cesium:north") with CustomLayoutGroup("Zoom Settings", collapsed=False): CustomLayoutProperty("cesium:specifyZoomLevels") if specify_zoom_levels: CustomLayoutProperty( "cesium:minimumZoomLevel", build_fn=build_slider( 0, 30, type="int", constrain={"attr": "cesium:maximumZoomLevel", "type": "maximum"} ), ) CustomLayoutProperty( "cesium:maximumZoomLevel", build_fn=build_slider( 0, 30, type="int", constrain={"attr": "cesium:minimumZoomLevel", "type": "minimum"} ), ) build_common_raster_overlay_properties() return frame.apply(props) def reset(self): if self._listener: self._listener.Revoke() self._listener = None super().reset()
4,112
Python
45.738636
115
0.606031
CesiumGS/cesium-omniverse/exts/cesium.omniverse/cesium/omniverse/ui/attributes/web_map_service_raster_overlay_attributes_widget.py
import logging from omni.kit.property.usd.custom_layout_helper import CustomLayoutFrame, CustomLayoutGroup, CustomLayoutProperty from omni.kit.property.usd.usd_property_widget import SchemaPropertiesWidget from cesium.usd.plugins.CesiumUsdSchemas import ( WebMapServiceRasterOverlay as CesiumWebMapServiceRasterOverlay, ) from .cesium_properties_widget_builder import build_slider, build_common_raster_overlay_properties class CesiumWebMapServiceRasterOverlayAttributesWidget(SchemaPropertiesWidget): def __init__(self): super().__init__( "Cesium Web Map Service Raster Overlay Settings", CesiumWebMapServiceRasterOverlay, include_inherited=True ) self._logger = logging.getLogger(__name__) def clean(self): super().clean() def _customize_props_layout(self, props): frame = CustomLayoutFrame(hide_extra=True) with frame: with CustomLayoutGroup("Base URL"): CustomLayoutProperty("cesium:baseUrl") with CustomLayoutGroup("Layers"): CustomLayoutProperty("cesium:layers") with CustomLayoutGroup("Tile Size"): CustomLayoutProperty("cesium:tileWidth", build_fn=build_slider(64, 2048, type="int")) CustomLayoutProperty("cesium:tileHeight", build_fn=build_slider(64, 2048, type="int")) with CustomLayoutGroup("Zoom Settings"): CustomLayoutProperty( "cesium:minimumLevel", build_fn=build_slider( 0, 30, type="int", constrain={"attr": "cesium:maximumLevel", "type": "maximum"} ), ) CustomLayoutProperty( "cesium:maximumLevel", build_fn=build_slider( 0, 30, type="int", constrain={"attr": "cesium:minimumLevel", "type": "minimum"} ), ) build_common_raster_overlay_properties() return frame.apply(props)
2,039
Python
41.499999
118
0.621383
CesiumGS/cesium-omniverse/exts/cesium.omniverse/cesium/omniverse/ui/attributes/cesium_properties_widget_builder.py
from typing import List import omni.ui as ui from pxr import Sdf from functools import partial from omni.kit.property.usd.custom_layout_helper import CustomLayoutGroup, CustomLayoutProperty def update_range(stage, prim_paths, constrain, attr_name): min_val = max_val = None for path in prim_paths: prim = stage.GetPrimAtPath(path) attr = prim.GetAttribute(constrain["attr"]) if prim else None if prim and attr: if constrain["type"] == "minimum": min_val = attr.Get() else: max_val = attr.Get() break for path in prim_paths: prim = stage.GetPrimAtPath(path) attr = prim.GetAttribute(attr_name) if prim else None if prim and attr: val = attr.Get() if min_val: val = max(min_val, val) elif max_val: val = min(max_val, val) attr.Set(val) break def _build_slider( stage, attr_name, metadata, property_type, prim_paths: List[Sdf.Path], type="float", additional_label_kwargs={}, additional_widget_kwargs={}, ): from omni.kit.window.property.templates import HORIZONTAL_SPACING from omni.kit.property.usd.usd_attribute_model import UsdAttributeModel from omni.kit.property.usd.usd_property_widget import UsdPropertiesWidgetBuilder if not attr_name or not property_type: return with ui.HStack(spacing=HORIZONTAL_SPACING): model_kwargs = UsdPropertiesWidgetBuilder.get_attr_value_range_kwargs(metadata) model = UsdAttributeModel( stage, [path.AppendProperty(attr_name) for path in prim_paths], False, metadata, **model_kwargs, ) UsdPropertiesWidgetBuilder.create_label(attr_name, metadata, additional_label_kwargs) widget_kwargs = {"model": model} widget_kwargs.update(UsdPropertiesWidgetBuilder.get_attr_value_soft_range_kwargs(metadata)) if additional_widget_kwargs: widget_kwargs.update(additional_widget_kwargs) with ui.ZStack(): if type == "float": value_widget = UsdPropertiesWidgetBuilder.create_drag_or_slider( ui.FloatDrag, ui.FloatSlider, **widget_kwargs ) else: value_widget = UsdPropertiesWidgetBuilder.create_drag_or_slider( ui.IntDrag, ui.IntSlider, **widget_kwargs ) mixed_overlay = UsdPropertiesWidgetBuilder.create_mixed_text_overlay() UsdPropertiesWidgetBuilder.create_control_state( value_widget=value_widget, mixed_overlay=mixed_overlay, **widget_kwargs ) if len(additional_widget_kwargs["constrain"]) == 2: callback = partial(update_range, stage, prim_paths, additional_widget_kwargs["constrain"], attr_name) model.add_value_changed_fn(lambda m: callback()) return model def build_slider(min_value, max_value, type="float", constrain={}): if type not in ["int", "float"]: raise ValueError("'type' must be 'int' or 'float'") if len(constrain) not in [0, 2]: raise ValueError("'constrain' must be empty or a {'attr': ___, 'type': ___} dictionary") if constrain[1] not in ["minimum", "maximum"]: raise ValueError("constrain['type'] must be 'minimum' or 'maximum'") def custom_slider(stage, attr_name, metadata, property_type, prim_paths, *args, **kwargs): additional_widget_kwargs = {"min": min_value, "max": max_value, "constrain": constrain} additional_widget_kwargs.update(kwargs) return _build_slider( stage, attr_name, metadata, property_type, prim_paths, additional_widget_kwargs=additional_widget_kwargs, type=type, ) return custom_slider def build_common_raster_overlay_properties(add_overlay_render_method=False): with CustomLayoutGroup("Rendering"): CustomLayoutProperty("cesium:alpha", build_fn=build_slider(0, 1)) if add_overlay_render_method: CustomLayoutProperty("cesium:overlayRenderMethod") CustomLayoutProperty("cesium:maximumScreenSpaceError") CustomLayoutProperty("cesium:maximumTextureSize") CustomLayoutProperty("cesium:maximumSimultaneousTileLoads") CustomLayoutProperty("cesium:subTileCacheBytes") CustomLayoutProperty("cesium:showCreditsOnScreen")
4,541
Python
36.53719
113
0.632019
CesiumGS/cesium-omniverse/exts/cesium.omniverse/cesium/omniverse/ui/attributes/ion_raster_overlay_attributes_widget.py
import logging from omni.kit.property.usd.custom_layout_helper import CustomLayoutFrame, CustomLayoutGroup, CustomLayoutProperty from omni.kit.property.usd.usd_property_widget import SchemaPropertiesWidget from cesium.usd.plugins.CesiumUsdSchemas import ( IonRasterOverlay as CesiumIonRasterOverlay, IonServer as CesiumIonServer, ) from .cesium_properties_widget_builder import build_common_raster_overlay_properties class CesiumIonRasterOverlayAttributesWidget(SchemaPropertiesWidget): def __init__(self): super().__init__("Cesium Ion Raster Overlay Settings", CesiumIonRasterOverlay, include_inherited=True) self._logger = logging.getLogger(__name__) def clean(self): super().clean() def _customize_props_layout(self, props): frame = CustomLayoutFrame(hide_extra=True) with frame: with CustomLayoutGroup("Source"): CustomLayoutProperty("cesium:ionAssetId") CustomLayoutProperty("cesium:ionAccessToken") CustomLayoutProperty("cesium:ionServerBinding") build_common_raster_overlay_properties(add_overlay_render_method=True) return frame.apply(props) def _filter_props_to_build(self, props): filtered_props = super()._filter_props_to_build(props) filtered_props.extend(prop for prop in props if prop.GetName() == "cesium:ionServerBinding") return filtered_props def get_additional_kwargs(self, ui_attr): if ui_attr.prop_name == "cesium:ionServerBinding": return None, {"target_picker_filter_type_list": [CesiumIonServer], "targets_limit": 1} return None, {"targets_limit": 0}
1,685
Python
39.142856
113
0.706825
CesiumGS/cesium-omniverse/exts/cesium.omniverse/cesium/omniverse/ui/attributes/__init__.py
from .data_attributes_widget import CesiumDataSchemaAttributesWidget # noqa: F401 from .georeference_attributes_widget import CesiumGeoreferenceSchemaAttributesWidget # noqa :F401 from .tileset_attributes_widget import CesiumTilesetAttributesWidget # noqa: F401 from .globe_anchor_attributes_widget import CesiumGlobeAnchorAttributesWidget # noqa: F401 from .ion_server_attributes_widget import CesiumIonServerAttributesWidget # noqa: F401 from .ion_raster_overlay_attributes_widget import CesiumIonRasterOverlayAttributesWidget # noqa: F401 from .polygon_raster_overlay_attributes_widget import CesiumPolygonRasterOverlayAttributesWidget # noqa: F401 from .tile_map_service_raster_overlay_attributes_widget import ( # noqa: F401 CesiumTileMapServiceRasterOverlayAttributesWidget, ) from .web_map_service_raster_overlay_attributes_widget import ( # noqa: F401 CesiumWebMapServiceRasterOverlayAttributesWidget, ) from .web_map_tile_service_raster_overlay_attributes_widget import ( # noqa: F401 CesiumWebMapTileServiceRasterOverlayAttributesWidget, )
1,072
Python
62.117643
110
0.835821
CesiumGS/cesium-omniverse/exts/cesium.omniverse/cesium/omniverse/ui/attributes/ion_server_attributes_widget.py
import logging from omni.kit.property.usd.custom_layout_helper import CustomLayoutFrame, CustomLayoutGroup, CustomLayoutProperty from omni.kit.property.usd.usd_property_widget import SchemaPropertiesWidget from ...bindings import ICesiumOmniverseInterface from cesium.usd.plugins.CesiumUsdSchemas import IonServer as CesiumIonServer class CesiumIonServerAttributesWidget(SchemaPropertiesWidget): def __init__(self, _cesium_omniverse_interface: ICesiumOmniverseInterface): super().__init__("Cesium ion Server Settings", CesiumIonServer, include_inherited=False) self._logger = logging.getLogger(__name__) self._cesium_omniverse_interface = _cesium_omniverse_interface def clean(self): super().clean() def _customize_props_layout(self, props): frame = CustomLayoutFrame(hide_extra=True) with frame: with CustomLayoutGroup("ion Server"): CustomLayoutProperty("cesium:displayName") CustomLayoutProperty("cesium:ionServerUrl") CustomLayoutProperty("cesium:ionServerApiUrl") CustomLayoutProperty("cesium:ionServerApplicationId") with CustomLayoutGroup("Project Default Token"): CustomLayoutProperty("cesium:projectDefaultIonAccessToken") CustomLayoutProperty("cesium:projectDefaultIonAccessTokenId") return frame.apply(props)
1,416
Python
41.939393
113
0.721751
CesiumGS/cesium-omniverse/exts/cesium.omniverse/cesium/omniverse/ui/attributes/globe_anchor_attributes_widget.py
import logging from omni.kit.property.usd.custom_layout_helper import CustomLayoutFrame, CustomLayoutGroup, CustomLayoutProperty from omni.kit.property.usd.usd_property_widget import SchemaPropertiesWidget from ...bindings import ICesiumOmniverseInterface from cesium.usd.plugins.CesiumUsdSchemas import ( GlobeAnchorAPI as CesiumGlobeAnchorAPI, Georeference as CesiumGeoreference, ) class CesiumGlobeAnchorAttributesWidget(SchemaPropertiesWidget): def __init__(self, _cesium_omniverse_interface: ICesiumOmniverseInterface): super().__init__("Cesium Globe Anchor", CesiumGlobeAnchorAPI, include_inherited=False) self._logger = logging.getLogger(__name__) self._cesium_omniverse_interface = _cesium_omniverse_interface def clean(self): super().clean() def _customize_props_layout(self, props): frame = CustomLayoutFrame(hide_extra=True) with frame: with CustomLayoutGroup("Options"): CustomLayoutProperty("cesium:anchor:adjustOrientationForGlobeWhenMoving") CustomLayoutProperty("cesium:anchor:detectTransformChanges") CustomLayoutProperty("cesium:anchor:georeferenceBinding") with CustomLayoutGroup("Global Positioning"): CustomLayoutProperty("cesium:anchor:latitude") CustomLayoutProperty("cesium:anchor:longitude") CustomLayoutProperty("cesium:anchor:height") with CustomLayoutGroup("Advanced Positioning", collapsed=True): CustomLayoutProperty("cesium:anchor:position") return frame.apply(props) def _filter_props_to_build(self, props): filtered_props = super()._filter_props_to_build(props) filtered_props.extend(prop for prop in props if prop.GetName() == "cesium:anchor:georeferenceBinding") return filtered_props def get_additional_kwargs(self, ui_attr): if ui_attr.prop_name == "cesium:anchor:georeferenceBinding": return None, {"target_picker_filter_type_list": [CesiumGeoreference], "targets_limit": 1} return None, {"targets_limit": 0}
2,142
Python
42.734693
113
0.705415
CesiumGS/cesium-omniverse/exts/cesium.omniverse/cesium/omniverse/ui/attributes/data_attributes_widget.py
import logging from omni.kit.property.usd.custom_layout_helper import CustomLayoutFrame, CustomLayoutGroup, CustomLayoutProperty from omni.kit.property.usd.usd_property_widget import SchemaPropertiesWidget from cesium.usd.plugins.CesiumUsdSchemas import Data as CesiumData class CesiumDataSchemaAttributesWidget(SchemaPropertiesWidget): def __init__(self): super().__init__("Cesium Settings", CesiumData, include_inherited=False) self._logger = logging.getLogger(__name__) def clean(self): super().clean() def _customize_props_layout(self, props): frame = CustomLayoutFrame(hide_extra=True) with frame: with CustomLayoutGroup("Debug Options", collapsed=True): CustomLayoutProperty("cesium:debug:disableMaterials") CustomLayoutProperty("cesium:debug:disableTextures") CustomLayoutProperty("cesium:debug:disableGeometryPool") CustomLayoutProperty("cesium:debug:disableMaterialPool") CustomLayoutProperty("cesium:debug:disableTexturePool") CustomLayoutProperty("cesium:debug:geometryPoolInitialCapacity") CustomLayoutProperty("cesium:debug:materialPoolInitialCapacity") CustomLayoutProperty("cesium:debug:texturePoolInitialCapacity") CustomLayoutProperty("cesium:debug:randomColors") CustomLayoutProperty("cesium:debug:disableGeoreferencing") return frame.apply(props)
1,505
Python
44.636362
113
0.70897
CesiumGS/cesium-omniverse/exts/cesium.omniverse/cesium/omniverse/ui/attributes/georeference_attributes_widget.py
import logging from omni.kit.property.usd.custom_layout_helper import CustomLayoutFrame, CustomLayoutGroup, CustomLayoutProperty from omni.kit.property.usd.usd_property_widget import SchemaPropertiesWidget from cesium.usd.plugins.CesiumUsdSchemas import Georeference as CesiumGeoreference class CesiumGeoreferenceSchemaAttributesWidget(SchemaPropertiesWidget): def __init__(self): super().__init__("Cesium Georeference", CesiumGeoreference, include_inherited=False) self._logger = logging.getLogger(__name__) def clean(self): super().clean() def _customize_props_layout(self, props): frame = CustomLayoutFrame(hide_extra=True) with frame: with CustomLayoutGroup("Georeference Origin Point Coordinates"): CustomLayoutProperty("cesium:georeferenceOrigin:latitude", "Latitude") CustomLayoutProperty("cesium:georeferenceOrigin:longitude", "Longitude") CustomLayoutProperty("cesium:georeferenceOrigin:height", "Height") return frame.apply(props)
1,068
Python
40.115383
113
0.730337
CesiumGS/cesium-omniverse/exts/cesium.omniverse/cesium/omniverse/ui/attributes/tile_map_service_raster_overlay_attributes_widget.py
import logging import omni.usd import omni.ui import omni.kit.window.property from omni.kit.property.usd.custom_layout_helper import CustomLayoutFrame, CustomLayoutGroup, CustomLayoutProperty from omni.kit.property.usd.usd_property_widget import SchemaPropertiesWidget from cesium.usd.plugins.CesiumUsdSchemas import ( TileMapServiceRasterOverlay as CesiumTileMapServiceRasterOverlay, ) from .cesium_properties_widget_builder import build_slider, build_common_raster_overlay_properties from pxr import Usd, Tf class CesiumTileMapServiceRasterOverlayAttributesWidget(SchemaPropertiesWidget): def __init__(self): super().__init__( "Cesium Tile Map Service Raster Overlay Settings", CesiumTileMapServiceRasterOverlay, include_inherited=True, ) self._logger = logging.getLogger(__name__) self._listener = None self._props = None self._stage = omni.usd.get_context().get_stage() def clean(self): super().clean() def _on_usd_changed(self, notice, stage): window = omni.kit.window.property.get_window() window.request_rebuild() def _customize_props_layout(self, props): if not self._listener: self._listener = Tf.Notice.Register(Usd.Notice.ObjectsChanged, self._on_usd_changed, self._stage) frame = CustomLayoutFrame(hide_extra=True) prim_path = self._payload.get_paths()[0] tileMapServiceRasterOverlay = CesiumTileMapServiceRasterOverlay.Get(self._stage, prim_path) specify_zoom_levels = tileMapServiceRasterOverlay.GetSpecifyZoomLevelsAttr().Get() with frame: with CustomLayoutGroup("URL"): CustomLayoutProperty("cesium:url") with CustomLayoutGroup("Zoom Settings"): CustomLayoutProperty( "cesium:specifyZoomLevels", ) if specify_zoom_levels: CustomLayoutProperty( "cesium:minimumZoomLevel", build_fn=build_slider( 0, 30, type="int", constrain={"attr": "cesium:maximumZoomLevel", "type": "maximum"} ), ) CustomLayoutProperty( "cesium:maximumZoomLevel", build_fn=build_slider( 0, 30, type="int", constrain={"attr": "cesium:minimumZoomLevel", "type": "minimum"} ), ) build_common_raster_overlay_properties() return frame.apply(props) def reset(self): if self._listener: self._listener.Revoke() self._listener = None super().reset()
2,777
Python
36.54054
113
0.60569
CesiumGS/cesium-omniverse/exts/cesium.omniverse/cesium/omniverse/ui/attributes/tileset_attributes_widget.py
import logging from omni.kit.property.usd.custom_layout_helper import CustomLayoutFrame, CustomLayoutGroup, CustomLayoutProperty from omni.kit.property.usd.usd_property_widget import SchemaPropertiesWidget import omni.ui as ui from ...bindings import ICesiumOmniverseInterface from cesium.usd.plugins.CesiumUsdSchemas import ( Tileset as CesiumTileset, IonServer as CesiumIonServer, Georeference as CesiumGeoreference, RasterOverlay as CesiumRasterOverlay, ) class CesiumTilesetAttributesWidget(SchemaPropertiesWidget): def __init__(self, _cesium_omniverse_interface: ICesiumOmniverseInterface): super().__init__("Cesium Tileset Settings", CesiumTileset, include_inherited=False) self._logger = logging.getLogger(__name__) self._cesium_omniverse_interface = _cesium_omniverse_interface def clean(self): super().clean() def on_refresh_button_clicked(self): tileset_path = self._payload[0] self._cesium_omniverse_interface.reload_tileset(tileset_path.pathString) def _customize_props_layout(self, props): frame = CustomLayoutFrame(hide_extra=True) with frame: ui.Button("Refresh Tileset", clicked_fn=self.on_refresh_button_clicked) with CustomLayoutGroup("Credit Display"): CustomLayoutProperty("cesium:showCreditsOnScreen") with CustomLayoutGroup("Source"): CustomLayoutProperty("cesium:sourceType") CustomLayoutProperty("cesium:ionAssetId") CustomLayoutProperty("cesium:ionAccessToken") CustomLayoutProperty("cesium:ionServerBinding") CustomLayoutProperty("cesium:url") with CustomLayoutGroup("Raster Overlays"): CustomLayoutProperty("cesium:rasterOverlayBinding") with CustomLayoutGroup("Level of Detail"): CustomLayoutProperty("cesium:maximumScreenSpaceError") with CustomLayoutGroup("Tile Loading"): CustomLayoutProperty("cesium:preloadAncestors") CustomLayoutProperty("cesium:preloadSiblings") CustomLayoutProperty("cesium:forbidHoles") CustomLayoutProperty("cesium:maximumSimultaneousTileLoads") CustomLayoutProperty("cesium:maximumCachedBytes") CustomLayoutProperty("cesium:loadingDescendantLimit") CustomLayoutProperty("cesium:mainThreadLoadingTimeLimit") with CustomLayoutGroup("Tile Culling"): CustomLayoutProperty("cesium:enableFrustumCulling") CustomLayoutProperty("cesium:enableFogCulling") CustomLayoutProperty("cesium:enforceCulledScreenSpaceError") CustomLayoutProperty("cesium:culledScreenSpaceError") with CustomLayoutGroup("Rendering"): CustomLayoutProperty("cesium:suspendUpdate") CustomLayoutProperty("cesium:smoothNormals") with CustomLayoutGroup("Georeference"): CustomLayoutProperty("cesium:georeferenceBinding") return frame.apply(props) def _filter_props_to_build(self, props): filtered_props = super()._filter_props_to_build(props) filtered_props.extend( prop for prop in props if prop.GetName() == "cesium:ionServerBinding" or prop.GetName() == "cesium:georeferenceBinding" or prop.GetName() == "cesium:rasterOverlayBinding" ) return filtered_props def get_additional_kwargs(self, ui_attr): if ui_attr.prop_name == "cesium:ionServerBinding": return None, {"target_picker_filter_type_list": [CesiumIonServer], "targets_limit": 1} elif ui_attr.prop_name == "cesium:georeferenceBinding": return None, {"target_picker_filter_type_list": [CesiumGeoreference], "targets_limit": 1} elif ui_attr.prop_name == "cesium:rasterOverlayBinding": return None, {"target_picker_filter_type_list": [CesiumRasterOverlay]} return None, {"targets_limit": 0}
4,108
Python
46.229885
113
0.672833
CesiumGS/cesium-omniverse/exts/cesium.omniverse/cesium/omniverse/ui/attributes/polygon_raster_overlay_attributes_widget.py
import logging from omni.kit.property.usd.custom_layout_helper import CustomLayoutFrame, CustomLayoutGroup, CustomLayoutProperty from omni.kit.property.usd.usd_property_widget import SchemaPropertiesWidget from cesium.usd.plugins.CesiumUsdSchemas import ( PolygonRasterOverlay as CesiumPolygonRasterOverlay, ) from pxr import UsdGeom from .cesium_properties_widget_builder import build_common_raster_overlay_properties class CesiumPolygonRasterOverlayAttributesWidget(SchemaPropertiesWidget): def __init__(self): super().__init__("Cesium Polygon Raster Overlay Settings", CesiumPolygonRasterOverlay, include_inherited=True) self._logger = logging.getLogger(__name__) def clean(self): super().clean() def _customize_props_layout(self, props): frame = CustomLayoutFrame(hide_extra=True) with frame: with CustomLayoutGroup("Cartographic Polygons"): CustomLayoutProperty("cesium:cartographicPolygonBinding") with CustomLayoutGroup("Invert Selection"): CustomLayoutProperty("cesium:invertSelection") build_common_raster_overlay_properties() return frame.apply(props) def _filter_props_to_build(self, props): filtered_props = super()._filter_props_to_build(props) filtered_props.extend(prop for prop in props if prop.GetName() == "cesium:cartographicPolygonBinding") return filtered_props def get_additional_kwargs(self, ui_attr): if ui_attr.prop_name == "cesium:cartographicPolygonBinding": return None, {"target_picker_filter_type_list": [UsdGeom.BasisCurves]} return None, {"targets_limit": 0}
1,693
Python
39.333332
118
0.71707
CesiumGS/cesium-omniverse/exts/cesium.omniverse/cesium/omniverse/ui/models/__init__.py
from .date_model import DateModel # noqa: F401 from .asset_window_models import IonAssets, IonAssetItem, IonAssetDelegate # noqa: F401 from .space_delimited_number_model import SpaceDelimitedNumberModel # noqa: F401 from .human_readable_bytes_model import HumanReadableBytesModel # noqa: F401
297
Python
58.599988
88
0.808081
CesiumGS/cesium-omniverse/exts/cesium.omniverse/cesium/omniverse/ui/models/asset_window_models.py
from typing import List import omni.ui as ui from .date_model import DateModel class IonAssetItem(ui.AbstractItem): """Represents an ion Asset.""" def __init__( self, asset_id: int, name: str, description: str, attribution: str, asset_type: str, date_added: str ): super().__init__() self.id = ui.SimpleIntModel(asset_id) self.name = ui.SimpleStringModel(name) self.description = ui.SimpleStringModel(description) self.attribution = ui.SimpleStringModel(attribution) self.type = ui.SimpleStringModel(asset_type) self.dateAdded = DateModel(date_added) def __repr__(self): return f"{self.name.as_string} (ID: {self.id.as_int})" class IonAssets(ui.AbstractItemModel): """Represents a list of ion assets for the asset window.""" def __init__(self, items=None, filter_value=""): super().__init__() if items is None: items = [] self._items: List[IonAssetItem] = items self._visible_items: List[IonAssetItem] = [] self._current_filter = filter_value self.filter_items(filter_value) def replace_items(self, items: List[IonAssetItem]): self._items.clear() self._items.extend(items) self.filter_items(self._current_filter) def filter_items(self, filter_value: str): self._current_filter = filter_value if filter_value == "": self._visible_items = self._items.copy() else: self._visible_items = [ item for item in self._items if filter_value.lower() in item.name.as_string.lower() ] self._item_changed(None) def get_item_children(self, item: IonAssetItem = None) -> List[IonAssetItem]: if item is not None: return [] return self._visible_items def get_item_value_model_count(self, item: IonAssetItem = None) -> int: """The number of columns""" return 3 def get_item_value_model(self, item: IonAssetItem = None, column_id: int = 0) -> ui.AbstractValueModel: """Returns the value model for the specific column.""" if item is None: item = self._visible_items[0] # When we are finally on Python 3.10 with Omniverse, we should change this to a switch. return item.name if column_id == 0 else item.type if column_id == 1 else item.dateAdded class IonAssetDelegate(ui.AbstractItemDelegate): def build_header(self, column_id: int = 0) -> None: with ui.ZStack(height=20): if column_id == 0: ui.Label("Name") elif column_id == 1: ui.Label("Type") else: ui.Label("Date Added") def build_branch( self, model: ui.AbstractItemModel, item: ui.AbstractItem = None, column_id: int = 0, level: int = 0, expanded: bool = False, ) -> None: # We don't use this because we don't have a hierarchy, but we need to at least stub it out. pass def build_widget( self, model: IonAssets, item: IonAssetItem = None, column_id: int = 0, level: int = 0, expanded: bool = False ) -> None: with ui.ZStack(height=20): value_model = model.get_item_value_model(item, column_id) ui.Label(value_model.as_string)
3,372
Python
32.396039
117
0.596085
CesiumGS/cesium-omniverse/exts/cesium.omniverse/cesium/omniverse/ui/models/human_readable_bytes_model.py
import omni.ui as ui class HumanReadableBytesModel(ui.AbstractValueModel): """Takes an integer containing bytes and outputs a human-readable string.""" def __init__(self, value: int): super().__init__() self._value = value def __str__(self): return self.get_value_as_string() def set_value(self, value: int): self._value = value self._value_changed() def get_value_as_bool(self) -> bool: raise NotImplementedError def get_value_as_int(self) -> int: return self._value def get_value_as_float(self) -> float: return float(self._value) def get_value_as_string(self) -> str: value = self._value for unit in ["B", "KiB", "MiB", "GiB", "TiB", "PiB", "EiB", "ZiB"]: if abs(value) < 1024: return f"{value:3.2f} {unit}" value /= 1024 return f"{value:.2f}YiB"
919
Python
26.058823
80
0.563656
CesiumGS/cesium-omniverse/exts/cesium.omniverse/cesium/omniverse/ui/models/date_model.py
from datetime import datetime import omni.ui as ui class DateModel(ui.AbstractValueModel): """Takes an RFC 3339 formatted timestamp and produces a date value.""" def __init__(self, value: str): super().__init__() self._value = datetime.strptime(value[0:19], "%Y-%m-%dT%H:%M:%S") def get_value_as_string(self) -> str: return self._value.strftime("%Y-%m-%d")
397
Python
27.428569
74
0.627204
CesiumGS/cesium-omniverse/exts/cesium.omniverse/cesium/omniverse/ui/models/space_delimited_number_model.py
import math import omni.ui as ui class SpaceDelimitedNumberModel(ui.AbstractValueModel): """Divides large numbers into delimited groups for readability.""" def __init__(self, value: float): super().__init__() self._value = value def __str__(self): return self.get_value_as_string() def set_value(self, value: float) -> None: self._value = value self._value_changed() def get_value_as_bool(self) -> bool: raise NotImplementedError def get_value_as_int(self) -> int: return math.trunc(self._value) def get_value_as_float(self) -> float: return self._value def get_value_as_string(self) -> str: # Replacing the comma with spaces because NIST did a lot of research and recommends it. # https://physics.nist.gov/cuu/pdf/sp811.pdf#10.5.3 return f"{self._value:,}".replace(",", " ")
907
Python
27.374999
95
0.618523
CesiumGS/cesium-omniverse/exts/cesium.omniverse/cesium/omniverse/ui/models/tests/date_model_test.py
import omni.kit.test from cesium.omniverse.ui.models.date_model import DateModel class Test(omni.kit.test.AsyncTestCase): async def setUp(self): pass async def tearDown(self): pass async def test_date_model(self): input_value = "2016-10-17T22:04:30.353Z" expected_output = "2016-10-17" date_model = DateModel(input_value) self.assertEqual(date_model.as_string, expected_output)
443
Python
23.666665
63
0.668172
CesiumGS/cesium-omniverse/exts/cesium.omniverse/cesium/omniverse/ui/models/tests/__init__.py
from .date_model_test import * # noqa: F401 F403
50
Python
24.499988
49
0.7
CesiumGS/cesium-omniverse/exts/cesium.omniverse/cesium/omniverse/ui/tests/pass_fail_widget_test.py
import omni.ui as ui from omni.ui.tests.test_base import OmniUiTest from cesium.omniverse.tests.utils import get_golden_img_dir, wait_for_update from cesium.omniverse.ui.pass_fail_widget import CesiumPassFailWidget class PassFailWidgetTest(OmniUiTest): async def setUp(self): await super().setUp() self._golden_image_dir = get_golden_img_dir() async def tearDown(self): await super().tearDown() async def test_pass_fail_widget_passed(self): window = await self.create_test_window() with window.frame: with ui.VStack(height=0): widget = CesiumPassFailWidget(True) self.assertIsNotNone(widget) self.assertTrue(widget.passed) await wait_for_update() await self.finalize_test( golden_img_dir=self._golden_image_dir, golden_img_name="test_pass_fail_widget_passed.png" ) widget.destroy() async def test_pass_fail_widget_failed(self): window = await self.create_test_window() with window.frame: with ui.VStack(height=0): widget = CesiumPassFailWidget(False) self.assertIsNotNone(widget) self.assertFalse(widget.passed) await wait_for_update() await self.finalize_test( golden_img_dir=self._golden_image_dir, golden_img_name="test_pass_fail_widget_failed.png" ) widget.destroy() async def test_pass_fail_widget_updated(self): window = await self.create_test_window() with window.frame: with ui.VStack(height=0): widget = CesiumPassFailWidget(False) self.assertIsNotNone(widget) self.assertFalse(widget.passed) await wait_for_update() widget.passed = True await wait_for_update() self.assertTrue(widget.passed) await self.finalize_test( golden_img_dir=self._golden_image_dir, golden_img_name="test_pass_fail_widget_changed.png" ) widget.destroy()
2,090
Python
27.256756
102
0.61866
CesiumGS/cesium-omniverse/exts/cesium.omniverse/cesium/omniverse/ui/tests/__init__.py
from .pass_fail_widget_test import PassFailWidgetTest # noqa: F401
68
Python
33.499983
67
0.794118
CesiumGS/cesium-omniverse/exts/cesium.omniverse/cesium/omniverse/bindings/__init__.py
from .CesiumOmniversePythonBindings import * # noqa: F401 F403
64
Python
31.499984
63
0.796875
CesiumGS/cesium-omniverse/exts/cesium.omniverse/cesium/omniverse/bindings/CesiumOmniversePythonBindings.pyi
from typing import Any, List, Tuple from typing import overload class Asset: def __init__(self, *args, **kwargs) -> None: ... @property def asset_id(self) -> int: ... @property def asset_type(self) -> str: ... @property def attribution(self) -> str: ... @property def bytes(self) -> int: ... @property def date_added(self) -> str: ... @property def description(self) -> str: ... @property def name(self) -> str: ... @property def percent_complete(self) -> int: ... @property def status(self) -> str: ... class AssetTroubleshootingDetails: def __init__(self, *args, **kwargs) -> None: ... @property def asset_exists_in_user_account(self) -> bool: ... @property def asset_id(self) -> int: ... class Assets: def __init__(self, *args, **kwargs) -> None: ... @property def items(self) -> Any: ... @property def link(self) -> str: ... class CesiumIonSession: def __init__(self, *args, **kwargs) -> None: ... def disconnect(self) -> None: ... def get_assets(self, *args, **kwargs) -> Any: ... def get_authorize_url(self) -> str: ... def get_connection(self, *args, **kwargs) -> Any: ... def get_profile(self, *args, **kwargs) -> Any: ... def get_tokens(self, *args, **kwargs) -> Any: ... def is_asset_list_loaded(self) -> bool: ... def is_connected(self) -> bool: ... def is_connecting(self) -> bool: ... def is_loading_asset_list(self) -> bool: ... def is_loading_profile(self) -> bool: ... def is_loading_token_list(self) -> bool: ... def is_profile_loaded(self) -> bool: ... def is_resuming(self) -> bool: ... def is_token_list_loaded(self) -> bool: ... def refresh_assets(self) -> None: ... def refresh_profile(self) -> None: ... def refresh_tokens(self) -> None: ... class Connection: def __init__(self, *args, **kwargs) -> None: ... def get_access_token(self) -> str: ... def get_api_uri(self) -> str: ... class ICesiumOmniverseInterface: def __init__(self, *args, **kwargs) -> None: ... def clear_accessor_cache(self) -> None: ... def connect_to_ion(self) -> None: ... def create_token(self, arg0: str) -> None: ... def credits_available(self) -> bool: ... def credits_start_next_frame(self) -> None: ... def get_asset_token_troubleshooting_details(self, *args, **kwargs) -> Any: ... def get_asset_troubleshooting_details(self, *args, **kwargs) -> Any: ... def get_credits(self) -> List[Tuple[str, bool]]: ... def get_default_token_troubleshooting_details(self, *args, **kwargs) -> Any: ... def get_render_statistics(self, *args, **kwargs) -> Any: ... def get_server_path(self) -> str: ... def get_server_paths(self) -> List[str]: ... def get_session(self, *args, **kwargs) -> Any: ... def get_sessions(self, *args, **kwargs) -> Any: ... def get_set_default_token_result(self, *args, **kwargs) -> Any: ... def is_default_token_set(self) -> bool: ... def is_tracing_enabled(self) -> bool: ... def on_shutdown(self) -> None: ... def on_stage_change(self, arg0: int) -> None: ... def on_startup(self, arg0: str) -> None: ... def on_update_frame(self, arg0: List[ViewportPythonBinding], arg1: bool) -> None: ... def print_fabric_stage(self) -> str: ... def reload_tileset(self, arg0: str) -> None: ... def select_token(self, arg0: str, arg1: str) -> None: ... def specify_token(self, arg0: str) -> None: ... @overload def update_troubleshooting_details(self, arg0: str, arg1: int, arg2: int, arg3: int) -> None: ... @overload def update_troubleshooting_details(self, arg0: str, arg1: int, arg2: int, arg3: int, arg4: int) -> None: ... class Profile: def __init__(self, *args, **kwargs) -> None: ... @property def id(self) -> int: ... @property def username(self) -> str: ... class RenderStatistics: def __init__(self, *args, **kwargs) -> None: ... @property def culled_tiles_visited(self) -> int: ... @property def geometries_capacity(self) -> int: ... @property def geometries_loaded(self) -> int: ... @property def geometries_rendered(self) -> int: ... @property def materials_capacity(self) -> int: ... @property def materials_loaded(self) -> int: ... @property def max_depth_visited(self) -> int: ... @property def tiles_culled(self) -> int: ... @property def tiles_loaded(self) -> int: ... @property def tiles_loading_main(self) -> int: ... @property def tiles_loading_worker(self) -> int: ... @property def tiles_rendered(self) -> int: ... @property def tiles_visited(self) -> int: ... @property def tileset_cached_bytes(self) -> int: ... @property def triangles_loaded(self) -> int: ... @property def triangles_rendered(self) -> int: ... class SetDefaultTokenResult: def __init__(self, *args, **kwargs) -> None: ... @property def code(self) -> int: ... @property def message(self) -> str: ... class Token: def __init__(self, *args, **kwargs) -> None: ... @property def id(self) -> str: ... @property def is_default(self) -> bool: ... @property def name(self) -> str: ... @property def token(self) -> str: ... class TokenTroubleshootingDetails: def __init__(self, *args, **kwargs) -> None: ... @property def allows_access_to_asset(self) -> bool: ... @property def associated_with_user_account(self) -> bool: ... @property def is_valid(self) -> bool: ... @property def show_details(self) -> bool: ... @property def token(self) -> Token: ... class Viewport: height: float projMatrix: Matrix4d viewMatrix: Matrix4d width: float def __init__(self) -> None: ... def acquire_cesium_omniverse_interface( plugin_name: str = ..., library_path: str = ... ) -> ICesiumOmniverseInterface: ... def release_cesium_omniverse_interface(arg0: ICesiumOmniverseInterface) -> None: ...
6,082
unknown
32.423077
112
0.582539
CesiumGS/cesium-omniverse/exts/cesium.omniverse/cesium/omniverse/models/raster_overlay_to_add.py
from __future__ import annotations from typing import Optional import carb.events class RasterOverlayToAdd: def __init__(self, tileset_path: str, raster_overlay_ion_asset_id: int, raster_overlay_name: str): self.tileset_path = tileset_path self.raster_overlay_ion_asset_id = raster_overlay_ion_asset_id self.raster_overlay_name = raster_overlay_name def to_dict(self) -> dict: return { "tileset_path": self.tileset_path, "raster_overlay_ion_asset_id": self.raster_overlay_ion_asset_id, "raster_overlay_name": self.raster_overlay_name, } @staticmethod def from_event(event: carb.events.IEvent) -> Optional[RasterOverlayToAdd]: if event.payload is None or len(event.payload) == 0: return None return RasterOverlayToAdd( event.payload["tileset_path"], event.payload["raster_overlay_ion_asset_id"], event.payload["raster_overlay_name"], )
1,004
Python
33.655171
102
0.639442
CesiumGS/cesium-omniverse/exts/cesium.omniverse/cesium/omniverse/models/__init__.py
from .asset_to_add import AssetToAdd # noqa: F401 from .raster_overlay_to_add import RasterOverlayToAdd # noqa: F401
119
Python
38.999987
67
0.773109
CesiumGS/cesium-omniverse/exts/cesium.omniverse/cesium/omniverse/models/asset_to_add.py
from __future__ import annotations from typing import Optional import carb.events class AssetToAdd: def __init__( self, tileset_name: str, tileset_ion_asset_id: int, raster_overlay_name: Optional[str] = None, raster_overlay_ion_asset_id: Optional[int] = None, ): self.tileset_name = tileset_name self.tileset_ion_asset_id = tileset_ion_asset_id self.raster_overlay_name = raster_overlay_name self.raster_overlay_ion_asset_id = raster_overlay_ion_asset_id def to_dict(self) -> dict: return { "tileset_name": self.tileset_name, "tileset_ion_asset_id": self.tileset_ion_asset_id, "raster_overlay_name": self.raster_overlay_name, "raster_overlay_ion_asset_id": self.raster_overlay_ion_asset_id, } @staticmethod def from_event(event: carb.events.IEvent) -> Optional[AssetToAdd]: if event.payload is None or len(event.payload) == 0: return None return AssetToAdd( event.payload["tileset_name"], event.payload["tileset_ion_asset_id"], event.payload["raster_overlay_name"], event.payload["raster_overlay_ion_asset_id"], )
1,259
Python
32.157894
76
0.609214
CesiumGS/cesium-omniverse/exts/cesium.omniverse/cesium/omniverse/models/tests/raster_overlay_to_add_test.py
import carb.events import omni.kit.test from unittest.mock import MagicMock from cesium.omniverse.models.raster_overlay_to_add import RasterOverlayToAdd TILESET_PATH = "/fake/tileset/path" RASTER_OVERLAY_NAME = "fake_raster_overlay_name" RASTER_OVERLAY_ION_ASSET_ID = 2 PAYLOAD_DICT = { "tileset_path": TILESET_PATH, "raster_overlay_name": RASTER_OVERLAY_NAME, "raster_overlay_ion_asset_id": RASTER_OVERLAY_ION_ASSET_ID, } class RasterOverlayToAddTest(omni.kit.test.AsyncTestCase): async def setUp(self): pass async def tearDown(self): pass async def test_convert_raster_overlay_to_add_to_dict(self): raster_overlay_to_add = RasterOverlayToAdd( tileset_path=TILESET_PATH, raster_overlay_ion_asset_id=RASTER_OVERLAY_ION_ASSET_ID, raster_overlay_name=RASTER_OVERLAY_NAME, ) result = raster_overlay_to_add.to_dict() self.assertEqual(result["tileset_path"], TILESET_PATH) self.assertEqual(result["raster_overlay_name"], RASTER_OVERLAY_NAME) self.assertEqual(result["raster_overlay_ion_asset_id"], RASTER_OVERLAY_ION_ASSET_ID) async def test_create_raster_overlay_to_add_from_event(self): mock_event = MagicMock(spec=carb.events.IEvent) mock_event.payload = PAYLOAD_DICT raster_overlay_to_add = RasterOverlayToAdd.from_event(mock_event) self.assertIsNotNone(raster_overlay_to_add) self.assertEqual(raster_overlay_to_add.tileset_path, TILESET_PATH) self.assertEqual(raster_overlay_to_add.raster_overlay_name, RASTER_OVERLAY_NAME) self.assertEqual(raster_overlay_to_add.raster_overlay_ion_asset_id, RASTER_OVERLAY_ION_ASSET_ID) async def test_create_raster_overlay_to_add_from_empty_event(self): mock_event = MagicMock(spec=carb.events.IEvent) mock_event.payload = None raster_overlay_to_add = RasterOverlayToAdd.from_event(mock_event) self.assertIsNone(raster_overlay_to_add)
1,998
Python
39.795918
104
0.707708
CesiumGS/cesium-omniverse/exts/cesium.omniverse/cesium/omniverse/models/tests/__init__.py
from .asset_to_add_test import AssetToAddTest # noqa: F401 from .raster_overlay_to_add_test import RasterOverlayToAddTest # noqa: F401
137
Python
44.999985
76
0.788321
CesiumGS/cesium-omniverse/exts/cesium.omniverse/cesium/omniverse/models/tests/asset_to_add_test.py
import carb.events import omni.kit.test from unittest.mock import MagicMock from cesium.omniverse.models.asset_to_add import AssetToAdd TILESET_NAME = "fake_tileset_name" TILESET_ION_ASSET_ID = 1 RASTER_OVERLAY_NAME = "fake_raster_overlay_name" RASTER_OVERLAY_ION_ASSET_ID = 2 PAYLOAD_DICT = { "tileset_name": TILESET_NAME, "tileset_ion_asset_id": TILESET_ION_ASSET_ID, "raster_overlay_name": RASTER_OVERLAY_NAME, "raster_overlay_ion_asset_id": RASTER_OVERLAY_ION_ASSET_ID, } class AssetToAddTest(omni.kit.test.AsyncTestCase): async def setUp(self): pass async def tearDown(self): pass async def test_convert_asset_to_add_to_dict(self): asset_to_add = AssetToAdd( tileset_name=TILESET_NAME, tileset_ion_asset_id=TILESET_ION_ASSET_ID, raster_overlay_name=RASTER_OVERLAY_NAME, raster_overlay_ion_asset_id=RASTER_OVERLAY_ION_ASSET_ID, ) result = asset_to_add.to_dict() self.assertEqual(result["tileset_name"], TILESET_NAME) self.assertEqual(result["tileset_ion_asset_id"], TILESET_ION_ASSET_ID) self.assertEqual(result["raster_overlay_name"], RASTER_OVERLAY_NAME) self.assertEqual(result["raster_overlay_ion_asset_id"], RASTER_OVERLAY_ION_ASSET_ID) async def test_create_asset_to_add_from_event(self): mock_event = MagicMock(spec=carb.events.IEvent) mock_event.payload = PAYLOAD_DICT asset_to_add = AssetToAdd.from_event(mock_event) self.assertIsNotNone(asset_to_add) self.assertEqual(asset_to_add.tileset_name, TILESET_NAME) self.assertEqual(asset_to_add.tileset_ion_asset_id, TILESET_ION_ASSET_ID) self.assertEqual(asset_to_add.raster_overlay_name, RASTER_OVERLAY_NAME) self.assertEqual(asset_to_add.raster_overlay_ion_asset_id, RASTER_OVERLAY_ION_ASSET_ID) async def test_create_asset_to_add_from_empty_event(self): mock_event = MagicMock(spec=carb.events.IEvent) mock_event.payload = None asset_to_add = AssetToAdd.from_event(mock_event) self.assertIsNone(asset_to_add)
2,131
Python
38.481481
95
0.689817
CesiumGS/cesium-omniverse/exts/cesium.omniverse/cesium/omniverse/tests/__init__.py
# For Python testing within Omniverse, it only looks in the `.tests` submodule in whatever is defined # as an extensions Python module. For organization purposes, we then import all of our tests from our other # testing submodules. from .extension_test import * # noqa: F401 F403 from ..models.tests import * # noqa: F401 F403 from ..ui.tests import * # noqa: F401 F403 from ..ui.models.tests import * # noqa: F401 F403
424
Python
52.124993
107
0.742925
CesiumGS/cesium-omniverse/exts/cesium.omniverse/cesium/omniverse/tests/utils.py
from pathlib import Path import omni.kit.app def get_golden_img_dir(): manager = omni.kit.app.get_app().get_extension_manager() ext_id = manager.get_extension_id_by_module("cesium.omniverse") return Path(manager.get_extension_path(ext_id)).joinpath("images/tests/ui/pass_fail_widget") async def wait_for_update(wait_frames=10): for _ in range(wait_frames): await omni.kit.app.get_app().next_update_async()
434
Python
30.071426
96
0.709677
CesiumGS/cesium-omniverse/exts/cesium.omniverse/cesium/omniverse/tests/extension_test.py
import omni.kit.test import omni.kit.ui_test as ui_test import omni.usd import pxr.Usd import cesium.usd from typing import Optional _window_ref: Optional[ui_test.WidgetRef] = None class ExtensionTest(omni.kit.test.AsyncTestCase): async def setUp(self): global _window_ref # can be removed (or at least decreased) once there is no delay # required before spawning the cesium window. See: # https://github.com/CesiumGS/cesium-omniverse/pull/423 await ui_test.wait_n_updates(24) _window_ref = ui_test.find("Cesium") async def tearDown(self): pass async def test_cesium_window_opens(self): global _window_ref self.assertIsNotNone(_window_ref) async def test_window_docked(self): global _window_ref # docked is false if the window is not in focus, # as may be the case if other extensions are loaded await _window_ref.focus() self.assertTrue(_window_ref.window.docked) async def test_blank_tileset(self): global _window_ref blankTilesetButton = _window_ref.find("**/Button[*].text=='Blank 3D Tiles Tileset'") self.assertIsNotNone(blankTilesetButton) stage: pxr.Usd.Stage = omni.usd.get_context().get_stage() self.assertIsNotNone(stage) self.assertFalse(any([i.IsA(cesium.usd.plugins.CesiumUsdSchemas.Tileset) for i in stage.Traverse()])) await blankTilesetButton.click() await ui_test.wait_n_updates(2) # passes without, but seems prudent self.assertTrue(any([i.IsA(cesium.usd.plugins.CesiumUsdSchemas.Tileset) for i in stage.Traverse()]))
1,657
Python
30.283018
109
0.67411
CesiumGS/cesium-omniverse/exts/cesium.omniverse/cesium/omniverse/utils/custom_fields.py
import omni.ui as ui READ_ONLY_STYLE = {"color": ui.color("#888888")} def string_field_with_label(label_text, model=None, enabled=True): with ui.HStack(spacing=4, height=20): ui.Label(label_text, height=20, width=100) field = ui.StringField(height=20, enabled=enabled) if not enabled: field.style = READ_ONLY_STYLE if model: field.model = model return field def int_field_with_label(label_text, model=None, enabled=True): with ui.HStack(spacing=4, height=20): ui.Label(label_text, height=20, width=100) field = ui.IntField(height=20, enabled=enabled) if not enabled: field.style = READ_ONLY_STYLE if model: field.model = model return field def float_field_with_label(label_text, model=None, enabled=True): with ui.HStack(spacing=4, height=20): ui.Label(label_text, height=20, width=100) field = ui.FloatField(height=20, enabled=enabled, precision=7) if not enabled: field.style = READ_ONLY_STYLE if model: field.model = model return field
1,150
Python
30.108107
70
0.616522
CesiumGS/cesium-omniverse/exts/cesium.omniverse/cesium/omniverse/utils/utils.py
from typing import Optional, Callable import omni.usd import omni.kit import omni.ui as ui async def wait_n_frames(n: int) -> None: for i in range(0, n): await omni.kit.app.get_app().next_update_async() async def dock_window_async( window: Optional[ui.Window], target: str = "Stage", position: ui.DockPosition = ui.DockPosition.SAME ) -> None: if window is None: return # Wait five frame await wait_n_frames(5) stage_window = ui.Workspace.get_window(target) window.dock_in(stage_window, position, 1) window.focus() async def perform_action_after_n_frames_async(n: int, action: Callable[[], None]) -> None: await wait_n_frames(n) action() def str_is_empty_or_none(s: Optional[str]) -> bool: if s is None: return True if s == "": return True return False
848
Python
21.342105
104
0.646226
CesiumGS/cesium-omniverse/exts/cesium.omniverse/cesium/omniverse/utils/cesium_interface.py
from ..bindings import acquire_cesium_omniverse_interface class CesiumInterfaceManager: def __init__(self): # Acquires the interface. Is a singleton. self.interface = acquire_cesium_omniverse_interface() def __enter__(self): return self.interface def __exit__(self, exc_type, exc_val, exc_tb): # We release the interface when we pull down the plugin. pass
412
Python
26.533332
64
0.657767
CesiumGS/cesium-omniverse/exts/cesium.omniverse/config/extension.toml
[package] version = "0.19.0" category = "simulation" feature = false app = false title = "Cesium for Omniverse" description = "High-accuracy full-scale WGS84 globe for Omniverse" authors = "Cesium GS Inc." repository = "https://github.com/CesiumGS/cesium-omniverse" keywords = [ "cesium", "omniverse", "geospatial", "3D Tiles", "glTF", "globe", "earth", "simulation", ] # Paths are relative to the extension folder changelog = "doc/CHANGES.md" readme = "doc/README.md" preview_image = "doc/resources/preview.jpg" icon = "doc/resources/icon.png" [package.target] kit = ["105.1"] [package.writeTarget] kit = true python = false # Which extensions this extension depends on [dependencies] "cesium.usd.plugins" = { version = "0.4.0" } "usdrt.scenegraph" = {} "omni.ui" = {} "omni.usd" = {} "omni.ui.scene" = {} "omni.usd.libs" = {} "omni.kit.commands" = {} "omni.kit.pipapi" = {} "omni.kit.uiapp" = {} "omni.kit.viewport.utility" = {} "omni.kit.property.usd" = {} "omni.kit.menu.utils" = {} "omni.kit.capture.viewport" = {} # Main python module this extension provides, it will be publicly available as "import cesium.omniverse" [[python.module]] name = "cesium.omniverse" [python.pipapi] archiveDirs = ["vendor"] [[native.plugin]] path = "bin/cesium.omniverse.plugin" [settings] exts."cesium.omniverse".defaultAccessToken = "" persistent.exts."cesium.omniverse".userAccessToken = "" exts."cesium.omniverse".showOnStartup = true [[test]] args = [ "--/renderer/enabled=rtx", "--/renderer/active=rtx", "--/app/window/dpiScaleOverride=1.0", "--/app/window/scaleToMonitor=false", "--/app/file/ignoreUnsavedOnExit=true", ] dependencies = [ "omni.hydra.pxr", "omni.kit.mainwindow", "omni.kit.ui_test", "omni.kit.test_suite.helpers", "omni.kit.window.file", "omni.kit.viewport.window", ] pythonTests.include = ["cesium.omniverse.*"] pythonTests.exclude = [] pythonTests.unreliable = [ "*test_window_docked", # window does not dock when tests run from the empty test kit via the omniverse app ] timeout = 180
2,088
TOML
22.47191
110
0.674808
CesiumGS/cesium-omniverse/apps/exts/cesium.performance.app/cesium/performance/app/extension.py
from functools import partial import asyncio import time from typing import Callable, List, Optional import logging import carb.events import omni.ext import omni.ui as ui import omni.usd import omni.kit.app as app import omni.kit.ui from omni.kit.viewport.utility import get_active_viewport from pxr import Gf, Sdf, UsdGeom from .performance_window import CesiumPerformanceWindow from .fps_sampler import FpsSampler from cesium.omniverse.bindings import acquire_cesium_omniverse_interface, release_cesium_omniverse_interface from cesium.omniverse.utils import wait_n_frames, dock_window_async from cesium.usd.plugins.CesiumUsdSchemas import ( Data as CesiumData, Georeference as CesiumGeoreference, IonRasterOverlay as CesiumIonRasterOverlay, Tileset as CesiumTileset, Tokens as CesiumTokens, ) ION_ACCESS_TOKEN = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJqdGkiOiI0Y2ZjNzY3NC04MWIyLTQyN2ItODg3Zi0zYzk3MmQxZWYxMmIiLCJpZCI6MjU5LCJpYXQiOjE3MTE5NzkyNzl9.GuvRiyuJO14zjA5_mIwgocOShmF4EUj2xbmikcCeXxs" # noqa: E501 GOOGLE_3D_TILES_ION_ID = 2275207 CESIUM_DATA_PRIM_PATH = "/Cesium" CESIUM_GEOREFERENCE_PRIM_PATH = "/CesiumGeoreference" CESIUM_CAMERA_PATH = "/Camera" class CesiumPerformanceExtension(omni.ext.IExt): def __init__(self): super().__init__() self._logger = logging.getLogger(__name__) self._performance_window: Optional[CesiumPerformanceWindow] = None self._view_new_york_city_subscription: Optional[carb.events.ISubscription] = None self._view_paris_subscription: Optional[carb.events.ISubscription] = None self._view_grand_canyon_subscription: Optional[carb.events.ISubscription] = None self._view_tour_subscription: Optional[carb.events.ISubscription] = None self._view_new_york_city_google_subscription: Optional[carb.events.ISubscription] = None self._view_paris_google_subscription: Optional[carb.events.ISubscription] = None self._view_grand_canyon_google_subscription: Optional[carb.events.ISubscription] = None self._view_tour_google_subscription: Optional[carb.events.ISubscription] = None self._stop_subscription: Optional[carb.events.ISubscription] = None self._on_stage_subscription: Optional[carb.events.ISubscription] = None self._update_frame_subscription: Optional[carb.events.ISubscription] = None self._tileset_loaded_subscription: Optional[carb.events.ISubscription] = None self._camera_path: Optional[str] = None self._tileset_path: Optional[str] = None self._active: bool = False self._start_time: float = 0.0 self._fps_sampler: FpsSampler = FpsSampler() def on_startup(self): global _cesium_omniverse_interface _cesium_omniverse_interface = acquire_cesium_omniverse_interface() self._setup_menus() self._show_and_dock_startup_windows() bus = app.get_app().get_message_bus_event_stream() view_new_york_city_event = carb.events.type_from_string("cesium.performance.VIEW_NEW_YORK_CITY") self._view_new_york_city_subscription = bus.create_subscription_to_pop_by_type( view_new_york_city_event, self._view_new_york_city ) view_paris_event = carb.events.type_from_string("cesium.performance.VIEW_PARIS") self._view_paris_subscription = bus.create_subscription_to_pop_by_type(view_paris_event, self._view_paris) view_grand_canyon_event = carb.events.type_from_string("cesium.performance.VIEW_GRAND_CANYON") self._view_grand_canyon_subscription = bus.create_subscription_to_pop_by_type( view_grand_canyon_event, self._view_grand_canyon ) view_tour_event = carb.events.type_from_string("cesium.performance.VIEW_TOUR") self._view_tour_subscription = bus.create_subscription_to_pop_by_type(view_tour_event, self._view_tour) view_new_york_city_google_event = carb.events.type_from_string("cesium.performance.VIEW_NEW_YORK_CITY_GOOGLE") self._view_new_york_city_google_subscription = bus.create_subscription_to_pop_by_type( view_new_york_city_google_event, self._view_new_york_city_google ) view_paris_google_event = carb.events.type_from_string("cesium.performance.VIEW_PARIS_GOOGLE") self._view_paris_google_subscription = bus.create_subscription_to_pop_by_type( view_paris_google_event, self._view_paris_google ) view_grand_canyon_google_event = carb.events.type_from_string("cesium.performance.VIEW_GRAND_CANYON_GOOGLE") self._view_grand_canyon_google_subscription = bus.create_subscription_to_pop_by_type( view_grand_canyon_google_event, self._view_grand_canyon_google ) view_tour_google_event = carb.events.type_from_string("cesium.performance.VIEW_TOUR_GOOGLE") self._view_tour_google_subscription = bus.create_subscription_to_pop_by_type( view_tour_google_event, self._view_tour_google ) stop_event = carb.events.type_from_string("cesium.performance.STOP") self._stop_subscription = bus.create_subscription_to_pop_by_type(stop_event, self._on_stop) usd_context = omni.usd.get_context() if usd_context.get_stage_state() == omni.usd.StageState.OPENED: self._on_stage_opened() self._on_stage_subscription = usd_context.get_stage_event_stream().create_subscription_to_pop( self._on_stage_event, name="cesium.performance.ON_STAGE_EVENT" ) update_stream = app.get_app().get_update_event_stream() self._update_frame_subscription = update_stream.create_subscription_to_pop( self._on_update_frame, name="cesium.performance.ON_UPDATE_FRAME" ) def on_shutdown(self): self._clear_scene() if self._view_new_york_city_subscription is not None: self._view_new_york_city_subscription.unsubscribe() self._view_new_york_city_subscription = None if self._view_paris_subscription is not None: self._view_paris_subscription.unsubscribe() self._view_paris_subscription = None if self._view_grand_canyon_subscription is not None: self._view_grand_canyon_subscription.unsubscribe() self._view_grand_canyon_subscription = None if self._view_tour_subscription is not None: self._view_tour_subscription.unsubscribe() self._view_tour_subscription = None if self._view_new_york_city_google_subscription is not None: self._view_new_york_city_google_subscription.unsubscribe() self._view_new_york_city_google_subscription = None if self._view_paris_google_subscription is not None: self._view_paris_google_subscription.unsubscribe() self._view_paris_google_subscription = None if self._view_grand_canyon_google_subscription is not None: self._view_grand_canyon_google_subscription.unsubscribe() self._view_grand_canyon_google_subscription = None if self._view_tour_google_subscription is not None: self._view_tour_google_subscription.unsubscribe() self._view_tour_google_subscription = None if self._stop_subscription is not None: self._stop_subscription.unsubscribe() self._stop_subscription = None if self._on_stage_subscription is not None: self._on_stage_subscription.unsubscribe() self._on_stage_subscription = None if self._update_frame_subscription is not None: self._update_frame_subscription.unsubscribe() self._update_frame_subscription = None self._fps_sampler.destroy() self._destroy_performance_window() release_cesium_omniverse_interface(_cesium_omniverse_interface) def _setup_menus(self): ui.Workspace.set_show_window_fn( CesiumPerformanceWindow.WINDOW_NAME, partial(self._show_performance_window, None) ) editor_menu = omni.kit.ui.get_editor_menu() if editor_menu: editor_menu.add_item( CesiumPerformanceWindow.MENU_PATH, self._show_performance_window, toggle=True, value=True ) def _show_and_dock_startup_windows(self): ui.Workspace.show_window(CesiumPerformanceWindow.WINDOW_NAME) asyncio.ensure_future(dock_window_async(self._performance_window, target="Property")) def _destroy_performance_window(self): if self._performance_window is not None: self._performance_window.destroy() self._performance_window = None async def _destroy_window_async(self, path): # Wait one frame, this is due to the one frame defer in Window::_moveToMainOSWindow() await wait_n_frames(1) if path is CesiumPerformanceWindow.MENU_PATH: self._destroy_performance_window() def _visibility_changed_fn(self, path, visible): editor_menu = omni.kit.ui.get_editor_menu() if editor_menu: editor_menu.set_value(path, visible) if not visible: asyncio.ensure_future(self._destroy_window_async(path)) def _show_performance_window(self, _menu, value): if value: self._performance_window = CesiumPerformanceWindow(_cesium_omniverse_interface, width=300, height=400) self._performance_window.set_visibility_changed_fn( partial(self._visibility_changed_fn, CesiumPerformanceWindow.MENU_PATH) ) elif self._performance_window is not None: self._performance_window.visible = False def _on_update_frame(self, _e: carb.events.IEvent): if self._active is True: duration = self._get_duration() self._update_duration_ui(duration) self._update_fps_ui(self._fps_sampler.get_fps()) def _on_stage_event(self, _e: carb.events.IEvent): usd_context = omni.usd.get_context() if usd_context.get_stage_state() == omni.usd.StageState.OPENED: self._on_stage_opened() def _on_stage_opened(self): self._camera_path = self._create_camera(CESIUM_CAMERA_PATH) @staticmethod def _create_tileset_ion(path: str, asset_id: int, access_token: str) -> str: stage = omni.usd.get_context().get_stage() tileset_path = omni.usd.get_stage_next_free_path(stage, path, False) tileset = CesiumTileset.Define(stage, tileset_path) assert tileset.GetPrim().IsValid() tileset.GetIonAssetIdAttr().Set(asset_id) tileset.GetIonAccessTokenAttr().Set(access_token) tileset.GetSourceTypeAttr().Set(CesiumTokens.ion) return tileset_path @staticmethod def _create_tileset_google() -> str: stage = omni.usd.get_context().get_stage() tileset_path = omni.usd.get_stage_next_free_path(stage, "/Google_3D_Tiles", False) tileset = CesiumTileset.Define(stage, tileset_path) tileset.GetIonAssetIdAttr().Set(GOOGLE_3D_TILES_ION_ID) tileset.GetIonAccessTokenAttr().Set(ION_ACCESS_TOKEN) tileset.GetSourceTypeAttr().Set(CesiumTokens.ion) return tileset_path @staticmethod def _create_raster_overlay_ion(path: str, asset_id: int, access_token: str) -> str: stage = omni.usd.get_context().get_stage() raster_overlay_path = omni.usd.get_stage_next_free_path(stage, path, False) raster_overlay = CesiumIonRasterOverlay.Define(stage, raster_overlay_path) assert raster_overlay.GetPrim().IsValid() parent = raster_overlay.GetPrim().GetParent() assert parent.IsA(CesiumTileset) tileset_prim = CesiumTileset.Get(stage, parent.GetPath()) tileset_prim.GetRasterOverlayBindingRel().AddTarget(raster_overlay_path) raster_overlay.GetIonAssetIdAttr().Set(asset_id) raster_overlay.GetIonAccessTokenAttr().Set(access_token) return raster_overlay_path @staticmethod def _create_camera(path: str) -> str: stage = omni.usd.get_context().get_stage() if stage.GetPrimAtPath(path): return path camera = UsdGeom.Camera.Define(stage, path) assert camera.GetPrim().IsValid() camera.GetClippingRangeAttr().Set(Gf.Vec2f(1.0, 100000000.0)) return path @staticmethod def _get_raster_overlay_path(tileset_path: str, raster_overlay_name: str) -> str: return Sdf.Path(tileset_path).AppendPath(raster_overlay_name).pathString @staticmethod def _set_georeference(longitude: float, latitude: float, height: float): stage = omni.usd.get_context().get_stage() cesium_georeference = CesiumGeoreference.Get(stage, CESIUM_GEOREFERENCE_PRIM_PATH) assert cesium_georeference.GetPrim().IsValid() cesium_georeference.GetGeoreferenceOriginLongitudeAttr().Set(longitude) cesium_georeference.GetGeoreferenceOriginLatitudeAttr().Set(latitude) cesium_georeference.GetGeoreferenceOriginHeightAttr().Set(height) def _set_camera( self, translate: Gf.Vec3d, rotate: Gf.Vec3f, focal_length: float, horizontal_aperture: float, vertical_aperture: float, ): stage = omni.usd.get_context().get_stage() viewport = get_active_viewport() viewport.set_active_camera(self._camera_path) camera = UsdGeom.Camera.Get(stage, self._camera_path) camera.GetFocalLengthAttr().Set(focal_length) camera.GetHorizontalApertureAttr().Set(horizontal_aperture) camera.GetVerticalApertureAttr().Set(vertical_aperture) xform_common_api = UsdGeom.XformCommonAPI(camera.GetPrim()) xform_common_api.SetTranslate(translate) xform_common_api.SetRotate(rotate, UsdGeom.XformCommonAPI.RotationOrderYXZ) @staticmethod def _get_tileset(path: str) -> CesiumTileset: stage = omni.usd.get_context().get_stage() tileset = CesiumTileset.Get(stage, path) assert tileset.GetPrim().IsValid() return tileset @staticmethod def _get_cesium_data() -> CesiumData: stage = omni.usd.get_context().get_stage() cesium_data = CesiumData.Get(stage, CESIUM_DATA_PRIM_PATH) assert cesium_data.GetPrim().IsValid() return cesium_data @staticmethod def _remove_prim(path: str): stage = omni.usd.get_context().get_stage() stage.RemovePrim(path) def _setup_location_new_york_city(self): self._set_georeference(-74.0060, 40.7128, 50.0) self._set_camera( Gf.Vec3d(-176516.8372437113, 33877.019622553846, 197777.19771945066), Gf.Vec3f(-7.9392824, -37.71652, -6.0970836), 18.14756, 20.955, 15.2908, ) def _setup_location_paris(self): self._set_georeference(2.3522, 48.8566, 100.0) self._set_camera( Gf.Vec3d(-285275.1368718885, 780.3607448845705, 35392.91845506678), Gf.Vec3f(0.46399376, 65.245544, -1.0061567), 18.14756, 20.955, 15.2908, ) def _setup_location_grand_canyon(self): self._set_georeference(-112.3535, 36.2679, 2100.0) self._set_camera( Gf.Vec3d(-339866.7567928189, 27967.440239271935, -59650.894693908194), Gf.Vec3f(5.532731, -129.35608, -6.704948), 18.14756, 20.955, 15.2908, ) def _view_new_york_city(self, _e: carb.events.IEvent): self._logger.warning("View New York City") self._clear_scene() self._setup_location_new_york_city() tileset_path = self._create_tileset_ion("/Cesium_World_Terrain", 1, ION_ACCESS_TOKEN) self._create_raster_overlay_ion( self._get_raster_overlay_path(tileset_path, "Bing_Maps_Aerial_Imagery"), 2, ION_ACCESS_TOKEN, ) self._load_tileset(tileset_path, self._tileset_loaded) def _view_paris(self, _e: carb.events.IEvent): self._logger.warning("View Paris") self._clear_scene() self._setup_location_paris() tileset_path = self._create_tileset_ion("/Cesium_World_Terrain", 1, ION_ACCESS_TOKEN) self._create_raster_overlay_ion( self._get_raster_overlay_path(tileset_path, "Bing_Maps_Aerial_Imagery"), 2, ION_ACCESS_TOKEN, ) self._load_tileset(tileset_path, self._tileset_loaded) def _view_grand_canyon(self, _e: carb.events.IEvent): self._logger.warning("View Grand Canyon") self._clear_scene() self._setup_location_grand_canyon() tileset_path = self._create_tileset_ion("/Cesium_World_Terrain", 1, ION_ACCESS_TOKEN) self._create_raster_overlay_ion( self._get_raster_overlay_path(tileset_path, "Bing_Maps_Aerial_Imagery"), 2, ION_ACCESS_TOKEN, ) self._load_tileset(tileset_path, self._tileset_loaded) def _view_tour(self, _e: carb.events.IEvent): self._logger.warning("View Tour") self._clear_scene() tileset_path = self._create_tileset_ion("/Cesium_World_Terrain", 1, ION_ACCESS_TOKEN) self._create_raster_overlay_ion( self._get_raster_overlay_path(tileset_path, "Bing_Maps_Aerial_Imagery"), 2, ION_ACCESS_TOKEN, ) def tour_stop_0(): self._setup_location_new_york_city() def tour_stop_1(): self._setup_location_paris() def tour_stop_2(): self._setup_location_grand_canyon() tour = Tour(self, [tour_stop_0, tour_stop_1, tour_stop_2], self._tileset_loaded) self._load_tileset(tileset_path, tour.tour_stop_loaded) def _view_new_york_city_google(self, _e: carb.events.IEvent): self._logger.warning("View New York City Google") self._clear_scene() self._setup_location_new_york_city() tileset_path = self._create_tileset_google() self._load_tileset(tileset_path, self._tileset_loaded) def _view_paris_google(self, _e: carb.events.IEvent): self._logger.warning("View Paris Google") self._clear_scene() self._setup_location_paris() tileset_path = self._create_tileset_google() self._load_tileset(tileset_path, self._tileset_loaded) def _view_grand_canyon_google(self, _e: carb.events.IEvent): self._logger.warning("View Grand Canyon Google") self._clear_scene() self._setup_location_grand_canyon() tileset_path = self._create_tileset_google() self._load_tileset(tileset_path, self._tileset_loaded) def _view_tour_google(self, _e: carb.events.IEvent): self._logger.warning("View Tour Google") self._clear_scene() tileset_path = self._create_tileset_google() def tour_stop_0(): self._setup_location_new_york_city() def tour_stop_1(): self._setup_location_paris() def tour_stop_2(): self._setup_location_grand_canyon() tour = Tour(self, [tour_stop_0, tour_stop_1, tour_stop_2], self._tileset_loaded) self._load_tileset(tileset_path, tour.tour_stop_loaded) def _load_tileset(self, tileset_path: str, tileset_loaded: Callable): tileset = self._get_tileset(tileset_path) cesium_data = self._get_cesium_data() assert self._performance_window is not None bus = app.get_app().get_message_bus_event_stream() tileset_loaded_event = carb.events.type_from_string("cesium.omniverse.TILESET_LOADED") self._tileset_loaded_subscription = bus.create_subscription_to_pop_by_type( tileset_loaded_event, tileset_loaded ) random_colors = self._performance_window.get_random_colors() forbid_holes = self._performance_window.get_forbid_holes() frustum_culling = self._performance_window.get_frustum_culling() main_thread_loading_time_limit = self._performance_window.get_main_thread_loading_time_limit_model() cesium_data.GetDebugRandomColorsAttr().Set(random_colors) tileset.GetForbidHolesAttr().Set(forbid_holes) tileset.GetEnableFrustumCullingAttr().Set(frustum_culling) tileset.GetMainThreadLoadingTimeLimitAttr().Set(main_thread_loading_time_limit) self._tileset_path = tileset_path self._active = True self._start_time = time.time() self._fps_sampler.start() def _tileset_loaded(self, _e: carb.events.IEvent): self._stop() duration = self._get_duration() self._update_duration_ui(duration) self._update_fps_mean_ui(self._fps_sampler.get_mean()) self._update_fps_median_ui(self._fps_sampler.get_median()) self._update_fps_low_ui(self._fps_sampler.get_low()) self._update_fps_high_ui(self._fps_sampler.get_high()) self._logger.warning("Loaded in {} seconds".format(duration)) def _get_duration(self) -> float: current_time = time.time() duration = current_time - self._start_time return duration def _update_duration_ui(self, value: float): if self._performance_window is not None: self._performance_window.set_duration(value) def _update_fps_ui(self, value: float): if self._performance_window is not None: self._performance_window.set_fps(value) def _update_fps_mean_ui(self, value: float): if self._performance_window is not None: self._performance_window.set_fps_mean(value) def _update_fps_median_ui(self, value: float): if self._performance_window is not None: self._performance_window.set_fps_median(value) def _update_fps_low_ui(self, value: float): if self._performance_window is not None: self._performance_window.set_fps_low(value) def _update_fps_high_ui(self, value: float): if self._performance_window is not None: self._performance_window.set_fps_high(value) def _clear_scene(self): self._stop() self._update_duration_ui(0.0) self._update_fps_ui(0.0) self._update_fps_mean_ui(0.0) self._update_fps_median_ui(0.0) self._update_fps_low_ui(0.0) self._update_fps_high_ui(0.0) if self._tileset_path is not None: self._remove_prim(self._tileset_path) def _on_stop(self, _e: carb.events.IEvent): self._stop() def _stop(self): self._active = False self._fps_sampler.stop() if self._tileset_loaded_subscription is not None: self._tileset_loaded_subscription.unsubscribe() self._tileset_loaded_subscription = None class Tour: def __init__(self, ext: CesiumPerformanceExtension, tour_stops: List[Callable], tour_complete: Callable): self._ext: CesiumPerformanceExtension = ext self._tour_stops: List[Callable] = tour_stops self._tour_complete: Callable = tour_complete self._current_stop: int = 0 self._duration: float = 0.0 assert len(tour_stops) > 0 tour_stops[0]() def tour_stop_loaded(self, _e: carb.events.IEvent): duration = self._ext._get_duration() current_duration = duration - self._duration self._duration = duration self._ext._logger.warning("Tour stop {} loaded in {} seconds".format(self._current_stop, current_duration)) if self._current_stop == len(self._tour_stops) - 1: self._tour_complete(_e) else: self._current_stop += 1 self._tour_stops[self._current_stop]()
23,749
Python
39.667808
212
0.652659
CesiumGS/cesium-omniverse/apps/exts/cesium.performance.app/cesium/performance/app/performance_window.py
import logging import carb.events import omni.kit.app as app import omni.ui as ui from cesium.omniverse.bindings import ICesiumOmniverseInterface RANDOM_COLORS_TEXT = "Random colors" FORBID_HOLES_TEXT = "Forbid holes" FRUSTUM_CULLING_TEXT = "Frustum culling" TRACING_ENABLED_TEXT = "Tracing enabled" MAIN_THREAD_LOADING_TIME_LIMIT_TEXT = "Main thread loading time limit (ms)" NEW_YORK_CITY_TEXT = "New York City" PARIS_TEXT = "Paris" GRAND_CANYON_TEXT = "Grand Canyon" TOUR_TEXT = "Tour" NEW_YORK_CITY_GOOGLE_TEXT = "New York City (Google)" PARIS_GOOGLE_TEXT = "Paris (Google)" GRAND_CANYON_GOOGLE_TEXT = "Grand Canyon (Google)" TOUR_GOOGLE_TEXT = "Tour (Google)" DURATION_TEXT = "Duration (seconds)" FPS_TEXT = "FPS" FPS_MEAN_TEXT = "FPS (mean)" FPS_MEDIAN_TEXT = "FPS (median)" FPS_LOW_TEXT = "FPS (low)" FPS_HIGH_TEXT = "FPS (high)" class CesiumPerformanceWindow(ui.Window): WINDOW_NAME = "Cesium Performance Testing" MENU_PATH = f"Window/Cesium/{WINDOW_NAME}" def __init__(self, cesium_omniverse_interface: ICesiumOmniverseInterface, **kwargs): super().__init__(CesiumPerformanceWindow.WINDOW_NAME, **kwargs) self._cesium_omniverse_interface = cesium_omniverse_interface self._logger = logging.getLogger(__name__) self._random_colors_checkbox_model = ui.SimpleBoolModel(False) self._forbid_holes_checkbox_model = ui.SimpleBoolModel(False) self._frustum_culling_checkbox_model = ui.SimpleBoolModel(True) self._main_thread_loading_time_limit_model = ui.SimpleFloatModel(0.0) self._duration_model = ui.SimpleFloatModel(0.0) self._fps_model = ui.SimpleFloatModel(0.0) self._fps_mean_model = ui.SimpleFloatModel(0.0) self._fps_median_model = ui.SimpleFloatModel(0.0) self._fps_low_model = ui.SimpleFloatModel(0.0) self._fps_high_model = ui.SimpleFloatModel(0.0) self.frame.set_build_fn(self._build_fn) def destroy(self) -> None: super().destroy() def _build_fn(self): with ui.VStack(spacing=10): with ui.VStack(spacing=4): with ui.HStack(height=16): ui.Label("Options", height=0) ui.Spacer() for label, model in [ (RANDOM_COLORS_TEXT, self._random_colors_checkbox_model), (FORBID_HOLES_TEXT, self._forbid_holes_checkbox_model), (FRUSTUM_CULLING_TEXT, self._frustum_culling_checkbox_model), ]: with ui.HStack(height=0): ui.Label(label, height=0) ui.CheckBox(model) with ui.HStack(height=0): ui.Label(MAIN_THREAD_LOADING_TIME_LIMIT_TEXT, height=0) ui.StringField(self._main_thread_loading_time_limit_model) with ui.HStack(height=16): tracing_label = ui.Label(TRACING_ENABLED_TEXT, height=0) tracing_label.set_tooltip( "Enabled when the project is configured with -D CESIUM_OMNI_ENABLE_TRACING=ON" ) enabled_string = "ON" if self._cesium_omniverse_interface.is_tracing_enabled() else "OFF" ui.Label(enabled_string, height=0) with ui.VStack(spacing=0): ui.Label("Scenarios", height=16) for label, callback in [ (NEW_YORK_CITY_TEXT, self._view_new_york_city), (PARIS_TEXT, self._view_paris), (GRAND_CANYON_TEXT, self._view_grand_canyon), (TOUR_TEXT, self._view_tour), (NEW_YORK_CITY_GOOGLE_TEXT, self._view_new_york_city_google), (PARIS_GOOGLE_TEXT, self._view_paris_google), (GRAND_CANYON_GOOGLE_TEXT, self._view_grand_canyon_google), (TOUR_GOOGLE_TEXT, self._view_tour_google), ]: ui.Button(label, height=20, clicked_fn=callback) with ui.VStack(spacing=4): with ui.HStack(height=16): ui.Label("Stats", height=0) ui.Spacer() for label, model in [ (DURATION_TEXT, self._duration_model), (FPS_TEXT, self._fps_model), (FPS_MEAN_TEXT, self._fps_mean_model), (FPS_MEDIAN_TEXT, self._fps_median_model), (FPS_LOW_TEXT, self._fps_low_model), (FPS_HIGH_TEXT, self._fps_high_model), ]: with ui.HStack(height=0): ui.Label(label, height=0) ui.StringField(model=model, height=0, read_only=True) with ui.VStack(spacing=0): ui.Button("Stop", height=16, clicked_fn=self._stop) def _view_new_york_city(self): bus = app.get_app().get_message_bus_event_stream() view_new_york_city_event = carb.events.type_from_string("cesium.performance.VIEW_NEW_YORK_CITY") bus.push(view_new_york_city_event) def _view_paris(self): bus = app.get_app().get_message_bus_event_stream() view_paris_event = carb.events.type_from_string("cesium.performance.VIEW_PARIS") bus.push(view_paris_event) def _view_grand_canyon(self): bus = app.get_app().get_message_bus_event_stream() view_grand_canyon_event = carb.events.type_from_string("cesium.performance.VIEW_GRAND_CANYON") bus.push(view_grand_canyon_event) def _view_tour(self): bus = app.get_app().get_message_bus_event_stream() view_tour_event = carb.events.type_from_string("cesium.performance.VIEW_TOUR") bus.push(view_tour_event) def _view_new_york_city_google(self): bus = app.get_app().get_message_bus_event_stream() view_new_york_city_google_event = carb.events.type_from_string("cesium.performance.VIEW_NEW_YORK_CITY_GOOGLE") bus.push(view_new_york_city_google_event) def _view_paris_google(self): bus = app.get_app().get_message_bus_event_stream() view_paris_google_event = carb.events.type_from_string("cesium.performance.VIEW_PARIS_GOOGLE") bus.push(view_paris_google_event) def _view_grand_canyon_google(self): bus = app.get_app().get_message_bus_event_stream() view_grand_canyon_google_event = carb.events.type_from_string("cesium.performance.VIEW_GRAND_CANYON_GOOGLE") bus.push(view_grand_canyon_google_event) def _view_tour_google(self): bus = app.get_app().get_message_bus_event_stream() view_tour_google_event = carb.events.type_from_string("cesium.performance.VIEW_TOUR_GOOGLE") bus.push(view_tour_google_event) def _stop(self): bus = app.get_app().get_message_bus_event_stream() stop_event = carb.events.type_from_string("cesium.performance.STOP") bus.push(stop_event) def get_random_colors(self) -> bool: return self._random_colors_checkbox_model.get_value_as_bool() def get_forbid_holes(self) -> bool: return self._forbid_holes_checkbox_model.get_value_as_bool() def get_frustum_culling(self) -> bool: return self._frustum_culling_checkbox_model.get_value_as_bool() def get_main_thread_loading_time_limit_model(self) -> float: return self._main_thread_loading_time_limit_model.get_value_as_float() def set_duration(self, value: float): self._duration_model.set_value(value) def set_fps(self, value: float): self._fps_model.set_value(value) def set_fps_mean(self, value: float): self._fps_mean_model.set_value(value) def set_fps_median(self, value: float): self._fps_median_model.set_value(value) def set_fps_low(self, value: float): self._fps_low_model.set_value(value) def set_fps_high(self, value: float): self._fps_high_model.set_value(value)
8,013
Python
40.097436
118
0.606639
CesiumGS/cesium-omniverse/apps/exts/cesium.performance.app/cesium/performance/app/fps_sampler.py
import array import time import carb.events import omni.kit.app as app import statistics from omni.kit.viewport.utility import get_active_viewport FREQUENCY_IN_SECONDS: float = 0.025 class FpsSampler: def __init__( self, ): self._last_time: float = 0.0 self._active: bool = False self._fps = 0.0 self._samples = array.array("f") self._median: float = 0.0 self._mean: float = 0.0 self._low: float = 0.0 self._high: float = 0.0 self._viewport = get_active_viewport() update_stream = app.get_app().get_update_event_stream() self._update_frame_subscription = update_stream.create_subscription_to_pop( self._on_update_frame, name="cesium.performance.ON_UPDATE_FRAME" ) def __del__(self): self.destroy() def destroy(self): if self._update_frame_subscription is not None: self._update_frame_subscription.unsubscribe() self._update_frame_subscription = None def start(self): self._last_time = time.time() self._active = True def stop(self): self._active = False if len(self._samples) > 0: self._mean = statistics.mean(self._samples) self._median = statistics.median(self._samples) self._low = min(self._samples) self._high = max(self._samples) self._samples = array.array("f") def get_mean(self): assert not self._active return self._mean def get_median(self): assert not self._active return self._median def get_low(self): assert not self._active return self._low def get_high(self): assert not self._active return self._high def get_fps(self): assert self._active return self._fps def _on_update_frame(self, _e: carb.events.IEvent): if not self._active: return current_time = time.time() elapsed = current_time - self._last_time if elapsed > FREQUENCY_IN_SECONDS: fps = self._viewport.fps self._samples.append(fps) self._last_time = current_time self._fps = fps
2,243
Python
25.093023
83
0.576014
CesiumGS/cesium-omniverse/apps/exts/cesium.performance.app/config/extension.toml
[package] title = "Cesium for Omniverse Performance Testing Extension" version = "0.0.0" app = false toggleable = false [dependencies] "cesium.omniverse" = {} [[python.module]] name = "cesium.performance.app"
211
TOML
16.666665
60
0.725118