file_path
stringlengths 21
202
| content
stringlengths 12
1.02M
| size
int64 12
1.02M
| lang
stringclasses 9
values | avg_line_length
float64 3.33
100
| max_line_length
int64 10
993
| alphanum_fraction
float64 0.27
0.93
|
---|---|---|---|---|---|---|
CesiumGS/cesium-omniverse/src/core/src/FabricAttributesBuilder.cpp | #include "cesium/omniverse/FabricAttributesBuilder.h"
#include "cesium/omniverse/Context.h"
#include "cesium/omniverse/UsdUtil.h"
#include <omni/fabric/SimStageWithHistory.h>
namespace cesium::omniverse {
FabricAttributesBuilder::FabricAttributesBuilder(Context* pContext)
: _pContext(pContext) {}
void FabricAttributesBuilder::addAttribute(const omni::fabric::Type& type, const omni::fabric::Token& name) {
assert(_size < MAX_ATTRIBUTES);
_attributes[_size++] = omni::fabric::AttrNameAndType(type, name);
}
void FabricAttributesBuilder::createAttributes(const omni::fabric::Path& path) const {
// Somewhat annoyingly, fabricStage.createAttributes takes an std::array instead of a gsl::span. This is fine if
// you know exactly which set of attributes to create at compile time but we don't. For example, not all prims will
// have texture coordinates or materials. This class allows attributes to be added dynamically up to a hardcoded maximum
// count (MAX_ATTRIBUTES) and avoids heap allocations. The downside is that we need this ugly if/else chain below.
auto& fabricStage = _pContext->getFabricStage();
// clang-format off
if (_size == 0) fabricStage.createAttributes<0>(path, *reinterpret_cast<const std::array<omni::fabric::AttrNameAndType, 0>*>(_attributes.data()));
else if (_size == 1) fabricStage.createAttributes<1>(path, *reinterpret_cast<const std::array<omni::fabric::AttrNameAndType, 1>*>(_attributes.data()));
else if (_size == 2) fabricStage.createAttributes<2>(path, *reinterpret_cast<const std::array<omni::fabric::AttrNameAndType, 2>*>(_attributes.data()));
else if (_size == 3) fabricStage.createAttributes<3>(path, *reinterpret_cast<const std::array<omni::fabric::AttrNameAndType, 3>*>(_attributes.data()));
else if (_size == 4) fabricStage.createAttributes<4>(path, *reinterpret_cast<const std::array<omni::fabric::AttrNameAndType, 4>*>(_attributes.data()));
else if (_size == 5) fabricStage.createAttributes<5>(path, *reinterpret_cast<const std::array<omni::fabric::AttrNameAndType, 5>*>(_attributes.data()));
else if (_size == 6) fabricStage.createAttributes<6>(path, *reinterpret_cast<const std::array<omni::fabric::AttrNameAndType, 6>*>(_attributes.data()));
else if (_size == 7) fabricStage.createAttributes<7>(path, *reinterpret_cast<const std::array<omni::fabric::AttrNameAndType, 7>*>(_attributes.data()));
else if (_size == 8) fabricStage.createAttributes<8>(path, *reinterpret_cast<const std::array<omni::fabric::AttrNameAndType, 8>*>(_attributes.data()));
else if (_size == 9) fabricStage.createAttributes<9>(path, *reinterpret_cast<const std::array<omni::fabric::AttrNameAndType, 9>*>(_attributes.data()));
else if (_size == 10) fabricStage.createAttributes<10>(path, *reinterpret_cast<const std::array<omni::fabric::AttrNameAndType, 10>*>(_attributes.data()));
else if (_size == 11) fabricStage.createAttributes<11>(path, *reinterpret_cast<const std::array<omni::fabric::AttrNameAndType, 11>*>(_attributes.data()));
else if (_size == 12) fabricStage.createAttributes<12>(path, *reinterpret_cast<const std::array<omni::fabric::AttrNameAndType, 12>*>(_attributes.data()));
else if (_size == 13) fabricStage.createAttributes<13>(path, *reinterpret_cast<const std::array<omni::fabric::AttrNameAndType, 13>*>(_attributes.data()));
else if (_size == 14) fabricStage.createAttributes<14>(path, *reinterpret_cast<const std::array<omni::fabric::AttrNameAndType, 14>*>(_attributes.data()));
else if (_size == 15) fabricStage.createAttributes<15>(path, *reinterpret_cast<const std::array<omni::fabric::AttrNameAndType, 15>*>(_attributes.data()));
else if (_size == 16) fabricStage.createAttributes<16>(path, *reinterpret_cast<const std::array<omni::fabric::AttrNameAndType, 16>*>(_attributes.data()));
else if (_size == 17) fabricStage.createAttributes<17>(path, *reinterpret_cast<const std::array<omni::fabric::AttrNameAndType, 17>*>(_attributes.data()));
else if (_size == 18) fabricStage.createAttributes<18>(path, *reinterpret_cast<const std::array<omni::fabric::AttrNameAndType, 18>*>(_attributes.data()));
else if (_size == 19) fabricStage.createAttributes<19>(path, *reinterpret_cast<const std::array<omni::fabric::AttrNameAndType, 19>*>(_attributes.data()));
else if (_size == 20) fabricStage.createAttributes<20>(path, *reinterpret_cast<const std::array<omni::fabric::AttrNameAndType, 20>*>(_attributes.data()));
else if (_size == 21) fabricStage.createAttributes<21>(path, *reinterpret_cast<const std::array<omni::fabric::AttrNameAndType, 21>*>(_attributes.data()));
else if (_size == 22) fabricStage.createAttributes<22>(path, *reinterpret_cast<const std::array<omni::fabric::AttrNameAndType, 22>*>(_attributes.data()));
else if (_size == 23) fabricStage.createAttributes<23>(path, *reinterpret_cast<const std::array<omni::fabric::AttrNameAndType, 23>*>(_attributes.data()));
else if (_size == 24) fabricStage.createAttributes<24>(path, *reinterpret_cast<const std::array<omni::fabric::AttrNameAndType, 24>*>(_attributes.data()));
else if (_size == 25) fabricStage.createAttributes<25>(path, *reinterpret_cast<const std::array<omni::fabric::AttrNameAndType, 25>*>(_attributes.data()));
else if (_size == 26) fabricStage.createAttributes<26>(path, *reinterpret_cast<const std::array<omni::fabric::AttrNameAndType, 26>*>(_attributes.data()));
else if (_size == 27) fabricStage.createAttributes<27>(path, *reinterpret_cast<const std::array<omni::fabric::AttrNameAndType, 27>*>(_attributes.data()));
else if (_size == 28) fabricStage.createAttributes<28>(path, *reinterpret_cast<const std::array<omni::fabric::AttrNameAndType, 28>*>(_attributes.data()));
else if (_size == 29) fabricStage.createAttributes<29>(path, *reinterpret_cast<const std::array<omni::fabric::AttrNameAndType, 29>*>(_attributes.data()));
// clang-format on
}
} // namespace cesium::omniverse
| 5,966 | C++ | 98.449998 | 158 | 0.722595 |
CesiumGS/cesium-omniverse/src/core/src/FabricMaterialDescriptor.cpp | #include "cesium/omniverse/FabricMaterialDescriptor.h"
#include "cesium/omniverse/FabricFeaturesInfo.h"
#include "cesium/omniverse/FabricFeaturesUtil.h"
#include "cesium/omniverse/FabricMaterialInfo.h"
#include "cesium/omniverse/FabricPropertyDescriptor.h"
#include "cesium/omniverse/FabricRasterOverlaysInfo.h"
#include "cesium/omniverse/GltfUtil.h"
#include "cesium/omniverse/MetadataUtil.h"
#ifdef CESIUM_OMNI_MSVC
#pragma push_macro("OPAQUE")
#undef OPAQUE
#endif
#include <CesiumGltf/Model.h>
namespace cesium::omniverse {
FabricMaterialDescriptor::FabricMaterialDescriptor(
const Context& context,
const CesiumGltf::Model& model,
const CesiumGltf::MeshPrimitive& primitive,
const FabricMaterialInfo& materialInfo,
const FabricFeaturesInfo& featuresInfo,
const FabricRasterOverlaysInfo& rasterOverlaysInfo,
const pxr::SdfPath& tilesetMaterialPath)
: _hasVertexColors(materialInfo.hasVertexColors)
, _hasBaseColorTexture(materialInfo.baseColorTexture.has_value())
, _featureIdTypes(FabricFeaturesUtil::getFeatureIdTypes(featuresInfo))
, _rasterOverlayRenderMethods(rasterOverlaysInfo.overlayRenderMethods)
, _tilesetMaterialPath(tilesetMaterialPath) {
// Ignore styleable properties unless the tileset has a material
if (!_tilesetMaterialPath.IsEmpty()) {
std::tie(_styleableProperties, _unsupportedPropertyWarnings) =
MetadataUtil::getStyleableProperties(context, model, primitive);
}
}
bool FabricMaterialDescriptor::hasVertexColors() const {
return _hasVertexColors;
}
bool FabricMaterialDescriptor::hasBaseColorTexture() const {
return _hasBaseColorTexture;
}
const std::vector<FabricFeatureIdType>& FabricMaterialDescriptor::getFeatureIdTypes() const {
return _featureIdTypes;
}
const std::vector<FabricOverlayRenderMethod>& FabricMaterialDescriptor::getRasterOverlayRenderMethods() const {
return _rasterOverlayRenderMethods;
}
bool FabricMaterialDescriptor::hasTilesetMaterial() const {
return !_tilesetMaterialPath.IsEmpty();
}
const pxr::SdfPath& FabricMaterialDescriptor::getTilesetMaterialPath() const {
return _tilesetMaterialPath;
}
const std::vector<FabricPropertyDescriptor>& FabricMaterialDescriptor::getStyleableProperties() const {
return _styleableProperties;
}
const std::map<std::string, std::string>& FabricMaterialDescriptor::getUnsupportedPropertyWarnings() const {
return _unsupportedPropertyWarnings;
}
// Make sure to update this function when adding new fields to the class
bool FabricMaterialDescriptor::operator==(const FabricMaterialDescriptor& other) const {
// clang-format off
return _hasVertexColors == other._hasVertexColors &&
_hasBaseColorTexture == other._hasBaseColorTexture &&
_featureIdTypes == other._featureIdTypes &&
_rasterOverlayRenderMethods == other._rasterOverlayRenderMethods &&
_tilesetMaterialPath == other._tilesetMaterialPath &&
_styleableProperties == other._styleableProperties;
// _unsupportedPropertyWarnings is intentionally not checked because it adds unecessary overhead
// clang-format on
}
} // namespace cesium::omniverse
| 3,197 | C++ | 35.75862 | 111 | 0.772599 |
CesiumGS/cesium-omniverse/src/core/src/FilesystemUtil.cpp | #include "cesium/omniverse/FilesystemUtil.h"
#include <carb/Framework.h>
#include <carb/tokens/ITokens.h>
#include <carb/tokens/TokensUtils.h>
#include <cstdlib>
#include <filesystem>
#if defined(__linux__)
#include <pwd.h>
#include <sys/types.h>
#include <unistd.h>
#include <cerrno>
#endif
namespace cesium::omniverse::FilesystemUtil {
std::filesystem::path getCesiumCacheDirectory() {
auto f = carb::getFramework();
auto* tokensInterface = f->tryAcquireInterface<carb::tokens::ITokens>();
std::string cacheDir;
if (tokensInterface) {
cacheDir = carb::tokens::resolveString(tokensInterface, "${omni_global_cache}");
}
if (!cacheDir.empty()) {
std::filesystem::path cacheDirPath(cacheDir);
if (exists(cacheDirPath)) {
return cacheDirPath;
}
// Should we create the directory if it doesn't exist? It's hard to believe that Omniverse
// won't have already created it.
}
auto homeDirPath = getUserHomeDirectory();
if (!homeDirPath.empty()) {
auto cacheDirPath = homeDirPath / ".nvidia-omniverse";
if (exists(cacheDirPath)) {
return cacheDirPath;
}
}
return {};
}
// Quite a lot of ceremony to get the home directory.
std::filesystem::path getUserHomeDirectory() {
std::string homeDir;
#if defined(__linux__)
if (char* cString = std::getenv("HOME")) {
homeDir = cString;
} else {
passwd pwd;
long bufsize = sysconf(_SC_GETPW_R_SIZE_MAX);
if (bufsize == -1) {
bufsize = 16384;
}
char* buf = new char[static_cast<size_t>(bufsize)];
passwd* result = nullptr;
int getResult = getpwuid_r(getuid(), &pwd, buf, static_cast<size_t>(bufsize), &result);
if (getResult == 0) {
homeDir = pwd.pw_dir;
}
delete[] buf;
}
#elif defined(_WIN32)
if (char* cString = std::getenv("USERPROFILE")) {
homeDir = cString;
}
#endif
return homeDir;
}
} // namespace cesium::omniverse::FilesystemUtil
| 2,066 | C++ | 26.932432 | 98 | 0.617135 |
CesiumGS/cesium-omniverse/src/core/src/UsdUtil.cpp | #include "cesium/omniverse/UsdUtil.h"
#include "CesiumUsdSchemas/webMapServiceRasterOverlay.h"
#include "cesium/omniverse/AssetRegistry.h"
#include "cesium/omniverse/Context.h"
#include "cesium/omniverse/CppUtil.h"
#include "cesium/omniverse/MathUtil.h"
#include "cesium/omniverse/OmniData.h"
#include "cesium/omniverse/OmniGeoreference.h"
#include "cesium/omniverse/UsdScopedEdit.h"
#include "cesium/omniverse/UsdTokens.h"
#include "cesium/omniverse/Viewport.h"
#include <Cesium3DTilesSelection/ViewState.h>
#include <CesiumGeometry/Transforms.h>
#include <CesiumGeospatial/Cartographic.h>
#include <CesiumGeospatial/Ellipsoid.h>
#include <CesiumGeospatial/GlobeAnchor.h>
#include <CesiumGeospatial/GlobeTransforms.h>
#include <CesiumGeospatial/LocalHorizontalCoordinateSystem.h>
#include <CesiumUsdSchemas/data.h>
#include <CesiumUsdSchemas/georeference.h>
#include <CesiumUsdSchemas/globeAnchorAPI.h>
#include <CesiumUsdSchemas/ionRasterOverlay.h>
#include <CesiumUsdSchemas/ionServer.h>
#include <CesiumUsdSchemas/polygonRasterOverlay.h>
#include <CesiumUsdSchemas/session.h>
#include <CesiumUsdSchemas/tileMapServiceRasterOverlay.h>
#include <CesiumUsdSchemas/tileset.h>
#include <CesiumUsdSchemas/webMapServiceRasterOverlay.h>
#include <CesiumUsdSchemas/webMapTileServiceRasterOverlay.h>
#include <glm/gtc/matrix_access.hpp>
#include <glm/gtc/matrix_inverse.hpp>
#include <glm/gtc/matrix_transform.hpp>
#include <glm/gtc/quaternion.hpp>
#include <omni/ui/ImageProvider/DynamicTextureProvider.h>
#include <pxr/base/gf/rotation.h>
#include <pxr/usd/sdf/primSpec.h>
#include <pxr/usd/usd/prim.h>
#include <pxr/usd/usd/stage.h>
#include <pxr/usd/usd/timeCode.h>
#include <pxr/usd/usdGeom/metrics.h>
#include <pxr/usd/usdGeom/xform.h>
#include <pxr/usd/usdGeom/xformCommonAPI.h>
#include <pxr/usd/usdShade/material.h>
#include <pxr/usd/usdShade/shader.h>
#include <spdlog/fmt/fmt.h>
#include <cctype>
namespace cesium::omniverse::UsdUtil {
namespace {
bool getDebugDisableGeoreferencing(const Context& context) {
const auto pData = context.getAssetRegistry().getFirstData();
if (!pData) {
return false;
}
return pData->getDebugDisableGeoreferencing();
}
} // namespace
glm::dvec3 usdToGlmVector(const pxr::GfVec3d& vector) {
return {vector[0], vector[1], vector[2]};
}
glm::fvec3 usdToGlmVector(const pxr::GfVec3f& vector) {
return {vector[0], vector[1], vector[2]};
}
glm::dmat4 usdToGlmMatrix(const pxr::GfMatrix4d& matrix) {
// USD is row-major with left-to-right matrix multiplication
// glm is column-major with right-to-left matrix multiplication
// This means they have the same data layout
return {
matrix[0][0],
matrix[0][1],
matrix[0][2],
matrix[0][3],
matrix[1][0],
matrix[1][1],
matrix[1][2],
matrix[1][3],
matrix[2][0],
matrix[2][1],
matrix[2][2],
matrix[2][3],
matrix[3][0],
matrix[3][1],
matrix[3][2],
matrix[3][3],
};
}
glm::dquat usdToGlmQuat(const pxr::GfQuatd& quat) {
const auto real = quat.GetReal();
const auto imaginary = usdToGlmVector(quat.GetImaginary());
return {real, imaginary.x, imaginary.y, imaginary.z};
}
glm::fquat usdToGlmQuat(const pxr::GfQuatf& quat) {
const auto real = quat.GetReal();
const auto imaginary = usdToGlmVector(quat.GetImaginary());
return {real, imaginary.x, imaginary.y, imaginary.z};
}
std::array<glm::dvec3, 2> usdToGlmExtent(const pxr::GfRange3d& extent) {
return {{usdToGlmVector(extent.GetMin()), usdToGlmVector(extent.GetMax())}};
}
pxr::GfVec3d glmToUsdVector(const glm::dvec3& vector) {
return {vector.x, vector.y, vector.z};
}
pxr::GfVec2f glmToUsdVector(const glm::fvec2& vector) {
return {vector.x, vector.y};
}
pxr::GfVec3f glmToUsdVector(const glm::fvec3& vector) {
return {vector.x, vector.y, vector.z};
}
pxr::GfVec4f glmToUsdVector(const glm::fvec4& vector) {
return {vector.x, vector.y, vector.z, vector.w};
}
pxr::GfRange3d glmToUsdExtent(const std::array<glm::dvec3, 2>& extent) {
return {glmToUsdVector(extent[0]), glmToUsdVector(extent[1])};
}
pxr::GfQuatd glmToUsdQuat(const glm::dquat& quat) {
return {quat.w, quat.x, quat.y, quat.z};
}
pxr::GfQuatf glmToUsdQuat(const glm::fquat& quat) {
return {quat.w, quat.x, quat.y, quat.z};
}
pxr::GfMatrix4d glmToUsdMatrix(const glm::dmat4& matrix) {
// USD is row-major with left-to-right matrix multiplication
// glm is column-major with right-to-left matrix multiplication
// This means they have the same data layout
return pxr::GfMatrix4d{
matrix[0][0],
matrix[0][1],
matrix[0][2],
matrix[0][3],
matrix[1][0],
matrix[1][1],
matrix[1][2],
matrix[1][3],
matrix[2][0],
matrix[2][1],
matrix[2][2],
matrix[2][3],
matrix[3][0],
matrix[3][1],
matrix[3][2],
matrix[3][3],
};
}
glm::dmat4 computePrimLocalToWorldTransform(const pxr::UsdStageWeakPtr& pStage, const pxr::SdfPath& path) {
const auto prim = pStage->GetPrimAtPath(path);
const auto xform = pxr::UsdGeomXformable(prim);
if (!isSchemaValid(xform)) {
return glm::dmat4(1.0);
}
const auto time = pxr::UsdTimeCode::Default();
const auto transform = xform.ComputeLocalToWorldTransform(time);
return usdToGlmMatrix(transform);
}
glm::dmat4 computePrimWorldToLocalTransform(const pxr::UsdStageWeakPtr& pStage, const pxr::SdfPath& path) {
return glm::affineInverse(computePrimLocalToWorldTransform(pStage, path));
}
glm::dmat4 computeEcefToStageTransform(const Context& context, const pxr::SdfPath& georeferencePath) {
const auto disableGeoreferencing = getDebugDisableGeoreferencing(context);
const auto pGeoreference =
georeferencePath.IsEmpty() ? nullptr : context.getAssetRegistry().getGeoreference(georeferencePath);
if (disableGeoreferencing || !pGeoreference) {
const auto zUp = getUsdUpAxis(context.getUsdStage()) == pxr::UsdGeomTokens->z;
const auto axisConversion = zUp ? glm::dmat4(1.0) : CesiumGeometry::Transforms::Z_UP_TO_Y_UP;
const auto scale = glm::scale(glm::dmat4(1.0), glm::dvec3(1.0 / getUsdMetersPerUnit(context.getUsdStage())));
return scale * axisConversion;
}
return pGeoreference->getLocalCoordinateSystem().getEcefToLocalTransformation();
}
glm::dmat4 computeEcefToPrimWorldTransform(
const Context& context,
const pxr::SdfPath& georeferencePath,
const pxr::SdfPath& primPath) {
const auto ecefToStageTransform = computeEcefToStageTransform(context, georeferencePath);
const auto primLocalToWorldTransform = computePrimLocalToWorldTransform(context.getUsdStage(), primPath);
return primLocalToWorldTransform * ecefToStageTransform;
}
glm::dmat4 computePrimWorldToEcefTransform(
const Context& context,
const pxr::SdfPath& georeferencePath,
const pxr::SdfPath& primPath) {
return glm::affineInverse(computeEcefToPrimWorldTransform(context, georeferencePath, primPath));
}
glm::dmat4 computeEcefToPrimLocalTransform(
const Context& context,
const pxr::SdfPath& georeferencePath,
const pxr::SdfPath& primPath) {
const auto ecefToStageTransform = computeEcefToStageTransform(context, georeferencePath);
const auto primWorldToLocalTransform = computePrimWorldToLocalTransform(context.getUsdStage(), primPath);
return primWorldToLocalTransform * ecefToStageTransform;
}
glm::dmat4 computePrimLocalToEcefTransform(
const Context& context,
const pxr::SdfPath& georeferencePath,
const pxr::SdfPath& primPath) {
return glm::affineInverse(computeEcefToPrimLocalTransform(context, georeferencePath, primPath));
}
Cesium3DTilesSelection::ViewState computeViewState(
const Context& context,
const pxr::SdfPath& georeferencePath,
const pxr::SdfPath& primPath,
const Viewport& viewport) {
const auto& viewMatrix = viewport.viewMatrix;
const auto& projMatrix = viewport.projMatrix;
const auto width = viewport.width;
const auto height = viewport.height;
const auto primWorldToEcefTransform = computePrimWorldToEcefTransform(context, georeferencePath, primPath);
const auto inverseView = glm::affineInverse(viewMatrix);
const auto usdCameraUp = glm::dvec3(inverseView[1]);
const auto usdCameraFwd = glm::dvec3(-inverseView[2]);
const auto usdCameraPosition = glm::dvec3(inverseView[3]);
const auto cameraUp = glm::normalize(glm::dvec3(primWorldToEcefTransform * glm::dvec4(usdCameraUp, 0.0)));
const auto cameraFwd = glm::normalize(glm::dvec3(primWorldToEcefTransform * glm::dvec4(usdCameraFwd, 0.0)));
const auto cameraPosition = glm::dvec3(primWorldToEcefTransform * glm::dvec4(usdCameraPosition, 1.0));
const auto aspect = width / height;
const auto verticalFov = 2.0 * glm::atan(1.0 / projMatrix[1][1]);
const auto horizontalFov = 2.0 * glm::atan(glm::tan(verticalFov * 0.5) * aspect);
return Cesium3DTilesSelection::ViewState::create(
cameraPosition, cameraFwd, cameraUp, glm::dvec2(width, height), horizontalFov, verticalFov);
}
bool primExists(const pxr::UsdStageWeakPtr& pStage, const pxr::SdfPath& path) {
return pStage->GetPrimAtPath(path).IsValid();
}
bool isSchemaValid(const pxr::UsdSchemaBase& schema) {
return schema.GetPrim().IsValid() && schema.GetSchemaKind() != pxr::UsdSchemaKind::Invalid;
}
bool isPrimVisible(const pxr::UsdStageWeakPtr& pStage, const pxr::SdfPath& path) {
// This is similar to isPrimVisible in kit-sdk/dev/include/omni/usd/UsdUtils.h
const auto prim = pStage->GetPrimAtPath(path);
const auto imageable = pxr::UsdGeomImageable(prim);
if (!isSchemaValid(imageable)) {
return false;
}
const auto time = pxr::UsdTimeCode::Default();
const auto visibility = imageable.ComputeVisibility(time);
return visibility != pxr::UsdGeomTokens->invisible;
}
const std::string& getName(const pxr::UsdStageWeakPtr& pStage, const pxr::SdfPath& path) {
return pStage->GetPrimAtPath(path).GetName().GetString();
}
pxr::TfToken getUsdUpAxis(const pxr::UsdStageWeakPtr& pStage) {
return pxr::UsdGeomGetStageUpAxis(pStage);
}
double getUsdMetersPerUnit(const pxr::UsdStageWeakPtr& pStage) {
return pxr::UsdGeomGetStageMetersPerUnit(pStage);
}
pxr::SdfPath getRootPath(const pxr::UsdStageWeakPtr& pStage) {
return pStage->GetPseudoRoot().GetPath();
}
pxr::SdfPath
makeUniquePath(const pxr::UsdStageWeakPtr& pStage, const pxr::SdfPath& parentPath, const std::string& name) {
pxr::UsdPrim prim;
pxr::SdfPath path;
auto copy = 0;
do {
const auto copyName = copy > 0 ? fmt::format("{}_{}", name, copy) : name;
path = parentPath.AppendChild(pxr::TfToken(copyName));
prim = pStage->GetPrimAtPath(path);
++copy;
} while (prim.IsValid());
return path;
}
std::string getSafeName(const std::string& name) {
auto safeName = name;
for (auto& c : safeName) {
if (!std::isalnum(c)) {
c = '_';
}
}
return safeName;
}
pxr::TfToken getDynamicTextureProviderAssetPathToken(const std::string_view& name) {
return pxr::TfToken(pxr::SdfAssetPath(fmt::format("dynamic://{}", name)).GetAssetPath());
}
pxr::CesiumData defineCesiumData(const pxr::UsdStageWeakPtr& pStage, const pxr::SdfPath& path) {
return pxr::CesiumData::Define(pStage, path);
}
pxr::CesiumTileset defineCesiumTileset(const pxr::UsdStageWeakPtr& pStage, const pxr::SdfPath& path) {
return pxr::CesiumTileset::Define(pStage, path);
}
pxr::CesiumIonRasterOverlay defineCesiumIonRasterOverlay(const pxr::UsdStageWeakPtr& pStage, const pxr::SdfPath& path) {
return pxr::CesiumIonRasterOverlay::Define(pStage, path);
}
pxr::CesiumPolygonRasterOverlay
defineCesiumPolygonRasterOverlay(const pxr::UsdStageWeakPtr& pStage, const pxr::SdfPath& path) {
return pxr::CesiumPolygonRasterOverlay::Define(pStage, path);
}
pxr::CesiumGeoreference defineCesiumGeoreference(const pxr::UsdStageWeakPtr& pStage, const pxr::SdfPath& path) {
return pxr::CesiumGeoreference::Define(pStage, path);
}
pxr::CesiumIonServer defineCesiumIonServer(const pxr::UsdStageWeakPtr& pStage, const pxr::SdfPath& path) {
return pxr::CesiumIonServer::Define(pStage, path);
}
pxr::CesiumGlobeAnchorAPI applyCesiumGlobeAnchor(const pxr::UsdStageWeakPtr& pStage, const pxr::SdfPath& path) {
const auto prim = pStage->GetPrimAtPath(path);
assert(prim.IsValid() && prim.IsA<pxr::UsdGeomXformable>());
return pxr::CesiumGlobeAnchorAPI::Apply(prim);
}
pxr::CesiumSession defineCesiumSession(const pxr::UsdStageWeakPtr& pStage, const pxr::SdfPath& path) {
return pxr::CesiumSession::Define(pStage, path);
}
pxr::CesiumData getCesiumData(const pxr::UsdStageWeakPtr& pStage, const pxr::SdfPath& path) {
return pxr::CesiumData::Get(pStage, path);
}
pxr::CesiumTileset getCesiumTileset(const pxr::UsdStageWeakPtr& pStage, const pxr::SdfPath& path) {
return pxr::CesiumTileset::Get(pStage, path);
}
pxr::CesiumRasterOverlay getCesiumRasterOverlay(const pxr::UsdStageWeakPtr& pStage, const pxr::SdfPath& path) {
return pxr::CesiumRasterOverlay::Get(pStage, path);
}
pxr::CesiumIonRasterOverlay getCesiumIonRasterOverlay(const pxr::UsdStageWeakPtr& pStage, const pxr::SdfPath& path) {
return pxr::CesiumIonRasterOverlay::Get(pStage, path);
}
pxr::CesiumPolygonRasterOverlay
getCesiumPolygonRasterOverlay(const pxr::UsdStageWeakPtr& pStage, const pxr::SdfPath& path) {
return pxr::CesiumPolygonRasterOverlay::Get(pStage, path);
}
pxr::CesiumWebMapServiceRasterOverlay
getCesiumWebMapServiceRasterOverlay(const pxr::UsdStageWeakPtr& pStage, const pxr::SdfPath& path) {
return pxr::CesiumWebMapServiceRasterOverlay::Get(pStage, path);
}
pxr::CesiumTileMapServiceRasterOverlay
getCesiumTileMapServiceRasterOverlay(const pxr::UsdStageWeakPtr& pStage, const pxr::SdfPath& path) {
return pxr::CesiumTileMapServiceRasterOverlay::Get(pStage, path);
}
pxr::CesiumWebMapTileServiceRasterOverlay
getCesiumWebMapTileServiceRasterOverlay(const pxr::UsdStageWeakPtr& pStage, const pxr::SdfPath& path) {
return pxr::CesiumWebMapTileServiceRasterOverlay::Get(pStage, path);
}
pxr::CesiumGeoreference getCesiumGeoreference(const pxr::UsdStageWeakPtr& pStage, const pxr::SdfPath& path) {
return pxr::CesiumGeoreference::Get(pStage, path);
}
pxr::CesiumGlobeAnchorAPI getCesiumGlobeAnchor(const pxr::UsdStageWeakPtr& pStage, const pxr::SdfPath& path) {
return pxr::CesiumGlobeAnchorAPI::Get(pStage, path);
}
pxr::CesiumIonServer getCesiumIonServer(const pxr::UsdStageWeakPtr& pStage, const pxr::SdfPath& path) {
return pxr::CesiumIonServer::Get(pStage, path);
}
// This is currently a pass-through to getUsdBasisCurves until
// issue with crashes in prims that inherit from BasisCurves is resolved
pxr::UsdGeomBasisCurves getCesiumCartographicPolygon(const pxr::UsdStageWeakPtr& pStage, const pxr::SdfPath& path) {
return getUsdBasisCurves(pStage, path);
}
pxr::UsdShadeShader getUsdShader(const pxr::UsdStageWeakPtr& pStage, const pxr::SdfPath& path) {
return pxr::UsdShadeShader::Get(pStage, path);
}
pxr::UsdGeomBasisCurves getUsdBasisCurves(const pxr::UsdStageWeakPtr& pStage, const pxr::SdfPath& path) {
return pxr::UsdGeomBasisCurves::Get(pStage, path);
}
pxr::CesiumSession getOrCreateCesiumSession(const pxr::UsdStageWeakPtr& pStage) {
static const auto CesiumSessionPath = pxr::SdfPath("/CesiumSession");
if (isCesiumSession(pStage, CesiumSessionPath)) {
return pxr::CesiumSession::Get(pStage, CesiumSessionPath);
}
// Ensures that CesiumSession is created in the session layer
const UsdScopedEdit scopedEdit(pStage);
// Create the CesiumSession
const auto cesiumSession = defineCesiumSession(pStage, CesiumSessionPath);
// Prevent CesiumSession from being traversed and composed into the stage
cesiumSession.GetPrim().SetActive(false);
return cesiumSession;
}
bool isCesiumData(const pxr::UsdStageWeakPtr& pStage, const pxr::SdfPath& path) {
const auto prim = pStage->GetPrimAtPath(path);
if (!prim.IsValid()) {
return false;
}
return prim.IsA<pxr::CesiumData>();
}
bool isCesiumTileset(const pxr::UsdStageWeakPtr& pStage, const pxr::SdfPath& path) {
const auto prim = pStage->GetPrimAtPath(path);
if (!prim.IsValid()) {
return false;
}
return prim.IsA<pxr::CesiumTileset>();
}
bool isCesiumRasterOverlay(const pxr::UsdStageWeakPtr& pStage, const pxr::SdfPath& path) {
const auto prim = pStage->GetPrimAtPath(path);
if (!prim.IsValid()) {
return false;
}
return prim.IsA<pxr::CesiumRasterOverlay>();
}
bool isCesiumIonRasterOverlay(const pxr::UsdStageWeakPtr& pStage, const pxr::SdfPath& path) {
const auto prim = pStage->GetPrimAtPath(path);
if (!prim.IsValid()) {
return false;
}
return prim.IsA<pxr::CesiumIonRasterOverlay>();
}
bool isCesiumPolygonRasterOverlay(const pxr::UsdStageWeakPtr& pStage, const pxr::SdfPath& path) {
const auto prim = pStage->GetPrimAtPath(path);
if (!prim.IsValid()) {
return false;
}
return prim.IsA<pxr::CesiumPolygonRasterOverlay>();
}
bool isCesiumWebMapServiceRasterOverlay(const pxr::UsdStageWeakPtr& pStage, const pxr::SdfPath& path) {
const auto prim = pStage->GetPrimAtPath(path);
if (!prim.IsValid()) {
return false;
}
return prim.IsA<pxr::CesiumWebMapServiceRasterOverlay>();
}
bool isCesiumTileMapServiceRasterOverlay(const pxr::UsdStageWeakPtr& pStage, const pxr::SdfPath& path) {
const auto prim = pStage->GetPrimAtPath(path);
if (!prim.IsValid()) {
return false;
}
return prim.IsA<pxr::CesiumTileMapServiceRasterOverlay>();
}
bool isCesiumWebMapTileServiceRasterOverlay(const pxr::UsdStageWeakPtr& pStage, const pxr::SdfPath& path) {
const auto prim = pStage->GetPrimAtPath(path);
if (!prim.IsValid()) {
return false;
}
return prim.IsA<pxr::CesiumWebMapTileServiceRasterOverlay>();
}
bool isCesiumGeoreference(const pxr::UsdStageWeakPtr& pStage, const pxr::SdfPath& path) {
const auto prim = pStage->GetPrimAtPath(path);
if (!prim.IsValid()) {
return false;
}
return prim.IsA<pxr::CesiumGeoreference>();
}
bool isCesiumIonServer(const pxr::UsdStageWeakPtr& pStage, const pxr::SdfPath& path) {
const auto prim = pStage->GetPrimAtPath(path);
if (!prim.IsValid()) {
return false;
}
return prim.IsA<pxr::CesiumIonServer>();
}
bool isCesiumCartographicPolygon(const pxr::UsdStageWeakPtr& pStage, const pxr::SdfPath& path) {
const auto prim = pStage->GetPrimAtPath(path);
if (!prim.IsValid()) {
return false;
}
if (!prim.IsA<pxr::UsdGeomBasisCurves>()) {
return false;
}
return prim.HasAPI<pxr::CesiumGlobeAnchorAPI>();
}
bool isCesiumSession(const pxr::UsdStageWeakPtr& pStage, const pxr::SdfPath& path) {
const auto prim = pStage->GetPrimAtPath(path);
if (!prim.IsValid()) {
return false;
}
return prim.IsA<pxr::CesiumSession>();
}
bool hasCesiumGlobeAnchor(const pxr::UsdStageWeakPtr& pStage, const pxr::SdfPath& path) {
const auto prim = pStage->GetPrimAtPath(path);
if (!prim.IsValid()) {
return false;
}
return prim.IsA<pxr::UsdGeomXformable>() && prim.HasAPI<pxr::CesiumGlobeAnchorAPI>();
}
bool isUsdShader(const pxr::UsdStageWeakPtr& pStage, const pxr::SdfPath& path) {
const auto prim = pStage->GetPrimAtPath(path);
if (!prim.IsValid()) {
return false;
}
return prim.IsA<pxr::UsdShadeShader>();
}
bool isUsdMaterial(const pxr::UsdStageWeakPtr& pStage, const pxr::SdfPath& path) {
const auto prim = pStage->GetPrimAtPath(path);
if (!prim.IsValid()) {
return false;
}
return prim.IsA<pxr::UsdShadeMaterial>();
}
glm::dvec3 getTranslate(const pxr::UsdGeomXformOp& translateOp) {
if (translateOp.GetPrecision() == pxr::UsdGeomXformOp::PrecisionDouble) {
pxr::GfVec3d translation;
translateOp.Get(&translation);
return UsdUtil::usdToGlmVector(translation);
} else if (translateOp.GetPrecision() == pxr::UsdGeomXformOp::PrecisionFloat) {
pxr::GfVec3f translation;
translateOp.Get(&translation);
return glm::dvec3(UsdUtil::usdToGlmVector(translation));
}
return glm::dvec3(0.0);
}
glm::dvec3 getRotate(const pxr::UsdGeomXformOp& rotateOp) {
if (rotateOp.GetPrecision() == pxr::UsdGeomXformOp::PrecisionDouble) {
pxr::GfVec3d rotation;
rotateOp.Get(&rotation);
return UsdUtil::usdToGlmVector(rotation);
} else if (rotateOp.GetPrecision() == pxr::UsdGeomXformOp::PrecisionFloat) {
pxr::GfVec3f rotation;
rotateOp.Get(&rotation);
return glm::dvec3(UsdUtil::usdToGlmVector(rotation));
}
return glm::dvec3(0.0);
}
glm::dquat getOrient(const pxr::UsdGeomXformOp& orientOp) {
if (orientOp.GetPrecision() == pxr::UsdGeomXformOp::PrecisionDouble) {
pxr::GfQuatd orient;
orientOp.Get(&orient);
return UsdUtil::usdToGlmQuat(orient);
} else if (orientOp.GetPrecision() == pxr::UsdGeomXformOp::PrecisionFloat) {
pxr::GfQuatf orient;
orientOp.Get(&orient);
return glm::dquat(UsdUtil::usdToGlmQuat(orient));
}
return {1.0, 0.0, 0.0, 0.0};
}
glm::dvec3 getScale(const pxr::UsdGeomXformOp& scaleOp) {
if (scaleOp.GetPrecision() == pxr::UsdGeomXformOp::PrecisionDouble) {
pxr::GfVec3d scale;
scaleOp.Get(&scale);
return UsdUtil::usdToGlmVector(scale);
} else if (scaleOp.GetPrecision() == pxr::UsdGeomXformOp::PrecisionFloat) {
pxr::GfVec3f scale;
scaleOp.Get(&scale);
return glm::dvec3(UsdUtil::usdToGlmVector(scale));
}
return glm::dvec3(1.0);
}
void setTranslate(pxr::UsdGeomXformOp& translateOp, const glm::dvec3& translate) {
if (translateOp.GetPrecision() == pxr::UsdGeomXformOp::PrecisionDouble) {
translateOp.Set(UsdUtil::glmToUsdVector(translate));
} else if (translateOp.GetPrecision() == pxr::UsdGeomXformOp::PrecisionFloat) {
translateOp.Set(UsdUtil::glmToUsdVector(glm::fvec3(translate)));
}
}
void setRotate(pxr::UsdGeomXformOp& rotateOp, const glm::dvec3& rotate) {
if (rotateOp.GetPrecision() == pxr::UsdGeomXformOp::PrecisionDouble) {
rotateOp.Set(UsdUtil::glmToUsdVector(rotate));
} else if (rotateOp.GetPrecision() == pxr::UsdGeomXformOp::PrecisionFloat) {
rotateOp.Set(UsdUtil::glmToUsdVector(glm::fvec3(rotate)));
}
}
void setOrient(pxr::UsdGeomXformOp& orientOp, const glm::dquat& orient) {
if (orientOp.GetPrecision() == pxr::UsdGeomXformOp::PrecisionDouble) {
orientOp.Set(UsdUtil::glmToUsdQuat(orient));
} else if (orientOp.GetPrecision() == pxr::UsdGeomXformOp::PrecisionFloat) {
orientOp.Set(UsdUtil::glmToUsdQuat(glm::fquat(orient)));
}
}
void setScale(pxr::UsdGeomXformOp& scaleOp, const glm::dvec3& scale) {
if (scaleOp.GetPrecision() == pxr::UsdGeomXformOp::PrecisionDouble) {
scaleOp.Set(UsdUtil::glmToUsdVector(scale));
} else if (scaleOp.GetPrecision() == pxr::UsdGeomXformOp::PrecisionFloat) {
scaleOp.Set(UsdUtil::glmToUsdVector(glm::fvec3(scale)));
}
}
std::optional<TranslateRotateScaleOps> getOrCreateTranslateRotateScaleOps(const pxr::UsdGeomXformable& xformable) {
pxr::UsdGeomXformOp translateOp;
pxr::UsdGeomXformOp rotateOp;
pxr::UsdGeomXformOp orientOp;
pxr::UsdGeomXformOp scaleOp;
int64_t translateOpIndex = -1;
int64_t rotateOpIndex = -1;
int64_t orientOpIndex = -1;
int64_t scaleOpIndex = -1;
int64_t opCount = 0;
bool resetsXformStack;
const auto xformOps = xformable.GetOrderedXformOps(&resetsXformStack);
auto eulerAngleOrder = MathUtil::EulerAngleOrder::XYZ;
for (const auto& xformOp : xformOps) {
switch (xformOp.GetOpType()) {
case pxr::UsdGeomXformOp::TypeTranslate:
if (translateOpIndex == -1) {
translateOp = xformOp;
translateOpIndex = opCount;
}
break;
case pxr::UsdGeomXformOp::TypeRotateXYZ:
if (rotateOpIndex == -1) {
eulerAngleOrder = MathUtil::EulerAngleOrder::XYZ;
rotateOp = xformOp;
rotateOpIndex = opCount;
}
break;
case pxr::UsdGeomXformOp::TypeRotateXZY:
if (rotateOpIndex == -1) {
eulerAngleOrder = MathUtil::EulerAngleOrder::XZY;
rotateOp = xformOp;
rotateOpIndex = opCount;
}
break;
case pxr::UsdGeomXformOp::TypeRotateYXZ:
if (rotateOpIndex == -1) {
eulerAngleOrder = MathUtil::EulerAngleOrder::YXZ;
rotateOp = xformOp;
rotateOpIndex = opCount;
}
break;
case pxr::UsdGeomXformOp::TypeRotateYZX:
if (rotateOpIndex == -1) {
eulerAngleOrder = MathUtil::EulerAngleOrder::YZX;
rotateOp = xformOp;
rotateOpIndex = opCount;
}
break;
case pxr::UsdGeomXformOp::TypeRotateZXY:
if (rotateOpIndex == -1) {
eulerAngleOrder = MathUtil::EulerAngleOrder::ZXY;
rotateOp = xformOp;
rotateOpIndex = opCount;
}
break;
case pxr::UsdGeomXformOp::TypeRotateZYX:
if (rotateOpIndex == -1) {
eulerAngleOrder = MathUtil::EulerAngleOrder::ZYX;
rotateOp = xformOp;
rotateOpIndex = opCount;
}
break;
case pxr::UsdGeomXformOp::TypeOrient:
if (orientOpIndex == -1) {
orientOp = xformOp;
orientOpIndex = opCount;
}
break;
case pxr::UsdGeomXformOp::TypeScale:
if (scaleOpIndex == -1) {
scaleOp = xformOp;
scaleOpIndex = opCount;
}
break;
default:
break;
}
++opCount;
}
const auto translateOpDefined = translateOp.IsDefined();
const auto rotateOpDefined = rotateOp.IsDefined();
const auto orientOpDefined = orientOp.IsDefined();
const auto scaleOpDefined = scaleOp.IsDefined();
if (rotateOpDefined && orientOpDefined) {
return std::nullopt;
}
opCount = 0;
if (translateOpDefined && translateOpIndex != opCount++) {
return std::nullopt;
}
if (rotateOpDefined && rotateOpIndex != opCount++) {
return std::nullopt;
}
if (orientOpDefined && orientOpIndex != opCount++) {
return std::nullopt;
}
if (scaleOpDefined && scaleOpIndex != opCount++) {
return std::nullopt;
}
const auto isPrecisionSupported = [](pxr::UsdGeomXformOp::Precision precision) {
return precision == pxr::UsdGeomXformOp::PrecisionDouble || precision == pxr::UsdGeomXformOp::PrecisionFloat;
};
if (translateOpDefined && !isPrecisionSupported(translateOp.GetPrecision())) {
return std::nullopt;
}
if (rotateOpDefined && !isPrecisionSupported(rotateOp.GetPrecision())) {
return std::nullopt;
}
if (orientOpDefined && !isPrecisionSupported(orientOp.GetPrecision())) {
return std::nullopt;
}
if (scaleOpDefined && !isPrecisionSupported(scaleOp.GetPrecision())) {
return std::nullopt;
}
if (!translateOpDefined) {
translateOp = xformable.AddTranslateOp(pxr::UsdGeomXformOp::PrecisionDouble);
translateOp.Set(UsdUtil::glmToUsdVector(glm::dvec3(0.0)));
}
if (!rotateOpDefined && !orientOpDefined) {
rotateOp = xformable.AddRotateXYZOp(pxr::UsdGeomXformOp::PrecisionDouble);
rotateOp.Set(UsdUtil::glmToUsdVector(glm::dvec3(0.0)));
}
if (!scaleOpDefined) {
scaleOp = xformable.AddScaleOp(pxr::UsdGeomXformOp::PrecisionDouble);
scaleOp.Set(UsdUtil::glmToUsdVector(glm::dvec3(1.0)));
}
if (!translateOpDefined || (!rotateOpDefined && !orientOpDefined) || !scaleOpDefined) {
std::vector<pxr::UsdGeomXformOp> reorderedXformOps;
if (orientOpDefined) {
reorderedXformOps = {translateOp, orientOp, scaleOp};
} else {
reorderedXformOps = {translateOp, rotateOp, scaleOp};
}
// Add back additional xform ops like xformOp:rotateX:unitsResolve
reorderedXformOps.insert(reorderedXformOps.end(), xformOps.begin() + opCount, xformOps.end());
xformable.SetXformOpOrder(reorderedXformOps);
}
if (orientOpDefined) {
return TranslateRotateScaleOps{translateOp, orientOp, scaleOp, eulerAngleOrder};
}
return TranslateRotateScaleOps{translateOp, rotateOp, scaleOp, eulerAngleOrder};
}
} // namespace cesium::omniverse::UsdUtil
| 29,345 | C++ | 33.935714 | 120 | 0.684376 |
CesiumGS/cesium-omniverse/src/core/src/Broadcast.cpp | #include "cesium/omniverse/Broadcast.h"
#include <omni/kit/IApp.h>
#include <pxr/usd/sdf/path.h>
namespace cesium::omniverse::Broadcast {
namespace {
const std::string_view ASSETS_UPDATED_EVENT_KEY = "cesium.omniverse.ASSETS_UPDATED";
const std::string_view CONNECTION_UPDATED_EVENT_KEY = "cesium.omniverse.CONNECTION_UPDATED";
const std::string_view PROFILE_UPDATED_EVENT_KEY = "cesium.omniverse.PROFILE_UPDATED";
const std::string_view TOKENS_UPDATED_EVENT_KEY = "cesium.omniverse.TOKENS_UPDATED";
const std::string_view SHOW_TROUBLESHOOTER_EVENT_KEY = "cesium.omniverse.SHOW_TROUBLESHOOTER";
const std::string_view SET_DEFAULT_PROJECT_TOKEN_COMPLETE_KEY = "cesium.omniverse.SET_DEFAULT_PROJECT_TOKEN_COMPLETE";
const std::string_view TILESET_LOADED_KEY = "cesium.omniverse.TILESET_LOADED";
template <typename... ValuesT>
void sendMessageToBusWithPayload(carb::events::EventType eventType, ValuesT&&... payload) {
const auto iApp = carb::getCachedInterface<omni::kit::IApp>();
const auto bus = iApp->getMessageBusEventStream();
bus->push(eventType, std::forward<ValuesT>(payload)...);
}
template <typename... ValuesT>
void sendMessageToBusWithPayload(const std::string_view& eventKey, ValuesT&&... payload) {
const auto eventType = carb::events::typeFromString(eventKey.data());
sendMessageToBusWithPayload(eventType, std::forward<ValuesT>(payload)...);
}
} // namespace
void assetsUpdated() {
sendMessageToBus(ASSETS_UPDATED_EVENT_KEY);
}
void connectionUpdated() {
sendMessageToBus(CONNECTION_UPDATED_EVENT_KEY);
}
void profileUpdated() {
sendMessageToBus(PROFILE_UPDATED_EVENT_KEY);
}
void tokensUpdated() {
sendMessageToBus(TOKENS_UPDATED_EVENT_KEY);
}
void showTroubleshooter(
const pxr::SdfPath& tilesetPath,
int64_t tilesetIonAssetId,
const std::string& tilesetName,
int64_t rasterOverlayIonAssetId,
const std::string& rasterOverlayName,
const std::string& message) {
sendMessageToBusWithPayload(
SHOW_TROUBLESHOOTER_EVENT_KEY,
std::make_pair("tilesetPath", tilesetPath.GetText()),
std::make_pair("tilesetIonAssetId", tilesetIonAssetId),
std::make_pair("tilesetName", tilesetName.c_str()),
std::make_pair("rasterOverlayIonAssetId", rasterOverlayIonAssetId),
std::make_pair("rasterOverlayName", rasterOverlayName.c_str()),
std::make_pair("message", message.c_str()));
}
void setDefaultTokenComplete() {
sendMessageToBus(SET_DEFAULT_PROJECT_TOKEN_COMPLETE_KEY);
}
void tilesetLoaded(const pxr::SdfPath& tilesetPath) {
sendMessageToBusWithPayload(TILESET_LOADED_KEY, std::make_pair("tilesetPath", tilesetPath.GetText()));
}
void sendMessageToBus(carb::events::EventType eventType) {
const auto iApp = carb::getCachedInterface<omni::kit::IApp>();
const auto bus = iApp->getMessageBusEventStream();
bus->push(eventType);
}
void sendMessageToBus(const std::string_view& eventKey) {
const auto eventType = carb::events::typeFromString(eventKey.data());
sendMessageToBus(eventType);
}
} // namespace cesium::omniverse::Broadcast
| 3,094 | C++ | 35.411764 | 118 | 0.739819 |
CesiumGS/cesium-omniverse/src/core/src/OmniWebMapServiceRasterOverlay.cpp | #include "cesium/omniverse/OmniWebMapServiceRasterOverlay.h"
#include "cesium/omniverse/AssetRegistry.h"
#include "cesium/omniverse/Context.h"
#include "cesium/omniverse/GltfUtil.h"
#include "cesium/omniverse/Logger.h"
#include "cesium/omniverse/OmniGeoreference.h"
#include "cesium/omniverse/UsdUtil.h"
#include <CesiumRasterOverlays/WebMapServiceRasterOverlay.h>
#include <CesiumUsdSchemas/webMapServiceRasterOverlay.h>
namespace cesium::omniverse {
OmniWebMapServiceRasterOverlay::OmniWebMapServiceRasterOverlay(Context* pContext, const pxr::SdfPath& path)
: OmniRasterOverlay(pContext, path) {
reload();
}
CesiumRasterOverlays::RasterOverlay* OmniWebMapServiceRasterOverlay::getRasterOverlay() const {
return _pWebMapServiceRasterOverlay.get();
}
std::string OmniWebMapServiceRasterOverlay::getBaseUrl() const {
const auto cesiumWebMapServiceRasterOverlay =
UsdUtil::getCesiumWebMapServiceRasterOverlay(_pContext->getUsdStage(), _path);
if (!UsdUtil::isSchemaValid(cesiumWebMapServiceRasterOverlay)) {
return "";
}
std::string baseUrl;
cesiumWebMapServiceRasterOverlay.GetBaseUrlAttr().Get(&baseUrl);
return baseUrl;
}
int OmniWebMapServiceRasterOverlay::getMinimumLevel() const {
const auto cesiumWebMapServiceRasterOverlay =
UsdUtil::getCesiumWebMapServiceRasterOverlay(_pContext->getUsdStage(), _path);
if (!UsdUtil::isSchemaValid(cesiumWebMapServiceRasterOverlay)) {
return 0;
}
int minimumLevel;
cesiumWebMapServiceRasterOverlay.GetMinimumLevelAttr().Get(&minimumLevel);
return minimumLevel;
}
int OmniWebMapServiceRasterOverlay::getMaximumLevel() const {
const auto cesiumWebMapServiceRasterOverlay =
UsdUtil::getCesiumWebMapServiceRasterOverlay(_pContext->getUsdStage(), _path);
if (!UsdUtil::isSchemaValid(cesiumWebMapServiceRasterOverlay)) {
return 14;
}
int maximumLevel;
cesiumWebMapServiceRasterOverlay.GetMaximumLevelAttr().Get(&maximumLevel);
return maximumLevel;
}
int OmniWebMapServiceRasterOverlay::getTileWidth() const {
const auto cesiumWebMapServiceRasterOverlay =
UsdUtil::getCesiumWebMapServiceRasterOverlay(_pContext->getUsdStage(), _path);
if (!UsdUtil::isSchemaValid(cesiumWebMapServiceRasterOverlay)) {
return 256;
}
int tileWidth;
cesiumWebMapServiceRasterOverlay.GetTileWidthAttr().Get(&tileWidth);
return tileWidth;
}
int OmniWebMapServiceRasterOverlay::getTileHeight() const {
const auto cesiumWebMapServiceRasterOverlay =
UsdUtil::getCesiumWebMapServiceRasterOverlay(_pContext->getUsdStage(), _path);
if (!UsdUtil::isSchemaValid(cesiumWebMapServiceRasterOverlay)) {
return 256;
}
int tileHeight;
cesiumWebMapServiceRasterOverlay.GetTileHeightAttr().Get(&tileHeight);
return tileHeight;
}
std::string OmniWebMapServiceRasterOverlay::getLayers() const {
const auto cesiumWebMapServiceRasterOverlay =
UsdUtil::getCesiumWebMapServiceRasterOverlay(_pContext->getUsdStage(), _path);
if (!UsdUtil::isSchemaValid(cesiumWebMapServiceRasterOverlay)) {
return "1";
}
std::string layers;
cesiumWebMapServiceRasterOverlay.GetLayersAttr().Get(&layers);
return layers;
}
void OmniWebMapServiceRasterOverlay::reload() {
const auto rasterOverlayName = UsdUtil::getName(_pContext->getUsdStage(), _path);
auto options = createRasterOverlayOptions();
options.loadErrorCallback = [this](const CesiumRasterOverlays::RasterOverlayLoadFailureDetails& error) {
_pContext->getLogger()->error(error.message);
};
CesiumRasterOverlays::WebMapServiceRasterOverlayOptions wmsOptions;
const auto minimumLevel = getMinimumLevel();
const auto maximumLevel = getMaximumLevel();
const auto tileWidth = getTileWidth();
const auto tileHeight = getTileHeight();
std::string layers = getLayers();
wmsOptions.minimumLevel = minimumLevel;
wmsOptions.maximumLevel = maximumLevel;
wmsOptions.layers = layers;
wmsOptions.tileWidth = tileWidth;
wmsOptions.tileHeight = tileHeight;
_pWebMapServiceRasterOverlay = new CesiumRasterOverlays::WebMapServiceRasterOverlay(
rasterOverlayName, getBaseUrl(), std::vector<CesiumAsync::IAssetAccessor::THeader>(), wmsOptions, options);
}
} // namespace cesium::omniverse
| 4,354 | C++ | 34.406504 | 115 | 0.758842 |
CesiumGS/cesium-omniverse/src/core/src/OmniPolygonRasterOverlay.cpp | #include "cesium/omniverse/OmniPolygonRasterOverlay.h"
#include "cesium/omniverse/AssetRegistry.h"
#include "cesium/omniverse/Context.h"
#include "cesium/omniverse/GltfUtil.h"
#include "cesium/omniverse/Logger.h"
#include "cesium/omniverse/OmniCartographicPolygon.h"
#include "cesium/omniverse/OmniGeoreference.h"
#include "cesium/omniverse/OmniGlobeAnchor.h"
#include "cesium/omniverse/UsdUtil.h"
#include <CesiumGeospatial/Ellipsoid.h>
#include <CesiumRasterOverlays/RasterizedPolygonsOverlay.h>
#include <CesiumUsdSchemas/polygonRasterOverlay.h>
namespace cesium::omniverse {
OmniPolygonRasterOverlay::OmniPolygonRasterOverlay(Context* pContext, const pxr::SdfPath& path)
: OmniRasterOverlay(pContext, path) {}
std::vector<pxr::SdfPath> OmniPolygonRasterOverlay::getCartographicPolygonPaths() const {
const auto cesiumPolygonRasterOverlay = UsdUtil::getCesiumPolygonRasterOverlay(_pContext->getUsdStage(), _path);
if (!UsdUtil::isSchemaValid(cesiumPolygonRasterOverlay)) {
return {};
}
pxr::SdfPathVector targets;
cesiumPolygonRasterOverlay.GetCartographicPolygonBindingRel().GetForwardedTargets(&targets);
return targets;
}
CesiumRasterOverlays::RasterOverlay* OmniPolygonRasterOverlay::getRasterOverlay() const {
return _pPolygonRasterOverlay.get();
}
bool OmniPolygonRasterOverlay::getInvertSelection() const {
const auto cesiumPolygonRasterOverlay = UsdUtil::getCesiumPolygonRasterOverlay(_pContext->getUsdStage(), _path);
if (!UsdUtil::isSchemaValid(cesiumPolygonRasterOverlay)) {
return false;
}
bool invertSelection;
cesiumPolygonRasterOverlay.GetInvertSelectionAttr().Get(&invertSelection);
return invertSelection;
}
bool OmniPolygonRasterOverlay::getExcludeSelectedTiles() const {
auto cesiumPolygonRasterOverlay = UsdUtil::getCesiumPolygonRasterOverlay(_pContext->getUsdStage(), _path);
bool val;
cesiumPolygonRasterOverlay.GetExcludeSelectedTilesAttr().Get(&val);
return val;
}
std::shared_ptr<Cesium3DTilesSelection::RasterizedPolygonsTileExcluder> OmniPolygonRasterOverlay::getExcluder() {
return _pExcluder;
}
void OmniPolygonRasterOverlay::reload() {
const auto rasterOverlayName = UsdUtil::getName(_pContext->getUsdStage(), _path);
const auto cartographicPolygonPaths = getCartographicPolygonPaths();
std::vector<CesiumGeospatial::CartographicPolygon> polygons;
const CesiumGeospatial::Ellipsoid* pEllipsoid = nullptr;
for (const auto& cartographicPolygonPath : cartographicPolygonPaths) {
const auto pCartographicPolygon = _pContext->getAssetRegistry().getCartographicPolygon(cartographicPolygonPath);
if (!pCartographicPolygon) {
continue;
}
const auto pGlobeAnchor = _pContext->getAssetRegistry().getGlobeAnchor(cartographicPolygonPath);
if (!pGlobeAnchor) {
continue;
}
const auto georeferencePath = pGlobeAnchor->getResolvedGeoreferencePath();
if (georeferencePath.IsEmpty()) {
continue;
}
const auto pGeoreference = _pContext->getAssetRegistry().getGeoreference(georeferencePath);
if (!pGeoreference) {
continue;
}
const auto& ellipsoid = pGeoreference->getEllipsoid();
if (!pEllipsoid) {
pEllipsoid = &ellipsoid;
} else if (*pEllipsoid != ellipsoid) {
return; // All cartographic polygons must use the same ellipsoid
}
const auto cartographics = pCartographicPolygon->getCartographics();
std::vector<glm::dvec2> polygon;
for (const auto& cartographic : cartographics) {
polygon.emplace_back(cartographic.longitude, cartographic.latitude);
}
polygons.emplace_back(polygon);
}
if (polygons.empty()) {
return;
}
if (!pEllipsoid) {
return;
}
const auto projection = CesiumGeospatial::GeographicProjection(*pEllipsoid);
auto options = createRasterOverlayOptions();
options.loadErrorCallback = [this](const CesiumRasterOverlays::RasterOverlayLoadFailureDetails& error) {
_pContext->getLogger()->error(error.message);
};
_pPolygonRasterOverlay = new CesiumRasterOverlays::RasterizedPolygonsOverlay(
rasterOverlayName, polygons, getInvertSelection(), *pEllipsoid, projection, options);
if (getExcludeSelectedTiles()) {
auto pPolygons = _pPolygonRasterOverlay.get();
_pExcluder = std::make_shared<Cesium3DTilesSelection::RasterizedPolygonsTileExcluder>(pPolygons);
}
}
} // namespace cesium::omniverse
| 4,610 | C++ | 34.198473 | 120 | 0.7282 |
CesiumGS/cesium-omniverse/src/core/src/AssetRegistry.cpp | #include "cesium/omniverse/AssetRegistry.h"
#include "cesium/omniverse/Context.h"
#include "cesium/omniverse/CppUtil.h"
#include "cesium/omniverse/OmniCartographicPolygon.h"
#include "cesium/omniverse/OmniData.h"
#include "cesium/omniverse/OmniGeoreference.h"
#include "cesium/omniverse/OmniGlobeAnchor.h"
#include "cesium/omniverse/OmniIonRasterOverlay.h"
#include "cesium/omniverse/OmniIonServer.h"
#include "cesium/omniverse/OmniPolygonRasterOverlay.h"
#include "cesium/omniverse/OmniTileMapServiceRasterOverlay.h"
#include "cesium/omniverse/OmniTileset.h"
#include "cesium/omniverse/OmniWebMapServiceRasterOverlay.h"
#include "cesium/omniverse/OmniWebMapTileServiceRasterOverlay.h"
#include "cesium/omniverse/UsdUtil.h"
#include "cesium/omniverse/Viewport.h"
namespace cesium::omniverse {
AssetRegistry::AssetRegistry(Context* pContext)
: _pContext(pContext) {}
AssetRegistry::~AssetRegistry() = default;
void AssetRegistry::onUpdateFrame(const gsl::span<const Viewport>& viewports, bool waitForLoadingTiles) {
for (const auto& pTileset : _tilesets) {
pTileset->onUpdateFrame(viewports, waitForLoadingTiles);
}
}
OmniData& AssetRegistry::addData(const pxr::SdfPath& path) {
return *_datas.insert(_datas.end(), std::make_unique<OmniData>(_pContext, path))->get();
}
void AssetRegistry::removeData(const pxr::SdfPath& path) {
CppUtil::eraseIf(_datas, [&path](const auto& pData) { return pData->getPath() == path; });
}
OmniData* AssetRegistry::getData(const pxr::SdfPath& path) const {
for (const auto& pData : _datas) {
if (pData->getPath() == path) {
return pData.get();
}
}
return nullptr;
}
OmniData* AssetRegistry::getFirstData() const {
if (_datas.empty()) {
return nullptr;
}
return _datas.front().get();
}
OmniTileset& AssetRegistry::addTileset(const pxr::SdfPath& path) {
return *_tilesets.insert(_tilesets.end(), std::make_unique<OmniTileset>(_pContext, path, _tilesetId++))->get();
}
void AssetRegistry::removeTileset(const pxr::SdfPath& path) {
CppUtil::eraseIf(_tilesets, [&path](const auto& pTileset) { return pTileset->getPath() == path; });
}
OmniTileset* AssetRegistry::getTileset(const pxr::SdfPath& path) const {
for (const auto& pTileset : _tilesets) {
if (pTileset->getPath() == path) {
return pTileset.get();
}
}
return nullptr;
}
const std::vector<std::unique_ptr<OmniTileset>>& AssetRegistry::getTilesets() const {
return _tilesets;
}
OmniIonRasterOverlay& AssetRegistry::addIonRasterOverlay(const pxr::SdfPath& path) {
return *_ionRasterOverlays
.insert(_ionRasterOverlays.end(), std::make_unique<OmniIonRasterOverlay>(_pContext, path))
->get();
}
void AssetRegistry::removeIonRasterOverlay(const pxr::SdfPath& path) {
CppUtil::eraseIf(
_ionRasterOverlays, [&path](const auto& pIonRasterOverlay) { return pIonRasterOverlay->getPath() == path; });
}
OmniIonRasterOverlay* AssetRegistry::getIonRasterOverlay(const pxr::SdfPath& path) const {
for (const auto& pIonRasterOverlay : _ionRasterOverlays) {
if (pIonRasterOverlay->getPath() == path) {
return pIonRasterOverlay.get();
}
}
return nullptr;
}
OmniIonRasterOverlay* AssetRegistry::getIonRasterOverlayByIonAssetId(int64_t ionAssetId) const {
for (const auto& pIonRasterOverlay : _ionRasterOverlays) {
if (pIonRasterOverlay->getIonAssetId() == ionAssetId) {
return pIonRasterOverlay.get();
}
}
return nullptr;
}
const std::vector<std::unique_ptr<OmniIonRasterOverlay>>& AssetRegistry::getIonRasterOverlays() const {
return _ionRasterOverlays;
}
OmniPolygonRasterOverlay& AssetRegistry::addPolygonRasterOverlay(const pxr::SdfPath& path) {
return *_polygonRasterOverlays
.insert(_polygonRasterOverlays.end(), std::make_unique<OmniPolygonRasterOverlay>(_pContext, path))
->get();
}
void AssetRegistry::removePolygonRasterOverlay(const pxr::SdfPath& path) {
CppUtil::eraseIf(_polygonRasterOverlays, [&path](const auto& pPolygonRasterOverlay) {
return pPolygonRasterOverlay->getPath() == path;
});
}
OmniPolygonRasterOverlay* AssetRegistry::getPolygonRasterOverlay(const pxr::SdfPath& path) const {
for (const auto& pPolygonRasterOverlay : _polygonRasterOverlays) {
if (pPolygonRasterOverlay->getPath() == path) {
return pPolygonRasterOverlay.get();
}
}
return nullptr;
}
OmniWebMapServiceRasterOverlay& AssetRegistry::addWebMapServiceRasterOverlay(const pxr::SdfPath& path) {
return *_webMapServiceRasterOverlays
.insert(
_webMapServiceRasterOverlays.end(),
std::make_unique<OmniWebMapServiceRasterOverlay>(_pContext, path))
->get();
}
void AssetRegistry::removeWebMapServiceRasterOverlay(const pxr::SdfPath& path) {
CppUtil::eraseIf(_webMapServiceRasterOverlays, [&path](const auto& pWebMapServiceRasterOverlay) {
return pWebMapServiceRasterOverlay->getPath() == path;
});
}
OmniWebMapServiceRasterOverlay* AssetRegistry::getWebMapServiceRasterOverlay(const pxr::SdfPath& path) const {
for (const auto& pWebMapServiceRasterOverlay : _webMapServiceRasterOverlays) {
if (pWebMapServiceRasterOverlay->getPath() == path) {
return pWebMapServiceRasterOverlay.get();
}
}
return nullptr;
}
OmniTileMapServiceRasterOverlay& AssetRegistry::addTileMapServiceRasterOverlay(const pxr::SdfPath& path) {
return *_tileMapServiceRasterOverlays
.insert(
_tileMapServiceRasterOverlays.end(),
std::make_unique<OmniTileMapServiceRasterOverlay>(_pContext, path))
->get();
}
void AssetRegistry::removeTileMapServiceRasterOverlay(const pxr::SdfPath& path) {
CppUtil::eraseIf(_tileMapServiceRasterOverlays, [&path](const auto& pTileMapServiceRasterOverlay) {
return pTileMapServiceRasterOverlay->getPath() == path;
});
}
OmniTileMapServiceRasterOverlay* AssetRegistry::getTileMapServiceRasterOverlay(const pxr::SdfPath& path) const {
for (const auto& pTileMapServiceRasterOverlay : _tileMapServiceRasterOverlays) {
if (pTileMapServiceRasterOverlay->getPath() == path) {
return pTileMapServiceRasterOverlay.get();
}
}
return nullptr;
}
OmniWebMapTileServiceRasterOverlay& AssetRegistry::addWebMapTileServiceRasterOverlay(const pxr::SdfPath& path) {
return *_webMapTileServiceRasterOverlays
.insert(
_webMapTileServiceRasterOverlays.end(),
std::make_unique<OmniWebMapTileServiceRasterOverlay>(_pContext, path))
->get();
}
void AssetRegistry::removeWebMapTileServiceRasterOverlay(const pxr::SdfPath& path) {
CppUtil::eraseIf(_webMapTileServiceRasterOverlays, [&path](const auto& pWebMapTileServiceRasterOverlay) {
return pWebMapTileServiceRasterOverlay->getPath() == path;
});
}
OmniWebMapTileServiceRasterOverlay* AssetRegistry::getWebMapTileServiceRasterOverlay(const pxr::SdfPath& path) const {
for (const auto& pWebMapTileServiceRasterOverlay : _webMapTileServiceRasterOverlays) {
if (pWebMapTileServiceRasterOverlay->getPath() == path) {
return pWebMapTileServiceRasterOverlay.get();
}
}
return nullptr;
}
const std::vector<std::unique_ptr<OmniPolygonRasterOverlay>>& AssetRegistry::getPolygonRasterOverlays() const {
return _polygonRasterOverlays;
}
OmniRasterOverlay* AssetRegistry::getRasterOverlay(const pxr::SdfPath& path) const {
const auto pIonRasterOverlay = getIonRasterOverlay(path);
if (pIonRasterOverlay) {
return pIonRasterOverlay;
}
const auto pPolygonRasterOverlay = getPolygonRasterOverlay(path);
if (pPolygonRasterOverlay) {
return pPolygonRasterOverlay;
}
const auto pWebMapServiceRasterOverlay = getWebMapServiceRasterOverlay(path);
if (pWebMapServiceRasterOverlay) {
return pWebMapServiceRasterOverlay;
}
const auto pTileMapServiceRasterOverlay = getTileMapServiceRasterOverlay(path);
if (pTileMapServiceRasterOverlay) {
return pTileMapServiceRasterOverlay;
}
const auto pWebMapTileServiceRasterOverlay = getWebMapTileServiceRasterOverlay(path);
if (pWebMapTileServiceRasterOverlay) {
return pWebMapTileServiceRasterOverlay;
}
return nullptr;
}
OmniGeoreference& AssetRegistry::addGeoreference(const pxr::SdfPath& path) {
return *_georeferences.insert(_georeferences.end(), std::make_unique<OmniGeoreference>(_pContext, path))->get();
}
void AssetRegistry::removeGeoreference(const pxr::SdfPath& path) {
CppUtil::eraseIf(_georeferences, [&path](const auto& pGeoreference) { return pGeoreference->getPath() == path; });
}
OmniGeoreference* AssetRegistry::getGeoreference(const pxr::SdfPath& path) const {
for (const auto& pGeoreference : _georeferences) {
if (pGeoreference->getPath() == path) {
return pGeoreference.get();
}
}
return nullptr;
}
const std::vector<std::unique_ptr<OmniGeoreference>>& AssetRegistry::getGeoreferences() const {
return _georeferences;
}
OmniGeoreference* AssetRegistry::getFirstGeoreference() const {
if (_georeferences.empty()) {
return nullptr;
}
return _georeferences.front().get();
}
OmniGlobeAnchor& AssetRegistry::addGlobeAnchor(const pxr::SdfPath& path) {
return *_globeAnchors.insert(_globeAnchors.end(), std::make_unique<OmniGlobeAnchor>(_pContext, path))->get();
}
void AssetRegistry::removeGlobeAnchor(const pxr::SdfPath& path) {
CppUtil::eraseIf(_globeAnchors, [&path](const auto& pGlobeAnchor) { return pGlobeAnchor->getPath() == path; });
}
OmniGlobeAnchor* AssetRegistry::getGlobeAnchor(const pxr::SdfPath& path) const {
for (const auto& pGlobeAnchor : _globeAnchors) {
if (pGlobeAnchor->getPath() == path) {
return pGlobeAnchor.get();
}
}
return nullptr;
}
const std::vector<std::unique_ptr<OmniGlobeAnchor>>& AssetRegistry::getGlobeAnchors() const {
return _globeAnchors;
}
OmniIonServer& AssetRegistry::addIonServer(const pxr::SdfPath& path) {
return *_ionServers.insert(_ionServers.end(), std::make_unique<OmniIonServer>(_pContext, path))->get();
}
void AssetRegistry::removeIonServer(const pxr::SdfPath& path) {
CppUtil::eraseIf(_ionServers, [&path](const auto& pIonServer) { return pIonServer->getPath() == path; });
}
OmniIonServer* AssetRegistry::getIonServer(const pxr::SdfPath& path) const {
for (const auto& pIonServer : _ionServers) {
if (pIonServer->getPath() == path) {
return pIonServer.get();
}
}
return nullptr;
}
const std::vector<std::unique_ptr<OmniIonServer>>& AssetRegistry::getIonServers() const {
return _ionServers;
}
OmniIonServer* AssetRegistry::getFirstIonServer() const {
if (_ionServers.empty()) {
return nullptr;
}
return _ionServers.front().get();
}
OmniCartographicPolygon& AssetRegistry::addCartographicPolygon(const pxr::SdfPath& path) {
return *_cartographicPolygons
.insert(_cartographicPolygons.end(), std::make_unique<OmniCartographicPolygon>(_pContext, path))
->get();
}
void AssetRegistry::removeCartographicPolygon(const pxr::SdfPath& path) {
CppUtil::eraseIf(_cartographicPolygons, [&path](const auto& pCartographicPolygon) {
return pCartographicPolygon->getPath() == path;
});
}
OmniCartographicPolygon* AssetRegistry::getCartographicPolygon(const pxr::SdfPath& path) const {
for (const auto& pCartographicPolygon : _cartographicPolygons) {
if (pCartographicPolygon->getPath() == path) {
return pCartographicPolygon.get();
}
}
return nullptr;
}
const std::vector<std::unique_ptr<OmniCartographicPolygon>>& AssetRegistry::getCartographicPolygons() const {
return _cartographicPolygons;
}
AssetType AssetRegistry::getAssetType(const pxr::SdfPath& path) const {
if (getData(path)) {
return AssetType::DATA;
} else if (getTileset(path)) {
return AssetType::TILESET;
} else if (getIonRasterOverlay(path)) {
return AssetType::ION_RASTER_OVERLAY;
} else if (getPolygonRasterOverlay(path)) {
return AssetType::POLYGON_RASTER_OVERLAY;
} else if (getGeoreference(path)) {
return AssetType::GEOREFERENCE;
} else if (getIonServer(path)) {
return AssetType::ION_SERVER;
} else if (getCartographicPolygon(path)) {
return AssetType::CARTOGRAPHIC_POLYGON;
} else if (getGlobeAnchor(path)) {
// Globe anchor needs to be checked last since prim types take precedence over API schemas
return AssetType::GLOBE_ANCHOR;
} else {
return AssetType::OTHER;
}
}
bool AssetRegistry::hasAsset(const pxr::SdfPath& path) const {
return getAssetType(path) != AssetType::OTHER;
}
void AssetRegistry::clear() {
_datas.clear();
_tilesets.clear();
_ionRasterOverlays.clear();
_polygonRasterOverlays.clear();
_georeferences.clear();
_globeAnchors.clear();
_ionServers.clear();
_cartographicPolygons.clear();
}
} // namespace cesium::omniverse
| 13,357 | C++ | 33.427835 | 118 | 0.701954 |
CesiumGS/cesium-omniverse/src/core/src/OmniWebMapTileServiceRasterOverlay.cpp | #include "cesium/omniverse/OmniWebMapTileServiceRasterOverlay.h"
#include "cesium/omniverse/AssetRegistry.h"
#include "cesium/omniverse/Context.h"
#include "cesium/omniverse/GltfUtil.h"
#include "cesium/omniverse/Logger.h"
#include "cesium/omniverse/OmniGeoreference.h"
#include "cesium/omniverse/UsdUtil.h"
#include <CesiumRasterOverlays/WebMapTileServiceRasterOverlay.h>
#include <CesiumUsdSchemas/webMapTileServiceRasterOverlay.h>
#include <string>
namespace cesium::omniverse {
OmniWebMapTileServiceRasterOverlay::OmniWebMapTileServiceRasterOverlay(Context* pContext, const pxr::SdfPath& path)
: OmniRasterOverlay(pContext, path) {
reload();
}
CesiumRasterOverlays::RasterOverlay* OmniWebMapTileServiceRasterOverlay::getRasterOverlay() const {
return _pWebMapTileServiceRasterOverlay.get();
}
std::string OmniWebMapTileServiceRasterOverlay::getUrl() const {
const auto cesiumWebMapTileServiceRasterOverlay =
UsdUtil::getCesiumWebMapTileServiceRasterOverlay(_pContext->getUsdStage(), _path);
if (!UsdUtil::isSchemaValid(cesiumWebMapTileServiceRasterOverlay)) {
return "";
}
std::string url;
cesiumWebMapTileServiceRasterOverlay.GetUrlAttr().Get(&url);
return url;
}
std::string OmniWebMapTileServiceRasterOverlay::getLayer() const {
const auto cesiumWebMapTileServiceRasterOverlay =
UsdUtil::getCesiumWebMapTileServiceRasterOverlay(_pContext->getUsdStage(), _path);
if (!UsdUtil::isSchemaValid(cesiumWebMapTileServiceRasterOverlay)) {
return "";
}
std::string layer;
cesiumWebMapTileServiceRasterOverlay.GetLayerAttr().Get(&layer);
return layer;
}
std::string OmniWebMapTileServiceRasterOverlay::getTileMatrixSetId() const {
const auto cesiumWebMapTileServiceRasterOverlay =
UsdUtil::getCesiumWebMapTileServiceRasterOverlay(_pContext->getUsdStage(), _path);
if (!UsdUtil::isSchemaValid(cesiumWebMapTileServiceRasterOverlay)) {
return "";
}
std::string val;
cesiumWebMapTileServiceRasterOverlay.GetTileMatrixSetIdAttr().Get(&val);
return val;
}
std::string OmniWebMapTileServiceRasterOverlay::getStyle() const {
const auto cesiumWebMapTileServiceRasterOverlay =
UsdUtil::getCesiumWebMapTileServiceRasterOverlay(_pContext->getUsdStage(), _path);
if (!UsdUtil::isSchemaValid(cesiumWebMapTileServiceRasterOverlay)) {
return "";
}
std::string val;
cesiumWebMapTileServiceRasterOverlay.GetStyleAttr().Get(&val);
return val;
}
std::string OmniWebMapTileServiceRasterOverlay::getFormat() const {
const auto cesiumWebMapTileServiceRasterOverlay =
UsdUtil::getCesiumWebMapTileServiceRasterOverlay(_pContext->getUsdStage(), _path);
if (!UsdUtil::isSchemaValid(cesiumWebMapTileServiceRasterOverlay)) {
return "";
}
std::string val;
cesiumWebMapTileServiceRasterOverlay.GetFormatAttr().Get(&val);
return val;
}
int OmniWebMapTileServiceRasterOverlay::getMinimumZoomLevel() const {
const auto cesiumWebMapTileServiceRasterOverlay =
UsdUtil::getCesiumWebMapTileServiceRasterOverlay(_pContext->getUsdStage(), _path);
if (!UsdUtil::isSchemaValid(cesiumWebMapTileServiceRasterOverlay)) {
return 0;
}
int val;
cesiumWebMapTileServiceRasterOverlay.GetMinimumZoomLevelAttr().Get(&val);
return val;
}
int OmniWebMapTileServiceRasterOverlay::getMaximumZoomLevel() const {
const auto cesiumWebMapTileServiceRasterOverlay =
UsdUtil::getCesiumWebMapTileServiceRasterOverlay(_pContext->getUsdStage(), _path);
if (!UsdUtil::isSchemaValid(cesiumWebMapTileServiceRasterOverlay)) {
return 0;
}
int val;
cesiumWebMapTileServiceRasterOverlay.GetMaximumZoomLevelAttr().Get(&val);
return val;
}
bool OmniWebMapTileServiceRasterOverlay::getSpecifyZoomLevels() const {
const auto cesiumWebMapTileServiceRasterOverlay =
UsdUtil::getCesiumWebMapTileServiceRasterOverlay(_pContext->getUsdStage(), _path);
if (!UsdUtil::isSchemaValid(cesiumWebMapTileServiceRasterOverlay)) {
return false;
}
bool val;
cesiumWebMapTileServiceRasterOverlay.GetSpecifyZoomLevelsAttr().Get(&val);
return val;
}
bool OmniWebMapTileServiceRasterOverlay::getUseWebMercatorProjection() const {
const auto cesiumWebMapTileServiceRasterOverlay =
UsdUtil::getCesiumWebMapTileServiceRasterOverlay(_pContext->getUsdStage(), _path);
if (!UsdUtil::isSchemaValid(cesiumWebMapTileServiceRasterOverlay)) {
return false;
}
bool val;
cesiumWebMapTileServiceRasterOverlay.GetUseWebMercatorProjectionAttr().Get(&val);
return val;
}
bool OmniWebMapTileServiceRasterOverlay::getSpecifyTilingScheme() const {
const auto cesiumWebMapTileServiceRasterOverlay =
UsdUtil::getCesiumWebMapTileServiceRasterOverlay(_pContext->getUsdStage(), _path);
if (!UsdUtil::isSchemaValid(cesiumWebMapTileServiceRasterOverlay)) {
return false;
}
bool val;
cesiumWebMapTileServiceRasterOverlay.GetSpecifyTilingSchemeAttr().Get(&val);
return val;
}
double OmniWebMapTileServiceRasterOverlay::getNorth() const {
const auto cesiumWebMapTileServiceRasterOverlay =
UsdUtil::getCesiumWebMapTileServiceRasterOverlay(_pContext->getUsdStage(), _path);
if (!UsdUtil::isSchemaValid(cesiumWebMapTileServiceRasterOverlay)) {
return 90;
}
double val;
cesiumWebMapTileServiceRasterOverlay.GetNorthAttr().Get(&val);
return val;
}
double OmniWebMapTileServiceRasterOverlay::getSouth() const {
const auto cesiumWebMapTileServiceRasterOverlay =
UsdUtil::getCesiumWebMapTileServiceRasterOverlay(_pContext->getUsdStage(), _path);
if (!UsdUtil::isSchemaValid(cesiumWebMapTileServiceRasterOverlay)) {
return -90;
}
double val;
cesiumWebMapTileServiceRasterOverlay.GetSouthAttr().Get(&val);
return val;
}
double OmniWebMapTileServiceRasterOverlay::getEast() const {
const auto cesiumWebMapTileServiceRasterOverlay =
UsdUtil::getCesiumWebMapTileServiceRasterOverlay(_pContext->getUsdStage(), _path);
if (!UsdUtil::isSchemaValid(cesiumWebMapTileServiceRasterOverlay)) {
return 180;
}
double val;
cesiumWebMapTileServiceRasterOverlay.GetEastAttr().Get(&val);
return val;
}
double OmniWebMapTileServiceRasterOverlay::getWest() const {
const auto cesiumWebMapTileServiceRasterOverlay =
UsdUtil::getCesiumWebMapTileServiceRasterOverlay(_pContext->getUsdStage(), _path);
if (!UsdUtil::isSchemaValid(cesiumWebMapTileServiceRasterOverlay)) {
return -180;
}
double val;
cesiumWebMapTileServiceRasterOverlay.GetWestAttr().Get(&val);
return val;
}
bool OmniWebMapTileServiceRasterOverlay::getSpecifyTileMatrixSetLabels() const {
const auto cesiumWebMapTileServiceRasterOverlay =
UsdUtil::getCesiumWebMapTileServiceRasterOverlay(_pContext->getUsdStage(), _path);
if (!UsdUtil::isSchemaValid(cesiumWebMapTileServiceRasterOverlay)) {
return false;
}
bool val;
cesiumWebMapTileServiceRasterOverlay.GetSpecifyTileMatrixSetLabelsAttr().Get(&val);
return val;
}
std::vector<std::string> OmniWebMapTileServiceRasterOverlay::getTileMatrixSetLabels() const {
const auto cesiumWebMapTileServiceRasterOverlay =
UsdUtil::getCesiumWebMapTileServiceRasterOverlay(_pContext->getUsdStage(), _path);
if (!UsdUtil::isSchemaValid(cesiumWebMapTileServiceRasterOverlay)) {
return {};
}
std::string val;
cesiumWebMapTileServiceRasterOverlay.GetTileMatrixSetLabelsAttr().Get(&val);
std::vector<std::string> matrixSetLabels;
size_t pos = 0;
while ((pos = val.find(',')) != std::string::npos) {
matrixSetLabels.push_back(val.substr(0, pos));
val.erase(0, pos + 1);
}
matrixSetLabels.push_back(val);
return matrixSetLabels;
}
std::string OmniWebMapTileServiceRasterOverlay::getTileMatrixSetLabelPrefix() const {
const auto cesiumWebMapTileServiceRasterOverlay =
UsdUtil::getCesiumWebMapTileServiceRasterOverlay(_pContext->getUsdStage(), _path);
if (!UsdUtil::isSchemaValid(cesiumWebMapTileServiceRasterOverlay)) {
return "";
}
std::string val;
cesiumWebMapTileServiceRasterOverlay.GetTileMatrixSetLabelPrefixAttr().Get(&val);
return val;
}
int OmniWebMapTileServiceRasterOverlay::getRootTilesX() const {
const auto cesiumWebMapTileServiceRasterOverlay =
UsdUtil::getCesiumWebMapTileServiceRasterOverlay(_pContext->getUsdStage(), _path);
if (!UsdUtil::isSchemaValid(cesiumWebMapTileServiceRasterOverlay)) {
return 1;
}
int val;
cesiumWebMapTileServiceRasterOverlay.GetRootTilesXAttr().Get(&val);
return val;
}
int OmniWebMapTileServiceRasterOverlay::getRootTilesY() const {
const auto cesiumWebMapTileServiceRasterOverlay =
UsdUtil::getCesiumWebMapTileServiceRasterOverlay(_pContext->getUsdStage(), _path);
if (!UsdUtil::isSchemaValid(cesiumWebMapTileServiceRasterOverlay)) {
return 1;
}
int val;
cesiumWebMapTileServiceRasterOverlay.GetRootTilesYAttr().Get(&val);
return val;
}
void OmniWebMapTileServiceRasterOverlay::reload() {
const auto rasterOverlayName = UsdUtil::getName(_pContext->getUsdStage(), _path);
auto options = createRasterOverlayOptions();
options.loadErrorCallback = [this](const CesiumRasterOverlays::RasterOverlayLoadFailureDetails& error) {
_pContext->getLogger()->error(error.message);
};
CesiumRasterOverlays::WebMapTileServiceRasterOverlayOptions wmtsOptions;
const auto tileMatrixSetId = getTileMatrixSetId();
if (!tileMatrixSetId.empty()) {
wmtsOptions.tileMatrixSetID = tileMatrixSetId;
}
const auto style = getStyle();
if (!style.empty()) {
wmtsOptions.style = style;
}
const auto layer = getLayer();
if (!layer.empty()) {
wmtsOptions.layer = layer;
}
const auto format = getFormat();
if (!format.empty()) {
wmtsOptions.format = format;
}
if (getSpecifyZoomLevels()) {
wmtsOptions.minimumLevel = getMinimumZoomLevel();
wmtsOptions.maximumLevel = getMaximumZoomLevel();
}
CesiumGeospatial::Projection projection;
const auto useWebMercatorProjection = getUseWebMercatorProjection();
if (useWebMercatorProjection) {
projection = CesiumGeospatial::WebMercatorProjection();
wmtsOptions.projection = projection;
} else {
projection = CesiumGeospatial::GeographicProjection();
wmtsOptions.projection = projection;
}
if (getSpecifyTilingScheme()) {
CesiumGeospatial::GlobeRectangle globeRectangle =
CesiumGeospatial::GlobeRectangle::fromDegrees(getWest(), getSouth(), getEast(), getNorth());
CesiumGeometry::Rectangle coverageRectangle =
CesiumGeospatial::projectRectangleSimple(projection, globeRectangle);
wmtsOptions.coverageRectangle = coverageRectangle;
const auto rootTilesX = getRootTilesX();
const auto rootTilesY = getRootTilesY();
wmtsOptions.tilingScheme = CesiumGeometry::QuadtreeTilingScheme(coverageRectangle, rootTilesX, rootTilesY);
}
if (getSpecifyTileMatrixSetLabels()) {
const auto tileMatrixSetLabels = getTileMatrixSetLabels();
if (!tileMatrixSetLabels.empty()) {
wmtsOptions.tileMatrixLabels = getTileMatrixSetLabels();
}
} else {
const auto tileMatrixSetLabelPrefix = getTileMatrixSetLabelPrefix();
if (!tileMatrixSetLabelPrefix.empty()) {
std::vector<std::string> labels;
for (size_t level = 0; level <= 25; ++level) {
std::string label{tileMatrixSetLabelPrefix};
label.append(std::to_string(level));
labels.emplace_back(label);
}
wmtsOptions.tileMatrixLabels = labels;
}
}
_pWebMapTileServiceRasterOverlay = new CesiumRasterOverlays::WebMapTileServiceRasterOverlay(
rasterOverlayName, getUrl(), std::vector<CesiumAsync::IAssetAccessor::THeader>(), wmtsOptions, options);
}
} // namespace cesium::omniverse
| 12,199 | C++ | 34.672515 | 115 | 0.734404 |
CesiumGS/cesium-omniverse/src/core/src/OmniData.cpp | #include "cesium/omniverse/OmniData.h"
#include "cesium/omniverse/Context.h"
#include "cesium/omniverse/UsdUtil.h"
#include <CesiumUsdSchemas/data.h>
namespace cesium::omniverse {
OmniData::OmniData(Context* pContext, const pxr::SdfPath& path)
: _pContext(pContext)
, _path(path) {}
const pxr::SdfPath& OmniData::getPath() const {
return _path;
}
pxr::SdfPath OmniData::getSelectedIonServerPath() const {
const auto cesiumData = UsdUtil::getCesiumData(_pContext->getUsdStage(), _path);
if (!UsdUtil::isSchemaValid(cesiumData)) {
return {};
}
pxr::SdfPathVector targets;
cesiumData.GetSelectedIonServerRel().GetForwardedTargets(&targets);
if (targets.empty()) {
return {};
}
return targets.front();
}
bool OmniData::getDebugDisableMaterials() const {
const auto cesiumData = UsdUtil::getCesiumData(_pContext->getUsdStage(), _path);
if (!UsdUtil::isSchemaValid(cesiumData)) {
return false;
}
bool disableMaterials;
cesiumData.GetDebugDisableMaterialsAttr().Get(&disableMaterials);
return disableMaterials;
}
bool OmniData::getDebugDisableTextures() const {
const auto cesiumData = UsdUtil::getCesiumData(_pContext->getUsdStage(), _path);
if (!UsdUtil::isSchemaValid(cesiumData)) {
return false;
}
bool disableTextures;
cesiumData.GetDebugDisableTexturesAttr().Get(&disableTextures);
return disableTextures;
}
bool OmniData::getDebugDisableGeometryPool() const {
const auto cesiumData = UsdUtil::getCesiumData(_pContext->getUsdStage(), _path);
if (!UsdUtil::isSchemaValid(cesiumData)) {
return false;
}
bool disableGeometryPool;
cesiumData.GetDebugDisableGeometryPoolAttr().Get(&disableGeometryPool);
return disableGeometryPool;
}
bool OmniData::getDebugDisableMaterialPool() const {
const auto cesiumData = UsdUtil::getCesiumData(_pContext->getUsdStage(), _path);
if (!UsdUtil::isSchemaValid(cesiumData)) {
return false;
}
bool disableMaterialPool;
cesiumData.GetDebugDisableMaterialPoolAttr().Get(&disableMaterialPool);
return disableMaterialPool;
}
bool OmniData::getDebugDisableTexturePool() const {
const auto cesiumData = UsdUtil::getCesiumData(_pContext->getUsdStage(), _path);
if (!UsdUtil::isSchemaValid(cesiumData)) {
return false;
}
bool disableTexturePool;
cesiumData.GetDebugDisableTexturePoolAttr().Get(&disableTexturePool);
return disableTexturePool;
}
uint64_t OmniData::getDebugGeometryPoolInitialCapacity() const {
const auto cesiumData = UsdUtil::getCesiumData(_pContext->getUsdStage(), _path);
if (!UsdUtil::isSchemaValid(cesiumData)) {
return 2048;
}
uint64_t geometryPoolInitialCapacity;
cesiumData.GetDebugGeometryPoolInitialCapacityAttr().Get(&geometryPoolInitialCapacity);
return geometryPoolInitialCapacity;
}
uint64_t OmniData::getDebugMaterialPoolInitialCapacity() const {
const auto cesiumData = UsdUtil::getCesiumData(_pContext->getUsdStage(), _path);
if (!UsdUtil::isSchemaValid(cesiumData)) {
return 2048;
}
uint64_t materialPoolInitialCapacity;
cesiumData.GetDebugMaterialPoolInitialCapacityAttr().Get(&materialPoolInitialCapacity);
return materialPoolInitialCapacity;
}
uint64_t OmniData::getDebugTexturePoolInitialCapacity() const {
const auto cesiumData = UsdUtil::getCesiumData(_pContext->getUsdStage(), _path);
if (!UsdUtil::isSchemaValid(cesiumData)) {
return 2048;
}
uint64_t texturePoolInitialCapacity;
cesiumData.GetDebugTexturePoolInitialCapacityAttr().Get(&texturePoolInitialCapacity);
return texturePoolInitialCapacity;
}
bool OmniData::getDebugRandomColors() const {
const auto cesiumData = UsdUtil::getCesiumData(_pContext->getUsdStage(), _path);
if (!UsdUtil::isSchemaValid(cesiumData)) {
return false;
}
bool debugRandomColors;
cesiumData.GetDebugRandomColorsAttr().Get(&debugRandomColors);
return debugRandomColors;
}
bool OmniData::getDebugDisableGeoreferencing() const {
const auto cesiumData = UsdUtil::getCesiumData(_pContext->getUsdStage(), _path);
if (!UsdUtil::isSchemaValid(cesiumData)) {
return false;
}
bool debugDisableGeoreferencing;
cesiumData.GetDebugDisableGeoreferencingAttr().Get(&debugDisableGeoreferencing);
return debugDisableGeoreferencing;
}
} // namespace cesium::omniverse
| 4,464 | C++ | 27.806451 | 91 | 0.727599 |
CesiumGS/cesium-omniverse/src/core/src/OmniRasterOverlay.cpp | #include "cesium/omniverse/OmniRasterOverlay.h"
#include "cesium/omniverse/AssetRegistry.h"
#include "cesium/omniverse/Context.h"
#include "cesium/omniverse/FabricRasterOverlaysInfo.h"
#include "cesium/omniverse/GltfUtil.h"
#include "cesium/omniverse/Logger.h"
#include "cesium/omniverse/OmniIonServer.h"
#include "cesium/omniverse/UsdUtil.h"
#include <CesiumIonClient/Token.h>
#include <CesiumUsdSchemas/rasterOverlay.h>
namespace cesium::omniverse {
OmniRasterOverlay::OmniRasterOverlay(Context* pContext, const pxr::SdfPath& path)
: _pContext(pContext)
, _path(path) {}
const pxr::SdfPath& OmniRasterOverlay::getPath() const {
return _path;
}
bool OmniRasterOverlay::getShowCreditsOnScreen() const {
const auto cesiumRasterOverlay = UsdUtil::getCesiumRasterOverlay(_pContext->getUsdStage(), _path);
if (!UsdUtil::isSchemaValid(cesiumRasterOverlay)) {
return false;
}
bool showCreditsOnScreen;
cesiumRasterOverlay.GetShowCreditsOnScreenAttr().Get(&showCreditsOnScreen);
return showCreditsOnScreen;
}
double OmniRasterOverlay::getAlpha() const {
const auto cesiumRasterOverlay = UsdUtil::getCesiumRasterOverlay(_pContext->getUsdStage(), _path);
if (!UsdUtil::isSchemaValid(cesiumRasterOverlay)) {
return 1.0;
}
float alpha;
cesiumRasterOverlay.GetAlphaAttr().Get(&alpha);
return static_cast<double>(alpha);
}
float OmniRasterOverlay::getMaximumScreenSpaceError() const {
const auto cesiumRasterOverlay = UsdUtil::getCesiumRasterOverlay(_pContext->getUsdStage(), _path);
if (!UsdUtil::isSchemaValid(cesiumRasterOverlay)) {
return 2.0f;
}
float value;
cesiumRasterOverlay.GetMaximumScreenSpaceErrorAttr().Get(&value);
return static_cast<float>(value);
}
int OmniRasterOverlay::getMaximumTextureSize() const {
const auto cesiumRasterOverlay = UsdUtil::getCesiumRasterOverlay(_pContext->getUsdStage(), _path);
if (!UsdUtil::isSchemaValid(cesiumRasterOverlay)) {
return 2048;
}
int value;
cesiumRasterOverlay.GetMaximumTextureSizeAttr().Get(&value);
return static_cast<int>(value);
}
int OmniRasterOverlay::getMaximumSimultaneousTileLoads() const {
const auto cesiumRasterOverlay = UsdUtil::getCesiumRasterOverlay(_pContext->getUsdStage(), _path);
if (!UsdUtil::isSchemaValid(cesiumRasterOverlay)) {
return 20;
}
int value;
cesiumRasterOverlay.GetMaximumSimultaneousTileLoadsAttr().Get(&value);
return static_cast<int>(value);
}
int OmniRasterOverlay::getSubTileCacheBytes() const {
const auto cesiumRasterOverlay = UsdUtil::getCesiumRasterOverlay(_pContext->getUsdStage(), _path);
if (!UsdUtil::isSchemaValid(cesiumRasterOverlay)) {
return 16777216;
}
int value;
cesiumRasterOverlay.GetSubTileCacheBytesAttr().Get(&value);
return static_cast<int>(value);
}
FabricOverlayRenderMethod OmniRasterOverlay::getOverlayRenderMethod() const {
const auto cesiumRasterOverlay = UsdUtil::getCesiumRasterOverlay(_pContext->getUsdStage(), _path);
if (!UsdUtil::isSchemaValid(cesiumRasterOverlay)) {
return FabricOverlayRenderMethod::OVERLAY;
}
pxr::TfToken overlayRenderMethod;
cesiumRasterOverlay.GetOverlayRenderMethodAttr().Get(&overlayRenderMethod);
if (overlayRenderMethod == pxr::CesiumTokens->overlay) {
return FabricOverlayRenderMethod::OVERLAY;
} else if (overlayRenderMethod == pxr::CesiumTokens->clip) {
return FabricOverlayRenderMethod::CLIPPING;
}
_pContext->getLogger()->warn("Invalid overlay render method encountered {}.", overlayRenderMethod.GetText());
return FabricOverlayRenderMethod::OVERLAY;
}
CesiumRasterOverlays::RasterOverlayOptions OmniRasterOverlay::createRasterOverlayOptions() const {
CesiumRasterOverlays::RasterOverlayOptions options;
options.ktx2TranscodeTargets = GltfUtil::getKtx2TranscodeTargets();
setRasterOverlayOptionsFromUsd(options);
return options;
}
void OmniRasterOverlay::updateRasterOverlayOptions() const {
const auto pRasterOverlay = getRasterOverlay();
if (pRasterOverlay) {
setRasterOverlayOptionsFromUsd(pRasterOverlay->getOptions());
}
}
void OmniRasterOverlay::setRasterOverlayOptionsFromUsd(CesiumRasterOverlays::RasterOverlayOptions& options) const {
options.showCreditsOnScreen = getShowCreditsOnScreen();
options.maximumScreenSpaceError = getMaximumScreenSpaceError();
options.maximumTextureSize = getMaximumTextureSize();
options.maximumSimultaneousTileLoads = getMaximumSimultaneousTileLoads();
options.subTileCacheBytes = getSubTileCacheBytes();
}
} // namespace cesium::omniverse
| 4,681 | C++ | 32.927536 | 115 | 0.754112 |
CesiumGS/cesium-omniverse/src/core/src/OmniIonServer.cpp | #include "cesium/omniverse/OmniIonServer.h"
#include "cesium/omniverse/CesiumIonSession.h"
#include "cesium/omniverse/Context.h"
#include "cesium/omniverse/UsdUtil.h"
#include <CesiumUsdSchemas/ionServer.h>
namespace cesium::omniverse {
OmniIonServer::OmniIonServer(Context* pContext, const pxr::SdfPath& path)
: _pContext(pContext)
, _path(path)
, _session(std::make_shared<CesiumIonSession>(
pContext->getAsyncSystem(),
pContext->getAssetAccessor(),
getIonServerUrl(),
getIonServerApiUrl(),
getIonServerApplicationId())) {
_session->resume();
}
const pxr::SdfPath& OmniIonServer::getPath() const {
return _path;
}
std::shared_ptr<CesiumIonSession> OmniIonServer::getSession() const {
return _session;
}
std::string OmniIonServer::getIonServerUrl() const {
const auto cesiumIonServer = UsdUtil::getCesiumIonServer(_pContext->getUsdStage(), _path);
if (!UsdUtil::isSchemaValid(cesiumIonServer)) {
return "";
}
std::string ionServerUrl;
cesiumIonServer.GetIonServerUrlAttr().Get(&ionServerUrl);
return ionServerUrl;
}
std::string OmniIonServer::getIonServerApiUrl() const {
const auto cesiumIonServer = UsdUtil::getCesiumIonServer(_pContext->getUsdStage(), _path);
if (!UsdUtil::isSchemaValid(cesiumIonServer)) {
return "";
}
std::string ionServerApiUrl;
cesiumIonServer.GetIonServerApiUrlAttr().Get(&ionServerApiUrl);
return ionServerApiUrl;
}
int64_t OmniIonServer::getIonServerApplicationId() const {
const auto cesiumIonServer = UsdUtil::getCesiumIonServer(_pContext->getUsdStage(), _path);
if (!UsdUtil::isSchemaValid(cesiumIonServer)) {
return 0;
}
int64_t ionServerApplicationId;
cesiumIonServer.GetIonServerApplicationIdAttr().Get(&ionServerApplicationId);
return ionServerApplicationId;
}
CesiumIonClient::Token OmniIonServer::getToken() const {
const auto cesiumIonServer = UsdUtil::getCesiumIonServer(_pContext->getUsdStage(), _path);
if (!UsdUtil::isSchemaValid(cesiumIonServer)) {
return {};
}
std::string projectDefaultIonAccessToken;
std::string projectDefaultIonAccessTokenId;
cesiumIonServer.GetProjectDefaultIonAccessTokenAttr().Get(&projectDefaultIonAccessToken);
cesiumIonServer.GetProjectDefaultIonAccessTokenIdAttr().Get(&projectDefaultIonAccessTokenId);
CesiumIonClient::Token t;
t.id = projectDefaultIonAccessTokenId;
t.token = projectDefaultIonAccessToken;
return t;
}
void OmniIonServer::setToken(const CesiumIonClient::Token& token) {
const auto cesiumIonServer = UsdUtil::getCesiumIonServer(_pContext->getUsdStage(), _path);
if (!UsdUtil::isSchemaValid(cesiumIonServer)) {
return;
}
cesiumIonServer.GetProjectDefaultIonAccessTokenAttr().Set(token.token);
cesiumIonServer.GetProjectDefaultIonAccessTokenIdAttr().Set(token.id);
}
} // namespace cesium::omniverse
| 2,961 | C++ | 29.536082 | 97 | 0.729483 |
CesiumGS/cesium-omniverse/src/core/src/FabricMaterial.cpp | #include "cesium/omniverse/FabricMaterial.h"
#include "cesium/omniverse/Context.h"
#include "cesium/omniverse/CppUtil.h"
#include "cesium/omniverse/DataType.h"
#include "cesium/omniverse/FabricAttributesBuilder.h"
#include "cesium/omniverse/FabricFeaturesInfo.h"
#include "cesium/omniverse/FabricMaterialDescriptor.h"
#include "cesium/omniverse/FabricMaterialInfo.h"
#include "cesium/omniverse/FabricPropertyDescriptor.h"
#include "cesium/omniverse/FabricRasterOverlaysInfo.h"
#include "cesium/omniverse/FabricResourceManager.h"
#include "cesium/omniverse/FabricTexture.h"
#include "cesium/omniverse/FabricTextureInfo.h"
#include "cesium/omniverse/FabricUtil.h"
#include "cesium/omniverse/GltfUtil.h"
#include "cesium/omniverse/Logger.h"
#include "cesium/omniverse/MetadataUtil.h"
#include "cesium/omniverse/UsdTokens.h"
#include "cesium/omniverse/UsdUtil.h"
#include <CesiumGltf/MeshPrimitive.h>
#include <glm/gtc/random.hpp>
#include <omni/fabric/FabricUSD.h>
#include <omni/fabric/SimStageWithHistory.h>
#include <spdlog/fmt/fmt.h>
namespace cesium::omniverse {
namespace {
// Should match raster_overlays length in cesium.mdl
const uint64_t MAX_RASTER_OVERLAY_COUNT = 16;
const auto DEFAULT_DEBUG_COLOR = glm::dvec3(1.0, 1.0, 1.0);
const auto DEFAULT_ALPHA = 1.0f;
const auto DEFAULT_DISPLAY_COLOR = glm::dvec3(1.0, 1.0, 1.0);
const auto DEFAULT_DISPLAY_OPACITY = 1.0;
const auto DEFAULT_TEXCOORD_INDEX = uint64_t(0);
const auto DEFAULT_FEATURE_ID_PRIMVAR_NAME = std::string("_FEATURE_ID_0");
const auto DEFAULT_NULL_FEATURE_ID = -1;
const auto DEFAULT_OFFSET = 0;
const auto DEFAULT_SCALE = 1;
const auto DEFAULT_NO_DATA = 0;
const auto DEFAULT_VALUE = 0;
struct FeatureIdCounts {
uint64_t indexCount;
uint64_t attributeCount;
uint64_t textureCount;
uint64_t totalCount;
};
FeatureIdCounts getFeatureIdCounts(const FabricMaterialDescriptor& materialDescriptor) {
const auto& featureIdTypes = materialDescriptor.getFeatureIdTypes();
auto featureIdCount = featureIdTypes.size();
uint64_t indexCount = 0;
uint64_t attributeCount = 0;
uint64_t textureCount = 0;
for (uint64_t i = 0; i < featureIdCount; ++i) {
const auto featureIdType = featureIdTypes[i];
switch (featureIdType) {
case FabricFeatureIdType::INDEX:
++indexCount;
break;
case FabricFeatureIdType::ATTRIBUTE:
++attributeCount;
break;
case FabricFeatureIdType::TEXTURE:
++textureCount;
break;
}
}
return FeatureIdCounts{indexCount, attributeCount, textureCount, featureIdCount};
}
struct RasterOverlayIndices {
std::vector<uint64_t> overlayRasterOverlayIndices;
std::vector<uint64_t> clippingRasterOverlayIndices;
};
RasterOverlayIndices
getRasterOverlayIndices(const Context& context, const FabricMaterialDescriptor& materialDescriptor) {
uint64_t overlayRasterOverlayCount = 0;
uint64_t clippingRasterOverlayCount = 0;
uint64_t totalRasterOverlayCount = 0;
std::vector<uint64_t> overlayRasterOverlayIndices;
std::vector<uint64_t> clippingRasterOverlayIndices;
for (const auto& method : materialDescriptor.getRasterOverlayRenderMethods()) {
switch (method) {
case FabricOverlayRenderMethod::OVERLAY:
if (overlayRasterOverlayCount < MAX_RASTER_OVERLAY_COUNT) {
overlayRasterOverlayIndices.push_back(totalRasterOverlayCount);
}
++overlayRasterOverlayCount;
break;
case FabricOverlayRenderMethod::CLIPPING:
if (clippingRasterOverlayCount < MAX_RASTER_OVERLAY_COUNT) {
clippingRasterOverlayIndices.push_back(totalRasterOverlayCount);
}
++clippingRasterOverlayCount;
break;
}
++totalRasterOverlayCount;
}
if (overlayRasterOverlayCount > MAX_RASTER_OVERLAY_COUNT) {
context.getLogger()->warn(
"Number of overlay raster overlays ({}) exceeds maximum raster overlay count ({}). Excess "
"raster overlays "
"will be ignored.",
overlayRasterOverlayCount,
MAX_RASTER_OVERLAY_COUNT);
}
if (clippingRasterOverlayCount > MAX_RASTER_OVERLAY_COUNT) {
context.getLogger()->warn(
"Number of clipping raster overlays ({}) exceeds maximum raster overlay count ({}). Excess "
"raster overlays "
"will be ignored.",
clippingRasterOverlayCount,
MAX_RASTER_OVERLAY_COUNT);
}
return RasterOverlayIndices{std::move(overlayRasterOverlayIndices), std::move(clippingRasterOverlayIndices)};
}
uint64_t getRasterOverlayCount(const FabricMaterialDescriptor& materialDescriptor) {
return materialDescriptor.getRasterOverlayRenderMethods().size();
}
bool isClippingEnabled(const FabricMaterialDescriptor& materialDescriptor) {
return CppUtil::contains(materialDescriptor.getRasterOverlayRenderMethods(), FabricOverlayRenderMethod::CLIPPING);
}
FabricAlphaMode
getInitialAlphaMode(const FabricMaterialDescriptor& materialDescriptor, const FabricMaterialInfo& materialInfo) {
if (materialInfo.alphaMode == FabricAlphaMode::BLEND) {
return materialInfo.alphaMode;
}
if (isClippingEnabled(materialDescriptor)) {
return FabricAlphaMode::MASK;
}
return materialInfo.alphaMode;
}
int getAlphaMode(FabricAlphaMode alphaMode, double displayOpacity) {
return static_cast<int>(displayOpacity < 1.0 ? FabricAlphaMode::BLEND : alphaMode);
}
glm::dvec4 getTileColor(const glm::dvec3& debugColor, const glm::dvec3& displayColor, double displayOpacity) {
return {debugColor * displayColor, displayOpacity};
}
void createConnection(
omni::fabric::StageReaderWriter& fabricStage,
const omni::fabric::Path& outputPath,
const omni::fabric::Path& inputPath,
const omni::fabric::Token& inputName) {
fabricStage.createConnection(inputPath, inputName, omni::fabric::Connection{outputPath, FabricTokens::outputs_out});
}
void destroyConnection(
omni::fabric::StageReaderWriter& fabricStage,
const omni::fabric::Path& inputPath,
const omni::fabric::Token& inputName) {
fabricStage.destroyConnection(inputPath, inputName);
}
template <DataType T>
constexpr DataTypeUtil::GetMdlInternalPropertyTransformedType<DataTypeUtil::getMdlInternalPropertyType<T>()>
getOffset(const FabricPropertyInfo<T>& info) {
constexpr auto mdlType = DataTypeUtil::getMdlInternalPropertyType<T>();
using TransformedType = DataTypeUtil::GetNativeType<DataTypeUtil::getTransformedType<T>()>;
using MdlTransformedType = DataTypeUtil::GetMdlInternalPropertyTransformedType<mdlType>;
return static_cast<MdlTransformedType>(info.offset.value_or(TransformedType{DEFAULT_OFFSET}));
}
template <DataType T>
constexpr DataTypeUtil::GetMdlInternalPropertyTransformedType<DataTypeUtil::getMdlInternalPropertyType<T>()>
getScale(const FabricPropertyInfo<T>& info) {
constexpr auto mdlType = DataTypeUtil::getMdlInternalPropertyType<T>();
using TransformedType = DataTypeUtil::GetNativeType<DataTypeUtil::getTransformedType<T>()>;
using MdlTransformedType = DataTypeUtil::GetMdlInternalPropertyTransformedType<mdlType>;
return static_cast<MdlTransformedType>(info.scale.value_or(TransformedType{DEFAULT_SCALE}));
}
template <DataType T>
constexpr DataTypeUtil::GetMdlInternalPropertyRawType<DataTypeUtil::getMdlInternalPropertyType<T>()>
getNoData(const FabricPropertyInfo<T>& info) {
constexpr auto mdlType = DataTypeUtil::getMdlInternalPropertyType<T>();
using RawType = DataTypeUtil::GetNativeType<T>;
using MdlRawType = DataTypeUtil::GetMdlInternalPropertyRawType<mdlType>;
return static_cast<MdlRawType>(info.noData.value_or(RawType{DEFAULT_NO_DATA}));
}
template <DataType T>
constexpr DataTypeUtil::GetMdlInternalPropertyTransformedType<DataTypeUtil::getMdlInternalPropertyType<T>()>
getDefaultValue(const FabricPropertyInfo<T>& info) {
constexpr auto mdlType = DataTypeUtil::getMdlInternalPropertyType<T>();
using TransformedType = DataTypeUtil::GetNativeType<DataTypeUtil::getTransformedType<T>()>;
using MdlTransformedType = DataTypeUtil::GetMdlInternalPropertyTransformedType<mdlType>;
return static_cast<MdlTransformedType>(info.defaultValue.value_or(TransformedType{DEFAULT_VALUE}));
}
template <DataType T>
constexpr DataTypeUtil::GetMdlInternalPropertyRawType<DataTypeUtil::getMdlInternalPropertyType<T>()> getMaximumValue() {
constexpr auto mdlType = DataTypeUtil::getMdlInternalPropertyType<T>();
using RawComponentType = DataTypeUtil::GetNativeType<DataTypeUtil::getComponentType<T>()>;
using MdlRawType = DataTypeUtil::GetMdlInternalPropertyRawType<mdlType>;
if constexpr (DataTypeUtil::isNormalized<T>()) {
return MdlRawType{std::numeric_limits<RawComponentType>::max()};
}
return MdlRawType{0};
}
void createAttributes(
const Context& context,
omni::fabric::StageReaderWriter& fabricStage,
const omni::fabric::Path& path,
FabricAttributesBuilder& attributes,
const omni::fabric::Token& subidentifier) {
// clang-format off
attributes.addAttribute(FabricTypes::inputs_excludeFromWhiteMode, FabricTokens::inputs_excludeFromWhiteMode);
attributes.addAttribute(FabricTypes::outputs_out, FabricTokens::outputs_out);
attributes.addAttribute(FabricTypes::info_implementationSource, FabricTokens::info_implementationSource);
attributes.addAttribute(FabricTypes::info_mdl_sourceAsset, FabricTokens::info_mdl_sourceAsset);
attributes.addAttribute(FabricTypes::info_mdl_sourceAsset_subIdentifier, FabricTokens::info_mdl_sourceAsset_subIdentifier);
attributes.addAttribute(FabricTypes::_paramColorSpace, FabricTokens::_paramColorSpace);
attributes.addAttribute(FabricTypes::_sdrMetadata, FabricTokens::_sdrMetadata);
attributes.addAttribute(FabricTypes::Shader, FabricTokens::Shader);
attributes.addAttribute(FabricTypes::_cesium_tilesetId, FabricTokens::_cesium_tilesetId);
// clang-format on
attributes.createAttributes(path);
// clang-format off
const auto inputsExcludeFromWhiteModeFabric = fabricStage.getAttributeWr<bool>(path, FabricTokens::inputs_excludeFromWhiteMode);
const auto infoImplementationSourceFabric = fabricStage.getAttributeWr<omni::fabric::TokenC>(path, FabricTokens::info_implementationSource);
const auto infoMdlSourceAssetFabric = fabricStage.getAttributeWr<omni::fabric::AssetPath>(path, FabricTokens::info_mdl_sourceAsset);
const auto infoMdlSourceAssetSubIdentifierFabric = fabricStage.getAttributeWr<omni::fabric::TokenC>(path, FabricTokens::info_mdl_sourceAsset_subIdentifier);
// clang-format on
fabricStage.setArrayAttributeSize(path, FabricTokens::_paramColorSpace, 0);
fabricStage.setArrayAttributeSize(path, FabricTokens::_sdrMetadata, 0);
*inputsExcludeFromWhiteModeFabric = false;
*infoImplementationSourceFabric = FabricTokens::sourceAsset;
infoMdlSourceAssetFabric->assetPath = context.getCesiumMdlPathToken();
infoMdlSourceAssetFabric->resolvedPath = pxr::TfToken();
*infoMdlSourceAssetSubIdentifierFabric = subidentifier;
}
void setTextureValuesCommon(
omni::fabric::StageReaderWriter& fabricStage,
const omni::fabric::Path& path,
const pxr::TfToken& textureAssetPathToken,
const FabricTextureInfo& textureInfo,
uint64_t texcoordIndex) {
auto offset = textureInfo.offset;
auto rotation = textureInfo.rotation;
auto scale = textureInfo.scale;
if (!textureInfo.flipVertical) {
// gltf/pbr.mdl does texture transform math in glTF coordinates (top-left origin), so we needed to convert
// the translation and scale parameters to work in that space. This doesn't handle rotation yet because we
// haven't needed it for raster overlays.
offset = {offset.x, 1.0 - offset.y - scale.y};
scale = {scale.x, scale.y};
}
const auto textureFabric = fabricStage.getAttributeWr<omni::fabric::AssetPath>(path, FabricTokens::inputs_texture);
const auto texCoordIndexFabric = fabricStage.getAttributeWr<int>(path, FabricTokens::inputs_tex_coord_index);
const auto wrapSFabric = fabricStage.getAttributeWr<int>(path, FabricTokens::inputs_wrap_s);
const auto wrapTFabric = fabricStage.getAttributeWr<int>(path, FabricTokens::inputs_wrap_t);
const auto offsetFabric = fabricStage.getAttributeWr<pxr::GfVec2f>(path, FabricTokens::inputs_tex_coord_offset);
const auto rotationFabric = fabricStage.getAttributeWr<float>(path, FabricTokens::inputs_tex_coord_rotation);
const auto scaleFabric = fabricStage.getAttributeWr<pxr::GfVec2f>(path, FabricTokens::inputs_tex_coord_scale);
textureFabric->assetPath = textureAssetPathToken;
textureFabric->resolvedPath = pxr::TfToken();
*texCoordIndexFabric = static_cast<int>(texcoordIndex);
*wrapSFabric = textureInfo.wrapS;
*wrapTFabric = textureInfo.wrapT;
*offsetFabric = UsdUtil::glmToUsdVector(glm::fvec2(offset));
*rotationFabric = static_cast<float>(rotation);
*scaleFabric = UsdUtil::glmToUsdVector(glm::fvec2(scale));
}
void setTextureValuesCommonChannels(
omni::fabric::StageReaderWriter& fabricStage,
const omni::fabric::Path& path,
const pxr::TfToken& textureAssetPathToken,
const FabricTextureInfo& textureInfo,
uint64_t texcoordIndex) {
setTextureValuesCommon(fabricStage, path, textureAssetPathToken, textureInfo, texcoordIndex);
auto channelCount = glm::min(textureInfo.channels.size(), uint64_t(4));
auto channels = glm::u8vec4(0);
for (uint64_t i = 0; i < channelCount; ++i) {
channels[i] = textureInfo.channels[i];
}
channelCount = glm::max(channelCount, uint64_t(1));
const auto channelsFabric = fabricStage.getAttributeWr<glm::i32vec4>(path, FabricTokens::inputs_channels);
*channelsFabric = static_cast<glm::i32vec4>(channels);
if (fabricStage.attributeExists(path, FabricTokens::inputs_channel_count)) {
const auto channelCountFabric = fabricStage.getAttributeWr<int>(path, FabricTokens::inputs_channel_count);
*channelCountFabric = static_cast<int>(channelCount);
}
}
std::string getStringFabric(
omni::fabric::StageReaderWriter& fabricStage,
const omni::fabric::Path& path,
omni::fabric::TokenC attributeName) {
const auto valueFabric = fabricStage.getArrayAttributeRd<uint8_t>(path, attributeName);
return {reinterpret_cast<const char*>(valueFabric.data()), valueFabric.size()};
}
void setStringFabric(
omni::fabric::StageReaderWriter& fabricStage,
const omni::fabric::Path& path,
omni::fabric::TokenC attributeName,
const std::string& value) {
fabricStage.setArrayAttributeSize(path, attributeName, value.size());
const auto valueFabric = fabricStage.getArrayAttributeWr<uint8_t>(path, attributeName);
memcpy(valueFabric.data(), value.data(), value.size());
}
template <MdlInternalPropertyType T>
void setPropertyValues(
omni::fabric::StageReaderWriter& fabricStage,
const omni::fabric::Path& path,
const DataTypeUtil::GetMdlInternalPropertyTransformedType<T>& offset,
const DataTypeUtil::GetMdlInternalPropertyTransformedType<T>& scale,
const DataTypeUtil::GetMdlInternalPropertyRawType<T>& maximumValue,
bool hasNoData,
const DataTypeUtil::GetMdlInternalPropertyRawType<T>& noData,
const DataTypeUtil::GetMdlInternalPropertyTransformedType<T>& defaultValue) {
using MdlRawType = DataTypeUtil::GetMdlInternalPropertyRawType<T>;
using MdlTransformedType = DataTypeUtil::GetMdlInternalPropertyTransformedType<T>;
const auto hasNoDataFabric = fabricStage.getAttributeWr<bool>(path, FabricTokens::inputs_has_no_data);
const auto noDataFabric = fabricStage.getAttributeWr<MdlRawType>(path, FabricTokens::inputs_no_data);
const auto defaultValueFabric =
fabricStage.getAttributeWr<MdlTransformedType>(path, FabricTokens::inputs_default_value);
*hasNoDataFabric = hasNoData;
*noDataFabric = static_cast<MdlRawType>(noData);
*defaultValueFabric = static_cast<MdlTransformedType>(defaultValue);
if (fabricStage.attributeExists(path, FabricTokens::inputs_offset)) {
const auto offsetFabric = fabricStage.getAttributeWr<MdlTransformedType>(path, FabricTokens::inputs_offset);
*offsetFabric = static_cast<MdlTransformedType>(offset);
}
if (fabricStage.attributeExists(path, FabricTokens::inputs_scale)) {
const auto scaleFabric = fabricStage.getAttributeWr<MdlTransformedType>(path, FabricTokens::inputs_scale);
*scaleFabric = static_cast<MdlTransformedType>(scale);
}
if (fabricStage.attributeExists(path, FabricTokens::inputs_maximum_value)) {
const auto maximumValueFabric =
fabricStage.getAttributeWr<MdlRawType>(path, FabricTokens::inputs_maximum_value);
*maximumValueFabric = static_cast<MdlRawType>(maximumValue);
}
}
template <MdlInternalPropertyType T>
void setPropertyAttributePropertyValues(
omni::fabric::StageReaderWriter& fabricStage,
const omni::fabric::Path& path,
const std::string& primvarName,
const DataTypeUtil::GetMdlInternalPropertyTransformedType<T>& offset,
const DataTypeUtil::GetMdlInternalPropertyTransformedType<T>& scale,
const DataTypeUtil::GetMdlInternalPropertyRawType<T>& maximumValue,
bool hasNoData,
const DataTypeUtil::GetMdlInternalPropertyRawType<T>& noData,
const DataTypeUtil::GetMdlInternalPropertyTransformedType<T>& defaultValue) {
setStringFabric(fabricStage, path, FabricTokens::inputs_primvar_name, primvarName);
setPropertyValues<T>(fabricStage, path, offset, scale, maximumValue, hasNoData, noData, defaultValue);
}
template <MdlInternalPropertyType T>
void setPropertyTexturePropertyValues(
omni::fabric::StageReaderWriter& fabricStage,
const omni::fabric::Path& path,
const pxr::TfToken& textureAssetPathToken,
const FabricTextureInfo& textureInfo,
uint64_t texcoordIndex,
const DataTypeUtil::GetMdlInternalPropertyTransformedType<T>& offset,
const DataTypeUtil::GetMdlInternalPropertyTransformedType<T>& scale,
const DataTypeUtil::GetMdlInternalPropertyRawType<T>& maximumValue,
bool hasNoData,
const DataTypeUtil::GetMdlInternalPropertyRawType<T>& noData,
const DataTypeUtil::GetMdlInternalPropertyTransformedType<T>& defaultValue) {
setTextureValuesCommonChannels(fabricStage, path, textureAssetPathToken, textureInfo, texcoordIndex);
setPropertyValues<T>(fabricStage, path, offset, scale, maximumValue, hasNoData, noData, defaultValue);
}
template <MdlInternalPropertyType T>
void setPropertyTablePropertyValues(
omni::fabric::StageReaderWriter& fabricStage,
const omni::fabric::Path& path,
const pxr::TfToken& propertyTableTextureAssetPathToken,
const DataTypeUtil::GetMdlInternalPropertyTransformedType<T>& offset,
const DataTypeUtil::GetMdlInternalPropertyTransformedType<T>& scale,
const DataTypeUtil::GetMdlInternalPropertyRawType<T>& maximumValue,
bool hasNoData,
const DataTypeUtil::GetMdlInternalPropertyRawType<T>& noData,
const DataTypeUtil::GetMdlInternalPropertyTransformedType<T>& defaultValue) {
const auto textureFabric =
fabricStage.getAttributeWr<omni::fabric::AssetPath>(path, FabricTokens::inputs_property_table_texture);
textureFabric->assetPath = propertyTableTextureAssetPathToken;
textureFabric->resolvedPath = pxr::TfToken();
setPropertyValues<T>(fabricStage, path, offset, scale, maximumValue, hasNoData, noData, defaultValue);
}
template <MdlInternalPropertyType T>
void clearPropertyAttributeProperty(omni::fabric::StageReaderWriter& fabricStage, const omni::fabric::Path& path) {
using MdlRawType = DataTypeUtil::GetMdlInternalPropertyRawType<T>;
using MdlTransformedType = DataTypeUtil::GetMdlInternalPropertyTransformedType<T>;
setPropertyAttributePropertyValues<T>(
fabricStage,
path,
"",
MdlTransformedType{0},
MdlTransformedType{0},
MdlRawType{0},
false,
MdlRawType{0},
MdlTransformedType{0});
}
template <MdlInternalPropertyType T>
void clearPropertyTextureProperty(
omni::fabric::StageReaderWriter& fabricStage,
const omni::fabric::Path& path,
const pxr::TfToken& defaultTransparentTextureAssetPathToken) {
using MdlRawType = DataTypeUtil::GetMdlInternalPropertyRawType<T>;
using MdlTransformedType = DataTypeUtil::GetMdlInternalPropertyTransformedType<T>;
setPropertyTexturePropertyValues<T>(
fabricStage,
path,
defaultTransparentTextureAssetPathToken,
GltfUtil::getDefaultTextureInfo(),
DEFAULT_TEXCOORD_INDEX,
MdlTransformedType{0},
MdlTransformedType{0},
MdlRawType{0},
false,
MdlRawType{0},
MdlTransformedType{0});
}
template <MdlInternalPropertyType T>
void clearPropertyTableProperty(
omni::fabric::StageReaderWriter& fabricStage,
const omni::fabric::Path& path,
const pxr::TfToken& defaultTransparentTextureAssetPathToken) {
using MdlRawType = DataTypeUtil::GetMdlInternalPropertyRawType<T>;
using MdlTransformedType = DataTypeUtil::GetMdlInternalPropertyTransformedType<T>;
setPropertyTablePropertyValues<T>(
fabricStage,
path,
defaultTransparentTextureAssetPathToken,
MdlTransformedType{0},
MdlTransformedType{0},
MdlRawType{0},
false,
MdlRawType{0},
MdlTransformedType{0});
}
} // namespace
FabricMaterial::FabricMaterial(
Context* pContext,
const omni::fabric::Path& path,
const FabricMaterialDescriptor& materialDescriptor,
const pxr::TfToken& defaultWhiteTextureAssetPathToken,
const pxr::TfToken& defaultTransparentTextureAssetPathToken,
bool debugRandomColors,
int64_t poolId)
: _pContext(pContext)
, _materialPath(path)
, _materialDescriptor(materialDescriptor)
, _defaultWhiteTextureAssetPathToken(defaultWhiteTextureAssetPathToken)
, _defaultTransparentTextureAssetPathToken(defaultTransparentTextureAssetPathToken)
, _debugRandomColors(debugRandomColors)
, _poolId(poolId)
, _stageId(pContext->getUsdStageId())
, _usesDefaultMaterial(!materialDescriptor.hasTilesetMaterial()) {
if (stageDestroyed()) {
return;
}
initializeNodes();
if (_usesDefaultMaterial) {
initializeDefaultMaterial();
} else {
initializeExistingMaterial(FabricUtil::toFabricPath(materialDescriptor.getTilesetMaterialPath()));
}
reset();
}
FabricMaterial::~FabricMaterial() {
// The code below is temporarily commented out to avoid a crash.
// It will cause a leak, but since this only happens when materials
// pools are destroyed (which doesn't happen during normal usage) it
// shouldn't be a huge concern.
//
// See https://github.com/CesiumGS/cesium-omniverse/issues/444 for details.
// if (stageDestroyed()) {
// return;
// }
// for (const auto& path : _allPaths) {
// FabricUtil::destroyPrim(_pContext->getFabricStage(), path);
// }
}
void FabricMaterial::setActive(bool active) {
if (stageDestroyed()) {
return;
}
if (!active) {
reset();
}
}
const omni::fabric::Path& FabricMaterial::getPath() const {
return _materialPath;
}
const FabricMaterialDescriptor& FabricMaterial::getMaterialDescriptor() const {
return _materialDescriptor;
}
int64_t FabricMaterial::getPoolId() const {
return _poolId;
}
void FabricMaterial::initializeNodes() {
auto& fabricStage = _pContext->getFabricStage();
// Create base color texture
const auto hasBaseColorTexture = _materialDescriptor.hasBaseColorTexture();
if (hasBaseColorTexture) {
const auto baseColorTexturePath = FabricUtil::joinPaths(_materialPath, FabricTokens::base_color_texture);
createTexture(baseColorTexturePath);
_baseColorTexturePath = baseColorTexturePath;
_allPaths.push_back(baseColorTexturePath);
}
// Create raster overlays
const auto rasterOverlayCount = getRasterOverlayCount(_materialDescriptor);
_rasterOverlayPaths.reserve(rasterOverlayCount);
for (uint64_t i = 0; i < rasterOverlayCount; ++i) {
const auto rasterOverlayPath = FabricUtil::joinPaths(_materialPath, FabricTokens::raster_overlay_n(i));
createRasterOverlay(rasterOverlayPath);
_rasterOverlayPaths.push_back(rasterOverlayPath);
_allPaths.push_back(rasterOverlayPath);
}
// Create feature ids
const auto& featureIdTypes = _materialDescriptor.getFeatureIdTypes();
const auto featureIdCounts = getFeatureIdCounts(_materialDescriptor);
_featureIdPaths.reserve(featureIdCounts.totalCount);
_featureIdIndexPaths.reserve(featureIdCounts.indexCount);
_featureIdAttributePaths.reserve(featureIdCounts.attributeCount);
_featureIdTexturePaths.reserve(featureIdCounts.textureCount);
for (uint64_t i = 0; i < featureIdCounts.totalCount; ++i) {
const auto featureIdType = featureIdTypes[i];
const auto featureIdPath = FabricUtil::joinPaths(_materialPath, FabricTokens::feature_id_n(i));
switch (featureIdType) {
case FabricFeatureIdType::INDEX:
createFeatureIdIndex(featureIdPath);
_featureIdIndexPaths.push_back(featureIdPath);
break;
case FabricFeatureIdType::ATTRIBUTE:
createFeatureIdAttribute(featureIdPath);
_featureIdAttributePaths.push_back(featureIdPath);
break;
case FabricFeatureIdType::TEXTURE:
createFeatureIdTexture(featureIdPath);
_featureIdTexturePaths.push_back(featureIdPath);
break;
}
_featureIdPaths.push_back(featureIdPath);
_allPaths.push_back(featureIdPath);
}
// Create properties
const auto& properties = _materialDescriptor.getStyleableProperties();
for (uint64_t i = 0; i < properties.size(); ++i) {
const auto& property = properties[i];
const auto storageType = property.storageType;
const auto type = property.type;
const auto& propertyPath = FabricUtil::joinPaths(_materialPath, FabricTokens::property_n(i));
switch (storageType) {
case FabricPropertyStorageType::ATTRIBUTE:
createPropertyAttributeProperty(propertyPath, type);
_propertyAttributePropertyPaths[type].push_back(propertyPath);
break;
case FabricPropertyStorageType::TEXTURE:
createPropertyTextureProperty(propertyPath, type);
_propertyTexturePropertyPaths[type].push_back(propertyPath);
break;
case FabricPropertyStorageType::TABLE:
createPropertyTableProperty(propertyPath, type);
_propertyTablePropertyPaths[type].push_back(propertyPath);
// Create connection from the feature id node to the property table property node
const auto featureIdSetIndex = property.featureIdSetIndex;
const auto& featureIdPath = _featureIdPaths[featureIdSetIndex];
createConnection(fabricStage, featureIdPath, propertyPath, FabricTokens::inputs_feature_id);
break;
}
_propertyPaths.push_back(propertyPath);
_allPaths.push_back(propertyPath);
}
}
void FabricMaterial::initializeDefaultMaterial() {
auto& fabricStage = _pContext->getFabricStage();
const auto rasterOverlayIndices = getRasterOverlayIndices(*_pContext, _materialDescriptor);
const auto hasBaseColorTexture = _materialDescriptor.hasBaseColorTexture();
// Create material
const auto& materialPath = _materialPath;
createMaterial(materialPath);
_allPaths.push_back(materialPath);
// Create shader
const auto shaderPath = FabricUtil::joinPaths(materialPath, FabricTokens::cesium_internal_material);
createShader(shaderPath);
_shaderPath = shaderPath;
_allPaths.push_back(shaderPath);
const auto& overlayRasterOverlayIndices = rasterOverlayIndices.overlayRasterOverlayIndices;
const auto& clippingRasterOverlayIndices = rasterOverlayIndices.clippingRasterOverlayIndices;
const auto overlayRasterOverlayCount = overlayRasterOverlayIndices.size();
const auto clippingRasterOverlayCount = clippingRasterOverlayIndices.size();
// Create overlay raster overlay resolver if there are multiple overlay raster overlays
if (overlayRasterOverlayCount > 1) {
const auto rasterOverlayResolverPath =
FabricUtil::joinPaths(materialPath, FabricTokens::raster_overlay_resolver);
createRasterOverlayResolver(rasterOverlayResolverPath, overlayRasterOverlayCount);
_overlayRasterOverlayResolverPath = rasterOverlayResolverPath;
_allPaths.push_back(rasterOverlayResolverPath);
}
// Create clipping raster overlay resolver if there are multiple clipping raster overlays
if (clippingRasterOverlayCount > 1) {
const auto clippingRasterOverlayResolverPath =
FabricUtil::joinPaths(materialPath, FabricTokens::clipping_raster_overlay_resolver);
createClippingRasterOverlayResolver(clippingRasterOverlayResolverPath, clippingRasterOverlayCount);
_clippingRasterOverlayResolverPath = clippingRasterOverlayResolverPath;
_allPaths.push_back(_clippingRasterOverlayResolverPath);
}
// Create connection from shader to material
createConnection(fabricStage, shaderPath, materialPath, FabricTokens::outputs_mdl_surface);
createConnection(fabricStage, shaderPath, materialPath, FabricTokens::outputs_mdl_displacement);
createConnection(fabricStage, shaderPath, materialPath, FabricTokens::outputs_mdl_volume);
// Create connection from base color texture to shader
if (hasBaseColorTexture) {
createConnection(fabricStage, _baseColorTexturePath, shaderPath, FabricTokens::inputs_base_color_texture);
}
if (overlayRasterOverlayCount == 1) {
// Create connection from raster overlay to shader
const auto& rasterOverlayPath = _rasterOverlayPaths[overlayRasterOverlayIndices.front()];
createConnection(fabricStage, rasterOverlayPath, shaderPath, FabricTokens::inputs_raster_overlay);
} else if (overlayRasterOverlayCount > 1) {
// Create connection from raster overlay resolver to shader
createConnection(
fabricStage, _overlayRasterOverlayResolverPath, shaderPath, FabricTokens::inputs_raster_overlay);
// Create connections from raster overlays to raster overlay resolver
for (uint64_t i = 0; i < overlayRasterOverlayCount; ++i) {
const auto& rasterOverlayPath = _rasterOverlayPaths[overlayRasterOverlayIndices[i]];
createConnection(
fabricStage,
rasterOverlayPath,
_overlayRasterOverlayResolverPath,
FabricTokens::inputs_raster_overlay_n(i));
}
}
if (clippingRasterOverlayCount == 1) {
// Create connection from raster overlay to shader
const auto& rasterOverlayPath = _rasterOverlayPaths[clippingRasterOverlayIndices.front()];
createConnection(fabricStage, rasterOverlayPath, shaderPath, FabricTokens::inputs_alpha_clip);
} else if (clippingRasterOverlayCount > 1) {
// Create connection from raster overlay resolver to shader
createConnection(fabricStage, _clippingRasterOverlayResolverPath, shaderPath, FabricTokens::inputs_alpha_clip);
// Create connections from raster overlays to raster overlay resolver
for (uint64_t i = 0; i < clippingRasterOverlayCount; ++i) {
const auto& rasterOverlayPath = _rasterOverlayPaths[clippingRasterOverlayIndices[i]];
createConnection(
fabricStage,
rasterOverlayPath,
_clippingRasterOverlayResolverPath,
FabricTokens::inputs_raster_overlay_n(i));
}
}
}
void FabricMaterial::initializeExistingMaterial(const omni::fabric::Path& path) {
auto& fabricStage = _pContext->getFabricStage();
const auto copiedPaths = FabricUtil::copyMaterial(fabricStage, path, _materialPath);
for (const auto& copiedPath : copiedPaths) {
fabricStage.createAttribute(copiedPath, FabricTokens::_cesium_tilesetId, FabricTypes::_cesium_tilesetId);
_allPaths.push_back(copiedPath);
const auto mdlIdentifier = FabricUtil::getMdlIdentifier(fabricStage, copiedPath);
if (mdlIdentifier == FabricTokens::cesium_base_color_texture_float4) {
_copiedBaseColorTexturePaths.push_back(copiedPath);
} else if (mdlIdentifier == FabricTokens::cesium_raster_overlay_float4) {
_copiedRasterOverlayPaths.push_back(copiedPath);
} else if (mdlIdentifier == FabricTokens::cesium_feature_id_int) {
_copiedFeatureIdPaths.push_back(copiedPath);
} else if (FabricUtil::isCesiumPropertyNode(mdlIdentifier)) {
_copiedPropertyPaths.push_back(copiedPath);
}
}
createConnectionsToCopiedPaths();
createConnectionsToProperties();
}
void FabricMaterial::createMaterial(const omni::fabric::Path& path) {
auto& fabricStage = _pContext->getFabricStage();
fabricStage.createPrim(path);
FabricAttributesBuilder attributes(_pContext);
attributes.addAttribute(FabricTypes::Material, FabricTokens::Material);
attributes.addAttribute(FabricTypes::_cesium_tilesetId, FabricTokens::_cesium_tilesetId);
attributes.createAttributes(path);
}
void FabricMaterial::createShader(const omni::fabric::Path& path) {
auto& fabricStage = _pContext->getFabricStage();
fabricStage.createPrim(path);
FabricAttributesBuilder attributes(_pContext);
attributes.addAttribute(FabricTypes::inputs_tile_color, FabricTokens::inputs_tile_color);
attributes.addAttribute(FabricTypes::inputs_alpha_cutoff, FabricTokens::inputs_alpha_cutoff);
attributes.addAttribute(FabricTypes::inputs_alpha_mode, FabricTokens::inputs_alpha_mode);
attributes.addAttribute(FabricTypes::inputs_base_alpha, FabricTokens::inputs_base_alpha);
attributes.addAttribute(FabricTypes::inputs_base_color_factor, FabricTokens::inputs_base_color_factor);
attributes.addAttribute(FabricTypes::inputs_emissive_factor, FabricTokens::inputs_emissive_factor);
attributes.addAttribute(FabricTypes::inputs_metallic_factor, FabricTokens::inputs_metallic_factor);
attributes.addAttribute(FabricTypes::inputs_roughness_factor, FabricTokens::inputs_roughness_factor);
createAttributes(*_pContext, fabricStage, path, attributes, FabricTokens::cesium_internal_material);
}
void FabricMaterial::createTextureCommon(
const omni::fabric::Path& path,
const omni::fabric::Token& subIdentifier,
const std::vector<std::pair<omni::fabric::Type, omni::fabric::Token>>& additionalAttributes) {
auto& fabricStage = _pContext->getFabricStage();
fabricStage.createPrim(path);
FabricAttributesBuilder attributes(_pContext);
attributes.addAttribute(FabricTypes::inputs_tex_coord_offset, FabricTokens::inputs_tex_coord_offset);
attributes.addAttribute(FabricTypes::inputs_tex_coord_rotation, FabricTokens::inputs_tex_coord_rotation);
attributes.addAttribute(FabricTypes::inputs_tex_coord_scale, FabricTokens::inputs_tex_coord_scale);
attributes.addAttribute(FabricTypes::inputs_tex_coord_index, FabricTokens::inputs_tex_coord_index);
attributes.addAttribute(FabricTypes::inputs_texture, FabricTokens::inputs_texture);
attributes.addAttribute(FabricTypes::inputs_wrap_s, FabricTokens::inputs_wrap_s);
attributes.addAttribute(FabricTypes::inputs_wrap_t, FabricTokens::inputs_wrap_t);
for (const auto& additionalAttribute : additionalAttributes) {
attributes.addAttribute(additionalAttribute.first, additionalAttribute.second);
}
createAttributes(*_pContext, fabricStage, path, attributes, subIdentifier);
// _paramColorSpace is an array of pairs: [texture_parameter_token, color_space_enum], [texture_parameter_token, color_space_enum], ...
fabricStage.setArrayAttributeSize(path, FabricTokens::_paramColorSpace, 2);
const auto paramColorSpaceFabric =
fabricStage.getArrayAttributeWr<omni::fabric::TokenC>(path, FabricTokens::_paramColorSpace);
paramColorSpaceFabric[0] = FabricTokens::inputs_texture;
paramColorSpaceFabric[1] = FabricTokens::_auto;
}
void FabricMaterial::createTexture(const omni::fabric::Path& path) {
return createTextureCommon(path, FabricTokens::cesium_internal_texture_lookup);
}
void FabricMaterial::createRasterOverlay(const omni::fabric::Path& path) {
static const auto additionalAttributes = std::vector<std::pair<omni::fabric::Type, omni::fabric::Token>>{{
std::make_pair(FabricTypes::inputs_alpha, FabricTokens::inputs_alpha),
}};
return createTextureCommon(path, FabricTokens::cesium_internal_raster_overlay_lookup, additionalAttributes);
}
void FabricMaterial::createRasterOverlayResolverCommon(
const omni::fabric::Path& path,
uint64_t rasterOverlayCount,
const omni::fabric::Token& subidentifier) {
auto& fabricStage = _pContext->getFabricStage();
fabricStage.createPrim(path);
FabricAttributesBuilder attributes(_pContext);
attributes.addAttribute(FabricTypes::inputs_raster_overlay_count, FabricTokens::inputs_raster_overlay_count);
createAttributes(*_pContext, fabricStage, path, attributes, subidentifier);
const auto rasterOverlayCountFabric =
fabricStage.getAttributeWr<int>(path, FabricTokens::inputs_raster_overlay_count);
*rasterOverlayCountFabric = static_cast<int>(rasterOverlayCount);
}
void FabricMaterial::createRasterOverlayResolver(const omni::fabric::Path& path, uint64_t rasterOverlayCount) {
createRasterOverlayResolverCommon(path, rasterOverlayCount, FabricTokens::cesium_internal_raster_overlay_resolver);
}
void FabricMaterial::createClippingRasterOverlayResolver(
const omni::fabric::Path& path,
uint64_t clippingRasterOverlayCount) {
createRasterOverlayResolverCommon(
path, clippingRasterOverlayCount, FabricTokens::cesium_internal_clipping_raster_overlay_resolver);
}
void FabricMaterial::createFeatureIdIndex(const omni::fabric::Path& path) {
createFeatureIdAttribute(path);
}
void FabricMaterial::createFeatureIdAttribute(const omni::fabric::Path& path) {
auto& fabricStage = _pContext->getFabricStage();
fabricStage.createPrim(path);
FabricAttributesBuilder attributes(_pContext);
attributes.addAttribute(FabricTypes::inputs_primvar_name, FabricTokens::inputs_primvar_name);
attributes.addAttribute(FabricTypes::inputs_null_feature_id, FabricTokens::inputs_null_feature_id);
createAttributes(
*_pContext, fabricStage, path, attributes, FabricTokens::cesium_internal_feature_id_attribute_lookup);
}
void FabricMaterial::createFeatureIdTexture(const omni::fabric::Path& path) {
static const auto additionalAttributes = std::vector<std::pair<omni::fabric::Type, omni::fabric::Token>>{{
std::make_pair(FabricTypes::inputs_channels, FabricTokens::inputs_channels),
std::make_pair(FabricTypes::inputs_channel_count, FabricTokens::inputs_channel_count),
std::make_pair(FabricTypes::inputs_null_feature_id, FabricTokens::inputs_null_feature_id),
}};
return createTextureCommon(path, FabricTokens::cesium_internal_feature_id_texture_lookup, additionalAttributes);
}
void FabricMaterial::createPropertyAttributePropertyInt(
const omni::fabric::Path& path,
const omni::fabric::Token& subidentifier,
const omni::fabric::Type& noDataType,
const omni::fabric::Type& defaultValueType) {
auto& fabricStage = _pContext->getFabricStage();
fabricStage.createPrim(path);
FabricAttributesBuilder attributes(_pContext);
attributes.addAttribute(FabricTypes::inputs_primvar_name, FabricTokens::inputs_primvar_name);
attributes.addAttribute(FabricTypes::inputs_has_no_data, FabricTokens::inputs_has_no_data);
attributes.addAttribute(noDataType, FabricTokens::inputs_no_data);
attributes.addAttribute(defaultValueType, FabricTokens::inputs_default_value);
createAttributes(*_pContext, fabricStage, path, attributes, subidentifier);
}
void FabricMaterial::createPropertyAttributePropertyNormalizedInt(
const omni::fabric::Path& path,
const omni::fabric::Token& subidentifier,
const omni::fabric::Type& noDataType,
const omni::fabric::Type& defaultValueType,
const omni::fabric::Type& offsetType,
const omni::fabric::Type& scaleType,
const omni::fabric::Type& maximumValueType) {
auto& fabricStage = _pContext->getFabricStage();
fabricStage.createPrim(path);
FabricAttributesBuilder attributes(_pContext);
attributes.addAttribute(FabricTypes::inputs_primvar_name, FabricTokens::inputs_primvar_name);
attributes.addAttribute(FabricTypes::inputs_has_no_data, FabricTokens::inputs_has_no_data);
attributes.addAttribute(noDataType, FabricTokens::inputs_no_data);
attributes.addAttribute(defaultValueType, FabricTokens::inputs_default_value);
attributes.addAttribute(offsetType, FabricTokens::inputs_offset);
attributes.addAttribute(scaleType, FabricTokens::inputs_scale);
attributes.addAttribute(maximumValueType, FabricTokens::inputs_maximum_value);
createAttributes(*_pContext, fabricStage, path, attributes, subidentifier);
}
void FabricMaterial::createPropertyAttributePropertyFloat(
const omni::fabric::Path& path,
const omni::fabric::Token& subidentifier,
const omni::fabric::Type& noDataType,
const omni::fabric::Type& defaultValueType,
const omni::fabric::Type& offsetType,
const omni::fabric::Type& scaleType) {
auto& fabricStage = _pContext->getFabricStage();
fabricStage.createPrim(path);
FabricAttributesBuilder attributes(_pContext);
attributes.addAttribute(FabricTypes::inputs_primvar_name, FabricTokens::inputs_primvar_name);
attributes.addAttribute(FabricTypes::inputs_has_no_data, FabricTokens::inputs_has_no_data);
attributes.addAttribute(noDataType, FabricTokens::inputs_no_data);
attributes.addAttribute(defaultValueType, FabricTokens::inputs_default_value);
attributes.addAttribute(offsetType, FabricTokens::inputs_offset);
attributes.addAttribute(scaleType, FabricTokens::inputs_scale);
createAttributes(*_pContext, fabricStage, path, attributes, subidentifier);
}
void FabricMaterial::createPropertyAttributeProperty(const omni::fabric::Path& path, MdlInternalPropertyType type) {
switch (type) {
case MdlInternalPropertyType::INT32:
createPropertyAttributePropertyInt(
path,
FabricTokens::cesium_internal_property_attribute_int_lookup,
FabricTypes::inputs_no_data_int,
FabricTypes::inputs_default_value_int);
break;
case MdlInternalPropertyType::VEC2_INT32:
createPropertyAttributePropertyInt(
path,
FabricTokens::cesium_internal_property_attribute_int2_lookup,
FabricTypes::inputs_no_data_int2,
FabricTypes::inputs_default_value_int2);
break;
case MdlInternalPropertyType::VEC3_INT32:
createPropertyAttributePropertyInt(
path,
FabricTokens::cesium_internal_property_attribute_int3_lookup,
FabricTypes::inputs_no_data_int3,
FabricTypes::inputs_default_value_int3);
break;
case MdlInternalPropertyType::VEC4_INT32:
createPropertyAttributePropertyInt(
path,
FabricTokens::cesium_internal_property_attribute_int4_lookup,
FabricTypes::inputs_no_data_int4,
FabricTypes::inputs_default_value_int4);
break;
case MdlInternalPropertyType::INT32_NORM:
createPropertyAttributePropertyNormalizedInt(
path,
FabricTokens::cesium_internal_property_attribute_normalized_int_lookup,
FabricTypes::inputs_no_data_int,
FabricTypes::inputs_default_value_float,
FabricTypes::inputs_offset_float,
FabricTypes::inputs_scale_float,
FabricTypes::inputs_maximum_value_int);
break;
case MdlInternalPropertyType::VEC2_INT32_NORM:
createPropertyAttributePropertyNormalizedInt(
path,
FabricTokens::cesium_internal_property_attribute_normalized_int2_lookup,
FabricTypes::inputs_no_data_int2,
FabricTypes::inputs_default_value_float2,
FabricTypes::inputs_offset_float2,
FabricTypes::inputs_scale_float2,
FabricTypes::inputs_maximum_value_int2);
break;
case MdlInternalPropertyType::VEC3_INT32_NORM:
createPropertyAttributePropertyNormalizedInt(
path,
FabricTokens::cesium_internal_property_attribute_normalized_int3_lookup,
FabricTypes::inputs_no_data_int3,
FabricTypes::inputs_default_value_float3,
FabricTypes::inputs_offset_float3,
FabricTypes::inputs_scale_float3,
FabricTypes::inputs_maximum_value_int3);
break;
case MdlInternalPropertyType::VEC4_INT32_NORM:
createPropertyAttributePropertyNormalizedInt(
path,
FabricTokens::cesium_internal_property_attribute_normalized_int4_lookup,
FabricTypes::inputs_no_data_int4,
FabricTypes::inputs_default_value_float4,
FabricTypes::inputs_offset_float4,
FabricTypes::inputs_scale_float4,
FabricTypes::inputs_maximum_value_int4);
break;
case MdlInternalPropertyType::FLOAT32:
createPropertyAttributePropertyFloat(
path,
FabricTokens::cesium_internal_property_attribute_float_lookup,
FabricTypes::inputs_no_data_float,
FabricTypes::inputs_default_value_float,
FabricTypes::inputs_offset_float,
FabricTypes::inputs_scale_float);
break;
case MdlInternalPropertyType::VEC2_FLOAT32:
createPropertyAttributePropertyFloat(
path,
FabricTokens::cesium_internal_property_attribute_float2_lookup,
FabricTypes::inputs_no_data_float2,
FabricTypes::inputs_default_value_float2,
FabricTypes::inputs_offset_float2,
FabricTypes::inputs_scale_float2);
break;
case MdlInternalPropertyType::VEC3_FLOAT32:
createPropertyAttributePropertyFloat(
path,
FabricTokens::cesium_internal_property_attribute_float3_lookup,
FabricTypes::inputs_no_data_float3,
FabricTypes::inputs_default_value_float3,
FabricTypes::inputs_offset_float3,
FabricTypes::inputs_scale_float3);
break;
case MdlInternalPropertyType::VEC4_FLOAT32:
createPropertyAttributePropertyFloat(
path,
FabricTokens::cesium_internal_property_attribute_float4_lookup,
FabricTypes::inputs_no_data_float4,
FabricTypes::inputs_default_value_float4,
FabricTypes::inputs_offset_float4,
FabricTypes::inputs_scale_float4);
break;
case MdlInternalPropertyType::MAT2_INT32:
case MdlInternalPropertyType::MAT2_FLOAT32:
case MdlInternalPropertyType::MAT2_INT32_NORM:
case MdlInternalPropertyType::MAT3_INT32:
case MdlInternalPropertyType::MAT3_FLOAT32:
case MdlInternalPropertyType::MAT3_INT32_NORM:
case MdlInternalPropertyType::MAT4_INT32:
case MdlInternalPropertyType::MAT4_FLOAT32:
case MdlInternalPropertyType::MAT4_INT32_NORM:
break;
}
}
void FabricMaterial::createPropertyTexturePropertyInt(
const omni::fabric::Path& path,
const omni::fabric::Token& subidentifier,
const omni::fabric::Type& noDataType,
const omni::fabric::Type& defaultValueType) {
static const auto additionalAttributes = std::vector<std::pair<omni::fabric::Type, omni::fabric::Token>>{{
std::make_pair(FabricTypes::inputs_channels, FabricTokens::inputs_channels),
std::make_pair(FabricTypes::inputs_has_no_data, FabricTokens::inputs_has_no_data),
std::make_pair(noDataType, FabricTokens::inputs_no_data),
std::make_pair(defaultValueType, FabricTokens::inputs_default_value),
}};
return createTextureCommon(path, subidentifier, additionalAttributes);
}
void FabricMaterial::createPropertyTexturePropertyNormalizedInt(
const omni::fabric::Path& path,
const omni::fabric::Token& subidentifier,
const omni::fabric::Type& noDataType,
const omni::fabric::Type& defaultValueType,
const omni::fabric::Type& offsetType,
const omni::fabric::Type& scaleType,
const omni::fabric::Type& maximumValueType) {
static const auto additionalAttributes = std::vector<std::pair<omni::fabric::Type, omni::fabric::Token>>{{
std::make_pair(FabricTypes::inputs_channels, FabricTokens::inputs_channels),
std::make_pair(FabricTypes::inputs_has_no_data, FabricTokens::inputs_has_no_data),
std::make_pair(noDataType, FabricTokens::inputs_no_data),
std::make_pair(defaultValueType, FabricTokens::inputs_default_value),
std::make_pair(offsetType, FabricTokens::inputs_offset),
std::make_pair(scaleType, FabricTokens::inputs_scale),
std::make_pair(maximumValueType, FabricTokens::inputs_maximum_value),
}};
return createTextureCommon(path, subidentifier, additionalAttributes);
}
void FabricMaterial::createPropertyTextureProperty(const omni::fabric::Path& path, MdlInternalPropertyType type) {
switch (type) {
case MdlInternalPropertyType::INT32:
createPropertyTexturePropertyInt(
path,
FabricTokens::cesium_internal_property_texture_int_lookup,
FabricTypes::inputs_no_data_int,
FabricTypes::inputs_default_value_int);
break;
case MdlInternalPropertyType::VEC2_INT32:
createPropertyTexturePropertyInt(
path,
FabricTokens::cesium_internal_property_texture_int2_lookup,
FabricTypes::inputs_no_data_int2,
FabricTypes::inputs_default_value_int2);
break;
case MdlInternalPropertyType::VEC3_INT32:
createPropertyTexturePropertyInt(
path,
FabricTokens::cesium_internal_property_texture_int3_lookup,
FabricTypes::inputs_no_data_int3,
FabricTypes::inputs_default_value_int3);
break;
case MdlInternalPropertyType::VEC4_INT32:
createPropertyTexturePropertyInt(
path,
FabricTokens::cesium_internal_property_texture_int4_lookup,
FabricTypes::inputs_no_data_int4,
FabricTypes::inputs_default_value_int4);
break;
case MdlInternalPropertyType::INT32_NORM:
createPropertyTexturePropertyNormalizedInt(
path,
FabricTokens::cesium_internal_property_texture_normalized_int_lookup,
FabricTypes::inputs_no_data_int,
FabricTypes::inputs_default_value_float,
FabricTypes::inputs_offset_float,
FabricTypes::inputs_scale_float,
FabricTypes::inputs_maximum_value_int);
break;
case MdlInternalPropertyType::VEC2_INT32_NORM:
createPropertyTexturePropertyNormalizedInt(
path,
FabricTokens::cesium_internal_property_texture_normalized_int2_lookup,
FabricTypes::inputs_no_data_int2,
FabricTypes::inputs_default_value_float2,
FabricTypes::inputs_offset_float2,
FabricTypes::inputs_scale_float2,
FabricTypes::inputs_maximum_value_int2);
break;
case MdlInternalPropertyType::VEC3_INT32_NORM:
createPropertyTexturePropertyNormalizedInt(
path,
FabricTokens::cesium_internal_property_texture_normalized_int3_lookup,
FabricTypes::inputs_no_data_int3,
FabricTypes::inputs_default_value_float3,
FabricTypes::inputs_offset_float3,
FabricTypes::inputs_scale_float3,
FabricTypes::inputs_maximum_value_int3);
break;
case MdlInternalPropertyType::VEC4_INT32_NORM:
createPropertyTexturePropertyNormalizedInt(
path,
FabricTokens::cesium_internal_property_texture_normalized_int4_lookup,
FabricTypes::inputs_no_data_int4,
FabricTypes::inputs_default_value_float4,
FabricTypes::inputs_offset_float4,
FabricTypes::inputs_scale_float4,
FabricTypes::inputs_maximum_value_int4);
break;
case MdlInternalPropertyType::FLOAT32:
case MdlInternalPropertyType::VEC2_FLOAT32:
case MdlInternalPropertyType::VEC3_FLOAT32:
case MdlInternalPropertyType::VEC4_FLOAT32:
case MdlInternalPropertyType::MAT2_INT32:
case MdlInternalPropertyType::MAT2_FLOAT32:
case MdlInternalPropertyType::MAT2_INT32_NORM:
case MdlInternalPropertyType::MAT3_INT32:
case MdlInternalPropertyType::MAT3_FLOAT32:
case MdlInternalPropertyType::MAT3_INT32_NORM:
case MdlInternalPropertyType::MAT4_INT32:
case MdlInternalPropertyType::MAT4_FLOAT32:
case MdlInternalPropertyType::MAT4_INT32_NORM:
break;
}
}
void FabricMaterial::createPropertyTablePropertyInt(
const omni::fabric::Path& path,
const omni::fabric::Token& subidentifier,
const omni::fabric::Type& noDataType,
const omni::fabric::Type& defaultValueType) {
auto& fabricStage = _pContext->getFabricStage();
fabricStage.createPrim(path);
FabricAttributesBuilder attributes(_pContext);
attributes.addAttribute(FabricTypes::inputs_property_table_texture, FabricTokens::inputs_property_table_texture);
attributes.addAttribute(FabricTypes::inputs_has_no_data, FabricTokens::inputs_has_no_data);
attributes.addAttribute(noDataType, FabricTokens::inputs_no_data);
attributes.addAttribute(defaultValueType, FabricTokens::inputs_default_value);
createAttributes(*_pContext, fabricStage, path, attributes, subidentifier);
}
void FabricMaterial::createPropertyTablePropertyNormalizedInt(
const omni::fabric::Path& path,
const omni::fabric::Token& subidentifier,
const omni::fabric::Type& noDataType,
const omni::fabric::Type& defaultValueType,
const omni::fabric::Type& offsetType,
const omni::fabric::Type& scaleType,
const omni::fabric::Type& maximumValueType) {
auto& fabricStage = _pContext->getFabricStage();
fabricStage.createPrim(path);
FabricAttributesBuilder attributes(_pContext);
attributes.addAttribute(FabricTypes::inputs_property_table_texture, FabricTokens::inputs_property_table_texture);
attributes.addAttribute(FabricTypes::inputs_has_no_data, FabricTokens::inputs_has_no_data);
attributes.addAttribute(noDataType, FabricTokens::inputs_no_data);
attributes.addAttribute(defaultValueType, FabricTokens::inputs_default_value);
attributes.addAttribute(offsetType, FabricTokens::inputs_offset);
attributes.addAttribute(scaleType, FabricTokens::inputs_scale);
attributes.addAttribute(maximumValueType, FabricTokens::inputs_maximum_value);
createAttributes(*_pContext, fabricStage, path, attributes, subidentifier);
}
void FabricMaterial::createPropertyTablePropertyFloat(
const omni::fabric::Path& path,
const omni::fabric::Token& subidentifier,
const omni::fabric::Type& noDataType,
const omni::fabric::Type& defaultValueType,
const omni::fabric::Type& offsetType,
const omni::fabric::Type& scaleType) {
auto& fabricStage = _pContext->getFabricStage();
fabricStage.createPrim(path);
FabricAttributesBuilder attributes(_pContext);
attributes.addAttribute(FabricTypes::inputs_property_table_texture, FabricTokens::inputs_property_table_texture);
attributes.addAttribute(FabricTypes::inputs_has_no_data, FabricTokens::inputs_has_no_data);
attributes.addAttribute(noDataType, FabricTokens::inputs_no_data);
attributes.addAttribute(defaultValueType, FabricTokens::inputs_default_value);
attributes.addAttribute(offsetType, FabricTokens::inputs_offset);
attributes.addAttribute(scaleType, FabricTokens::inputs_scale);
createAttributes(*_pContext, fabricStage, path, attributes, subidentifier);
}
void FabricMaterial::createPropertyTableProperty(const omni::fabric::Path& path, MdlInternalPropertyType type) {
switch (type) {
case MdlInternalPropertyType::INT32:
createPropertyTablePropertyInt(
path,
FabricTokens::cesium_internal_property_table_int_lookup,
FabricTypes::inputs_no_data_int,
FabricTypes::inputs_default_value_int);
break;
case MdlInternalPropertyType::VEC2_INT32:
createPropertyTablePropertyInt(
path,
FabricTokens::cesium_internal_property_table_int2_lookup,
FabricTypes::inputs_no_data_int2,
FabricTypes::inputs_default_value_int2);
break;
case MdlInternalPropertyType::VEC3_INT32:
createPropertyTablePropertyInt(
path,
FabricTokens::cesium_internal_property_table_int3_lookup,
FabricTypes::inputs_no_data_int3,
FabricTypes::inputs_default_value_int3);
break;
case MdlInternalPropertyType::VEC4_INT32:
createPropertyTablePropertyInt(
path,
FabricTokens::cesium_internal_property_table_int4_lookup,
FabricTypes::inputs_no_data_int4,
FabricTypes::inputs_default_value_int4);
break;
case MdlInternalPropertyType::INT32_NORM:
createPropertyTablePropertyNormalizedInt(
path,
FabricTokens::cesium_internal_property_table_normalized_int_lookup,
FabricTypes::inputs_no_data_int,
FabricTypes::inputs_default_value_float,
FabricTypes::inputs_offset_float,
FabricTypes::inputs_scale_float,
FabricTypes::inputs_maximum_value_int);
break;
case MdlInternalPropertyType::VEC2_INT32_NORM:
createPropertyTablePropertyNormalizedInt(
path,
FabricTokens::cesium_internal_property_table_normalized_int2_lookup,
FabricTypes::inputs_no_data_int2,
FabricTypes::inputs_default_value_float2,
FabricTypes::inputs_offset_float2,
FabricTypes::inputs_scale_float2,
FabricTypes::inputs_maximum_value_int2);
break;
case MdlInternalPropertyType::VEC3_INT32_NORM:
createPropertyTablePropertyNormalizedInt(
path,
FabricTokens::cesium_internal_property_table_normalized_int3_lookup,
FabricTypes::inputs_no_data_int3,
FabricTypes::inputs_default_value_float3,
FabricTypes::inputs_offset_float3,
FabricTypes::inputs_scale_float3,
FabricTypes::inputs_maximum_value_int3);
break;
case MdlInternalPropertyType::VEC4_INT32_NORM:
createPropertyTablePropertyNormalizedInt(
path,
FabricTokens::cesium_internal_property_table_normalized_int4_lookup,
FabricTypes::inputs_no_data_int4,
FabricTypes::inputs_default_value_float4,
FabricTypes::inputs_offset_float4,
FabricTypes::inputs_scale_float4,
FabricTypes::inputs_maximum_value_int4);
break;
case MdlInternalPropertyType::FLOAT32:
createPropertyTablePropertyFloat(
path,
FabricTokens::cesium_internal_property_table_float_lookup,
FabricTypes::inputs_no_data_float,
FabricTypes::inputs_default_value_float,
FabricTypes::inputs_offset_float,
FabricTypes::inputs_scale_float);
break;
case MdlInternalPropertyType::VEC2_FLOAT32:
createPropertyTablePropertyFloat(
path,
FabricTokens::cesium_internal_property_table_float2_lookup,
FabricTypes::inputs_no_data_float2,
FabricTypes::inputs_default_value_float2,
FabricTypes::inputs_offset_float2,
FabricTypes::inputs_scale_float2);
break;
case MdlInternalPropertyType::VEC3_FLOAT32:
createPropertyTablePropertyFloat(
path,
FabricTokens::cesium_internal_property_table_float3_lookup,
FabricTypes::inputs_no_data_float3,
FabricTypes::inputs_default_value_float3,
FabricTypes::inputs_offset_float3,
FabricTypes::inputs_scale_float3);
break;
case MdlInternalPropertyType::VEC4_FLOAT32:
createPropertyTablePropertyFloat(
path,
FabricTokens::cesium_internal_property_table_float4_lookup,
FabricTypes::inputs_no_data_float4,
FabricTypes::inputs_default_value_float4,
FabricTypes::inputs_offset_float4,
FabricTypes::inputs_scale_float4);
break;
case MdlInternalPropertyType::MAT2_INT32:
case MdlInternalPropertyType::MAT2_FLOAT32:
case MdlInternalPropertyType::MAT2_INT32_NORM:
case MdlInternalPropertyType::MAT3_INT32:
case MdlInternalPropertyType::MAT3_FLOAT32:
case MdlInternalPropertyType::MAT3_INT32_NORM:
case MdlInternalPropertyType::MAT4_INT32:
case MdlInternalPropertyType::MAT4_FLOAT32:
case MdlInternalPropertyType::MAT4_INT32_NORM:
break;
}
}
void FabricMaterial::reset() {
if (_usesDefaultMaterial) {
setShaderValues(
_shaderPath, GltfUtil::getDefaultMaterialInfo(), DEFAULT_DISPLAY_COLOR, DEFAULT_DISPLAY_OPACITY);
}
if (_materialDescriptor.hasBaseColorTexture()) {
setTextureValues(
_baseColorTexturePath,
_defaultWhiteTextureAssetPathToken,
GltfUtil::getDefaultTextureInfo(),
DEFAULT_TEXCOORD_INDEX);
}
for (const auto& featureIdIndexPath : _featureIdIndexPaths) {
setFeatureIdIndexValues(featureIdIndexPath, DEFAULT_NULL_FEATURE_ID);
}
for (const auto& featureIdAttributePath : _featureIdAttributePaths) {
setFeatureIdAttributeValues(featureIdAttributePath, DEFAULT_FEATURE_ID_PRIMVAR_NAME, DEFAULT_NULL_FEATURE_ID);
}
for (const auto& featureIdTexturePath : _featureIdTexturePaths) {
setFeatureIdTextureValues(
featureIdTexturePath,
_defaultTransparentTextureAssetPathToken,
GltfUtil::getDefaultTextureInfo(),
DEFAULT_TEXCOORD_INDEX,
DEFAULT_NULL_FEATURE_ID);
}
for (const auto& [type, paths] : _propertyAttributePropertyPaths) {
for (const auto& path : paths) {
CALL_TEMPLATED_FUNCTION_WITH_RUNTIME_MDL_TYPE(
clearPropertyAttributeProperty, type, _pContext->getFabricStage(), path);
}
}
for (const auto& [type, paths] : _propertyTexturePropertyPaths) {
for (const auto& path : paths) {
CALL_TEMPLATED_FUNCTION_WITH_RUNTIME_MDL_TYPE(
clearPropertyTextureProperty,
type,
_pContext->getFabricStage(),
path,
_defaultTransparentTextureAssetPathToken);
}
}
for (const auto& [type, paths] : _propertyTablePropertyPaths) {
for (const auto& path : paths) {
CALL_TEMPLATED_FUNCTION_WITH_RUNTIME_MDL_TYPE(
clearPropertyTableProperty,
type,
_pContext->getFabricStage(),
path,
_defaultTransparentTextureAssetPathToken);
}
}
for (const auto& rasterOverlayPath : _rasterOverlayPaths) {
setRasterOverlayValues(
rasterOverlayPath,
_defaultTransparentTextureAssetPathToken,
GltfUtil::getDefaultTextureInfo(),
DEFAULT_TEXCOORD_INDEX,
DEFAULT_ALPHA);
}
for (const auto& path : _allPaths) {
auto& fabricStage = _pContext->getFabricStage();
const auto tilesetIdFabric = fabricStage.getAttributeWr<int64_t>(path, FabricTokens::_cesium_tilesetId);
*tilesetIdFabric = FabricUtil::NO_TILESET_ID;
}
}
void FabricMaterial::setMaterial(
const CesiumGltf::Model& model,
const CesiumGltf::MeshPrimitive& primitive,
int64_t tilesetId,
const FabricMaterialInfo& materialInfo,
const FabricFeaturesInfo& featuresInfo,
FabricTexture* pBaseColorTexture,
const std::vector<std::shared_ptr<FabricTexture>>& featureIdTextures,
const std::vector<std::shared_ptr<FabricTexture>>& propertyTextures,
const std::vector<std::shared_ptr<FabricTexture>>& propertyTableTextures,
const glm::dvec3& displayColor,
double displayOpacity,
const std::unordered_map<uint64_t, uint64_t>& texcoordIndexMapping,
const std::vector<uint64_t>& featureIdIndexSetIndexMapping,
const std::vector<uint64_t>& featureIdAttributeSetIndexMapping,
const std::vector<uint64_t>& featureIdTextureSetIndexMapping,
const std::unordered_map<uint64_t, uint64_t>& propertyTextureIndexMapping) {
if (stageDestroyed()) {
return;
}
if (_usesDefaultMaterial) {
_alphaMode = getInitialAlphaMode(_materialDescriptor, materialInfo);
if (_debugRandomColors) {
const auto r = glm::linearRand(0.0, 1.0);
const auto g = glm::linearRand(0.0, 1.0);
const auto b = glm::linearRand(0.0, 1.0);
_debugColor = glm::dvec3(r, g, b);
} else {
_debugColor = DEFAULT_DEBUG_COLOR;
}
setShaderValues(_shaderPath, materialInfo, displayColor, displayOpacity);
}
if (_materialDescriptor.hasBaseColorTexture()) {
const auto& textureInfo = materialInfo.baseColorTexture.value();
const auto& textureAssetPath = pBaseColorTexture->getAssetPathToken();
const auto texcoordIndex = texcoordIndexMapping.at(textureInfo.setIndex);
setTextureValues(_baseColorTexturePath, textureAssetPath, textureInfo, texcoordIndex);
}
const auto featureIdCounts = getFeatureIdCounts(_materialDescriptor);
for (uint64_t i = 0; i < featureIdCounts.indexCount; ++i) {
const auto featureIdSetIndex = featureIdIndexSetIndexMapping[i];
const auto featureId = featuresInfo.featureIds[featureIdSetIndex];
const auto& featureIdPath = _featureIdPaths[featureIdSetIndex];
const auto nullFeatureId = CppUtil::defaultValue(featureId.nullFeatureId, DEFAULT_NULL_FEATURE_ID);
setFeatureIdIndexValues(featureIdPath, nullFeatureId);
}
for (uint64_t i = 0; i < featureIdCounts.attributeCount; ++i) {
const auto featureIdSetIndex = featureIdAttributeSetIndexMapping[i];
const auto featureId = featuresInfo.featureIds[featureIdSetIndex];
const auto attributeSetIndex = std::get<uint64_t>(featureId.featureIdStorage);
const auto attributeName = fmt::format("_FEATURE_ID_{}", attributeSetIndex);
const auto& featureIdPath = _featureIdPaths[featureIdSetIndex];
const auto nullFeatureId = CppUtil::defaultValue(featureId.nullFeatureId, DEFAULT_NULL_FEATURE_ID);
setFeatureIdAttributeValues(featureIdPath, attributeName, nullFeatureId);
}
for (uint64_t i = 0; i < featureIdCounts.textureCount; ++i) {
const auto featureIdSetIndex = featureIdTextureSetIndexMapping[i];
const auto& featureId = featuresInfo.featureIds[featureIdSetIndex];
const auto& textureInfo = std::get<FabricTextureInfo>(featureId.featureIdStorage);
const auto& textureAssetPath = featureIdTextures[i]->getAssetPathToken();
const auto texcoordIndex = texcoordIndexMapping.at(textureInfo.setIndex);
const auto& featureIdPath = _featureIdPaths[featureIdSetIndex];
const auto nullFeatureId = CppUtil::defaultValue(featureId.nullFeatureId, DEFAULT_NULL_FEATURE_ID);
setFeatureIdTextureValues(featureIdPath, textureAssetPath, textureInfo, texcoordIndex, nullFeatureId);
}
const auto& properties = _materialDescriptor.getStyleableProperties();
if (!properties.empty()) {
const auto getPropertyPath = [this, &properties](const std::string& propertyId) {
const auto index = CppUtil::indexOfByMember(properties, &FabricPropertyDescriptor::propertyId, propertyId);
assert(index != properties.size());
return _propertyPaths[index];
};
const auto unsupportedCallback = []([[maybe_unused]] const std::string& propertyId,
[[maybe_unused]] const std::string& warning) {};
MetadataUtil::forEachStyleablePropertyAttributeProperty(
*_pContext,
model,
primitive,
[this, &getPropertyPath](
const std::string& propertyId,
[[maybe_unused]] const auto& propertyAttributePropertyView,
const auto& property) {
constexpr auto type = std::decay_t<decltype(property)>::Type;
constexpr auto mdlType = DataTypeUtil::getMdlInternalPropertyType<type>();
const auto& primvarName = property.attribute;
const auto& propertyPath = getPropertyPath(propertyId);
const auto& propertyInfo = property.propertyInfo;
const auto hasNoData = propertyInfo.noData.has_value();
const auto offset = getOffset(propertyInfo);
const auto scale = getScale(propertyInfo);
const auto noData = getNoData(propertyInfo);
const auto defaultValue = getDefaultValue(propertyInfo);
constexpr auto maximumValue = getMaximumValue<type>();
setPropertyAttributePropertyValues<mdlType>(
_pContext->getFabricStage(),
propertyPath,
primvarName,
offset,
scale,
maximumValue,
hasNoData,
noData,
defaultValue);
},
unsupportedCallback);
MetadataUtil::forEachStyleablePropertyTextureProperty(
*_pContext,
model,
primitive,
[this, &propertyTextures, &texcoordIndexMapping, &propertyTextureIndexMapping, &getPropertyPath](
const std::string& propertyId,
[[maybe_unused]] const auto& propertyTexturePropertyView,
const auto& property) {
constexpr auto type = std::decay_t<decltype(property)>::Type;
constexpr auto mdlType = DataTypeUtil::getMdlInternalPropertyType<type>();
const auto& textureInfo = property.textureInfo;
const auto textureIndex = property.textureIndex;
const auto& propertyPath = getPropertyPath(propertyId);
const auto texcoordIndex = texcoordIndexMapping.at(textureInfo.setIndex);
const auto propertyTextureIndex = propertyTextureIndexMapping.at(textureIndex);
const auto& textureAssetPath = propertyTextures[propertyTextureIndex]->getAssetPathToken();
const auto& propertyInfo = property.propertyInfo;
const auto hasNoData = propertyInfo.noData.has_value();
const auto offset = getOffset(propertyInfo);
const auto scale = getScale(propertyInfo);
const auto noData = getNoData(propertyInfo);
const auto defaultValue = getDefaultValue(propertyInfo);
constexpr auto maximumValue = getMaximumValue<type>();
setPropertyTexturePropertyValues<mdlType>(
_pContext->getFabricStage(),
propertyPath,
textureAssetPath,
textureInfo,
texcoordIndex,
offset,
scale,
maximumValue,
hasNoData,
noData,
defaultValue);
},
unsupportedCallback);
uint64_t propertyTablePropertyCounter = 0;
MetadataUtil::forEachStyleablePropertyTableProperty(
*_pContext,
model,
primitive,
[this, &propertyTableTextures, &propertyTablePropertyCounter, &getPropertyPath](
const std::string& propertyId,
[[maybe_unused]] const auto& propertyTablePropertyView,
const auto& property) {
constexpr auto type = std::decay_t<decltype(property)>::Type;
constexpr auto mdlType = DataTypeUtil::getMdlInternalPropertyType<type>();
const auto& propertyPath = getPropertyPath(propertyId);
const auto textureIndex = propertyTablePropertyCounter++;
const auto& textureAssetPath = propertyTableTextures[textureIndex]->getAssetPathToken();
const auto& propertyInfo = property.propertyInfo;
const auto hasNoData = propertyInfo.noData.has_value();
const auto offset = getOffset(propertyInfo);
const auto scale = getScale(propertyInfo);
const auto noData = getNoData(propertyInfo);
const auto defaultValue = getDefaultValue(propertyInfo);
constexpr auto maximumValue = getMaximumValue<type>();
setPropertyTablePropertyValues<mdlType>(
_pContext->getFabricStage(),
propertyPath,
textureAssetPath,
offset,
scale,
maximumValue,
hasNoData,
noData,
defaultValue);
},
unsupportedCallback);
}
for (const auto& path : _allPaths) {
auto& fabricStage = _pContext->getFabricStage();
const auto tilesetIdFabric = fabricStage.getAttributeWr<int64_t>(path, FabricTokens::_cesium_tilesetId);
*tilesetIdFabric = tilesetId;
}
}
void FabricMaterial::createConnectionsToCopiedPaths() {
auto& fabricStage = _pContext->getFabricStage();
const auto hasBaseColorTexture = _materialDescriptor.hasBaseColorTexture();
const auto rasterOverlay = getRasterOverlayCount(_materialDescriptor);
const auto featureIdCount = getFeatureIdCounts(_materialDescriptor).totalCount;
for (const auto& copiedPath : _copiedBaseColorTexturePaths) {
if (hasBaseColorTexture) {
createConnection(fabricStage, _baseColorTexturePath, copiedPath, FabricTokens::inputs_base_color_texture);
}
}
for (const auto& copiedPath : _copiedRasterOverlayPaths) {
const auto indexFabric = fabricStage.getAttributeRd<int>(copiedPath, FabricTokens::inputs_raster_overlay_index);
const auto index = static_cast<uint64_t>(CppUtil::defaultValue(indexFabric, 0));
if (index < rasterOverlay) {
createConnection(fabricStage, _rasterOverlayPaths[index], copiedPath, FabricTokens::inputs_raster_overlay);
}
}
for (const auto& copiedPath : _copiedFeatureIdPaths) {
const auto indexFabric = fabricStage.getAttributeRd<int>(copiedPath, FabricTokens::inputs_feature_id_set_index);
const auto index = static_cast<uint64_t>(CppUtil::defaultValue(indexFabric, 0));
if (index < featureIdCount) {
createConnection(fabricStage, _featureIdPaths[index], copiedPath, FabricTokens::inputs_feature_id);
}
}
}
void FabricMaterial::destroyConnectionsToCopiedPaths() {
auto& fabricStage = _pContext->getFabricStage();
for (const auto& copiedPath : _copiedBaseColorTexturePaths) {
destroyConnection(fabricStage, copiedPath, FabricTokens::inputs_base_color_texture);
}
for (const auto& copiedPath : _copiedRasterOverlayPaths) {
destroyConnection(fabricStage, copiedPath, FabricTokens::inputs_raster_overlay);
}
for (const auto& copiedPath : _copiedFeatureIdPaths) {
destroyConnection(fabricStage, copiedPath, FabricTokens::inputs_feature_id);
}
}
void FabricMaterial::createConnectionsToProperties() {
auto& fabricStage = _pContext->getFabricStage();
const auto& properties = _materialDescriptor.getStyleableProperties();
const auto& unsupportedPropertyWarnings = _materialDescriptor.getUnsupportedPropertyWarnings();
for (const auto& propertyPathExternal : _copiedPropertyPaths) {
const auto propertyId = getStringFabric(fabricStage, propertyPathExternal, FabricTokens::inputs_property_id);
const auto mdlIdentifier = FabricUtil::getMdlIdentifier(fabricStage, propertyPathExternal);
const auto propertyTypeExternal = FabricUtil::getMdlExternalPropertyType(mdlIdentifier);
const auto index = CppUtil::indexOfByMember(properties, &FabricPropertyDescriptor::propertyId, propertyId);
if (index == properties.size()) {
if (CppUtil::contains(unsupportedPropertyWarnings, propertyId)) {
_pContext->getLogger()->oneTimeWarning(unsupportedPropertyWarnings.at(propertyId));
} else {
_pContext->getLogger()->oneTimeWarning(
"Could not find property \"{}\" referenced by {}. A default value will be returned instead.",
propertyId,
mdlIdentifier.getText());
}
continue;
}
const auto propertyTypeInternal = properties[index].type;
if (!FabricUtil::typesCompatible(propertyTypeExternal, propertyTypeInternal)) {
_pContext->getLogger()->oneTimeWarning(
"Property \"{}\" referenced by {} has incompatible type. A default value will be returned instead.",
propertyId,
mdlIdentifier.getText());
continue;
}
const auto& propertyPathInternal = _propertyPaths[index];
createConnection(fabricStage, propertyPathInternal, propertyPathExternal, FabricTokens::inputs_property_value);
}
}
void FabricMaterial::destroyConnectionsToProperties() {
auto& fabricStage = _pContext->getFabricStage();
for (const auto& copiedPath : _copiedPropertyPaths) {
destroyConnection(fabricStage, copiedPath, FabricTokens::inputs_property_value);
}
}
void FabricMaterial::setRasterOverlay(
FabricTexture* pTexture,
const FabricTextureInfo& textureInfo,
uint64_t rasterOverlayIndex,
double alpha,
const std::unordered_map<uint64_t, uint64_t>& rasterOverlayTexcoordIndexMapping) {
if (stageDestroyed()) {
return;
}
if (rasterOverlayIndex >= _rasterOverlayPaths.size()) {
return;
}
const auto& textureAssetPath = pTexture->getAssetPathToken();
const auto texcoordIndex = rasterOverlayTexcoordIndexMapping.at(textureInfo.setIndex);
const auto& rasterOverlay = _rasterOverlayPaths[rasterOverlayIndex];
setRasterOverlayValues(rasterOverlay, textureAssetPath, textureInfo, texcoordIndex, alpha);
}
void FabricMaterial::setRasterOverlayAlpha(uint64_t rasterOverlayIndex, double alpha) {
if (stageDestroyed()) {
return;
}
if (rasterOverlayIndex >= _rasterOverlayPaths.size()) {
return;
}
const auto& rasterOverlayPath = _rasterOverlayPaths[rasterOverlayIndex];
setRasterOverlayAlphaValue(rasterOverlayPath, alpha);
}
void FabricMaterial::setDisplayColorAndOpacity(const glm::dvec3& displayColor, double displayOpacity) {
if (stageDestroyed()) {
return;
}
if (!_usesDefaultMaterial) {
return;
}
auto& fabricStage = _pContext->getFabricStage();
const auto tileColorFabric = fabricStage.getAttributeWr<glm::fvec4>(_shaderPath, FabricTokens::inputs_tile_color);
const auto alphaModeFabric = fabricStage.getAttributeWr<int>(_shaderPath, FabricTokens::inputs_alpha_mode);
*tileColorFabric = glm::fvec4(getTileColor(_debugColor, displayColor, displayOpacity));
*alphaModeFabric = getAlphaMode(_alphaMode, displayOpacity);
}
void FabricMaterial::updateShaderInput(const omni::fabric::Path& path, const omni::fabric::Token& attributeName) {
if (stageDestroyed()) {
return;
}
auto& fabricStage = _pContext->getFabricStage();
const auto iFabricStage = carb::getCachedInterface<omni::fabric::IStageReaderWriter>();
const auto copiedShaderPath = FabricUtil::getCopiedShaderPath(_materialPath, path);
const auto attributesToCopy = std::vector<omni::fabric::TokenC>{attributeName.asTokenC()};
assert(fabricStage.primExists(copiedShaderPath));
iFabricStage->copySpecifiedAttributes(
fabricStage.getId(),
path,
attributesToCopy.data(),
copiedShaderPath,
attributesToCopy.data(),
attributesToCopy.size());
if (attributeName == FabricTokens::inputs_raster_overlay_index ||
attributeName == FabricTokens::inputs_feature_id_set_index) {
destroyConnectionsToCopiedPaths();
createConnectionsToCopiedPaths();
}
if (attributeName == FabricTokens::inputs_property_id) {
destroyConnectionsToProperties();
createConnectionsToProperties();
}
}
void FabricMaterial::clearRasterOverlay(uint64_t rasterOverlayIndex) {
if (stageDestroyed()) {
return;
}
if (rasterOverlayIndex >= _rasterOverlayPaths.size()) {
return;
}
const auto& rasterOverlayPath = _rasterOverlayPaths[rasterOverlayIndex];
setRasterOverlayValues(
rasterOverlayPath,
_defaultTransparentTextureAssetPathToken,
GltfUtil::getDefaultTextureInfo(),
DEFAULT_TEXCOORD_INDEX,
DEFAULT_ALPHA);
}
void FabricMaterial::setShaderValues(
const omni::fabric::Path& path,
const FabricMaterialInfo& materialInfo,
const glm::dvec3& displayColor,
double displayOpacity) {
auto& fabricStage = _pContext->getFabricStage();
const auto tileColorFabric = fabricStage.getAttributeWr<pxr::GfVec4f>(path, FabricTokens::inputs_tile_color);
const auto alphaCutoffFabric = fabricStage.getAttributeWr<float>(path, FabricTokens::inputs_alpha_cutoff);
const auto alphaModeFabric = fabricStage.getAttributeWr<int>(path, FabricTokens::inputs_alpha_mode);
const auto baseAlphaFabric = fabricStage.getAttributeWr<float>(path, FabricTokens::inputs_base_alpha);
const auto baseColorFactorFabric =
fabricStage.getAttributeWr<pxr::GfVec3f>(path, FabricTokens::inputs_base_color_factor);
const auto emissiveFactorFabric =
fabricStage.getAttributeWr<pxr::GfVec3f>(path, FabricTokens::inputs_emissive_factor);
const auto metallicFactorFabric = fabricStage.getAttributeWr<float>(path, FabricTokens::inputs_metallic_factor);
const auto roughnessFactorFabric = fabricStage.getAttributeWr<float>(path, FabricTokens::inputs_roughness_factor);
*tileColorFabric = UsdUtil::glmToUsdVector(glm::fvec4(getTileColor(_debugColor, displayColor, displayOpacity)));
*alphaCutoffFabric = static_cast<float>(materialInfo.alphaCutoff);
*alphaModeFabric = getAlphaMode(_alphaMode, displayOpacity);
*baseAlphaFabric = static_cast<float>(materialInfo.baseAlpha);
*baseColorFactorFabric = UsdUtil::glmToUsdVector(glm::fvec3(materialInfo.baseColorFactor));
*emissiveFactorFabric = UsdUtil::glmToUsdVector(glm::fvec3(materialInfo.emissiveFactor));
*metallicFactorFabric = static_cast<float>(materialInfo.metallicFactor);
*roughnessFactorFabric = static_cast<float>(materialInfo.roughnessFactor);
}
void FabricMaterial::setTextureValues(
const omni::fabric::Path& path,
const pxr::TfToken& textureAssetPathToken,
const FabricTextureInfo& textureInfo,
uint64_t texcoordIndex) {
setTextureValuesCommon(_pContext->getFabricStage(), path, textureAssetPathToken, textureInfo, texcoordIndex);
}
void FabricMaterial::setRasterOverlayValues(
const omni::fabric::Path& path,
const pxr::TfToken& textureAssetPathToken,
const FabricTextureInfo& textureInfo,
uint64_t texcoordIndex,
double alpha) {
setTextureValuesCommon(_pContext->getFabricStage(), path, textureAssetPathToken, textureInfo, texcoordIndex);
setRasterOverlayAlphaValue(path, alpha);
}
void FabricMaterial::setRasterOverlayAlphaValue(const omni::fabric::Path& path, double alpha) {
const auto alphaFabric = _pContext->getFabricStage().getAttributeWr<float>(path, FabricTokens::inputs_alpha);
*alphaFabric = static_cast<float>(alpha);
}
void FabricMaterial::setFeatureIdIndexValues(const omni::fabric::Path& path, int nullFeatureId) {
setFeatureIdAttributeValues(path, pxr::UsdTokens->vertexId.GetString(), nullFeatureId);
}
void FabricMaterial::setFeatureIdAttributeValues(
const omni::fabric::Path& path,
const std::string& primvarName,
int nullFeatureId) {
auto& fabricStage = _pContext->getFabricStage();
setStringFabric(fabricStage, path, FabricTokens::inputs_primvar_name, primvarName);
const auto nullFeatureIdFabric = fabricStage.getAttributeWr<int>(path, FabricTokens::inputs_null_feature_id);
*nullFeatureIdFabric = nullFeatureId;
}
void FabricMaterial::setFeatureIdTextureValues(
const omni::fabric::Path& path,
const pxr::TfToken& textureAssetPathToken,
const FabricTextureInfo& textureInfo,
uint64_t texcoordIndex,
int nullFeatureId) {
auto& fabricStage = _pContext->getFabricStage();
setTextureValuesCommonChannels(fabricStage, path, textureAssetPathToken, textureInfo, texcoordIndex);
const auto nullFeatureIdFabric = fabricStage.getAttributeWr<int>(path, FabricTokens::inputs_null_feature_id);
*nullFeatureIdFabric = nullFeatureId;
}
bool FabricMaterial::stageDestroyed() {
// Tile render resources may be processed asynchronously even after the tileset and stage have been destroyed.
// Add this check to all public member functions, including constructors and destructors, to prevent them from
// modifying the stage.
return _stageId != _pContext->getUsdStageId();
}
} // namespace cesium::omniverse
| 87,750 | C++ | 44.139403 | 160 | 0.700536 |
CesiumGS/cesium-omniverse/src/core/src/UsdScopedEdit.cpp | #include "cesium/omniverse/UsdScopedEdit.h"
namespace cesium::omniverse {
UsdScopedEdit::UsdScopedEdit(const pxr::UsdStageWeakPtr& pStage)
: _pStage(pStage)
, _sessionLayer(_pStage->GetSessionLayer())
, _sessionLayerWasEditable(_sessionLayer->PermissionToEdit())
, _originalEditTarget(_pStage->GetEditTarget()) {
_sessionLayer->SetPermissionToEdit(true);
_pStage->SetEditTarget(pxr::UsdEditTarget(_sessionLayer));
}
UsdScopedEdit::~UsdScopedEdit() {
_sessionLayer->SetPermissionToEdit(_sessionLayerWasEditable);
_pStage->SetEditTarget(_originalEditTarget);
}
} // namespace cesium::omniverse
| 629 | C++ | 28.999999 | 65 | 0.748808 |
CesiumGS/cesium-omniverse/src/core/src/FabricTexture.cpp | #include "cesium/omniverse/FabricTexture.h"
#include "cesium/omniverse/Context.h"
#include "cesium/omniverse/FabricTextureInfo.h"
#include "cesium/omniverse/Logger.h"
#include "cesium/omniverse/UsdUtil.h"
#include <CesiumGltf/ImageCesium.h>
#include <carb/Types.h>
#include <omni/ui/ImageProvider/DynamicTextureProvider.h>
#include <array>
namespace cesium::omniverse {
namespace {
carb::Format
getCompressedImageFormat(CesiumGltf::GpuCompressedPixelFormat pixelFormat, TransferFunction transferFunction) {
switch (pixelFormat) {
case CesiumGltf::GpuCompressedPixelFormat::BC1_RGB:
switch (transferFunction) {
case TransferFunction::LINEAR:
return carb::Format::eBC1_RGBA_UNORM;
case TransferFunction::SRGB:
return carb::Format::eBC1_RGBA_SRGB;
}
return carb::Format::eUnknown;
case CesiumGltf::GpuCompressedPixelFormat::BC3_RGBA:
switch (transferFunction) {
case TransferFunction::LINEAR:
return carb::Format::eBC3_RGBA_UNORM;
case TransferFunction::SRGB:
return carb::Format::eBC3_RGBA_SRGB;
}
return carb::Format::eUnknown;
case CesiumGltf::GpuCompressedPixelFormat::BC4_R:
return carb::Format::eBC4_R_UNORM;
case CesiumGltf::GpuCompressedPixelFormat::BC5_RG:
return carb::Format::eBC5_RG_UNORM;
case CesiumGltf::GpuCompressedPixelFormat::BC7_RGBA:
switch (transferFunction) {
case TransferFunction::LINEAR:
return carb::Format::eBC7_RGBA_UNORM;
case TransferFunction::SRGB:
return carb::Format::eBC7_RGBA_SRGB;
}
return carb::Format::eUnknown;
default:
// Unsupported compressed texture format.
return carb::Format::eUnknown;
}
}
carb::Format
getUncompressedImageFormat(uint64_t channels, uint64_t bytesPerChannel, TransferFunction transferFunction) {
switch (channels) {
case 1:
switch (bytesPerChannel) {
case 1:
return carb::Format::eR8_UNORM;
case 2:
return carb::Format::eR16_UNORM;
}
break;
case 2:
switch (bytesPerChannel) {
case 1:
return carb::Format::eRG8_UNORM;
case 2:
return carb::Format::eRG16_UNORM;
}
break;
case 4:
switch (bytesPerChannel) {
case 1:
switch (transferFunction) {
case TransferFunction::LINEAR:
return carb::Format::eRGBA8_UNORM;
case TransferFunction::SRGB:
return carb::Format::eRGBA8_SRGB;
}
break;
case 2:
return carb::Format::eRGBA16_UNORM;
}
break;
}
return carb::Format::eUnknown;
}
} // namespace
FabricTexture::FabricTexture(Context* pContext, const std::string& name, int64_t poolId)
: _pContext(pContext)
, _pTexture(std::make_unique<omni::ui::DynamicTextureProvider>(name))
, _assetPathToken(UsdUtil::getDynamicTextureProviderAssetPathToken(name))
, _poolId(poolId) {
reset();
}
FabricTexture::~FabricTexture() = default;
void FabricTexture::setImage(const CesiumGltf::ImageCesium& image, TransferFunction transferFunction) {
carb::Format imageFormat;
const auto isCompressed = image.compressedPixelFormat != CesiumGltf::GpuCompressedPixelFormat::NONE;
if (isCompressed) {
imageFormat = getCompressedImageFormat(image.compressedPixelFormat, transferFunction);
} else {
imageFormat = getUncompressedImageFormat(
static_cast<uint64_t>(image.channels), static_cast<uint64_t>(image.bytesPerChannel), transferFunction);
}
if (imageFormat == carb::Format::eUnknown) {
_pContext->getLogger()->warn("Invalid image format");
} else {
// As of Kit 105.1, omni::ui::kAutoCalculateStride doesn't work for compressed textures. This value somehow works.
const auto stride = isCompressed ? 4ULL * static_cast<uint64_t>(image.width) : omni::ui::kAutoCalculateStride;
const auto data = reinterpret_cast<const uint8_t*>(image.pixelData.data());
const auto dimensions = carb::Uint2{static_cast<uint32_t>(image.width), static_cast<uint32_t>(image.height)};
_pTexture->setBytesData(data, dimensions, stride, imageFormat);
}
}
void FabricTexture::setBytes(
const std::vector<std::byte>& bytes,
uint64_t width,
uint64_t height,
carb::Format format) {
const auto data = reinterpret_cast<const uint8_t*>(bytes.data());
const auto dimensions = carb::Uint2{static_cast<uint32_t>(width), static_cast<uint32_t>(height)};
_pTexture->setBytesData(data, dimensions, omni::ui::kAutoCalculateStride, format);
}
void FabricTexture::setActive(bool active) {
if (!active) {
reset();
}
}
const pxr::TfToken& FabricTexture::getAssetPathToken() const {
return _assetPathToken;
}
int64_t FabricTexture::getPoolId() const {
return _poolId;
}
void FabricTexture::reset() {
const auto bytes = std::array<uint8_t, 4>{{255, 255, 255, 255}};
const auto size = carb::Uint2{1, 1};
_pTexture->setBytesData(bytes.data(), size, omni::ui::kAutoCalculateStride, carb::Format::eRGBA8_SRGB);
}
} // namespace cesium::omniverse
| 5,664 | C++ | 34.40625 | 122 | 0.617232 |
CesiumGS/cesium-omniverse/src/core/src/FabricTexturePool.cpp | #include "cesium/omniverse/FabricTexturePool.h"
#include "cesium/omniverse/Context.h"
#include <spdlog/fmt/fmt.h>
namespace cesium::omniverse {
FabricTexturePool::FabricTexturePool(Context* pContext, int64_t poolId, uint64_t initialCapacity)
: ObjectPool<FabricTexture>()
, _pContext(pContext)
, _poolId(poolId) {
setCapacity(initialCapacity);
}
int64_t FabricTexturePool::getPoolId() const {
return _poolId;
}
std::shared_ptr<FabricTexture> FabricTexturePool::createObject(uint64_t objectId) const {
const auto contextId = _pContext->getContextId();
const auto name = fmt::format("/cesium_texture_pool_{}_object_{}_context_{}", _poolId, objectId, contextId);
return std::make_shared<FabricTexture>(_pContext, name, _poolId);
}
void FabricTexturePool::setActive(FabricTexture* pTexture, bool active) const {
pTexture->setActive(active);
}
}; // namespace cesium::omniverse
| 917 | C++ | 28.612902 | 112 | 0.733915 |
CesiumGS/cesium-omniverse/src/core/src/UsdTokens.cpp | #include "cesium/omniverse/UsdTokens.h"
#include <spdlog/fmt/fmt.h>
// clang-format off
PXR_NAMESPACE_OPEN_SCOPE
#ifdef CESIUM_OMNI_MSVC
__pragma(warning(push))
__pragma(warning(disable: 4003))
#endif
#ifdef CESIUM_OMNI_CLANG
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wgnu-zero-variadic-macro-arguments"
#endif
TF_DEFINE_PUBLIC_TOKENS(
UsdTokens,
USD_TOKENS);
#ifdef CESIUM_OMNI_CLANG
#pragma clang diagnostic pop
#endif
#ifdef CESIUM_OMNI_MSVC
__pragma(warning(pop))
#endif
PXR_NAMESPACE_CLOSE_SCOPE
// clang-format on
namespace cesium::omniverse::FabricTokens {
FABRIC_DEFINE_TOKENS(USD_TOKENS);
namespace {
std::mutex tokenMutex;
std::vector<omni::fabric::Token> feature_id_tokens;
std::vector<omni::fabric::Token> raster_overlay_tokens;
std::vector<omni::fabric::Token> inputs_raster_overlay_tokens;
std::vector<omni::fabric::Token> primvars_st_tokens;
std::vector<omni::fabric::Token> property_tokens;
const omni::fabric::TokenC
getToken(std::vector<omni::fabric::Token>& tokens, uint64_t index, const std::string_view& prefix) {
const auto lock = std::scoped_lock(tokenMutex);
const auto size = index + 1;
if (size > tokens.size()) {
tokens.resize(size);
}
auto& token = tokens[index];
if (token.asTokenC() == omni::fabric::kUninitializedToken) {
const auto tokenStr = fmt::format("{}_{}", prefix, index);
token = omni::fabric::Token(tokenStr.c_str());
}
return token.asTokenC();
}
} // namespace
const omni::fabric::TokenC feature_id_n(uint64_t index) {
return getToken(feature_id_tokens, index, "feature_id");
}
const omni::fabric::TokenC raster_overlay_n(uint64_t index) {
return getToken(raster_overlay_tokens, index, "raster_overlay");
}
const omni::fabric::TokenC inputs_raster_overlay_n(uint64_t index) {
return getToken(inputs_raster_overlay_tokens, index, "inputs:raster_overlay");
}
const omni::fabric::TokenC primvars_st_n(uint64_t index) {
return getToken(primvars_st_tokens, index, "primvars:st");
}
const omni::fabric::TokenC property_n(uint64_t index) {
return getToken(property_tokens, index, "property");
}
} // namespace cesium::omniverse::FabricTokens
| 2,365 | C++ | 26.835294 | 104 | 0.664693 |
CesiumGS/cesium-omniverse/src/core/src/OmniIonRasterOverlay.cpp | #include "cesium/omniverse/OmniIonRasterOverlay.h"
#include "cesium/omniverse/AssetRegistry.h"
#include "cesium/omniverse/Broadcast.h"
#include "cesium/omniverse/Context.h"
#include "cesium/omniverse/Logger.h"
#include "cesium/omniverse/OmniIonServer.h"
#include "cesium/omniverse/UsdUtil.h"
#include <CesiumAsync/IAssetResponse.h>
#include <CesiumIonClient/Token.h>
#include <CesiumRasterOverlays/IonRasterOverlay.h>
#include <CesiumUsdSchemas/ionRasterOverlay.h>
#include <CesiumUtility/IntrusivePointer.h>
namespace cesium::omniverse {
namespace {} // namespace
OmniIonRasterOverlay::OmniIonRasterOverlay(Context* pContext, const pxr::SdfPath& path)
: OmniRasterOverlay(pContext, path) {
reload();
}
int64_t OmniIonRasterOverlay::getIonAssetId() const {
const auto cesiumIonRasterOverlay = UsdUtil::getCesiumIonRasterOverlay(_pContext->getUsdStage(), _path);
if (!UsdUtil::isSchemaValid(cesiumIonRasterOverlay)) {
return 0;
}
int64_t ionAssetId;
cesiumIonRasterOverlay.GetIonAssetIdAttr().Get(&ionAssetId);
return ionAssetId;
}
CesiumIonClient::Token OmniIonRasterOverlay::getIonAccessToken() const {
const auto cesiumIonRasterOverlay = UsdUtil::getCesiumIonRasterOverlay(_pContext->getUsdStage(), _path);
if (!UsdUtil::isSchemaValid(cesiumIonRasterOverlay)) {
return {};
}
std::string ionAccessToken;
cesiumIonRasterOverlay.GetIonAccessTokenAttr().Get(&ionAccessToken);
if (!ionAccessToken.empty()) {
CesiumIonClient::Token t;
t.token = ionAccessToken;
return t;
}
const auto ionServerPath = getResolvedIonServerPath();
if (ionServerPath.IsEmpty()) {
return {};
}
const auto pIonServer = _pContext->getAssetRegistry().getIonServer(ionServerPath);
if (!pIonServer) {
return {};
}
return pIonServer->getToken();
}
std::string OmniIonRasterOverlay::getIonApiUrl() const {
const auto ionServerPath = getResolvedIonServerPath();
if (ionServerPath.IsEmpty()) {
return {};
}
const auto pIonServer = _pContext->getAssetRegistry().getIonServer(ionServerPath);
if (!pIonServer) {
return {};
}
return pIonServer->getIonServerApiUrl();
}
pxr::SdfPath OmniIonRasterOverlay::getResolvedIonServerPath() const {
const auto cesiumIonRasterOverlay = UsdUtil::getCesiumIonRasterOverlay(_pContext->getUsdStage(), _path);
if (!UsdUtil::isSchemaValid(cesiumIonRasterOverlay)) {
return {};
}
pxr::SdfPathVector targets;
cesiumIonRasterOverlay.GetIonServerBindingRel().GetForwardedTargets(&targets);
if (!targets.empty()) {
return targets.front();
}
// Fall back to using the first ion server if there's no explicit binding
const auto pIonServer = _pContext->getAssetRegistry().getFirstIonServer();
if (pIonServer) {
return pIonServer->getPath();
}
return {};
}
CesiumRasterOverlays::RasterOverlay* OmniIonRasterOverlay::getRasterOverlay() const {
return _pIonRasterOverlay.get();
}
void OmniIonRasterOverlay::reload() {
const auto rasterOverlayIonAssetId = getIonAssetId();
const auto rasterOverlayIonAccessToken = getIonAccessToken();
const auto rasterOverlayIonApiUrl = getIonApiUrl();
if (rasterOverlayIonAssetId <= 0 || rasterOverlayIonAccessToken.token.empty() || rasterOverlayIonApiUrl.empty()) {
return;
}
const auto rasterOverlayName = UsdUtil::getName(_pContext->getUsdStage(), _path);
auto options = createRasterOverlayOptions();
options.loadErrorCallback = [this, rasterOverlayIonAssetId, rasterOverlayName](
const CesiumRasterOverlays::RasterOverlayLoadFailureDetails& error) {
// Check for a 401 connecting to Cesium ion, which means the token is invalid
// (or perhaps the asset ID is). Also check for a 404, because ion returns 404
// when the token is valid but not authorized for the asset.
const auto statusCode =
error.pRequest && error.pRequest->response() ? error.pRequest->response()->statusCode() : 0;
if (error.type == CesiumRasterOverlays::RasterOverlayLoadType::CesiumIon &&
(statusCode == 401 || statusCode == 404)) {
Broadcast::showTroubleshooter({}, 0, "", rasterOverlayIonAssetId, rasterOverlayName, error.message);
}
_pContext->getLogger()->error(error.message);
};
_pIonRasterOverlay = new CesiumRasterOverlays::IonRasterOverlay(
rasterOverlayName, rasterOverlayIonAssetId, rasterOverlayIonAccessToken.token, options, rasterOverlayIonApiUrl);
}
} // namespace cesium::omniverse
| 4,675 | C++ | 31.6993 | 120 | 0.708449 |
CesiumGS/cesium-omniverse/src/core/src/SettingsWrapper.cpp | #include "cesium/omniverse/SettingsWrapper.h"
#include <carb/InterfaceUtils.h>
#include <carb/settings/ISettings.h>
#include <spdlog/fmt/bundled/format.h>
namespace cesium::omniverse::Settings {
namespace {
const uint64_t MAX_SESSIONS = 10;
const std::string_view SESSION_ION_SERVER_URL_BASE =
"/persistent/exts/cesium.omniverse/sessions/session{}/ionServerUrl";
const std::string_view SESSION_USER_ACCESS_TOKEN_BASE =
"/persistent/exts/cesium.omniverse/sessions/session{}/userAccessToken";
const char* MAX_CACHE_ITEMS_PATH = "/persistent/exts/cesium.omniverse/maxCacheItems";
std::string getIonApiUrlSettingPath(const uint64_t index) {
return fmt::format(SESSION_ION_SERVER_URL_BASE, index);
}
std::string getAccessTokenSettingPath(const uint64_t index) {
return fmt::format(SESSION_USER_ACCESS_TOKEN_BASE, index);
}
} // namespace
std::vector<AccessToken> getAccessTokens() {
const auto iSettings = carb::getCachedInterface<carb::settings::ISettings>();
std::vector<AccessToken> accessTokens;
accessTokens.reserve(MAX_SESSIONS);
for (uint64_t i = 0; i < MAX_SESSIONS; ++i) {
const auto ionApiUrlKey = getIonApiUrlSettingPath(i);
const auto accessTokenKey = getAccessTokenSettingPath(i);
const auto ionApiUrlValue = iSettings->getStringBuffer(ionApiUrlKey.c_str());
const auto accessTokenValue = iSettings->getStringBuffer(accessTokenKey.c_str());
if (ionApiUrlValue && accessTokenValue) {
// In C++ 20 this can be emplace_back without the {}
accessTokens.push_back({ionApiUrlValue, accessTokenValue});
}
}
return accessTokens;
}
void setAccessToken(const AccessToken& accessToken) {
const auto iSettings = carb::getCachedInterface<carb::settings::ISettings>();
const auto oldAccessTokens = getAccessTokens();
std::vector<AccessToken> newAccessTokens;
newAccessTokens.reserve(oldAccessTokens.size() + 1); // Worst case we'll be growing by 1, so preempt that.
for (const auto& oldAccessToken : oldAccessTokens) {
if (oldAccessToken.ionApiUrl == accessToken.ionApiUrl) {
continue;
}
newAccessTokens.push_back(oldAccessToken);
}
newAccessTokens.push_back(accessToken);
clearTokens();
for (uint64_t i = 0; i < newAccessTokens.size(); ++i) {
const auto ionApiUrlKey = getIonApiUrlSettingPath(i);
const auto accessTokenKey = getAccessTokenSettingPath(i);
iSettings->set(ionApiUrlKey.c_str(), newAccessTokens[i].ionApiUrl.c_str());
iSettings->set(accessTokenKey.c_str(), newAccessTokens[i].accessToken.c_str());
}
}
void removeAccessToken(const std::string& ionApiUrl) {
const auto iSettings = carb::getCachedInterface<carb::settings::ISettings>();
const auto oldAccessTokens = getAccessTokens();
std::vector<AccessToken> newAccessTokens;
newAccessTokens.reserve(oldAccessTokens.size());
for (auto& oldAccessToken : oldAccessTokens) {
if (oldAccessToken.ionApiUrl == ionApiUrl) {
continue;
}
newAccessTokens.push_back(oldAccessToken);
}
clearTokens();
for (uint64_t i = 0; i < newAccessTokens.size(); ++i) {
const auto ionApiUrlKey = getIonApiUrlSettingPath(i);
const auto accessTokenKey = getAccessTokenSettingPath(i);
iSettings->set(ionApiUrlKey.c_str(), newAccessTokens[i].ionApiUrl.c_str());
iSettings->set(accessTokenKey.c_str(), newAccessTokens[i].accessToken.c_str());
}
}
void clearTokens() {
const auto iSettings = carb::getCachedInterface<carb::settings::ISettings>();
for (uint64_t i = 0; i < MAX_SESSIONS; ++i) {
const auto serverKey = getIonApiUrlSettingPath(i);
const auto tokenKey = getAccessTokenSettingPath(i);
iSettings->destroyItem(serverKey.c_str());
iSettings->destroyItem(tokenKey.c_str());
}
}
uint64_t getMaxCacheItems() {
const int64_t defaultMaxCacheItems = 4096;
const auto iSettings = carb::getCachedInterface<carb::settings::ISettings>();
iSettings->setDefaultInt64(MAX_CACHE_ITEMS_PATH, defaultMaxCacheItems);
auto maxCacheItems = iSettings->getAsInt64(MAX_CACHE_ITEMS_PATH);
return static_cast<uint64_t>(maxCacheItems);
}
} // namespace cesium::omniverse::Settings
| 4,311 | C++ | 33.496 | 110 | 0.700765 |
CesiumGS/cesium-omniverse/src/core/src/LoggerSink.cpp | #include "cesium/omniverse/LoggerSink.h"
namespace cesium::omniverse {
LoggerSink::LoggerSink(omni::log::Level logLevel)
: _logLevel(logLevel) {
switch (logLevel) {
case omni::log::Level::eVerbose:
set_level(spdlog::level::trace);
break;
case omni::log::Level::eInfo:
set_level(spdlog::level::info);
break;
case omni::log::Level::eWarn:
set_level(spdlog::level::warn);
break;
case omni::log::Level::eError:
set_level(spdlog::level::err);
break;
case omni::log::Level::eFatal:
set_level(spdlog::level::critical);
break;
default:
break;
}
}
void LoggerSink::sink_it_([[maybe_unused]] const spdlog::details::log_msg& msg) {
// The reason we don't need to provide a log channel as the first argument to each of these OMNI_LOG_ functions is
// because CARB_PLUGIN_IMPL calls CARB_GLOBALS_EX which calls OMNI_GLOBALS_ADD_DEFAULT_CHANNEL and sets the channel
// name to our plugin name: cesium.omniverse.plugin
switch (_logLevel) {
case omni::log::Level::eVerbose:
OMNI_LOG_VERBOSE("%s", formatMessage(msg).c_str());
break;
case omni::log::Level::eInfo:
OMNI_LOG_INFO("%s", formatMessage(msg).c_str());
break;
case omni::log::Level::eWarn:
OMNI_LOG_WARN("%s", formatMessage(msg).c_str());
break;
case omni::log::Level::eError:
OMNI_LOG_ERROR("%s", formatMessage(msg).c_str());
break;
case omni::log::Level::eFatal:
OMNI_LOG_FATAL("%s", formatMessage(msg).c_str());
break;
default:
break;
}
}
void LoggerSink::flush_() {}
std::string LoggerSink::formatMessage(const spdlog::details::log_msg& msg) {
// Frustratingly, spdlog::formatter isn't thread safe. So even though our sink
// itself doesn't need to be protected by a mutex, the formatter does.
// See https://github.com/gabime/spdlog/issues/897
std::scoped_lock<std::mutex> lock(_formatMutex);
spdlog::memory_buf_t formatted;
formatter_->format(msg, formatted);
return fmt::to_string(formatted);
}
} // namespace cesium::omniverse
| 2,305 | C++ | 33.41791 | 119 | 0.593059 |
CesiumGS/cesium-omniverse/src/core/src/UsdNotificationHandler.cpp | #include "cesium/omniverse/UsdNotificationHandler.h"
#include "cesium/omniverse/AssetRegistry.h"
#include "cesium/omniverse/Context.h"
#include "cesium/omniverse/CppUtil.h"
#include "cesium/omniverse/FabricResourceManager.h"
#include "cesium/omniverse/FabricUtil.h"
#include "cesium/omniverse/OmniCartographicPolygon.h"
#include "cesium/omniverse/OmniGeoreference.h"
#include "cesium/omniverse/OmniGlobeAnchor.h"
#include "cesium/omniverse/OmniIonRasterOverlay.h"
#include "cesium/omniverse/OmniIonServer.h"
#include "cesium/omniverse/OmniPolygonRasterOverlay.h"
#include "cesium/omniverse/OmniRasterOverlay.h"
#include "cesium/omniverse/OmniTileMapServiceRasterOverlay.h"
#include "cesium/omniverse/OmniTileset.h"
#include "cesium/omniverse/OmniWebMapServiceRasterOverlay.h"
#include "cesium/omniverse/OmniWebMapTileServiceRasterOverlay.h"
#include "cesium/omniverse/UsdTokens.h"
#include "cesium/omniverse/UsdUtil.h"
#include <CesiumUsdSchemas/tokens.h>
#include <pxr/usd/usd/primRange.h>
#include <pxr/usd/usdShade/shader.h>
namespace cesium::omniverse {
namespace {
bool isPrimOrDescendant(const pxr::SdfPath& descendantPath, const pxr::SdfPath& path) {
if (descendantPath == path) {
return true;
}
for (const auto& ancestorPath : descendantPath.GetAncestorsRange()) {
if (ancestorPath == path) {
return true;
}
}
return false;
}
void updateRasterOverlayBindings(const Context& context, const pxr::SdfPath& rasterOverlayPath) {
const auto& tilesets = context.getAssetRegistry().getTilesets();
// Update tilesets that reference this raster overlay
for (const auto& pTileset : tilesets) {
if (CppUtil::contains(pTileset->getRasterOverlayPaths(), rasterOverlayPath)) {
pTileset->reload();
}
}
}
void updateRasterOverlayBindingsAlpha(const Context& context, const pxr::SdfPath& rasterOverlayPath) {
const auto& tilesets = context.getAssetRegistry().getTilesets();
// Update tilesets that reference this raster overlay
for (const auto& pTileset : tilesets) {
if (CppUtil::contains(pTileset->getRasterOverlayPaths(), rasterOverlayPath)) {
pTileset->updateRasterOverlayAlpha(rasterOverlayPath);
}
}
}
void updateIonServerBindings(const Context& context) {
// Update all tilesets. Some tilesets may have referenced this ion server implicitly.
const auto& tilesets = context.getAssetRegistry().getTilesets();
for (const auto& pTileset : tilesets) {
pTileset->reload();
}
// Update all raster overlays. Some raster overlays may have referenced this ion server implicitly.
const auto& ionRasterOverlays = context.getAssetRegistry().getIonRasterOverlays();
for (const auto& pIonRasterOverlay : ionRasterOverlays) {
pIonRasterOverlay->reload();
updateRasterOverlayBindings(context, pIonRasterOverlay->getPath());
}
}
void updateCartographicPolygonBindings(const Context& context, const pxr::SdfPath& cartographicPolygonPath) {
// Update polygon raster overlays that reference this cartographic polygon
const auto& polygonRasterOverlays = context.getAssetRegistry().getPolygonRasterOverlays();
for (const auto& pPolygonRasterOverlay : polygonRasterOverlays) {
const auto paths = pPolygonRasterOverlay->getCartographicPolygonPaths();
if (CppUtil::contains(paths, cartographicPolygonPath)) {
pPolygonRasterOverlay->reload();
updateRasterOverlayBindings(context, pPolygonRasterOverlay->getPath());
}
}
}
void updateGlobeAnchorBindings(const Context& context, const pxr::SdfPath& globeAnchorPath) {
// Don't need to update tilesets. Globe anchor changes are handled automatically in the update loop.
if (context.getAssetRegistry().getCartographicPolygon(globeAnchorPath)) {
// Update cartographic polygon that this globe anchor is attached to
updateCartographicPolygonBindings(context, globeAnchorPath);
}
}
void updateGeoreferenceBindings(const Context& context) {
// Don't need to update tilesets. Georeference changes are handled automatically in the update loop.
// Update all globe anchors. Some globe anchors may have referenced this georeference implicitly.
const auto& globeAnchors = context.getAssetRegistry().getGlobeAnchors();
for (const auto& pGlobeAnchor : globeAnchors) {
pGlobeAnchor->updateByGeoreference();
updateGlobeAnchorBindings(context, pGlobeAnchor->getPath());
}
}
bool isFirstData(const Context& context, const pxr::SdfPath& dataPath) {
const auto pData = context.getAssetRegistry().getData(dataPath);
const auto pFirstData = context.getAssetRegistry().getFirstData();
return pData && pData == pFirstData;
}
[[nodiscard]] bool processCesiumDataChanged(
const Context& context,
const pxr::SdfPath& dataPath,
const std::vector<pxr::TfToken>& properties) {
if (!isFirstData(context, dataPath)) {
return false;
}
auto reloadStage = false;
auto updateGeoreference = false;
// No change tracking needed for
// * selectedIonServer
// * projectDefaultIonAccessToken (deprecated)
// * projectDefaultIonAccessTokenId (deprecated)
for (const auto& property : properties) {
if (property == pxr::CesiumTokens->cesiumDebugDisableMaterials ||
property == pxr::CesiumTokens->cesiumDebugDisableTextures ||
property == pxr::CesiumTokens->cesiumDebugDisableGeometryPool ||
property == pxr::CesiumTokens->cesiumDebugDisableMaterialPool ||
property == pxr::CesiumTokens->cesiumDebugDisableTexturePool ||
property == pxr::CesiumTokens->cesiumDebugGeometryPoolInitialCapacity ||
property == pxr::CesiumTokens->cesiumDebugMaterialPoolInitialCapacity ||
property == pxr::CesiumTokens->cesiumDebugTexturePoolInitialCapacity ||
property == pxr::CesiumTokens->cesiumDebugRandomColors) {
reloadStage = true;
} else if (property == pxr::CesiumTokens->cesiumDebugDisableGeoreferencing) {
updateGeoreference = true;
}
}
if (updateGeoreference) {
updateGeoreferenceBindings(context);
}
return reloadStage;
}
void processCesiumGlobeAnchorChanged(
const Context& context,
const pxr::SdfPath& globeAnchorPath,
const std::vector<pxr::TfToken>& properties) {
const auto pGlobeAnchor = context.getAssetRegistry().getGlobeAnchor(globeAnchorPath);
if (!pGlobeAnchor) {
return;
}
// No change tracking needed for
// * adjustOrientation
auto updateByGeoreference = false;
auto updateByPrimLocalTransform = false;
auto updateByGeographicCoordinates = false;
auto updateByEcefPosition = false;
auto updateBindings = false;
auto resetOrientation = false;
const auto detectTransformChanges = pGlobeAnchor->getDetectTransformChanges();
// clang-format off
for (const auto& property : properties) {
if (detectTransformChanges &&
(property == pxr::UsdTokens->xformOp_translate ||
property == pxr::UsdTokens->xformOp_rotateXYZ ||
property == pxr::UsdTokens->xformOp_rotateXZY ||
property == pxr::UsdTokens->xformOp_rotateYXZ ||
property == pxr::UsdTokens->xformOp_rotateYZX ||
property == pxr::UsdTokens->xformOp_rotateZXY ||
property == pxr::UsdTokens->xformOp_rotateZYX ||
property == pxr::UsdTokens->xformOp_orient ||
property == pxr::UsdTokens->xformOp_scale)) {
updateByPrimLocalTransform = true;
updateBindings = true;
} else if (property == pxr::CesiumTokens->cesiumAnchorLongitude ||
property == pxr::CesiumTokens->cesiumAnchorLatitude ||
property == pxr::CesiumTokens->cesiumAnchorHeight) {
updateByGeographicCoordinates = true;
updateBindings = true;
} else if (property == pxr::CesiumTokens->cesiumAnchorPosition) {
updateByEcefPosition = true;
updateBindings = true;
} else if (property == pxr::CesiumTokens->cesiumAnchorGeoreferenceBinding) {
updateByGeoreference = true;
updateBindings = true;
} else if (detectTransformChanges && property == pxr::CesiumTokens->cesiumAnchorDetectTransformChanges) {
updateByPrimLocalTransform = true;
updateBindings = true;
resetOrientation = true;
}
}
// clang-format on
if (updateByGeoreference) {
pGlobeAnchor->updateByGeoreference();
}
if (updateByEcefPosition) {
pGlobeAnchor->updateByEcefPosition();
}
if (updateByGeographicCoordinates) {
pGlobeAnchor->updateByGeographicCoordinates();
}
if (updateByPrimLocalTransform) {
pGlobeAnchor->updateByPrimLocalTransform(resetOrientation);
}
if (updateBindings) {
updateGlobeAnchorBindings(context, globeAnchorPath);
}
}
void processCesiumTilesetChanged(
const Context& context,
const pxr::SdfPath& tilesetPath,
const std::vector<pxr::TfToken>& properties) {
const auto pTileset = context.getAssetRegistry().getTileset(tilesetPath);
if (!pTileset) {
return;
}
// Process globe anchor API schema first
processCesiumGlobeAnchorChanged(context, tilesetPath, properties);
auto reload = false;
auto updateTilesetOptions = false;
auto updateDisplayColorAndOpacity = false;
// No change tracking needed for
// * suspendUpdate
// * georeferenceBinding
// * Transform changes (handled automatically in update loop)
// clang-format off
for (const auto& property : properties) {
if (property == pxr::CesiumTokens->cesiumSourceType ||
property == pxr::CesiumTokens->cesiumUrl ||
property == pxr::CesiumTokens->cesiumIonAssetId ||
property == pxr::CesiumTokens->cesiumIonAccessToken ||
property == pxr::CesiumTokens->cesiumIonServerBinding ||
property == pxr::CesiumTokens->cesiumSmoothNormals ||
property == pxr::CesiumTokens->cesiumShowCreditsOnScreen ||
property == pxr::CesiumTokens->cesiumRasterOverlayBinding ||
property == pxr::UsdTokens->material_binding) {
reload = true;
} else if (
property == pxr::CesiumTokens->cesiumMaximumScreenSpaceError ||
property == pxr::CesiumTokens->cesiumPreloadAncestors ||
property == pxr::CesiumTokens->cesiumPreloadSiblings ||
property == pxr::CesiumTokens->cesiumForbidHoles ||
property == pxr::CesiumTokens->cesiumMaximumSimultaneousTileLoads ||
property == pxr::CesiumTokens->cesiumMaximumCachedBytes ||
property == pxr::CesiumTokens->cesiumLoadingDescendantLimit ||
property == pxr::CesiumTokens->cesiumEnableFrustumCulling ||
property == pxr::CesiumTokens->cesiumEnableFogCulling ||
property == pxr::CesiumTokens->cesiumEnforceCulledScreenSpaceError ||
property == pxr::CesiumTokens->cesiumCulledScreenSpaceError ||
property == pxr::CesiumTokens->cesiumMainThreadLoadingTimeLimit) {
updateTilesetOptions = true;
} else if (
property == pxr::UsdTokens->primvars_displayColor ||
property == pxr::UsdTokens->primvars_displayOpacity) {
updateDisplayColorAndOpacity = true;
}
}
// clang-format on
if (reload) {
pTileset->reload();
}
if (updateTilesetOptions) {
pTileset->updateTilesetOptions();
}
if (updateDisplayColorAndOpacity) {
pTileset->updateDisplayColorAndOpacity();
}
}
void processCesiumRasterOverlayChanged(
const Context& context,
const pxr::SdfPath& rasterOverlayPath,
const std::vector<pxr::TfToken>& properties) {
const auto pRasterOverlay = context.getAssetRegistry().getRasterOverlay(rasterOverlayPath);
if (!pRasterOverlay) {
return;
}
auto reload = false;
auto updateBindings = false;
auto updateRasterOverlayAlpha = false;
auto updateRasterOverlayOptions = false;
for (const auto& property : properties) {
if (property == pxr::CesiumTokens->cesiumShowCreditsOnScreen) {
reload = true;
updateBindings = true;
} else if (property == pxr::CesiumTokens->cesiumOverlayRenderMethod) {
updateBindings = true;
} else if (property == pxr::CesiumTokens->cesiumAlpha) {
updateRasterOverlayAlpha = true;
} else if (
property == pxr::CesiumTokens->cesiumMaximumScreenSpaceError ||
property == pxr::CesiumTokens->cesiumMaximumTextureSize ||
property == pxr::CesiumTokens->cesiumMaximumSimultaneousTileLoads ||
property == pxr::CesiumTokens->cesiumSubTileCacheBytes) {
updateRasterOverlayOptions = true;
}
}
if (reload) {
pRasterOverlay->reload();
}
if (updateBindings) {
updateRasterOverlayBindings(context, rasterOverlayPath);
}
if (updateRasterOverlayAlpha) {
updateRasterOverlayBindingsAlpha(context, rasterOverlayPath);
}
if (updateRasterOverlayOptions) {
pRasterOverlay->updateRasterOverlayOptions();
}
}
void processCesiumIonRasterOverlayChanged(
const Context& context,
const pxr::SdfPath& ionRasterOverlayPath,
const std::vector<pxr::TfToken>& properties) {
const auto pIonRasterOverlay = context.getAssetRegistry().getIonRasterOverlay(ionRasterOverlayPath);
if (!pIonRasterOverlay) {
return;
}
// Process base class first
processCesiumRasterOverlayChanged(context, ionRasterOverlayPath, properties);
auto reload = false;
auto updateBindings = false;
for (const auto& property : properties) {
if (property == pxr::CesiumTokens->cesiumIonAssetId || property == pxr::CesiumTokens->cesiumIonAccessToken ||
property == pxr::CesiumTokens->cesiumIonServerBinding) {
reload = true;
updateBindings = true;
}
}
if (reload) {
pIonRasterOverlay->reload();
}
if (updateBindings) {
updateRasterOverlayBindings(context, ionRasterOverlayPath);
}
}
void processCesiumPolygonRasterOverlayChanged(
const Context& context,
const pxr::SdfPath& polygonRasterOverlayPath,
const std::vector<pxr::TfToken>& properties) {
const auto pPolygonRasterOverlay = context.getAssetRegistry().getPolygonRasterOverlay(polygonRasterOverlayPath);
if (!pPolygonRasterOverlay) {
return;
}
// Process base class first
processCesiumRasterOverlayChanged(context, polygonRasterOverlayPath, properties);
auto reload = false;
auto updateBindings = false;
for (const auto& property : properties) {
if (property == pxr::CesiumTokens->cesiumCartographicPolygonBinding ||
property == pxr::CesiumTokens->cesiumInvertSelection ||
property == pxr::CesiumTokens->cesiumExcludeSelectedTiles) {
reload = true;
updateBindings = true;
}
}
if (reload) {
pPolygonRasterOverlay->reload();
}
if (updateBindings) {
updateRasterOverlayBindings(context, polygonRasterOverlayPath);
}
}
void processCesiumWebMapServiceRasterOverlayChanged(
const Context& context,
const pxr::SdfPath& webMapServiceRasterOverlayPath,
const std::vector<pxr::TfToken>& properties) {
const auto pWebMapServiceRasterOverlay =
context.getAssetRegistry().getWebMapServiceRasterOverlay(webMapServiceRasterOverlayPath);
if (!pWebMapServiceRasterOverlay) {
return;
}
// Process base class first
processCesiumRasterOverlayChanged(context, webMapServiceRasterOverlayPath, properties);
auto reload = false;
auto updateBindings = false;
for (const auto& property : properties) {
if (property == pxr::CesiumTokens->cesiumBaseUrl || property == pxr::CesiumTokens->cesiumLayers ||
property == pxr::CesiumTokens->cesiumTileWidth || property == pxr::CesiumTokens->cesiumTileHeight ||
property == pxr::CesiumTokens->cesiumMinimumLevel || property == pxr::CesiumTokens->cesiumMaximumLevel) {
reload = true;
updateBindings = true;
}
}
if (reload) {
pWebMapServiceRasterOverlay->reload();
}
if (updateBindings) {
updateRasterOverlayBindings(context, webMapServiceRasterOverlayPath);
}
}
void processCesiumTileMapServiceRasterOverlayChanged(
const Context& context,
const pxr::SdfPath& tileMapServiceRasterOverlayPath,
const std::vector<pxr::TfToken>& properties) {
const auto pTileMapServiceRasterOverlay =
context.getAssetRegistry().getTileMapServiceRasterOverlay(tileMapServiceRasterOverlayPath);
if (!pTileMapServiceRasterOverlay) {
return;
}
// Process base class first
processCesiumRasterOverlayChanged(context, tileMapServiceRasterOverlayPath, properties);
auto reload = false;
auto updateBindings = false;
for (const auto& property : properties) {
if (property == pxr::CesiumTokens->cesiumUrl || property == pxr::CesiumTokens->cesiumMinimumZoomLevel ||
property == pxr::CesiumTokens->cesiumMaximumZoomLevel) {
reload = true;
updateBindings = true;
}
}
if (reload) {
pTileMapServiceRasterOverlay->reload();
}
if (updateBindings) {
updateRasterOverlayBindings(context, tileMapServiceRasterOverlayPath);
}
}
void processCesiumWebMapTileServiceRasterOverlayChanged(
const Context& context,
const pxr::SdfPath& webMapTileServiceRasterOverlayPath,
const std::vector<pxr::TfToken>& properties) {
const auto pWebMapTileServiceRasterOverlay =
context.getAssetRegistry().getWebMapTileServiceRasterOverlay(webMapTileServiceRasterOverlayPath);
if (!pWebMapTileServiceRasterOverlay) {
return;
}
// Process base class first
processCesiumRasterOverlayChanged(context, webMapTileServiceRasterOverlayPath, properties);
auto reload = false;
auto updateBindings = false;
for (const auto& property : properties) {
if (property == pxr::CesiumTokens->cesiumUrl || property == pxr::CesiumTokens->cesiumLayer ||
property == pxr::CesiumTokens->cesiumStyle || property == pxr::CesiumTokens->cesiumFormat ||
property == pxr::CesiumTokens->cesiumTileMatrixSetId ||
property == pxr::CesiumTokens->cesiumSpecifyTileMatrixSetLabels ||
property == pxr::CesiumTokens->cesiumTileMatrixSetLabelPrefix ||
property == pxr::CesiumTokens->cesiumTileMatrixSetLabels ||
property == pxr::CesiumTokens->cesiumUseWebMercatorProjection ||
property == pxr::CesiumTokens->cesiumSpecifyTilingScheme ||
property == pxr::CesiumTokens->cesiumRootTilesX || property == pxr::CesiumTokens->cesiumRootTilesY ||
property == pxr::CesiumTokens->cesiumWest || property == pxr::CesiumTokens->cesiumEast ||
property == pxr::CesiumTokens->cesiumSouth || property == pxr::CesiumTokens->cesiumNorth ||
property == pxr::CesiumTokens->cesiumSpecifyZoomLevels ||
property == pxr::CesiumTokens->cesiumMinimumZoomLevel ||
property == pxr::CesiumTokens->cesiumMaximumZoomLevel) {
reload = true;
updateBindings = true;
}
}
if (reload) {
pWebMapTileServiceRasterOverlay->reload();
}
if (updateBindings) {
updateRasterOverlayBindings(context, webMapTileServiceRasterOverlayPath);
}
}
void processCesiumGeoreferenceChanged(const Context& context, const std::vector<pxr::TfToken>& properties) {
auto updateBindings = false;
// clang-format off
for (const auto& property : properties) {
if (property == pxr::CesiumTokens->cesiumGeoreferenceOriginLongitude ||
property == pxr::CesiumTokens->cesiumGeoreferenceOriginLatitude ||
property == pxr::CesiumTokens->cesiumGeoreferenceOriginHeight) {
updateBindings = true;
}
}
// clang-format on
if (updateBindings) {
updateGeoreferenceBindings(context);
}
}
void processCesiumIonServerChanged(
Context& context,
const pxr::SdfPath& ionServerPath,
const std::vector<pxr::TfToken>& properties) {
auto reloadSession = false;
auto updateBindings = false;
// No change tracking needed for
// * displayName
// clang-format off
for (const auto& property : properties) {
if (property == pxr::CesiumTokens->cesiumIonServerUrl ||
property == pxr::CesiumTokens->cesiumIonServerApiUrl ||
property == pxr::CesiumTokens->cesiumIonServerApplicationId) {
reloadSession = true;
updateBindings = true;
} else if (
property == pxr::CesiumTokens->cesiumProjectDefaultIonAccessToken ||
property == pxr::CesiumTokens->cesiumProjectDefaultIonAccessTokenId) {
updateBindings = true;
}
}
// clang-format on
if (reloadSession) {
context.getAssetRegistry().removeIonServer(ionServerPath);
context.getAssetRegistry().addIonServer(ionServerPath);
}
if (updateBindings) {
updateIonServerBindings(context);
}
}
void processCesiumCartographicPolygonChanged(
const Context& context,
const pxr::SdfPath& cartographicPolygonPath,
const std::vector<pxr::TfToken>& properties) {
// Process globe anchor API schema first
processCesiumGlobeAnchorChanged(context, cartographicPolygonPath, properties);
auto updateBindings = false;
for (const auto& property : properties) {
if (property == pxr::UsdTokens->points) {
updateBindings = true;
}
}
if (updateBindings) {
updateCartographicPolygonBindings(context, cartographicPolygonPath);
}
}
void processUsdShaderChanged(
const Context& context,
const pxr::SdfPath& shaderPath,
const std::vector<pxr::TfToken>& properties) {
const auto usdShader = UsdUtil::getUsdShader(context.getUsdStage(), shaderPath);
const auto shaderPathFabric = FabricUtil::toFabricPath(shaderPath);
const auto materialPath = shaderPath.GetParentPath();
const auto materialPathFabric = FabricUtil::toFabricPath(materialPath);
if (!UsdUtil::isUsdMaterial(context.getUsdStage(), materialPath)) {
// Skip if parent path is not a material
return;
}
for (const auto& property : properties) {
const auto inputNamespace = std::string_view("inputs:");
const auto& attributeName = property.GetString();
if (attributeName.rfind(inputNamespace) != 0) {
// Skip if changed attribute is not a shader input
return;
}
const auto inputName = pxr::TfToken(attributeName.substr(inputNamespace.size()));
const auto shaderInput = usdShader.GetInput(inputName);
if (!shaderInput.IsDefined()) {
// Skip if changed attribute is not a shader input
return;
}
if (shaderInput.HasConnectedSource()) {
// Skip if shader input is connected to something else
return;
}
if (!FabricUtil::materialHasCesiumNodes(context.getFabricStage(), materialPathFabric)) {
// Simple materials can be skipped. We only need to handle materials that have been copied to each tile.
return;
}
if (!FabricUtil::isShaderConnectedToMaterial(context.getFabricStage(), materialPathFabric, shaderPathFabric)) {
// Skip if shader is not connected to the material
return;
}
const auto& tilesets = context.getAssetRegistry().getTilesets();
for (const auto& pTileset : tilesets) {
if (pTileset->getMaterialPath() == materialPath) {
pTileset->updateShaderInput(shaderPath, property);
}
}
context.getFabricResourceManager().updateShaderInput(materialPath, shaderPath, property);
}
}
[[nodiscard]] bool processCesiumDataRemoved(Context& context, const pxr::SdfPath& dataPath) {
const auto reloadStage = isFirstData(context, dataPath);
context.getAssetRegistry().removeData(dataPath);
return reloadStage;
}
void processCesiumTilesetRemoved(Context& context, const pxr::SdfPath& tilesetPath) {
context.getAssetRegistry().removeTileset(tilesetPath);
}
void processCesiumIonRasterOverlayRemoved(Context& context, const pxr::SdfPath& ionRasterOverlayPath) {
context.getAssetRegistry().removeIonRasterOverlay(ionRasterOverlayPath);
updateRasterOverlayBindings(context, ionRasterOverlayPath);
}
void processCesiumPolygonRasterOverlayRemoved(Context& context, const pxr::SdfPath& polygonRasterOverlayPath) {
context.getAssetRegistry().removePolygonRasterOverlay(polygonRasterOverlayPath);
updateRasterOverlayBindings(context, polygonRasterOverlayPath);
}
void processCesiumWebMapServiceRasterOverlayRemoved(
Context& context,
const pxr::SdfPath& webMapServiceRasterOverlayPath) {
context.getAssetRegistry().removeWebMapServiceRasterOverlay(webMapServiceRasterOverlayPath);
updateRasterOverlayBindings(context, webMapServiceRasterOverlayPath);
}
void processCesiumTileMapServiceRasterOverlayRemoved(
Context& context,
const pxr::SdfPath& tileMapServiceRasterOverlayPath) {
context.getAssetRegistry().removeTileMapServiceRasterOverlay(tileMapServiceRasterOverlayPath);
updateRasterOverlayBindings(context, tileMapServiceRasterOverlayPath);
}
void processCesiumWebMapTileServiceRasterOverlayRemoved(
Context& context,
const pxr::SdfPath& webMapTileServiceRasterOverlayPath) {
context.getAssetRegistry().removeWebMapServiceRasterOverlay(webMapTileServiceRasterOverlayPath);
updateRasterOverlayBindings(context, webMapTileServiceRasterOverlayPath);
}
void processCesiumGeoreferenceRemoved(Context& context, const pxr::SdfPath& georeferencePath) {
context.getAssetRegistry().removeGeoreference(georeferencePath);
updateGeoreferenceBindings(context);
}
void processCesiumGlobeAnchorRemoved(Context& context, const pxr::SdfPath& globeAnchorPath) {
context.getAssetRegistry().removeGlobeAnchor(globeAnchorPath);
updateGlobeAnchorBindings(context, globeAnchorPath);
}
void processCesiumIonServerRemoved(Context& context, const pxr::SdfPath& ionServerPath) {
context.getAssetRegistry().removeIonServer(ionServerPath);
updateIonServerBindings(context);
}
void processCesiumCartographicPolygonRemoved(Context& context, const pxr::SdfPath& cartographicPolygonPath) {
context.getAssetRegistry().removeCartographicPolygon(cartographicPolygonPath);
processCesiumGlobeAnchorRemoved(context, cartographicPolygonPath);
updateCartographicPolygonBindings(context, cartographicPolygonPath);
}
[[nodiscard]] bool processCesiumDataAdded(Context& context, const pxr::SdfPath& dataPath) {
if (context.getAssetRegistry().getData(dataPath)) {
return false;
}
context.getAssetRegistry().addData(dataPath);
return isFirstData(context, dataPath);
}
void processCesiumGlobeAnchorAdded(Context& context, const pxr::SdfPath& globeAnchorPath) {
if (context.getAssetRegistry().getGlobeAnchor(globeAnchorPath)) {
return;
}
context.getAssetRegistry().addGlobeAnchor(globeAnchorPath);
updateGlobeAnchorBindings(context, globeAnchorPath);
}
void processCesiumTilesetAdded(Context& context, const pxr::SdfPath& tilesetPath) {
if (UsdUtil::hasCesiumGlobeAnchor(context.getUsdStage(), tilesetPath)) {
processCesiumGlobeAnchorAdded(context, tilesetPath);
}
if (context.getAssetRegistry().getTileset(tilesetPath)) {
return;
}
context.getAssetRegistry().addTileset(tilesetPath);
}
void processCesiumIonRasterOverlayAdded(Context& context, const pxr::SdfPath& ionRasterOverlayPath) {
if (context.getAssetRegistry().getIonRasterOverlay(ionRasterOverlayPath)) {
return;
}
context.getAssetRegistry().addIonRasterOverlay(ionRasterOverlayPath);
updateRasterOverlayBindings(context, ionRasterOverlayPath);
}
void processCesiumPolygonRasterOverlayAdded(Context& context, const pxr::SdfPath& polygonRasterOverlayPath) {
if (context.getAssetRegistry().getPolygonRasterOverlay(polygonRasterOverlayPath)) {
return;
}
context.getAssetRegistry().addPolygonRasterOverlay(polygonRasterOverlayPath);
updateRasterOverlayBindings(context, polygonRasterOverlayPath);
}
void processCesiumWebMapServiceRasterOverlayAdded(
Context& context,
const pxr::SdfPath& webMapServiceRasterOverlayPath) {
if (context.getAssetRegistry().getWebMapServiceRasterOverlay(webMapServiceRasterOverlayPath)) {
return;
}
context.getAssetRegistry().addWebMapServiceRasterOverlay(webMapServiceRasterOverlayPath);
updateRasterOverlayBindings(context, webMapServiceRasterOverlayPath);
}
void processCesiumTileMapServiceRasterOverlayAdded(
Context& context,
const pxr::SdfPath& tileMapServiceRasterOverlayPath) {
if (context.getAssetRegistry().getTileMapServiceRasterOverlay(tileMapServiceRasterOverlayPath)) {
return;
}
context.getAssetRegistry().addTileMapServiceRasterOverlay(tileMapServiceRasterOverlayPath);
updateRasterOverlayBindings(context, tileMapServiceRasterOverlayPath);
}
void processCesiumWebMapTileServiceRasterOverlayAdded(
Context& context,
const pxr::SdfPath& webMapTileServiceRasterOverlayPath) {
if (context.getAssetRegistry().getWebMapTileServiceRasterOverlay(webMapTileServiceRasterOverlayPath)) {
return;
}
context.getAssetRegistry().addWebMapTileServiceRasterOverlay(webMapTileServiceRasterOverlayPath);
updateRasterOverlayBindings(context, webMapTileServiceRasterOverlayPath);
}
void processCesiumGeoreferenceAdded(Context& context, const pxr::SdfPath& georeferencePath) {
if (context.getAssetRegistry().getGeoreference(georeferencePath)) {
return;
}
context.getAssetRegistry().addGeoreference(georeferencePath);
updateGeoreferenceBindings(context);
}
void processCesiumIonServerAdded(Context& context, const pxr::SdfPath& ionServerPath) {
if (context.getAssetRegistry().getIonServer(ionServerPath)) {
return;
}
context.getAssetRegistry().addIonServer(ionServerPath);
updateIonServerBindings(context);
}
void processCesiumCartographicPolygonAdded(Context& context, const pxr::SdfPath& cartographicPolygonPath) {
if (UsdUtil::hasCesiumGlobeAnchor(context.getUsdStage(), cartographicPolygonPath)) {
processCesiumGlobeAnchorAdded(context, cartographicPolygonPath);
}
if (context.getAssetRegistry().getCartographicPolygon(cartographicPolygonPath)) {
return;
}
context.getAssetRegistry().addCartographicPolygon(cartographicPolygonPath);
updateCartographicPolygonBindings(context, cartographicPolygonPath);
}
} // namespace
UsdNotificationHandler::UsdNotificationHandler(Context* pContext)
: _pContext(pContext)
, _noticeListenerKey(
pxr::TfNotice::Register(pxr::TfCreateWeakPtr(this), &UsdNotificationHandler::onObjectsChanged)) {}
UsdNotificationHandler::~UsdNotificationHandler() {
pxr::TfNotice::Revoke(_noticeListenerKey);
}
void UsdNotificationHandler::onStageLoaded() {
// Insert prims manually since USD doesn't notify us about changes when the stage is first loaded
for (const auto& prim : _pContext->getUsdStage()->Traverse()) {
const auto type = getTypeFromStage(prim.GetPath());
if (type != ChangedPrimType::OTHER) {
insertAddedPrim(prim.GetPath(), type);
}
}
// Process changes immediately
processChangedPrims();
}
void UsdNotificationHandler::onUpdateFrame() {
const auto reloadStage = processChangedPrims();
if (reloadStage) {
_pContext->reloadStage();
}
}
void UsdNotificationHandler::clear() {
_changedPrims.clear();
}
bool UsdNotificationHandler::processChangedPrims() {
std::vector<ChangedPrim> consolidatedChangedPrims;
ChangedPrim* pPrevious = nullptr;
for (const auto& changedPrim : _changedPrims) {
if (pPrevious && changedPrim.primPath == pPrevious->primPath) {
if (pPrevious->changedType == ChangedType::PRIM_ADDED &&
changedPrim.changedType == ChangedType::PROPERTY_CHANGED) {
// Ignore property changes that occur immediately after the prim is added. This avoids unecessary churn.
continue;
}
if (pPrevious->changedType == ChangedType::PROPERTY_CHANGED &&
changedPrim.changedType == ChangedType::PROPERTY_CHANGED) {
// Consolidate property changes so that they can be processed together
CppUtil::append(pPrevious->properties, changedPrim.properties);
continue;
}
}
consolidatedChangedPrims.push_back(changedPrim);
pPrevious = &consolidatedChangedPrims.back();
}
_changedPrims.clear();
auto reloadStage = false;
for (const auto& changedPrim : consolidatedChangedPrims) {
reloadStage = processChangedPrim(changedPrim) || reloadStage;
}
// Process newly added changes
if (!_changedPrims.empty()) {
reloadStage = processChangedPrims() || reloadStage;
}
return reloadStage;
}
bool UsdNotificationHandler::processChangedPrim(const ChangedPrim& changedPrim) const {
auto reloadStage = false;
switch (changedPrim.changedType) {
case ChangedType::PROPERTY_CHANGED:
switch (changedPrim.primType) {
case ChangedPrimType::CESIUM_DATA:
reloadStage = processCesiumDataChanged(*_pContext, changedPrim.primPath, changedPrim.properties);
break;
case ChangedPrimType::CESIUM_TILESET:
processCesiumTilesetChanged(*_pContext, changedPrim.primPath, changedPrim.properties);
break;
case ChangedPrimType::CESIUM_ION_RASTER_OVERLAY:
processCesiumIonRasterOverlayChanged(*_pContext, changedPrim.primPath, changedPrim.properties);
break;
case ChangedPrimType::CESIUM_POLYGON_RASTER_OVERLAY:
processCesiumPolygonRasterOverlayChanged(*_pContext, changedPrim.primPath, changedPrim.properties);
break;
case ChangedPrimType::CESIUM_WEB_MAP_SERVICE_RASTER_OVERLAY:
processCesiumWebMapServiceRasterOverlayChanged(
*_pContext, changedPrim.primPath, changedPrim.properties);
break;
case ChangedPrimType::CESIUM_TILE_MAP_SERVICE_RASTER_OVERLAY:
processCesiumTileMapServiceRasterOverlayChanged(
*_pContext, changedPrim.primPath, changedPrim.properties);
break;
case ChangedPrimType::CESIUM_WEB_MAP_TILE_SERVICE_RASTER_OVERLAY:
processCesiumWebMapTileServiceRasterOverlayChanged(
*_pContext, changedPrim.primPath, changedPrim.properties);
break;
case ChangedPrimType::CESIUM_GEOREFERENCE:
processCesiumGeoreferenceChanged(*_pContext, changedPrim.properties);
break;
case ChangedPrimType::CESIUM_GLOBE_ANCHOR:
processCesiumGlobeAnchorChanged(*_pContext, changedPrim.primPath, changedPrim.properties);
break;
case ChangedPrimType::CESIUM_ION_SERVER:
processCesiumIonServerChanged(*_pContext, changedPrim.primPath, changedPrim.properties);
break;
case ChangedPrimType::CESIUM_CARTOGRAPHIC_POLYGON:
processCesiumCartographicPolygonChanged(*_pContext, changedPrim.primPath, changedPrim.properties);
break;
case ChangedPrimType::USD_SHADER:
processUsdShaderChanged(*_pContext, changedPrim.primPath, changedPrim.properties);
break;
case ChangedPrimType::OTHER:
break;
}
break;
case ChangedType::PRIM_ADDED:
switch (changedPrim.primType) {
case ChangedPrimType::CESIUM_DATA:
reloadStage = processCesiumDataAdded(*_pContext, changedPrim.primPath);
break;
case ChangedPrimType::CESIUM_TILESET:
processCesiumTilesetAdded(*_pContext, changedPrim.primPath);
break;
case ChangedPrimType::CESIUM_ION_RASTER_OVERLAY:
processCesiumIonRasterOverlayAdded(*_pContext, changedPrim.primPath);
break;
case ChangedPrimType::CESIUM_POLYGON_RASTER_OVERLAY:
processCesiumPolygonRasterOverlayAdded(*_pContext, changedPrim.primPath);
break;
case ChangedPrimType::CESIUM_WEB_MAP_SERVICE_RASTER_OVERLAY:
processCesiumWebMapServiceRasterOverlayAdded(*_pContext, changedPrim.primPath);
break;
case ChangedPrimType::CESIUM_TILE_MAP_SERVICE_RASTER_OVERLAY:
processCesiumTileMapServiceRasterOverlayAdded(*_pContext, changedPrim.primPath);
break;
case ChangedPrimType::CESIUM_WEB_MAP_TILE_SERVICE_RASTER_OVERLAY:
processCesiumWebMapTileServiceRasterOverlayAdded(*_pContext, changedPrim.primPath);
break;
case ChangedPrimType::CESIUM_GEOREFERENCE:
processCesiumGeoreferenceAdded(*_pContext, changedPrim.primPath);
break;
case ChangedPrimType::CESIUM_GLOBE_ANCHOR:
processCesiumGlobeAnchorAdded(*_pContext, changedPrim.primPath);
break;
case ChangedPrimType::CESIUM_ION_SERVER:
processCesiumIonServerAdded(*_pContext, changedPrim.primPath);
break;
case ChangedPrimType::CESIUM_CARTOGRAPHIC_POLYGON:
processCesiumCartographicPolygonAdded(*_pContext, changedPrim.primPath);
break;
case ChangedPrimType::USD_SHADER:
case ChangedPrimType::OTHER:
break;
}
break;
case ChangedType::PRIM_REMOVED:
switch (changedPrim.primType) {
case ChangedPrimType::CESIUM_DATA:
reloadStage = processCesiumDataRemoved(*_pContext, changedPrim.primPath);
break;
case ChangedPrimType::CESIUM_TILESET:
processCesiumTilesetRemoved(*_pContext, changedPrim.primPath);
break;
case ChangedPrimType::CESIUM_ION_RASTER_OVERLAY:
processCesiumIonRasterOverlayRemoved(*_pContext, changedPrim.primPath);
break;
case ChangedPrimType::CESIUM_POLYGON_RASTER_OVERLAY:
processCesiumPolygonRasterOverlayRemoved(*_pContext, changedPrim.primPath);
break;
case ChangedPrimType::CESIUM_WEB_MAP_SERVICE_RASTER_OVERLAY:
processCesiumWebMapServiceRasterOverlayRemoved(*_pContext, changedPrim.primPath);
break;
case ChangedPrimType::CESIUM_TILE_MAP_SERVICE_RASTER_OVERLAY:
processCesiumTileMapServiceRasterOverlayRemoved(*_pContext, changedPrim.primPath);
break;
case ChangedPrimType::CESIUM_WEB_MAP_TILE_SERVICE_RASTER_OVERLAY:
processCesiumWebMapTileServiceRasterOverlayRemoved(*_pContext, changedPrim.primPath);
break;
case ChangedPrimType::CESIUM_GEOREFERENCE:
processCesiumGeoreferenceRemoved(*_pContext, changedPrim.primPath);
break;
case ChangedPrimType::CESIUM_GLOBE_ANCHOR:
processCesiumGlobeAnchorRemoved(*_pContext, changedPrim.primPath);
break;
case ChangedPrimType::CESIUM_ION_SERVER:
processCesiumIonServerRemoved(*_pContext, changedPrim.primPath);
break;
case ChangedPrimType::CESIUM_CARTOGRAPHIC_POLYGON:
processCesiumCartographicPolygonRemoved(*_pContext, changedPrim.primPath);
break;
case ChangedPrimType::USD_SHADER:
case ChangedPrimType::OTHER:
break;
}
break;
}
return reloadStage;
}
void UsdNotificationHandler::onObjectsChanged(const pxr::UsdNotice::ObjectsChanged& objectsChanged) {
if (!_pContext->hasUsdStage()) {
return;
}
const auto resyncedPaths = objectsChanged.GetResyncedPaths();
for (const auto& path : resyncedPaths) {
if (path.IsPrimPath()) {
if (UsdUtil::primExists(_pContext->getUsdStage(), path)) {
// A prim is resynced when it is added to the stage or when an API schema is applied to it, e.g. when
// a material or globe anchor is assigned to a tileset for the first time. We let onPrimAdded get
// called potentially multiple times so that API schemas can be registered. There are checks later
// that prevent the prim from being added to the asset registry twice.
onPrimAdded(path);
} else {
onPrimRemoved(path);
}
} else if (path.IsPropertyPath()) {
onPropertyChanged(path);
}
}
const auto changedPaths = objectsChanged.GetChangedInfoOnlyPaths();
for (const auto& path : changedPaths) {
if (path.IsPropertyPath()) {
onPropertyChanged(path);
}
}
}
void UsdNotificationHandler::onPrimAdded(const pxr::SdfPath& primPath) {
const auto type = getTypeFromStage(primPath);
if (type != ChangedPrimType::OTHER) {
insertAddedPrim(primPath, type);
}
// USD only notifies us about the top-most prim being added. Find all descendant prims
// and add those as well (recursively)
const auto prim = _pContext->getUsdStage()->GetPrimAtPath(primPath);
for (const auto& child : prim.GetAllChildren()) {
onPrimAdded(child.GetPath());
}
}
void UsdNotificationHandler::onPrimRemoved(const pxr::SdfPath& primPath) {
// USD only notifies us about the top-most prim being removed. Find all descendant prims
// and remove those as well. Since the prims no longer exist on the stage we need
// to look the paths in _changedPrims and the asset registry.
// Remove prims that haven't been added to asset registry yet
// This needs to be an index-based for loop since _changedPrims can grow in size
const auto changedPrimsCount = _changedPrims.size();
for (uint64_t i = 0; i < changedPrimsCount; ++i) {
if (_changedPrims[i].changedType == ChangedType::PRIM_ADDED) {
if (isPrimOrDescendant(_changedPrims[i].primPath, primPath)) {
insertRemovedPrim(_changedPrims[i].primPath, _changedPrims[i].primType);
}
}
}
// Remove prims in the asset registry
const auto& tilesets = _pContext->getAssetRegistry().getTilesets();
for (const auto& pTileset : tilesets) {
const auto tilesetPath = pTileset->getPath();
if (isPrimOrDescendant(tilesetPath, primPath)) {
insertRemovedPrim(tilesetPath, ChangedPrimType::CESIUM_TILESET);
}
}
const auto& ionRasterOverlays = _pContext->getAssetRegistry().getIonRasterOverlays();
for (const auto& pIonRasterOverlay : ionRasterOverlays) {
const auto ionRasterOverlayPath = pIonRasterOverlay->getPath();
if (isPrimOrDescendant(ionRasterOverlayPath, primPath)) {
insertRemovedPrim(ionRasterOverlayPath, ChangedPrimType::CESIUM_ION_RASTER_OVERLAY);
}
}
const auto& polygonRasterOverlays = _pContext->getAssetRegistry().getPolygonRasterOverlays();
for (const auto& pPolygonRasterOverlay : polygonRasterOverlays) {
const auto polygonRasterOverlayPath = pPolygonRasterOverlay->getPath();
if (isPrimOrDescendant(polygonRasterOverlayPath, primPath)) {
insertRemovedPrim(polygonRasterOverlayPath, ChangedPrimType::CESIUM_POLYGON_RASTER_OVERLAY);
}
}
const auto& georeferences = _pContext->getAssetRegistry().getGeoreferences();
for (const auto& pGeoreference : georeferences) {
const auto georeferencePath = pGeoreference->getPath();
if (isPrimOrDescendant(georeferencePath, primPath)) {
insertRemovedPrim(georeferencePath, ChangedPrimType::CESIUM_GEOREFERENCE);
}
}
const auto& ionServers = _pContext->getAssetRegistry().getIonServers();
for (const auto& pIonServer : ionServers) {
const auto ionServerPath = pIonServer->getPath();
if (isPrimOrDescendant(ionServerPath, primPath)) {
insertRemovedPrim(ionServerPath, ChangedPrimType::CESIUM_ION_SERVER);
}
}
const auto& cartographicPolygons = _pContext->getAssetRegistry().getCartographicPolygons();
for (const auto& pCartographicPolygon : cartographicPolygons) {
const auto cartographicPolygonPath = pCartographicPolygon->getPath();
if (isPrimOrDescendant(cartographicPolygonPath, primPath)) {
insertRemovedPrim(cartographicPolygonPath, ChangedPrimType::CESIUM_CARTOGRAPHIC_POLYGON);
}
}
const auto& globeAnchors = _pContext->getAssetRegistry().getGlobeAnchors();
for (const auto& pGlobeAnchor : globeAnchors) {
const auto globeAnchorPath = pGlobeAnchor->getPath();
const auto type = getTypeFromAssetRegistry(globeAnchorPath);
if (type == ChangedPrimType::CESIUM_GLOBE_ANCHOR) {
// Make sure it's not one of the types previously handled (e.g. cartographic polygon or tileset)
if (isPrimOrDescendant(globeAnchorPath, primPath)) {
insertRemovedPrim(globeAnchorPath, ChangedPrimType::CESIUM_GLOBE_ANCHOR);
}
}
}
}
void UsdNotificationHandler::onPropertyChanged(const pxr::SdfPath& propertyPath) {
const auto& propertyName = propertyPath.GetNameToken();
const auto primPath = propertyPath.GetPrimPath();
const auto type = getTypeFromStage(primPath);
if (type != ChangedPrimType::OTHER) {
insertPropertyChanged(primPath, type, propertyName);
}
}
void UsdNotificationHandler::insertAddedPrim(const pxr::SdfPath& primPath, ChangedPrimType primType) {
// In C++ 20 this can be emplace_back without the {}
_changedPrims.push_back({primPath, {}, primType, ChangedType::PRIM_ADDED});
}
void UsdNotificationHandler::insertRemovedPrim(const pxr::SdfPath& primPath, ChangedPrimType primType) {
// In C++ 20 this can be emplace_back without the {}
_changedPrims.push_back({primPath, {}, primType, ChangedType::PRIM_REMOVED});
}
void UsdNotificationHandler::insertPropertyChanged(
const pxr::SdfPath& primPath,
ChangedPrimType primType,
const pxr::TfToken& propertyName) {
// In C++ 20 this can be emplace_back without the {}
_changedPrims.push_back({primPath, {propertyName}, primType, ChangedType::PROPERTY_CHANGED});
}
UsdNotificationHandler::ChangedPrimType UsdNotificationHandler::getTypeFromStage(const pxr::SdfPath& path) const {
if (UsdUtil::isCesiumData(_pContext->getUsdStage(), path)) {
return ChangedPrimType::CESIUM_DATA;
} else if (UsdUtil::isCesiumTileset(_pContext->getUsdStage(), path)) {
return ChangedPrimType::CESIUM_TILESET;
} else if (UsdUtil::isCesiumIonRasterOverlay(_pContext->getUsdStage(), path)) {
return ChangedPrimType::CESIUM_ION_RASTER_OVERLAY;
} else if (UsdUtil::isCesiumPolygonRasterOverlay(_pContext->getUsdStage(), path)) {
return ChangedPrimType::CESIUM_POLYGON_RASTER_OVERLAY;
} else if (UsdUtil::isCesiumWebMapServiceRasterOverlay(_pContext->getUsdStage(), path)) {
return ChangedPrimType::CESIUM_WEB_MAP_SERVICE_RASTER_OVERLAY;
} else if (UsdUtil::isCesiumTileMapServiceRasterOverlay(_pContext->getUsdStage(), path)) {
return ChangedPrimType::CESIUM_TILE_MAP_SERVICE_RASTER_OVERLAY;
} else if (UsdUtil::isCesiumWebMapTileServiceRasterOverlay(_pContext->getUsdStage(), path)) {
return ChangedPrimType::CESIUM_WEB_MAP_TILE_SERVICE_RASTER_OVERLAY;
} else if (UsdUtil::isCesiumGeoreference(_pContext->getUsdStage(), path)) {
return ChangedPrimType::CESIUM_GEOREFERENCE;
} else if (UsdUtil::isCesiumIonServer(_pContext->getUsdStage(), path)) {
return ChangedPrimType::CESIUM_ION_SERVER;
} else if (UsdUtil::isCesiumCartographicPolygon(_pContext->getUsdStage(), path)) {
return ChangedPrimType::CESIUM_CARTOGRAPHIC_POLYGON;
} else if (UsdUtil::isUsdShader(_pContext->getUsdStage(), path)) {
return ChangedPrimType::USD_SHADER;
} else if (UsdUtil::hasCesiumGlobeAnchor(_pContext->getUsdStage(), path)) {
// Globe anchor needs to be checked last since prim types take precedence over API schemas
return ChangedPrimType::CESIUM_GLOBE_ANCHOR;
}
return ChangedPrimType::OTHER;
}
UsdNotificationHandler::ChangedPrimType
UsdNotificationHandler::getTypeFromAssetRegistry(const pxr::SdfPath& path) const {
const auto assetType = _pContext->getAssetRegistry().getAssetType(path);
switch (assetType) {
case AssetType::DATA:
return ChangedPrimType::CESIUM_DATA;
case AssetType::TILESET:
return ChangedPrimType::CESIUM_TILESET;
case AssetType::ION_RASTER_OVERLAY:
return ChangedPrimType::CESIUM_ION_RASTER_OVERLAY;
case AssetType::POLYGON_RASTER_OVERLAY:
return ChangedPrimType::CESIUM_POLYGON_RASTER_OVERLAY;
case AssetType::WEB_MAP_SERVICE_RASTER_OVERLAY:
return ChangedPrimType::CESIUM_WEB_MAP_SERVICE_RASTER_OVERLAY;
case AssetType::TILE_MAP_SERVICE_RASTER_OVERLAY:
return ChangedPrimType::CESIUM_TILE_MAP_SERVICE_RASTER_OVERLAY;
case AssetType::WEB_MAP_TILE_SERVICE_RASTER_OVERLAY:
return ChangedPrimType::CESIUM_WEB_MAP_TILE_SERVICE_RASTER_OVERLAY;
case AssetType::GEOREFERENCE:
return ChangedPrimType::CESIUM_GEOREFERENCE;
case AssetType::GLOBE_ANCHOR:
return ChangedPrimType::CESIUM_GLOBE_ANCHOR;
case AssetType::ION_SERVER:
return ChangedPrimType::CESIUM_ION_SERVER;
case AssetType::CARTOGRAPHIC_POLYGON:
return ChangedPrimType::CESIUM_CARTOGRAPHIC_POLYGON;
case AssetType::OTHER:
return ChangedPrimType::OTHER;
}
return ChangedPrimType::OTHER;
}
} // namespace cesium::omniverse
| 51,453 | C++ | 39.64297 | 120 | 0.684625 |
CesiumGS/cesium-omniverse/src/core/src/FabricGeometry.cpp | #include "cesium/omniverse/FabricGeometry.h"
#include "cesium/omniverse/Context.h"
#include "cesium/omniverse/DataType.h"
#include "cesium/omniverse/FabricAttributesBuilder.h"
#include "cesium/omniverse/FabricMaterial.h"
#include "cesium/omniverse/FabricResourceManager.h"
#include "cesium/omniverse/FabricUtil.h"
#include "cesium/omniverse/FabricVertexAttributeDescriptor.h"
#include "cesium/omniverse/GltfUtil.h"
#include "cesium/omniverse/MathUtil.h"
#include "cesium/omniverse/UsdTokens.h"
#include "cesium/omniverse/UsdUtil.h"
#include <glm/fwd.hpp>
#ifdef CESIUM_OMNI_MSVC
#pragma push_macro("OPAQUE")
#undef OPAQUE
#endif
#include <CesiumGltf/Model.h>
#include <omni/fabric/FabricUSD.h>
#include <omni/fabric/SimStageWithHistory.h>
#include <pxr/base/gf/range3d.h>
namespace cesium::omniverse {
namespace {
const auto DEFAULT_DOUBLE_SIDED = false;
const auto DEFAULT_EXTENT = std::array<glm::dvec3, 2>{{glm::dvec3(0.0, 0.0, 0.0), glm::dvec3(0.0, 0.0, 0.0)}};
const auto DEFAULT_POSITION = glm::dvec3(0.0, 0.0, 0.0);
const auto DEFAULT_ORIENTATION = glm::dquat(1.0, 0.0, 0.0, 0.0);
const auto DEFAULT_SCALE = glm::dvec3(1.0, 1.0, 1.0);
const auto DEFAULT_MATRIX = glm::dmat4(1.0);
const auto DEFAULT_VISIBILITY = false;
template <DataType T>
void setVertexAttributeValues(
omni::fabric::StageReaderWriter& fabricStage,
const omni::fabric::Path& path,
const CesiumGltf::Model& model,
const CesiumGltf::MeshPrimitive& primitive,
const FabricVertexAttributeDescriptor& attribute,
uint64_t repeat) {
const auto accessor = GltfUtil::getVertexAttributeValues<T>(model, primitive, attribute.gltfAttributeName);
fabricStage.setArrayAttributeSize(path, attribute.fabricAttributeName, accessor.size() * repeat);
const auto fabricValues =
fabricStage.getArrayAttributeWr<DataTypeUtil::GetNativeType<DataTypeUtil::getPrimvarType<T>()>>(
path, attribute.fabricAttributeName);
accessor.fill(fabricValues, repeat);
}
} // namespace
FabricGeometry::FabricGeometry(
Context* pContext,
const omni::fabric::Path& path,
const FabricGeometryDescriptor& geometryDescriptor,
int64_t poolId)
: _pContext(pContext)
, _path(path)
, _geometryDescriptor(geometryDescriptor)
, _poolId(poolId)
, _stageId(pContext->getUsdStageId()) {
if (stageDestroyed()) {
return;
}
initialize();
reset();
}
FabricGeometry::~FabricGeometry() {
if (stageDestroyed()) {
return;
}
FabricUtil::destroyPrim(_pContext->getFabricStage(), _path);
}
void FabricGeometry::setActive(bool active) {
if (stageDestroyed()) {
return;
}
if (!active) {
reset();
}
}
void FabricGeometry::setVisibility(bool visible) {
if (stageDestroyed()) {
return;
}
auto& fabricStage = _pContext->getFabricStage();
const auto worldVisibilityFabric = fabricStage.getAttributeWr<bool>(_path, FabricTokens::_worldVisibility);
*worldVisibilityFabric = visible;
}
const omni::fabric::Path& FabricGeometry::getPath() const {
return _path;
}
const FabricGeometryDescriptor& FabricGeometry::getGeometryDescriptor() const {
return _geometryDescriptor;
}
int64_t FabricGeometry::getPoolId() const {
return _poolId;
}
void FabricGeometry::setMaterial(const omni::fabric::Path& materialPath) {
if (stageDestroyed()) {
return;
}
auto& fabricStage = _pContext->getFabricStage();
fabricStage.setArrayAttributeSize(_path, FabricTokens::material_binding, 1);
const auto materialBindingFabric =
fabricStage.getArrayAttributeWr<omni::fabric::PathC>(_path, FabricTokens::material_binding);
materialBindingFabric[0] = materialPath;
}
void FabricGeometry::initialize() {
const auto hasNormals = _geometryDescriptor.hasNormals();
const auto hasVertexColors = _geometryDescriptor.hasVertexColors();
const auto texcoordSetCount = _geometryDescriptor.getTexcoordSetCount();
const auto& customVertexAttributes = _geometryDescriptor.getCustomVertexAttributes();
const auto customVertexAttributesCount = customVertexAttributes.size();
const auto hasVertexIds = _geometryDescriptor.hasVertexIds();
auto& fabricStage = _pContext->getFabricStage();
fabricStage.createPrim(_path);
// clang-format off
FabricAttributesBuilder attributes(_pContext);
attributes.addAttribute(FabricTypes::faceVertexCounts, FabricTokens::faceVertexCounts);
attributes.addAttribute(FabricTypes::faceVertexIndices, FabricTokens::faceVertexIndices);
attributes.addAttribute(FabricTypes::points, FabricTokens::points);
attributes.addAttribute(FabricTypes::extent, FabricTokens::extent);
attributes.addAttribute(FabricTypes::_worldExtent, FabricTokens::_worldExtent);
attributes.addAttribute(FabricTypes::_worldVisibility, FabricTokens::_worldVisibility);
attributes.addAttribute(FabricTypes::primvars, FabricTokens::primvars);
attributes.addAttribute(FabricTypes::primvarInterpolations, FabricTokens::primvarInterpolations);
attributes.addAttribute(FabricTypes::Mesh, FabricTokens::Mesh);
attributes.addAttribute(FabricTypes::_cesium_tilesetId, FabricTokens::_cesium_tilesetId);
attributes.addAttribute(FabricTypes::_cesium_gltfLocalToEcefTransform, FabricTokens::_cesium_gltfLocalToEcefTransform);
attributes.addAttribute(FabricTypes::_worldPosition, FabricTokens::_worldPosition);
attributes.addAttribute(FabricTypes::_worldOrientation, FabricTokens::_worldOrientation);
attributes.addAttribute(FabricTypes::_worldScale, FabricTokens::_worldScale);
attributes.addAttribute(FabricTypes::doubleSided, FabricTokens::doubleSided);
attributes.addAttribute(FabricTypes::subdivisionScheme, FabricTokens::subdivisionScheme);
attributes.addAttribute(FabricTypes::material_binding, FabricTokens::material_binding);
// clang-format on
for (uint64_t i = 0; i < texcoordSetCount; ++i) {
attributes.addAttribute(FabricTypes::primvars_st, FabricTokens::primvars_st_n(i));
}
if (hasNormals) {
attributes.addAttribute(FabricTypes::primvars_normals, FabricTokens::primvars_normals);
}
if (hasVertexColors) {
attributes.addAttribute(FabricTypes::primvars_COLOR_0, FabricTokens::primvars_COLOR_0);
}
if (hasVertexIds) {
attributes.addAttribute(FabricTypes::primvars_vertexId, FabricTokens::primvars_vertexId);
}
for (const auto& customVertexAttribute : customVertexAttributes) {
attributes.addAttribute(
FabricUtil::getPrimvarType(customVertexAttribute.type), customVertexAttribute.fabricAttributeName);
}
attributes.createAttributes(_path);
const auto subdivisionSchemeFabric =
fabricStage.getAttributeWr<omni::fabric::TokenC>(_path, FabricTokens::subdivisionScheme);
*subdivisionSchemeFabric = FabricTokens::none;
// Initialize primvars
uint64_t primvarsCount = 0;
uint64_t primvarIndexNormal = 0;
uint64_t primvarIndexVertexColor = 0;
uint64_t primvarIndexVertexId = 0;
std::vector<uint64_t> primvarIndexStArray;
primvarIndexStArray.reserve(texcoordSetCount);
for (uint64_t i = 0; i < texcoordSetCount; ++i) {
primvarIndexStArray.push_back(primvarsCount++);
}
std::vector<uint64_t> primvarIndexCustomVertexAttributesArray;
primvarIndexCustomVertexAttributesArray.reserve(customVertexAttributesCount);
for (uint64_t i = 0; i < customVertexAttributesCount; ++i) {
primvarIndexCustomVertexAttributesArray.push_back(primvarsCount++);
}
if (hasNormals) {
primvarIndexNormal = primvarsCount++;
}
if (hasVertexColors) {
primvarIndexVertexColor = primvarsCount++;
}
if (hasVertexIds) {
primvarIndexVertexId = primvarsCount++;
}
fabricStage.setArrayAttributeSize(_path, FabricTokens::primvars, primvarsCount);
fabricStage.setArrayAttributeSize(_path, FabricTokens::primvarInterpolations, primvarsCount);
// clang-format off
const auto primvarsFabric = fabricStage.getArrayAttributeWr<omni::fabric::TokenC>(_path, FabricTokens::primvars);
const auto primvarInterpolationsFabric = fabricStage.getArrayAttributeWr<omni::fabric::TokenC>(_path, FabricTokens::primvarInterpolations);
// clang-format on
for (uint64_t i = 0; i < texcoordSetCount; ++i) {
primvarsFabric[primvarIndexStArray[i]] = FabricTokens::primvars_st_n(i);
primvarInterpolationsFabric[primvarIndexStArray[i]] = FabricTokens::vertex;
}
for (uint64_t i = 0; i < customVertexAttributesCount; ++i) {
const auto& customVertexAttribute = CppUtil::getElementByIndex(customVertexAttributes, i);
primvarsFabric[primvarIndexCustomVertexAttributesArray[i]] = customVertexAttribute.fabricAttributeName;
primvarInterpolationsFabric[primvarIndexCustomVertexAttributesArray[i]] = FabricTokens::vertex;
}
if (hasNormals) {
primvarsFabric[primvarIndexNormal] = FabricTokens::primvars_normals;
primvarInterpolationsFabric[primvarIndexNormal] = FabricTokens::vertex;
}
if (hasVertexColors) {
primvarsFabric[primvarIndexVertexColor] = FabricTokens::primvars_COLOR_0;
primvarInterpolationsFabric[primvarIndexVertexColor] = FabricTokens::vertex;
}
if (hasVertexIds) {
primvarsFabric[primvarIndexVertexId] = FabricTokens::primvars_vertexId;
primvarInterpolationsFabric[primvarIndexVertexId] = FabricTokens::vertex;
}
}
void FabricGeometry::reset() {
const auto hasNormals = _geometryDescriptor.hasNormals();
const auto hasVertexColors = _geometryDescriptor.hasVertexColors();
const auto texcoordSetCount = _geometryDescriptor.getTexcoordSetCount();
const auto& customVertexAttributes = _geometryDescriptor.getCustomVertexAttributes();
const auto hasVertexIds = _geometryDescriptor.hasVertexIds();
auto& fabricStage = _pContext->getFabricStage();
// clang-format off
const auto doubleSidedFabric = fabricStage.getAttributeWr<bool>(_path, FabricTokens::doubleSided);
const auto extentFabric = fabricStage.getAttributeWr<pxr::GfRange3d>(_path, FabricTokens::extent);
const auto worldExtentFabric = fabricStage.getAttributeWr<pxr::GfRange3d>(_path, FabricTokens::_worldExtent);
const auto worldVisibilityFabric = fabricStage.getAttributeWr<bool>(_path, FabricTokens::_worldVisibility);
const auto gltfLocalToEcefTransformFabric = fabricStage.getAttributeWr<pxr::GfMatrix4d>(_path, FabricTokens::_cesium_gltfLocalToEcefTransform);
const auto worldPositionFabric = fabricStage.getAttributeWr<pxr::GfVec3d>(_path, FabricTokens::_worldPosition);
const auto worldOrientationFabric = fabricStage.getAttributeWr<pxr::GfQuatf>(_path, FabricTokens::_worldOrientation);
const auto worldScaleFabric = fabricStage.getAttributeWr<pxr::GfVec3f>(_path, FabricTokens::_worldScale);
const auto tilesetIdFabric = fabricStage.getAttributeWr<int64_t>(_path, FabricTokens::_cesium_tilesetId);
// clang-format on
*doubleSidedFabric = DEFAULT_DOUBLE_SIDED;
*extentFabric = UsdUtil::glmToUsdExtent(DEFAULT_EXTENT);
*worldExtentFabric = UsdUtil::glmToUsdExtent(DEFAULT_EXTENT);
*worldVisibilityFabric = DEFAULT_VISIBILITY;
*gltfLocalToEcefTransformFabric = UsdUtil::glmToUsdMatrix(DEFAULT_MATRIX);
*worldPositionFabric = UsdUtil::glmToUsdVector(DEFAULT_POSITION);
*worldOrientationFabric = UsdUtil::glmToUsdQuat(glm::fquat(DEFAULT_ORIENTATION));
*worldScaleFabric = UsdUtil::glmToUsdVector(glm::fvec3(DEFAULT_SCALE));
*tilesetIdFabric = FabricUtil::NO_TILESET_ID;
fabricStage.setArrayAttributeSize(_path, FabricTokens::material_binding, 0);
fabricStage.setArrayAttributeSize(_path, FabricTokens::faceVertexCounts, 0);
fabricStage.setArrayAttributeSize(_path, FabricTokens::faceVertexIndices, 0);
fabricStage.setArrayAttributeSize(_path, FabricTokens::points, 0);
for (uint64_t i = 0; i < texcoordSetCount; ++i) {
fabricStage.setArrayAttributeSize(_path, FabricTokens::primvars_st_n(i), 0);
}
for (const auto& customVertexAttribute : customVertexAttributes) {
fabricStage.setArrayAttributeSize(_path, customVertexAttribute.fabricAttributeName, 0);
}
if (hasNormals) {
fabricStage.setArrayAttributeSize(_path, FabricTokens::primvars_normals, 0);
}
if (hasVertexColors) {
fabricStage.setArrayAttributeSize(_path, FabricTokens::primvars_COLOR_0, 0);
}
if (hasVertexIds) {
fabricStage.setArrayAttributeSize(_path, FabricTokens::primvars_vertexId, 0);
}
}
void FabricGeometry::setGeometry(
int64_t tilesetId,
const glm::dmat4& ecefToPrimWorldTransform,
const glm::dmat4& gltfLocalToEcefTransform,
const CesiumGltf::Model& model,
const CesiumGltf::MeshPrimitive& primitive,
const FabricMaterialInfo& materialInfo,
bool smoothNormals,
const std::unordered_map<uint64_t, uint64_t>& texcoordIndexMapping,
const std::unordered_map<uint64_t, uint64_t>& rasterOverlayTexcoordIndexMapping) {
if (stageDestroyed()) {
return;
}
const auto hasNormals = _geometryDescriptor.hasNormals();
const auto hasVertexColors = _geometryDescriptor.hasVertexColors();
const auto& customVertexAttributes = _geometryDescriptor.getCustomVertexAttributes();
const auto hasVertexIds = _geometryDescriptor.hasVertexIds();
auto& fabricStage = _pContext->getFabricStage();
const auto positions = GltfUtil::getPositions(model, primitive);
const auto indices = GltfUtil::getIndices(model, primitive, positions);
const auto normals = GltfUtil::getNormals(model, primitive, positions, indices, smoothNormals);
const auto vertexColors = GltfUtil::getVertexColors(model, primitive, 0);
const auto vertexIds = GltfUtil::getVertexIds(positions);
const auto gltfLocalExtent = GltfUtil::getExtent(model, primitive);
const auto faceVertexCounts = GltfUtil::getFaceVertexCounts(indices);
if (positions.size() == 0 || indices.size() == 0 || !gltfLocalExtent.has_value()) {
return;
}
const auto doubleSided = materialInfo.doubleSided;
const auto gltfLocalToPrimWorldTransform = ecefToPrimWorldTransform * gltfLocalToEcefTransform;
const auto [primWorldPosition, primWorldOrientation, primWorldScale] =
MathUtil::decompose(gltfLocalToPrimWorldTransform);
const auto primWorldExtent = MathUtil::transformExtent(gltfLocalExtent.value(), gltfLocalToPrimWorldTransform);
if (primitive.mode == CesiumGltf::MeshPrimitive::Mode::POINTS) {
const auto numVoxels = positions.size();
const auto shapeHalfSize = 1.5f;
fabricStage.setArrayAttributeSize(_path, FabricTokens::points, numVoxels * 8);
fabricStage.setArrayAttributeSize(_path, FabricTokens::faceVertexCounts, numVoxels * 2 * 6);
fabricStage.setArrayAttributeSize(_path, FabricTokens::faceVertexIndices, numVoxels * 6 * 2 * 3);
const auto pointsFabric = fabricStage.getArrayAttributeWr<glm::fvec3>(_path, FabricTokens::points);
const auto faceVertexCountsFabric = fabricStage.getArrayAttributeWr<int>(_path, FabricTokens::faceVertexCounts);
const auto faceVertexIndicesFabric =
fabricStage.getArrayAttributeWr<int>(_path, FabricTokens::faceVertexIndices);
if (hasVertexColors) {
fabricStage.setArrayAttributeSize(_path, FabricTokens::primvars_COLOR_0, numVoxels * 8);
const auto vertexColorsFabric =
fabricStage.getArrayAttributeWr<glm::fvec4>(_path, FabricTokens::primvars_COLOR_0);
vertexColors.fill(vertexColorsFabric, 8);
}
if (hasVertexIds) {
fabricStage.setArrayAttributeSize(_path, FabricTokens::primvars_vertexId, numVoxels * 8);
const auto vertexIdsFabric = fabricStage.getArrayAttributeWr<float>(_path, FabricTokens::primvars_vertexId);
vertexIds.fill(vertexIdsFabric, 8);
}
for (const auto& customVertexAttribute : customVertexAttributes) {
CALL_TEMPLATED_FUNCTION_WITH_RUNTIME_DATA_TYPE(
setVertexAttributeValues,
customVertexAttribute.type,
fabricStage,
_path,
model,
primitive,
customVertexAttribute,
uint64_t(8));
}
uint64_t vertIndex = 0;
uint64_t vertexCountsIndex = 0;
uint64_t faceVertexIndex = 0;
for (uint64_t voxelIndex = 0; voxelIndex < numVoxels; ++voxelIndex) {
const auto& center = positions.get(voxelIndex);
pointsFabric[vertIndex++] = glm::fvec3{-shapeHalfSize, -shapeHalfSize, -shapeHalfSize} + center;
pointsFabric[vertIndex++] = glm::fvec3{-shapeHalfSize, shapeHalfSize, -shapeHalfSize} + center;
pointsFabric[vertIndex++] = glm::fvec3{shapeHalfSize, shapeHalfSize, -shapeHalfSize} + center;
pointsFabric[vertIndex++] = glm::fvec3{shapeHalfSize, -shapeHalfSize, -shapeHalfSize} + center;
pointsFabric[vertIndex++] = glm::fvec3{-shapeHalfSize, -shapeHalfSize, shapeHalfSize} + center;
pointsFabric[vertIndex++] = glm::fvec3{-shapeHalfSize, shapeHalfSize, shapeHalfSize} + center;
pointsFabric[vertIndex++] = glm::fvec3{shapeHalfSize, shapeHalfSize, shapeHalfSize} + center;
pointsFabric[vertIndex++] = glm::fvec3{shapeHalfSize, -shapeHalfSize, shapeHalfSize} + center;
for (int i = 0; i < 6; ++i) {
faceVertexCountsFabric[vertexCountsIndex++] = 3;
faceVertexCountsFabric[vertexCountsIndex++] = 3;
}
// front
faceVertexIndicesFabric[faceVertexIndex++] = 0 + static_cast<int>(voxelIndex * 8);
faceVertexIndicesFabric[faceVertexIndex++] = 1 + static_cast<int>(voxelIndex * 8);
faceVertexIndicesFabric[faceVertexIndex++] = 2 + static_cast<int>(voxelIndex * 8);
faceVertexIndicesFabric[faceVertexIndex++] = 0 + static_cast<int>(voxelIndex * 8);
faceVertexIndicesFabric[faceVertexIndex++] = 2 + static_cast<int>(voxelIndex * 8);
faceVertexIndicesFabric[faceVertexIndex++] = 3 + static_cast<int>(voxelIndex * 8);
// left
faceVertexIndicesFabric[faceVertexIndex++] = 4 + static_cast<int>(voxelIndex * 8);
faceVertexIndicesFabric[faceVertexIndex++] = 5 + static_cast<int>(voxelIndex * 8);
faceVertexIndicesFabric[faceVertexIndex++] = 1 + static_cast<int>(voxelIndex * 8);
faceVertexIndicesFabric[faceVertexIndex++] = 4 + static_cast<int>(voxelIndex * 8);
faceVertexIndicesFabric[faceVertexIndex++] = 1 + static_cast<int>(voxelIndex * 8);
faceVertexIndicesFabric[faceVertexIndex++] = 0 + static_cast<int>(voxelIndex * 8);
// right
faceVertexIndicesFabric[faceVertexIndex++] = 3 + static_cast<int>(voxelIndex * 8);
faceVertexIndicesFabric[faceVertexIndex++] = 2 + static_cast<int>(voxelIndex * 8);
faceVertexIndicesFabric[faceVertexIndex++] = 6 + static_cast<int>(voxelIndex * 8);
faceVertexIndicesFabric[faceVertexIndex++] = 3 + static_cast<int>(voxelIndex * 8);
faceVertexIndicesFabric[faceVertexIndex++] = 6 + static_cast<int>(voxelIndex * 8);
faceVertexIndicesFabric[faceVertexIndex++] = 7 + static_cast<int>(voxelIndex * 8);
// top
faceVertexIndicesFabric[faceVertexIndex++] = 1 + static_cast<int>(voxelIndex * 8);
faceVertexIndicesFabric[faceVertexIndex++] = 5 + static_cast<int>(voxelIndex * 8);
faceVertexIndicesFabric[faceVertexIndex++] = 6 + static_cast<int>(voxelIndex * 8);
faceVertexIndicesFabric[faceVertexIndex++] = 1 + static_cast<int>(voxelIndex * 8);
faceVertexIndicesFabric[faceVertexIndex++] = 5 + static_cast<int>(voxelIndex * 8);
faceVertexIndicesFabric[faceVertexIndex++] = 2 + static_cast<int>(voxelIndex * 8);
// bottom
faceVertexIndicesFabric[faceVertexIndex++] = 3 + static_cast<int>(voxelIndex * 8);
faceVertexIndicesFabric[faceVertexIndex++] = 7 + static_cast<int>(voxelIndex * 8);
faceVertexIndicesFabric[faceVertexIndex++] = 4 + static_cast<int>(voxelIndex * 8);
faceVertexIndicesFabric[faceVertexIndex++] = 3 + static_cast<int>(voxelIndex * 8);
faceVertexIndicesFabric[faceVertexIndex++] = 4 + static_cast<int>(voxelIndex * 8);
faceVertexIndicesFabric[faceVertexIndex++] = 0 + static_cast<int>(voxelIndex * 8);
// back
faceVertexIndicesFabric[faceVertexIndex++] = 7 + static_cast<int>(voxelIndex * 8);
faceVertexIndicesFabric[faceVertexIndex++] = 6 + static_cast<int>(voxelIndex * 8);
faceVertexIndicesFabric[faceVertexIndex++] = 5 + static_cast<int>(voxelIndex * 8);
faceVertexIndicesFabric[faceVertexIndex++] = 7 + static_cast<int>(voxelIndex * 8);
faceVertexIndicesFabric[faceVertexIndex++] = 5 + static_cast<int>(voxelIndex * 8);
faceVertexIndicesFabric[faceVertexIndex++] = 4 + static_cast<int>(voxelIndex * 8);
}
} else {
fabricStage.setArrayAttributeSize(_path, FabricTokens::faceVertexCounts, faceVertexCounts.size());
fabricStage.setArrayAttributeSize(_path, FabricTokens::faceVertexIndices, indices.size());
fabricStage.setArrayAttributeSize(_path, FabricTokens::points, positions.size());
const auto faceVertexCountsFabric = fabricStage.getArrayAttributeWr<int>(_path, FabricTokens::faceVertexCounts);
const auto faceVertexIndicesFabric =
fabricStage.getArrayAttributeWr<int>(_path, FabricTokens::faceVertexIndices);
const auto pointsFabric = fabricStage.getArrayAttributeWr<glm::fvec3>(_path, FabricTokens::points);
faceVertexCounts.fill(faceVertexCountsFabric);
indices.fill(faceVertexIndicesFabric);
positions.fill(pointsFabric);
const auto fillTexcoords = [this, &fabricStage](uint64_t texcoordIndex, const TexcoordsAccessor& texcoords) {
assert(texcoordIndex < _geometryDescriptor.getTexcoordSetCount());
const auto& primvarStToken = FabricTokens::primvars_st_n(texcoordIndex);
fabricStage.setArrayAttributeSize(_path, primvarStToken, texcoords.size());
const auto stFabric = fabricStage.getArrayAttributeWr<glm::fvec2>(_path, primvarStToken);
texcoords.fill(stFabric);
};
for (const auto& [gltfSetIndex, primvarStIndex] : texcoordIndexMapping) {
const auto texcoords = GltfUtil::getTexcoords(model, primitive, gltfSetIndex);
fillTexcoords(primvarStIndex, texcoords);
}
for (const auto& [gltfSetIndex, primvarStIndex] : rasterOverlayTexcoordIndexMapping) {
const auto texcoords = GltfUtil::getRasterOverlayTexcoords(model, primitive, gltfSetIndex);
fillTexcoords(primvarStIndex, texcoords);
}
if (hasNormals) {
fabricStage.setArrayAttributeSize(_path, FabricTokens::primvars_normals, normals.size());
const auto normalsFabric =
fabricStage.getArrayAttributeWr<glm::fvec3>(_path, FabricTokens::primvars_normals);
normals.fill(normalsFabric);
}
if (hasVertexColors) {
fabricStage.setArrayAttributeSize(_path, FabricTokens::primvars_COLOR_0, vertexColors.size());
const auto vertexColorsFabric =
fabricStage.getArrayAttributeWr<glm::fvec4>(_path, FabricTokens::primvars_COLOR_0);
vertexColors.fill(vertexColorsFabric);
}
if (hasVertexIds) {
fabricStage.setArrayAttributeSize(_path, FabricTokens::primvars_vertexId, vertexIds.size());
const auto vertexIdsFabric = fabricStage.getArrayAttributeWr<float>(_path, FabricTokens::primvars_vertexId);
vertexIds.fill(vertexIdsFabric);
}
for (const auto& customVertexAttribute : customVertexAttributes) {
CALL_TEMPLATED_FUNCTION_WITH_RUNTIME_DATA_TYPE(
setVertexAttributeValues,
customVertexAttribute.type,
fabricStage,
_path,
model,
primitive,
customVertexAttribute,
uint64_t(1));
}
}
// clang-format off
const auto doubleSidedFabric = fabricStage.getAttributeWr<bool>(_path, FabricTokens::doubleSided);
const auto extentFabric = fabricStage.getAttributeWr<pxr::GfRange3d>(_path, FabricTokens::extent);
const auto worldExtentFabric = fabricStage.getAttributeWr<pxr::GfRange3d>(_path, FabricTokens::_worldExtent);
const auto gltfLocalToEcefTransformFabric = fabricStage.getAttributeWr<pxr::GfMatrix4d>(_path, FabricTokens::_cesium_gltfLocalToEcefTransform);
const auto worldPositionFabric = fabricStage.getAttributeWr<pxr::GfVec3d>(_path, FabricTokens::_worldPosition);
const auto worldOrientationFabric = fabricStage.getAttributeWr<pxr::GfQuatf>(_path, FabricTokens::_worldOrientation);
const auto worldScaleFabric = fabricStage.getAttributeWr<pxr::GfVec3f>(_path, FabricTokens::_worldScale);
const auto tilesetIdFabric = fabricStage.getAttributeWr<int64_t>(_path, FabricTokens::_cesium_tilesetId);
// clang-format on
*doubleSidedFabric = doubleSided;
*extentFabric = UsdUtil::glmToUsdExtent(gltfLocalExtent.value());
*worldExtentFabric = UsdUtil::glmToUsdExtent(primWorldExtent);
*gltfLocalToEcefTransformFabric = UsdUtil::glmToUsdMatrix(gltfLocalToEcefTransform);
*worldPositionFabric = UsdUtil::glmToUsdVector(primWorldPosition);
*worldOrientationFabric = UsdUtil::glmToUsdQuat(glm::fquat(primWorldOrientation));
*worldScaleFabric = UsdUtil::glmToUsdVector(glm::fvec3(primWorldScale));
*tilesetIdFabric = tilesetId;
}
bool FabricGeometry::stageDestroyed() {
// Tile render resources may be processed asynchronously even after the tileset and stage have been destroyed.
// Add this check to all public member functions, including constructors and destructors, to prevent them from
// modifying the stage.
return _stageId != _pContext->getUsdStageId();
}
}; // namespace cesium::omniverse
| 26,371 | C++ | 46.688969 | 147 | 0.712373 |
CesiumGS/cesium-omniverse/src/core/src/FabricUtil.cpp | #include "cesium/omniverse/FabricUtil.h"
#include "cesium/omniverse/Context.h"
#include "cesium/omniverse/DataType.h"
#include "cesium/omniverse/DataTypeUtil.h"
#include "cesium/omniverse/FabricStatistics.h"
#include "cesium/omniverse/MathUtil.h"
#include "cesium/omniverse/UsdTokens.h"
#include "cesium/omniverse/UsdUtil.h"
#include <omni/fabric/FabricUSD.h>
#include <omni/fabric/SimStageWithHistory.h>
#include <pxr/base/gf/matrix4d.h>
#include <pxr/base/gf/quatf.h>
#include <pxr/base/gf/range3d.h>
#include <pxr/base/gf/vec2f.h>
#include <pxr/base/gf/vec3f.h>
#include <spdlog/fmt/fmt.h>
#include <sstream>
namespace cesium::omniverse::FabricUtil {
namespace {
const std::string_view NO_DATA_STRING = "[No Data]";
const std::string_view TYPE_NOT_SUPPORTED_STRING = "[Type Not Supported]";
// Wraps the token type so that we can define a custom stream insertion operator
class TokenWrapper {
private:
omni::fabric::TokenC token;
public:
friend std::ostream& operator<<(std::ostream& os, const TokenWrapper& tokenWrapper);
};
std::ostream& operator<<(std::ostream& os, const TokenWrapper& tokenWrapper) {
os << omni::fabric::Token(tokenWrapper.token).getString();
return os;
}
// Wraps a boolean so that we print "true" and "false" instead of 0 and 1
class BoolWrapper {
private:
bool value;
public:
friend std::ostream& operator<<(std::ostream& os, const BoolWrapper& boolWrapper);
};
std::ostream& operator<<(std::ostream& os, const BoolWrapper& boolWrapper) {
os << (boolWrapper.value ? "true" : "false");
return os;
}
class AssetWrapper {
private:
omni::fabric::AssetPath asset;
public:
friend std::ostream& operator<<(std::ostream& os, const AssetWrapper& assetWrapper);
};
std::ostream& operator<<(std::ostream& os, const AssetWrapper& assetWrapper) {
if (assetWrapper.asset.assetPath.IsEmpty()) {
os << NO_DATA_STRING;
return os;
}
os << "Asset Path: " << assetWrapper.asset.assetPath.GetText()
<< ", Resolved Path: " << assetWrapper.asset.resolvedPath.GetText();
return os;
}
template <typename T>
std::string printAttributeValue(const T* values, uint64_t elementCount, uint64_t componentCount, bool isArray) {
std::stringstream stream;
if (isArray) {
stream << "[";
}
for (uint64_t i = 0; i < elementCount; ++i) {
if (componentCount > 1) {
stream << "[";
}
for (uint64_t j = 0; j < componentCount; ++j) {
stream << values[i * componentCount + j];
if (j < componentCount - 1) {
stream << ",";
}
}
if (componentCount > 1) {
stream << "]";
}
if (elementCount > 1 && i < elementCount - 1) {
stream << ",";
}
}
if (isArray) {
stream << "]";
}
return stream.str();
}
template <bool IsArray, typename BaseType, uint64_t ComponentCount>
std::string printAttributeValue(
omni::fabric::StageReaderWriter& fabricStage,
const omni::fabric::Path& primPath,
const omni::fabric::Token& attributeName,
const omni::fabric::AttributeRole& role) {
using ElementType = std::array<BaseType, ComponentCount>;
if constexpr (IsArray) {
const auto values = fabricStage.getArrayAttributeRd<ElementType>(primPath, attributeName);
const auto elementCount = values.size();
if (elementCount == 0) {
return std::string(NO_DATA_STRING);
}
const auto valuesPtr = values.front().data();
if (role == omni::fabric::AttributeRole::eText) {
return std::string(reinterpret_cast<const char*>(valuesPtr), elementCount);
}
return printAttributeValue<BaseType>(valuesPtr, elementCount, ComponentCount, true);
} else {
const auto pValue = fabricStage.getAttributeRd<ElementType>(primPath, attributeName);
if (!pValue) {
return std::string(NO_DATA_STRING);
}
return printAttributeValue<BaseType>(pValue->data(), 1, ComponentCount, false);
}
}
std::string printConnection(
omni::fabric::StageReaderWriter& fabricStage,
const omni::fabric::Path& primPath,
const omni::fabric::Token& attributeName) {
const auto pConnection = fabricStage.getConnection(primPath, attributeName);
if (!pConnection) {
return std::string(NO_DATA_STRING);
}
const auto path = omni::fabric::Path(pConnection->path).getText();
const auto attrName = omni::fabric::Token(pConnection->attrName).getText();
return fmt::format("Path: {}, Attribute Name: {}", path, attrName);
}
std::string printAttributeValue(
omni::fabric::StageReaderWriter& fabricStage,
const omni::fabric::Path& primPath,
const omni::fabric::AttrNameAndType& attribute) {
const auto attributeType = attribute.type;
const auto baseType = attributeType.baseType;
const auto componentCount = attributeType.componentCount;
const auto name = attribute.name;
const auto arrayDepth = attributeType.arrayDepth;
const auto role = attributeType.role;
// This switch statement should cover most of the attribute types we expect to see on the stage.
// This includes the USD types in SdfValueTypeNames and Fabric types like assets and tokens.
// We can add more as needed.
if (arrayDepth == 0) {
switch (baseType) {
case omni::fabric::BaseDataType::eAsset:
switch (componentCount) {
case 1:
return printAttributeValue<false, AssetWrapper, 1>(fabricStage, primPath, name, role);
default:
break;
}
break;
case omni::fabric::BaseDataType::eConnection:
switch (componentCount) {
case 1:
return printConnection(fabricStage, primPath, name);
default:
break;
}
break;
case omni::fabric::BaseDataType::eToken:
switch (componentCount) {
case 1:
return printAttributeValue<false, TokenWrapper, 1>(fabricStage, primPath, name, role);
default:
break;
}
break;
case omni::fabric::BaseDataType::eBool:
switch (componentCount) {
case 1:
return printAttributeValue<false, BoolWrapper, 1>(fabricStage, primPath, name, role);
default:
break;
}
break;
case omni::fabric::BaseDataType::eUChar:
switch (componentCount) {
case 1:
return printAttributeValue<false, uint8_t, 1>(fabricStage, primPath, name, role);
default:
break;
}
break;
case omni::fabric::BaseDataType::eInt:
switch (componentCount) {
case 1:
return printAttributeValue<false, int32_t, 1>(fabricStage, primPath, name, role);
case 2:
return printAttributeValue<false, int32_t, 2>(fabricStage, primPath, name, role);
case 3:
return printAttributeValue<false, int32_t, 3>(fabricStage, primPath, name, role);
case 4:
return printAttributeValue<false, int32_t, 4>(fabricStage, primPath, name, role);
default:
break;
}
break;
case omni::fabric::BaseDataType::eUInt:
switch (componentCount) {
case 1:
return printAttributeValue<false, uint32_t, 1>(fabricStage, primPath, name, role);
default:
break;
}
break;
case omni::fabric::BaseDataType::eInt64:
switch (componentCount) {
case 1:
return printAttributeValue<false, int64_t, 1>(fabricStage, primPath, name, role);
default:
break;
}
break;
case omni::fabric::BaseDataType::eUInt64:
switch (componentCount) {
case 1:
return printAttributeValue<false, uint64_t, 1>(fabricStage, primPath, name, role);
default:
break;
}
break;
case omni::fabric::BaseDataType::eFloat:
switch (componentCount) {
case 1:
return printAttributeValue<false, float, 1>(fabricStage, primPath, name, role);
case 2:
return printAttributeValue<false, float, 2>(fabricStage, primPath, name, role);
case 3:
return printAttributeValue<false, float, 3>(fabricStage, primPath, name, role);
case 4:
return printAttributeValue<false, float, 4>(fabricStage, primPath, name, role);
default:
break;
}
break;
case omni::fabric::BaseDataType::eDouble:
switch (componentCount) {
case 1:
return printAttributeValue<false, double, 1>(fabricStage, primPath, name, role);
case 2:
return printAttributeValue<false, double, 2>(fabricStage, primPath, name, role);
case 3:
return printAttributeValue<false, double, 3>(fabricStage, primPath, name, role);
case 4:
return printAttributeValue<false, double, 4>(fabricStage, primPath, name, role);
case 6:
return printAttributeValue<false, double, 6>(fabricStage, primPath, name, role);
case 9:
return printAttributeValue<false, double, 9>(fabricStage, primPath, name, role);
case 16:
return printAttributeValue<false, double, 16>(fabricStage, primPath, name, role);
default:
break;
}
break;
// Due to legacy support the eRelationship type is defined as a scalar value but is secretly an array
case omni::fabric::BaseDataType::eRelationship:
switch (componentCount) {
case 1:
return printAttributeValue<true, uint64_t, 1>(fabricStage, primPath, name, role);
default:
break;
}
break;
default:
break;
}
} else if (arrayDepth == 1) {
switch (baseType) {
case omni::fabric::BaseDataType::eAsset:
switch (componentCount) {
case 1:
return printAttributeValue<true, AssetWrapper, 1>(fabricStage, primPath, name, role);
default:
break;
}
break;
case omni::fabric::BaseDataType::eToken:
switch (componentCount) {
case 1:
return printAttributeValue<true, TokenWrapper, 1>(fabricStage, primPath, name, role);
default:
break;
}
break;
case omni::fabric::BaseDataType::eBool:
switch (componentCount) {
case 1:
return printAttributeValue<true, BoolWrapper, 1>(fabricStage, primPath, name, role);
default:
break;
}
break;
case omni::fabric::BaseDataType::eUChar:
switch (componentCount) {
case 1:
return printAttributeValue<true, uint8_t, 1>(fabricStage, primPath, name, role);
default:
break;
}
break;
case omni::fabric::BaseDataType::eInt:
switch (componentCount) {
case 1:
return printAttributeValue<true, int32_t, 1>(fabricStage, primPath, name, role);
case 2:
return printAttributeValue<true, int32_t, 2>(fabricStage, primPath, name, role);
case 3:
return printAttributeValue<true, int32_t, 3>(fabricStage, primPath, name, role);
case 4:
return printAttributeValue<true, int32_t, 4>(fabricStage, primPath, name, role);
default:
break;
}
break;
case omni::fabric::BaseDataType::eUInt:
switch (componentCount) {
case 1:
return printAttributeValue<true, uint32_t, 1>(fabricStage, primPath, name, role);
default:
break;
}
break;
case omni::fabric::BaseDataType::eInt64:
switch (componentCount) {
case 1:
return printAttributeValue<true, int64_t, 1>(fabricStage, primPath, name, role);
default:
break;
}
break;
case omni::fabric::BaseDataType::eUInt64:
switch (componentCount) {
case 1:
return printAttributeValue<true, uint64_t, 1>(fabricStage, primPath, name, role);
default:
break;
}
break;
case omni::fabric::BaseDataType::eFloat:
switch (componentCount) {
case 1:
return printAttributeValue<true, float, 1>(fabricStage, primPath, name, role);
case 2:
return printAttributeValue<true, float, 2>(fabricStage, primPath, name, role);
case 3:
return printAttributeValue<true, float, 3>(fabricStage, primPath, name, role);
case 4:
return printAttributeValue<true, float, 4>(fabricStage, primPath, name, role);
default:
break;
}
break;
case omni::fabric::BaseDataType::eDouble:
switch (componentCount) {
case 1:
return printAttributeValue<true, double, 1>(fabricStage, primPath, name, role);
case 2:
return printAttributeValue<true, double, 2>(fabricStage, primPath, name, role);
case 3:
return printAttributeValue<true, double, 3>(fabricStage, primPath, name, role);
case 4:
return printAttributeValue<true, double, 4>(fabricStage, primPath, name, role);
case 6:
return printAttributeValue<true, double, 6>(fabricStage, primPath, name, role);
case 9:
return printAttributeValue<true, double, 9>(fabricStage, primPath, name, role);
case 16:
return printAttributeValue<true, double, 16>(fabricStage, primPath, name, role);
default:
break;
}
break;
default:
break;
}
}
return std::string(TYPE_NOT_SUPPORTED_STRING);
}
} // namespace
std::string printFabricStage(omni::fabric::StageReaderWriter& fabricStage) {
std::stringstream stream;
// For extra debugging. This gets printed to the console.
fabricStage.printBucketNames();
// This returns ALL the buckets
const auto& buckets = fabricStage.findPrims({});
for (uint64_t bucketId = 0; bucketId < buckets.bucketCount(); ++bucketId) {
const auto& attributes = fabricStage.getAttributeNamesAndTypes(buckets, bucketId);
const auto& primPaths = fabricStage.getPathArray(buckets, bucketId);
for (const auto& primPath : primPaths) {
const auto primPathString = primPath.getText();
const auto primPathUint64 = primPath.asPathC().path;
stream << fmt::format("Prim: {} ({})\n", primPathString, primPathUint64);
stream << fmt::format(" Attributes:\n");
for (const auto& attribute : attributes) {
const auto attributeName = attribute.name.getText();
const auto attributeType = attribute.type.getTypeName();
const auto attributeBaseType = attribute.type.baseType;
const auto attributeValue = printAttributeValue(fabricStage, primPath, attribute);
stream << fmt::format(" Attribute: {}\n", attributeName);
stream << fmt::format(" Type: {}\n", attributeType);
if (attributeBaseType != omni::fabric::BaseDataType::eTag) {
stream << fmt::format(" Value: {}\n", attributeValue);
}
}
}
}
return stream.str();
}
FabricStatistics getStatistics(omni::fabric::StageReaderWriter& fabricStage) {
FabricStatistics statistics;
const auto geometryBuckets = fabricStage.findPrims(
{omni::fabric::AttrNameAndType(FabricTypes::_cesium_tilesetId, FabricTokens::_cesium_tilesetId)},
{omni::fabric::AttrNameAndType(FabricTypes::Mesh, FabricTokens::Mesh)});
const auto materialBuckets = fabricStage.findPrims(
{omni::fabric::AttrNameAndType(FabricTypes::_cesium_tilesetId, FabricTokens::_cesium_tilesetId)},
{omni::fabric::AttrNameAndType(FabricTypes::Material, FabricTokens::Material)});
for (uint64_t bucketId = 0; bucketId < geometryBuckets.bucketCount(); ++bucketId) {
const auto paths = fabricStage.getPathArray(geometryBuckets, bucketId);
statistics.geometriesCapacity += paths.size();
for (const auto& path : paths) {
const auto worldVisibilityFabric = fabricStage.getAttributeRd<bool>(path, FabricTokens::_worldVisibility);
const auto faceVertexCountsFabric =
fabricStage.getArrayAttributeRd<int>(path, FabricTokens::faceVertexCounts);
const auto tilesetIdFabric = fabricStage.getAttributeRd<int64_t>(path, FabricTokens::_cesium_tilesetId);
assert(worldVisibilityFabric);
assert(tilesetIdFabric);
if (*tilesetIdFabric == NO_TILESET_ID) {
continue;
}
++statistics.geometriesLoaded;
const auto triangleCount = faceVertexCountsFabric.size();
statistics.trianglesLoaded += triangleCount;
if (*worldVisibilityFabric) {
++statistics.geometriesRendered;
statistics.trianglesRendered += triangleCount;
}
}
}
for (uint64_t bucketId = 0; bucketId < materialBuckets.bucketCount(); ++bucketId) {
auto paths = fabricStage.getPathArray(materialBuckets, bucketId);
const auto tilesetIdFabric =
fabricStage.getAttributeArrayRd<int64_t>(materialBuckets, bucketId, FabricTokens::_cesium_tilesetId);
statistics.materialsCapacity += paths.size();
for (uint64_t i = 0; i < paths.size(); ++i) {
if (tilesetIdFabric[i] == NO_TILESET_ID) {
continue;
}
++statistics.materialsLoaded;
}
}
return statistics;
}
void destroyPrim(omni::fabric::StageReaderWriter& fabricStage, const omni::fabric::Path& path) {
fabricStage.destroyPrim(path);
// Prims removed from Fabric need special handling for their removal to be reflected in the Hydra render index
// This workaround may not be needed in future Kit versions, but is needed as of Kit 105.0
const omni::fabric::Path changeTrackingPath("/TempChangeTracking");
if (!fabricStage.getAttributeRd<omni::fabric::PathC>(changeTrackingPath, FabricTokens::_deletedPrims)) {
return;
}
const auto deletedPrimsSize = fabricStage.getArrayAttributeSize(changeTrackingPath, FabricTokens::_deletedPrims);
fabricStage.setArrayAttributeSize(changeTrackingPath, FabricTokens::_deletedPrims, deletedPrimsSize + 1);
const auto deletedPrimsFabric =
fabricStage.getArrayAttributeWr<omni::fabric::PathC>(changeTrackingPath, FabricTokens::_deletedPrims);
deletedPrimsFabric[deletedPrimsSize] = path;
}
void setTilesetTransform(
omni::fabric::StageReaderWriter& fabricStage,
int64_t tilesetId,
const glm::dmat4& ecefToPrimWorldTransform) {
const auto buckets = fabricStage.findPrims(
{omni::fabric::AttrNameAndType(FabricTypes::_cesium_tilesetId, FabricTokens::_cesium_tilesetId)},
{omni::fabric::AttrNameAndType(
FabricTypes::_cesium_gltfLocalToEcefTransform, FabricTokens::_cesium_gltfLocalToEcefTransform)});
for (uint64_t bucketId = 0; bucketId < buckets.bucketCount(); ++bucketId) {
// clang-format off
const auto tilesetIdFabric = fabricStage.getAttributeArrayRd<int64_t>(buckets, bucketId, FabricTokens::_cesium_tilesetId);
const auto gltfLocalToEcefTransformFabric = fabricStage.getAttributeArrayRd<pxr::GfMatrix4d>(buckets, bucketId, FabricTokens::_cesium_gltfLocalToEcefTransform);
const auto extentFabric = fabricStage.getAttributeArrayRd<pxr::GfRange3d>(buckets, bucketId, FabricTokens::extent);
const auto worldPositionFabric = fabricStage.getAttributeArrayWr<pxr::GfVec3d>(buckets, bucketId, FabricTokens::_worldPosition);
const auto worldOrientationFabric = fabricStage.getAttributeArrayWr<pxr::GfQuatf>(buckets, bucketId, FabricTokens::_worldOrientation);
const auto worldScaleFabric = fabricStage.getAttributeArrayWr<pxr::GfVec3f>(buckets, bucketId, FabricTokens::_worldScale);
const auto worldExtentFabric = fabricStage.getAttributeArrayWr<pxr::GfRange3d>(buckets, bucketId, FabricTokens::_worldExtent);
// clang-format on
for (uint64_t i = 0; i < tilesetIdFabric.size(); ++i) {
if (tilesetIdFabric[i] == tilesetId) {
const auto gltfLocalToEcefTransform = UsdUtil::usdToGlmMatrix(gltfLocalToEcefTransformFabric[i]);
const auto gltfLocalToPrimWorldTransform = ecefToPrimWorldTransform * gltfLocalToEcefTransform;
const auto gltfLocalExtent = UsdUtil::usdToGlmExtent(extentFabric[i]);
const auto [primWorldPosition, primWorldOrientation, primWorldScale] =
MathUtil::decompose(gltfLocalToPrimWorldTransform);
const auto primWorldExtent = MathUtil::transformExtent(gltfLocalExtent, gltfLocalToPrimWorldTransform);
worldPositionFabric[i] = UsdUtil::glmToUsdVector(primWorldPosition);
worldOrientationFabric[i] = UsdUtil::glmToUsdQuat(glm::fquat(primWorldOrientation));
worldScaleFabric[i] = UsdUtil::glmToUsdVector(glm::fvec3(primWorldScale));
worldExtentFabric[i] = UsdUtil::glmToUsdExtent(primWorldExtent);
}
}
}
}
omni::fabric::Path toFabricPath(const pxr::SdfPath& path) {
return {omni::fabric::asInt(path)};
}
omni::fabric::Token toFabricToken(const pxr::TfToken& token) {
return {omni::fabric::asInt(token)};
}
omni::fabric::Path joinPaths(const omni::fabric::Path& absolutePath, const omni::fabric::Token& relativePath) {
return {fmt::format("{}/{}", absolutePath.getText(), relativePath.getText()).c_str()};
}
omni::fabric::Path getCopiedShaderPath(const omni::fabric::Path& materialPath, const omni::fabric::Path& shaderPath) {
// materialPath is the FabricMaterial path
// shaderPath is the USD shader path
return FabricUtil::joinPaths(materialPath, omni::fabric::Token(UsdUtil::getSafeName(shaderPath.getText()).c_str()));
}
namespace {
struct FabricConnection {
omni::fabric::Connection* pConnection;
omni::fabric::Token attributeName;
};
std::vector<FabricConnection>
getConnections(omni::fabric::StageReaderWriter& fabricStage, const omni::fabric::Path& path) {
std::vector<FabricConnection> connections;
const auto attributes = fabricStage.getAttributeNamesAndTypes(path);
const auto& names = attributes.first;
const auto& types = attributes.second;
for (uint64_t i = 0; i < names.size(); ++i) {
const auto& name = names[i];
const auto& type = types[i];
if (type.baseType == omni::fabric::BaseDataType::eConnection) {
const auto pConnection = fabricStage.getConnection(path, name);
if (pConnection) {
// In C++ 20 this can be emplace_back without the {}
connections.push_back({pConnection, name});
}
}
}
return connections;
}
bool isOutput(const omni::fabric::Token& attributeName) {
return attributeName == FabricTokens::outputs_out;
}
bool isConnection(const omni::fabric::Type& attributeType) {
return attributeType.baseType == omni::fabric::BaseDataType::eConnection;
}
bool isEmptyToken(
omni::fabric::StageReaderWriter& fabricStage,
const omni::fabric::Path& path,
const omni::fabric::Token& attributeName,
const omni::fabric::Type& attributeType) {
if (attributeType.baseType == omni::fabric::BaseDataType::eToken) {
const auto pAttributeValue = fabricStage.getAttributeRd<omni::fabric::Token>(path, attributeName);
if (!pAttributeValue || pAttributeValue->size() == 0) {
return true;
}
}
return false;
}
std::vector<omni::fabric::TokenC>
getAttributesToCopy(omni::fabric::StageReaderWriter& fabricStage, const omni::fabric::Path& path) {
std::vector<omni::fabric::TokenC> attributeNames;
const auto attributes = fabricStage.getAttributeNamesAndTypes(path);
const auto& names = attributes.first;
const auto& types = attributes.second;
for (uint64_t i = 0; i < names.size(); ++i) {
const auto& name = names[i];
const auto& type = types[i];
if (!isOutput(name) && !isConnection(type) && !isEmptyToken(fabricStage, path, name, type)) {
attributeNames.push_back(name.asTokenC());
}
}
return attributeNames;
}
struct FabricAttribute {
omni::fabric::Token name;
omni::fabric::Type type;
};
std::vector<FabricAttribute>
getAttributesToCreate(omni::fabric::StageReaderWriter& fabricStage, const omni::fabric::Path& path) {
std::vector<FabricAttribute> attributeNames;
const auto attributes = fabricStage.getAttributeNamesAndTypes(path);
const auto& names = attributes.first;
const auto& types = attributes.second;
for (uint64_t i = 0; i < names.size(); ++i) {
const auto& name = names[i];
const auto& type = types[i];
if (isOutput(name) || isEmptyToken(fabricStage, path, name, type)) {
// In C++ 20 this can be emplace_back without the {}
attributeNames.push_back({name, type});
}
}
return attributeNames;
}
void getConnectedPrimsRecursive(
omni::fabric::StageReaderWriter& fabricStage,
const omni::fabric::Path& path,
std::vector<omni::fabric::Path>& connectedPaths) {
const auto connections = getConnections(fabricStage, path);
for (const auto& connection : connections) {
if (!CppUtil::contains(connectedPaths, connection.pConnection->path)) {
connectedPaths.push_back(connection.pConnection->path);
getConnectedPrimsRecursive(fabricStage, connection.pConnection->path, connectedPaths);
}
}
}
std::vector<omni::fabric::Path>
getPrimsInMaterialNetwork(omni::fabric::StageReaderWriter& fabricStage, const omni::fabric::Path& path) {
std::vector<omni::fabric::Path> paths;
paths.push_back(path);
getConnectedPrimsRecursive(fabricStage, path, paths);
return paths;
}
omni::fabric::Path getMaterialSource(omni::fabric::StageReaderWriter& fabricStage, const omni::fabric::Path& path) {
if (fabricStage.attributeExistsWithType(path, FabricTokens::_materialSource, FabricTypes::_materialSource)) {
const auto materialSourceFabric =
fabricStage.getArrayAttributeRd<omni::fabric::PathC>(path, FabricTokens::_materialSource);
if (!materialSourceFabric.empty()) {
return *materialSourceFabric.begin();
}
}
return path;
}
} // namespace
std::vector<omni::fabric::Path> copyMaterial(
omni::fabric::StageReaderWriter& fabricStage,
const omni::fabric::Path& srcMaterialPath,
const omni::fabric::Path& dstMaterialPath) {
const auto iFabricStage = carb::getCachedInterface<omni::fabric::IStageReaderWriter>();
const auto materialSourcePath = getMaterialSource(fabricStage, srcMaterialPath);
const auto srcPaths = getPrimsInMaterialNetwork(fabricStage, materialSourcePath);
std::vector<omni::fabric::Path> dstPaths;
dstPaths.reserve(srcPaths.size());
for (const auto& srcPath : srcPaths) {
auto dstPath = omni::fabric::Path();
if (srcPath == materialSourcePath) {
dstPath = dstMaterialPath;
} else {
const auto name = omni::fabric::Token(std::strrchr(srcPath.getText(), '/') + 1);
dstPath = FabricUtil::getCopiedShaderPath(dstMaterialPath, srcMaterialPath.appendChild(name));
}
dstPaths.push_back(dstPath);
fabricStage.createPrim(dstPath);
// This excludes connections, outputs, and empty tokens
// The material network will be reconnected later once all the prims have been copied
// The reason for excluding outputs and empty tokens is so that Omniverse doesn't print the warning
// [Warning] [omni.fabric.plugin] Warning: input has no valid data
const auto attributesToCopy = getAttributesToCopy(fabricStage, srcPath);
iFabricStage->copySpecifiedAttributes(
fabricStage.getId(),
srcPath,
attributesToCopy.data(),
dstPath,
attributesToCopy.data(),
attributesToCopy.size());
// Add the outputs and empty tokens back. This doesn't print a warning.
const auto attributesToCreate = getAttributesToCreate(fabricStage, srcPath);
for (const auto& attribute : attributesToCreate) {
fabricStage.createAttribute(dstPath, attribute.name, attribute.type);
}
}
// Reconnect the prims
for (uint64_t i = 0; i < srcPaths.size(); ++i) {
const auto& srcPath = srcPaths[i];
const auto& dstPath = dstPaths[i];
const auto connections = getConnections(fabricStage, srcPath);
for (const auto& connection : connections) {
const auto index = CppUtil::indexOf(srcPaths, connection.pConnection->path);
assert(index != srcPaths.size()); // Ensure that all connections are part of the material network
const auto dstConnection =
omni::fabric::Connection{dstPaths[index].asPathC(), connection.pConnection->attrName};
fabricStage.createConnection(dstPath, connection.attributeName, dstConnection);
}
}
return dstPaths;
}
bool materialHasCesiumNodes(omni::fabric::StageReaderWriter& fabricStage, const omni::fabric::Path& materialPath) {
const auto materialSourcePath = getMaterialSource(fabricStage, materialPath);
const auto paths = getPrimsInMaterialNetwork(fabricStage, materialSourcePath);
for (const auto& path : paths) {
const auto mdlIdentifier = getMdlIdentifier(fabricStage, path);
if (isCesiumNode(mdlIdentifier)) {
return true;
}
}
return false;
}
bool isCesiumNode(const omni::fabric::Token& mdlIdentifier) {
return mdlIdentifier == FabricTokens::cesium_base_color_texture_float4 ||
mdlIdentifier == FabricTokens::cesium_raster_overlay_float4 ||
mdlIdentifier == FabricTokens::cesium_feature_id_int || isCesiumPropertyNode(mdlIdentifier);
}
bool isCesiumPropertyNode(const omni::fabric::Token& mdlIdentifier) {
return mdlIdentifier == FabricTokens::cesium_property_int || mdlIdentifier == FabricTokens::cesium_property_int2 ||
mdlIdentifier == FabricTokens::cesium_property_int3 || mdlIdentifier == FabricTokens::cesium_property_int4 ||
mdlIdentifier == FabricTokens::cesium_property_float ||
mdlIdentifier == FabricTokens::cesium_property_float2 ||
mdlIdentifier == FabricTokens::cesium_property_float3 ||
mdlIdentifier == FabricTokens::cesium_property_float4;
}
bool isShaderConnectedToMaterial(
omni::fabric::StageReaderWriter& fabricStage,
const omni::fabric::Path& materialPath,
const omni::fabric::Path& shaderPath) {
const auto materialSourcePath = getMaterialSource(fabricStage, materialPath);
const auto paths = getPrimsInMaterialNetwork(fabricStage, materialSourcePath);
return CppUtil::contains(paths, shaderPath);
}
omni::fabric::Token getMdlIdentifier(omni::fabric::StageReaderWriter& fabricStage, const omni::fabric::Path& path) {
if (fabricStage.attributeExists(path, FabricTokens::info_mdl_sourceAsset_subIdentifier)) {
const auto pInfoMdlSourceAssetSubIdentifierFabric =
fabricStage.getAttributeRd<omni::fabric::Token>(path, FabricTokens::info_mdl_sourceAsset_subIdentifier);
if (pInfoMdlSourceAssetSubIdentifierFabric) {
return *pInfoMdlSourceAssetSubIdentifierFabric;
}
}
return {};
}
omni::fabric::Type getPrimvarType(DataType type) {
const auto baseDataType = DataTypeUtil::getPrimvarBaseDataType(type);
const auto componentCount = DataTypeUtil::getComponentCount(type);
return {baseDataType, static_cast<uint8_t>(componentCount), 1, omni::fabric::AttributeRole::eNone};
}
MdlExternalPropertyType getMdlExternalPropertyType(const omni::fabric::Token& mdlIdentifier) {
assert(isCesiumPropertyNode(mdlIdentifier));
if (mdlIdentifier == FabricTokens::cesium_property_int) {
return MdlExternalPropertyType::INT32;
} else if (mdlIdentifier == FabricTokens::cesium_property_int2) {
return MdlExternalPropertyType::VEC2_INT32;
} else if (mdlIdentifier == FabricTokens::cesium_property_int3) {
return MdlExternalPropertyType::VEC3_INT32;
} else if (mdlIdentifier == FabricTokens::cesium_property_int4) {
return MdlExternalPropertyType::VEC4_INT32;
} else if (mdlIdentifier == FabricTokens::cesium_property_float) {
return MdlExternalPropertyType::FLOAT32;
} else if (mdlIdentifier == FabricTokens::cesium_property_float2) {
return MdlExternalPropertyType::VEC2_FLOAT32;
} else if (mdlIdentifier == FabricTokens::cesium_property_float3) {
return MdlExternalPropertyType::VEC3_FLOAT32;
} else if (mdlIdentifier == FabricTokens::cesium_property_float4) {
return MdlExternalPropertyType::VEC4_FLOAT32;
}
return MdlExternalPropertyType::INT32;
}
bool typesCompatible(MdlExternalPropertyType externalType, MdlInternalPropertyType internalType) {
switch (externalType) {
case MdlExternalPropertyType::INT32:
switch (internalType) {
case MdlInternalPropertyType::INT32:
return true;
default:
return false;
}
case MdlExternalPropertyType::FLOAT32:
switch (internalType) {
case MdlInternalPropertyType::FLOAT32:
case MdlInternalPropertyType::INT32_NORM:
return true;
default:
return false;
}
case MdlExternalPropertyType::VEC2_INT32:
switch (internalType) {
case MdlInternalPropertyType::VEC2_INT32:
return true;
default:
return false;
}
case MdlExternalPropertyType::VEC2_FLOAT32:
switch (internalType) {
case MdlInternalPropertyType::VEC2_FLOAT32:
case MdlInternalPropertyType::VEC2_INT32_NORM:
return true;
default:
return false;
}
case MdlExternalPropertyType::VEC3_INT32:
switch (internalType) {
case MdlInternalPropertyType::VEC3_INT32:
return true;
default:
return false;
}
case MdlExternalPropertyType::VEC3_FLOAT32:
switch (internalType) {
case MdlInternalPropertyType::VEC3_FLOAT32:
case MdlInternalPropertyType::VEC3_INT32_NORM:
return true;
default:
return false;
}
case MdlExternalPropertyType::VEC4_INT32:
switch (internalType) {
case MdlInternalPropertyType::VEC4_INT32:
return true;
default:
return false;
}
case MdlExternalPropertyType::VEC4_FLOAT32:
switch (internalType) {
case MdlInternalPropertyType::VEC4_FLOAT32:
case MdlInternalPropertyType::VEC4_INT32_NORM:
return true;
default:
return false;
}
case MdlExternalPropertyType::MAT2_FLOAT32:
switch (internalType) {
case MdlInternalPropertyType::MAT2_INT32:
case MdlInternalPropertyType::MAT2_FLOAT32:
case MdlInternalPropertyType::MAT2_INT32_NORM:
return true;
default:
return false;
}
case MdlExternalPropertyType::MAT3_FLOAT32:
switch (internalType) {
case MdlInternalPropertyType::MAT3_INT32:
case MdlInternalPropertyType::MAT3_FLOAT32:
case MdlInternalPropertyType::MAT3_INT32_NORM:
return true;
default:
return false;
}
case MdlExternalPropertyType::MAT4_FLOAT32:
switch (internalType) {
case MdlInternalPropertyType::MAT4_INT32:
case MdlInternalPropertyType::MAT4_FLOAT32:
case MdlInternalPropertyType::MAT4_INT32_NORM:
return true;
default:
return false;
}
}
return false;
}
} // namespace cesium::omniverse::FabricUtil
| 39,284 | C++ | 39.5 | 168 | 0.60279 |
CesiumGS/cesium-omniverse/src/core/src/MathUtil.cpp | #include "cesium/omniverse/MathUtil.h"
#include <glm/gtx/euler_angles.hpp>
#include <glm/gtx/matrix_decompose.hpp>
namespace cesium::omniverse::MathUtil {
EulerAngleOrder getReversedEulerAngleOrder(EulerAngleOrder eulerAngleOrder) {
switch (eulerAngleOrder) {
case EulerAngleOrder::XYZ:
return EulerAngleOrder::ZYX;
case EulerAngleOrder::XZY:
return EulerAngleOrder::YZX;
case EulerAngleOrder::YXZ:
return EulerAngleOrder::ZXY;
case EulerAngleOrder::YZX:
return EulerAngleOrder::XZY;
case EulerAngleOrder::ZXY:
return EulerAngleOrder::YXZ;
case EulerAngleOrder::ZYX:
return EulerAngleOrder::XYZ;
}
return EulerAngleOrder::XYZ;
}
DecomposedEuler decomposeEuler(const glm::dmat4& matrix, EulerAngleOrder eulerAngleOrder) {
glm::dvec3 scale;
glm::dquat rotation;
glm::dvec3 translation;
glm::dvec3 skew;
glm::dvec4 perspective;
[[maybe_unused]] const auto decomposable = glm::decompose(matrix, scale, rotation, translation, skew, perspective);
assert(decomposable);
const auto rotationMatrix = glm::mat4_cast(rotation);
glm::dvec3 rotationEuler(0.0);
switch (eulerAngleOrder) {
case EulerAngleOrder::XYZ:
glm::extractEulerAngleXYZ(rotationMatrix, rotationEuler.x, rotationEuler.y, rotationEuler.z);
break;
case EulerAngleOrder::XZY:
glm::extractEulerAngleXZY(rotationMatrix, rotationEuler.x, rotationEuler.z, rotationEuler.y);
break;
case EulerAngleOrder::YXZ:
glm::extractEulerAngleYXZ(rotationMatrix, rotationEuler.y, rotationEuler.x, rotationEuler.z);
break;
case EulerAngleOrder::YZX:
glm::extractEulerAngleYZX(rotationMatrix, rotationEuler.y, rotationEuler.z, rotationEuler.x);
break;
case EulerAngleOrder::ZXY:
glm::extractEulerAngleZXY(rotationMatrix, rotationEuler.z, rotationEuler.x, rotationEuler.y);
break;
case EulerAngleOrder::ZYX:
glm::extractEulerAngleZYX(rotationMatrix, rotationEuler.z, rotationEuler.y, rotationEuler.x);
break;
}
return {translation, rotationEuler, scale};
}
Decomposed decompose(const glm::dmat4& matrix) {
glm::dvec3 scale;
glm::dquat rotation;
glm::dvec3 translation;
glm::dvec3 skew;
glm::dvec4 perspective;
[[maybe_unused]] const auto decomposable = glm::decompose(matrix, scale, rotation, translation, skew, perspective);
assert(decomposable);
return {translation, rotation, scale};
}
glm::dmat4 composeEuler(
const glm::dvec3& translation,
const glm::dvec3& rotation,
const glm::dvec3& scale,
EulerAngleOrder eulerAngleOrder) {
const auto translationMatrix = glm::translate(glm::dmat4(1.0), translation);
const auto scaleMatrix = glm::scale(glm::dmat4(1.0), scale);
auto rotationMatrix = glm::dmat4(1.0);
switch (eulerAngleOrder) {
case EulerAngleOrder::XYZ:
rotationMatrix = glm::eulerAngleXYZ(rotation.x, rotation.y, rotation.z);
break;
case EulerAngleOrder::XZY:
rotationMatrix = glm::eulerAngleXZY(rotation.x, rotation.z, rotation.y);
break;
case EulerAngleOrder::YXZ:
rotationMatrix = glm::eulerAngleYXZ(rotation.y, rotation.x, rotation.z);
break;
case EulerAngleOrder::YZX:
rotationMatrix = glm::eulerAngleYZX(rotation.y, rotation.z, rotation.x);
break;
case EulerAngleOrder::ZXY:
rotationMatrix = glm::eulerAngleZXY(rotation.z, rotation.x, rotation.y);
break;
case EulerAngleOrder::ZYX:
rotationMatrix = glm::eulerAngleZYX(rotation.z, rotation.y, rotation.x);
break;
}
return translationMatrix * rotationMatrix * scaleMatrix;
}
glm::dmat4 compose(const glm::dvec3& translation, const glm::dquat& rotation, const glm::dvec3& scale) {
const auto translationMatrix = glm::translate(glm::dmat4(1.0), translation);
const auto rotationMatrix = glm::mat4_cast(rotation);
const auto scaleMatrix = glm::scale(glm::dmat4(1.0), scale);
return translationMatrix * rotationMatrix * scaleMatrix;
}
bool equal(const CesiumGeospatial::Cartographic& a, const CesiumGeospatial::Cartographic& b) {
const auto& aVec = *reinterpret_cast<const glm::dvec3*>(&a);
const auto& bVec = *reinterpret_cast<const glm::dvec3*>(&b);
return aVec == bVec;
}
bool epsilonEqual(const CesiumGeospatial::Cartographic& a, const CesiumGeospatial::Cartographic& b, double epsilon) {
const auto& aVec = *reinterpret_cast<const glm::dvec3*>(&a);
const auto& bVec = *reinterpret_cast<const glm::dvec3*>(&b);
return glm::all(glm::epsilonEqual(aVec, bVec, epsilon));
}
bool epsilonEqual(const glm::dmat4& a, const glm::dmat4& b, double epsilon) {
return glm::all(glm::epsilonEqual(a[0], b[0], epsilon)) && glm::all(glm::epsilonEqual(a[1], b[1], epsilon)) &&
glm::all(glm::epsilonEqual(a[2], b[2], epsilon)) && glm::all(glm::epsilonEqual(a[3], b[3], epsilon));
}
bool epsilonEqual(const glm::dvec3& a, const glm::dvec3& b, double epsilon) {
return glm::all(glm::epsilonEqual(a, b, epsilon));
}
bool epsilonEqual(const glm::dquat& a, const glm::dquat& b, double epsilon) {
return glm::all(glm::epsilonEqual(a, b, epsilon));
}
glm::dvec3 getCorner(const std::array<glm::dvec3, 2>& extent, uint64_t index) {
return {
(index & 1) ? extent[1].x : extent[0].x,
(index & 2) ? extent[1].y : extent[0].y,
(index & 4) ? extent[1].z : extent[0].z,
};
}
std::array<glm::dvec3, 2> transformExtent(const std::array<glm::dvec3, 2>& extent, const glm::dmat4& transform) {
const auto min = std::numeric_limits<double>::lowest();
const auto max = std::numeric_limits<double>::max();
glm::dvec3 transformedMin(max);
glm::dvec3 transformedMax(min);
for (uint64_t i = 0; i < 8; ++i) {
const auto position = MathUtil::getCorner(extent, i);
const auto transformedPosition = glm::dvec3(transform * glm::dvec4(position, 1.0));
transformedMin = glm::min(transformedMin, transformedPosition);
transformedMax = glm::max(transformedMax, transformedPosition);
}
return {{transformedMin, transformedMax}};
}
} // namespace cesium::omniverse::MathUtil
| 6,440 | C++ | 36.666666 | 119 | 0.664286 |
CesiumGS/cesium-omniverse/src/core/include/cesium/omniverse/OmniTileMapServiceRasterOverlay.h | #pragma once
#include "cesium/omniverse/OmniRasterOverlay.h"
#include <CesiumRasterOverlays/TileMapServiceRasterOverlay.h>
#include <CesiumUtility/IntrusivePointer.h>
#include <string>
namespace cesium::omniverse {
class OmniTileMapServiceRasterOverlay final : public OmniRasterOverlay {
public:
OmniTileMapServiceRasterOverlay(Context* pContext, const pxr::SdfPath& path);
~OmniTileMapServiceRasterOverlay() override = default;
OmniTileMapServiceRasterOverlay(const OmniTileMapServiceRasterOverlay&) = delete;
OmniTileMapServiceRasterOverlay& operator=(const OmniTileMapServiceRasterOverlay&) = delete;
OmniTileMapServiceRasterOverlay(OmniTileMapServiceRasterOverlay&&) noexcept = default;
OmniTileMapServiceRasterOverlay& operator=(OmniTileMapServiceRasterOverlay&&) noexcept = default;
[[nodiscard]] CesiumRasterOverlays::RasterOverlay* getRasterOverlay() const override;
[[nodiscard]] std::string getUrl() const;
[[nodiscard]] int getMinimumZoomLevel() const;
[[nodiscard]] int getMaximumZoomLevel() const;
[[nodiscard]] bool getSpecifyZoomLevels() const;
void reload() override;
private:
CesiumUtility::IntrusivePointer<CesiumRasterOverlays::TileMapServiceRasterOverlay> _pTileMapServiceRasterOverlay;
};
} // namespace cesium::omniverse
| 1,306 | C | 39.843749 | 117 | 0.795559 |
CesiumGS/cesium-omniverse/src/core/include/cesium/omniverse/AssetTroubleshootingDetails.h | #pragma once
#include <cstdint>
namespace cesium::omniverse {
struct AssetTroubleshootingDetails {
int64_t assetId;
bool assetExistsInUserAccount{false};
};
} // namespace cesium::omniverse
| 202 | C | 14.615383 | 41 | 0.747525 |
CesiumGS/cesium-omniverse/src/core/include/cesium/omniverse/TokenTroubleshootingDetails.h | #pragma once
#include <CesiumIonClient/Token.h>
namespace cesium::omniverse {
struct TokenTroubleshootingDetails {
CesiumIonClient::Token token;
bool isValid{false};
bool allowsAccessToAsset{false};
bool associatedWithUserAccount{false};
bool showDetails{false};
};
} // namespace cesium::omniverse
| 323 | C | 19.249999 | 42 | 0.749226 |
CesiumGS/cesium-omniverse/src/core/include/cesium/omniverse/UsdNotificationHandler.h | #pragma once
#include <pxr/usd/usd/notice.h>
namespace cesium::omniverse {
class Context;
class UsdNotificationHandler final : public pxr::TfWeakBase {
public:
UsdNotificationHandler(Context* pContext);
~UsdNotificationHandler();
UsdNotificationHandler(const UsdNotificationHandler&) = delete;
UsdNotificationHandler& operator=(const UsdNotificationHandler&) = delete;
UsdNotificationHandler(UsdNotificationHandler&&) noexcept = delete;
UsdNotificationHandler& operator=(UsdNotificationHandler&&) noexcept = delete;
void onStageLoaded();
void onUpdateFrame();
void clear();
private:
enum class ChangedPrimType {
CESIUM_DATA,
CESIUM_TILESET,
CESIUM_ION_RASTER_OVERLAY,
CESIUM_POLYGON_RASTER_OVERLAY,
CESIUM_WEB_MAP_SERVICE_RASTER_OVERLAY,
CESIUM_TILE_MAP_SERVICE_RASTER_OVERLAY,
CESIUM_WEB_MAP_TILE_SERVICE_RASTER_OVERLAY,
CESIUM_GEOREFERENCE,
CESIUM_GLOBE_ANCHOR,
CESIUM_ION_SERVER,
CESIUM_CARTOGRAPHIC_POLYGON,
USD_SHADER,
OTHER,
};
enum class ChangedType {
PROPERTY_CHANGED,
PRIM_ADDED,
PRIM_REMOVED,
};
struct ChangedPrim {
pxr::SdfPath primPath;
std::vector<pxr::TfToken> properties;
ChangedPrimType primType;
ChangedType changedType;
};
bool processChangedPrims();
[[nodiscard]] bool processChangedPrim(const ChangedPrim& changedPrim) const;
bool alreadyRegistered(const pxr::SdfPath& path);
void onObjectsChanged(const pxr::UsdNotice::ObjectsChanged& objectsChanged);
void onPrimAdded(const pxr::SdfPath& path);
void onPrimRemoved(const pxr::SdfPath& path);
void onPropertyChanged(const pxr::SdfPath& path);
void insertAddedPrim(const pxr::SdfPath& primPath, ChangedPrimType primType);
void insertRemovedPrim(const pxr::SdfPath& primPath, ChangedPrimType primType);
void
insertPropertyChanged(const pxr::SdfPath& primPath, ChangedPrimType primType, const pxr::TfToken& propertyName);
ChangedPrimType getTypeFromStage(const pxr::SdfPath& path) const;
ChangedPrimType getTypeFromAssetRegistry(const pxr::SdfPath& path) const;
Context* _pContext;
pxr::TfNotice::Key _noticeListenerKey;
std::vector<ChangedPrim> _changedPrims;
};
} // namespace cesium::omniverse
| 2,368 | C | 30.171052 | 116 | 0.708193 |
CesiumGS/cesium-omniverse/src/core/include/cesium/omniverse/Context.h | #pragma once
#include <pxr/usd/usd/common.h>
#include <filesystem>
#include <memory>
#include <vector>
#include <gsl/span>
namespace omni::fabric {
class StageReaderWriter;
}
namespace CesiumUtility {
class CreditSystem;
}
namespace CesiumAsync {
class AsyncSystem;
class IAssetAccessor;
class ICacheDatabase;
} // namespace CesiumAsync
namespace cesium::omniverse {
class AssetRegistry;
class CesiumIonServerManager;
class FabricResourceManager;
class Logger;
class TaskProcessor;
class UsdNotificationHandler;
struct RenderStatistics;
struct Viewport;
class Context {
public:
Context(const std::filesystem::path& cesiumExtensionLocation);
~Context();
Context(const Context&) = delete;
Context& operator=(const Context&) = delete;
Context(Context&&) noexcept = delete;
Context& operator=(Context&&) noexcept = delete;
[[nodiscard]] const std::filesystem::path& getCesiumExtensionLocation() const;
[[nodiscard]] const std::filesystem::path& getCertificatePath() const;
[[nodiscard]] const pxr::TfToken& getCesiumMdlPathToken() const;
[[nodiscard]] std::shared_ptr<TaskProcessor> getTaskProcessor() const;
[[nodiscard]] const CesiumAsync::AsyncSystem& getAsyncSystem() const;
[[nodiscard]] std::shared_ptr<CesiumAsync::IAssetAccessor> getAssetAccessor() const;
[[nodiscard]] std::shared_ptr<CesiumUtility::CreditSystem> getCreditSystem() const;
[[nodiscard]] std::shared_ptr<Logger> getLogger() const;
[[nodiscard]] const AssetRegistry& getAssetRegistry() const;
[[nodiscard]] AssetRegistry& getAssetRegistry();
[[nodiscard]] const FabricResourceManager& getFabricResourceManager() const;
[[nodiscard]] FabricResourceManager& getFabricResourceManager();
[[nodiscard]] const CesiumIonServerManager& getCesiumIonServerManager() const;
[[nodiscard]] CesiumIonServerManager& getCesiumIonServerManager();
void clearStage();
void reloadStage();
void clearAccessorCache();
void onUpdateFrame(const gsl::span<const Viewport>& viewports, bool waitForLoadingTiles);
void onUsdStageChanged(int64_t stageId);
[[nodiscard]] const pxr::UsdStageWeakPtr& getUsdStage() const;
[[nodiscard]] pxr::UsdStageWeakPtr& getUsdStage();
[[nodiscard]] int64_t getUsdStageId() const;
[[nodiscard]] bool hasUsdStage() const;
[[nodiscard]] omni::fabric::StageReaderWriter& getFabricStage() const;
[[nodiscard]] RenderStatistics getRenderStatistics() const;
[[nodiscard]] int64_t getContextId() const;
private:
std::filesystem::path _cesiumExtensionLocation;
std::filesystem::path _certificatePath;
pxr::TfToken _cesiumMdlPathToken;
std::shared_ptr<TaskProcessor> _pTaskProcessor;
std::unique_ptr<CesiumAsync::AsyncSystem> _pAsyncSystem;
std::shared_ptr<Logger> _pLogger;
std::shared_ptr<CesiumAsync::IAssetAccessor> _pAssetAccessor;
std::shared_ptr<CesiumAsync::ICacheDatabase> _pCacheDatabase;
std::shared_ptr<CesiumUtility::CreditSystem> _pCreditSystem;
std::unique_ptr<AssetRegistry> _pAssetRegistry;
std::unique_ptr<FabricResourceManager> _pFabricResourceManager;
std::unique_ptr<CesiumIonServerManager> _pCesiumIonServerManager;
std::unique_ptr<UsdNotificationHandler> _pUsdNotificationHandler;
int64_t _contextId;
pxr::UsdStageWeakPtr _pUsdStage;
std::unique_ptr<omni::fabric::StageReaderWriter> _pFabricStage;
int64_t _usdStageId{0};
};
} // namespace cesium::omniverse
| 3,467 | C | 33 | 93 | 0.744159 |
CesiumGS/cesium-omniverse/src/core/include/cesium/omniverse/UsdScopedEdit.h | #include <pxr/usd/usd/stage.h>
namespace cesium::omniverse {
class UsdScopedEdit {
public:
UsdScopedEdit(const pxr::UsdStageWeakPtr& pStage);
~UsdScopedEdit();
UsdScopedEdit(const UsdScopedEdit&) = delete;
UsdScopedEdit& operator=(const UsdScopedEdit&) = delete;
UsdScopedEdit(UsdScopedEdit&&) noexcept = delete;
UsdScopedEdit& operator=(UsdScopedEdit&&) noexcept = delete;
private:
pxr::UsdStageWeakPtr _pStage;
pxr::SdfLayerHandle _sessionLayer;
bool _sessionLayerWasEditable;
pxr::UsdEditTarget _originalEditTarget;
};
} // namespace cesium::omniverse
| 603 | C | 26.454544 | 64 | 0.729685 |
CesiumGS/cesium-omniverse/src/core/include/cesium/omniverse/FabricFeaturesUtil.h | #pragma once
#include <cstdint>
#include <vector>
namespace cesium::omniverse {
struct FabricFeatureId;
struct FabricFeaturesInfo;
enum class FabricFeatureIdType;
} // namespace cesium::omniverse
namespace cesium::omniverse::FabricFeaturesUtil {
FabricFeatureIdType getFeatureIdType(const FabricFeatureId& featureId);
std::vector<FabricFeatureIdType> getFeatureIdTypes(const FabricFeaturesInfo& featuresInfo);
std::vector<uint64_t> getSetIndexMapping(const FabricFeaturesInfo& featuresInfo, FabricFeatureIdType type);
bool hasFeatureIdType(const FabricFeaturesInfo& featuresInfo, FabricFeatureIdType type);
} // namespace cesium::omniverse::FabricFeaturesUtil
| 665 | C | 32.299998 | 107 | 0.83609 |
CesiumGS/cesium-omniverse/src/core/include/cesium/omniverse/FabricVertexAttributeDescriptor.h | #pragma once
#include "cesium/omniverse/DataType.h"
#include <omni/fabric/IToken.h>
namespace cesium::omniverse {
struct FabricVertexAttributeDescriptor {
DataType type;
omni::fabric::Token fabricAttributeName;
std::string gltfAttributeName;
// Make sure to update this function when adding new fields to the struct
// In C++ 20 we can use the default equality comparison (= default)
// clang-format off
bool operator==(const FabricVertexAttributeDescriptor& other) const {
return type == other.type &&
fabricAttributeName == other.fabricAttributeName &&
gltfAttributeName == other.gltfAttributeName;
}
// clang-format on
// This is needed for std::set to be sorted
bool operator<(const FabricVertexAttributeDescriptor& other) const {
return fabricAttributeName < other.fabricAttributeName;
}
};
} // namespace cesium::omniverse
| 930 | C | 29.032257 | 77 | 0.701075 |
CesiumGS/cesium-omniverse/src/core/include/cesium/omniverse/FabricMaterialPool.h | #pragma once
#include "cesium/omniverse/FabricMaterial.h"
#include "cesium/omniverse/FabricMaterialDescriptor.h"
#include "cesium/omniverse/ObjectPool.h"
#include <pxr/usd/usd/common.h>
namespace cesium::omniverse {
class FabricMaterialPool final : public ObjectPool<FabricMaterial> {
public:
FabricMaterialPool(
Context* pContext,
int64_t poolId,
const FabricMaterialDescriptor& materialDescriptor,
uint64_t initialCapacity,
const pxr::TfToken& defaultWhiteTextureAssetPathToken,
const pxr::TfToken& defaultTransparentTextureAssetPathToken,
bool debugRandomColors);
~FabricMaterialPool() override = default;
FabricMaterialPool(const FabricMaterialPool&) = delete;
FabricMaterialPool& operator=(const FabricMaterialPool&) = delete;
FabricMaterialPool(FabricMaterialPool&&) noexcept = default;
FabricMaterialPool& operator=(FabricMaterialPool&&) noexcept = default;
[[nodiscard]] const FabricMaterialDescriptor& getMaterialDescriptor() const;
[[nodiscard]] int64_t getPoolId() const;
void updateShaderInput(const pxr::SdfPath& shaderPath, const pxr::TfToken& attributeName);
protected:
std::shared_ptr<FabricMaterial> createObject(uint64_t objectId) const override;
void setActive(FabricMaterial* pMaterial, bool active) const override;
private:
Context* _pContext;
int64_t _poolId;
FabricMaterialDescriptor _materialDescriptor;
pxr::TfToken _defaultWhiteTextureAssetPathToken;
pxr::TfToken _defaultTransparentTextureAssetPathToken;
bool _debugRandomColors;
};
} // namespace cesium::omniverse
| 1,632 | C | 34.499999 | 94 | 0.756127 |
CesiumGS/cesium-omniverse/src/core/include/cesium/omniverse/FabricGeometry.h | #pragma once
#include "cesium/omniverse/FabricGeometryDescriptor.h"
#include <glm/fwd.hpp>
#include <omni/fabric/IPath.h>
namespace CesiumGltf {
struct MeshPrimitive;
struct Model;
} // namespace CesiumGltf
namespace cesium::omniverse {
class Context;
struct FabricMaterialInfo;
class FabricGeometry {
public:
FabricGeometry(
Context* pContext,
const omni::fabric::Path& path,
const FabricGeometryDescriptor& geometryDescriptor,
int64_t poolId);
~FabricGeometry();
FabricGeometry(const FabricGeometry&) = delete;
FabricGeometry& operator=(const FabricGeometry&) = delete;
FabricGeometry(FabricGeometry&&) noexcept = default;
FabricGeometry& operator=(FabricGeometry&&) noexcept = default;
void setGeometry(
int64_t tilesetId,
const glm::dmat4& ecefToPrimWorldTransform,
const glm::dmat4& gltfLocalToEcefTransform,
const CesiumGltf::Model& model,
const CesiumGltf::MeshPrimitive& primitive,
const FabricMaterialInfo& materialInfo,
bool smoothNormals,
const std::unordered_map<uint64_t, uint64_t>& texcoordIndexMapping,
const std::unordered_map<uint64_t, uint64_t>& rasterOverlayTexcoordIndexMapping);
void setActive(bool active);
void setVisibility(bool visible);
[[nodiscard]] const omni::fabric::Path& getPath() const;
[[nodiscard]] const FabricGeometryDescriptor& getGeometryDescriptor() const;
[[nodiscard]] int64_t getPoolId() const;
void setMaterial(const omni::fabric::Path& materialPath);
private:
void initialize();
void reset();
bool stageDestroyed();
Context* _pContext;
omni::fabric::Path _path;
FabricGeometryDescriptor _geometryDescriptor;
int64_t _poolId;
int64_t _stageId;
};
} // namespace cesium::omniverse
| 1,829 | C | 27.59375 | 89 | 0.708037 |
CesiumGS/cesium-omniverse/src/core/include/cesium/omniverse/FabricMaterial.h | #pragma once
#include "cesium/omniverse/FabricMaterialDescriptor.h"
#include "cesium/omniverse/FabricMaterialInfo.h"
#include <glm/glm.hpp>
#include <omni/fabric/IPath.h>
#include <unordered_map>
namespace omni::fabric {
struct Type;
}
namespace omni::ui {
class DynamicTextureProvider;
}
namespace cesium::omniverse {
class FabricTexture;
enum class MdlInternalPropertyType;
struct FabricPropertyDescriptor;
struct FabricTextureInfo;
class FabricMaterial {
public:
FabricMaterial(
Context* pContext,
const omni::fabric::Path& path,
const FabricMaterialDescriptor& materialDescriptor,
const pxr::TfToken& defaultWhiteTextureAssetPathToken,
const pxr::TfToken& defaultTransparentTextureAssetPathToken,
bool debugRandomColors,
int64_t poolId);
~FabricMaterial();
FabricMaterial(const FabricMaterial&) = delete;
FabricMaterial& operator=(const FabricMaterial&) = delete;
FabricMaterial(FabricMaterial&&) noexcept = default;
FabricMaterial& operator=(FabricMaterial&&) noexcept = default;
void setMaterial(
const CesiumGltf::Model& model,
const CesiumGltf::MeshPrimitive& primitive,
int64_t tilesetId,
const FabricMaterialInfo& materialInfo,
const FabricFeaturesInfo& featuresInfo,
FabricTexture* pBaseColorTexture,
const std::vector<std::shared_ptr<FabricTexture>>& featureIdTextures,
const std::vector<std::shared_ptr<FabricTexture>>& propertyTextures,
const std::vector<std::shared_ptr<FabricTexture>>& propertyTableTextures,
const glm::dvec3& displayColor,
double displayOpacity,
const std::unordered_map<uint64_t, uint64_t>& texcoordIndexMapping,
const std::vector<uint64_t>& featureIdIndexSetIndexMapping,
const std::vector<uint64_t>& featureIdAttributeSetIndexMapping,
const std::vector<uint64_t>& featureIdTextureSetIndexMapping,
const std::unordered_map<uint64_t, uint64_t>& propertyTextureIndexMapping);
void setRasterOverlay(
FabricTexture* pTexture,
const FabricTextureInfo& textureInfo,
uint64_t rasterOverlayIndex,
double alpha,
const std::unordered_map<uint64_t, uint64_t>& rasterOverlayTexcoordIndexMapping);
void setRasterOverlayAlpha(uint64_t rasterOverlayIndex, double alpha);
void setDisplayColorAndOpacity(const glm::dvec3& displayColor, double displayOpacity);
void updateShaderInput(const omni::fabric::Path& shaderPath, const omni::fabric::Token& attributeName);
void clearRasterOverlay(uint64_t rasterOverlayIndex);
void setActive(bool active);
[[nodiscard]] const omni::fabric::Path& getPath() const;
[[nodiscard]] const FabricMaterialDescriptor& getMaterialDescriptor() const;
[[nodiscard]] int64_t getPoolId() const;
private:
void initializeNodes();
void initializeDefaultMaterial();
void initializeExistingMaterial(const omni::fabric::Path& path);
void createMaterial(const omni::fabric::Path& path);
void createShader(const omni::fabric::Path& path);
void createTextureCommon(
const omni::fabric::Path& path,
const omni::fabric::Token& subIdentifier,
const std::vector<std::pair<omni::fabric::Type, omni::fabric::Token>>& additionalAttributes = {});
void createTexture(const omni::fabric::Path& path);
void createRasterOverlay(const omni::fabric::Path& path);
void createRasterOverlayResolverCommon(
const omni::fabric::Path& path,
uint64_t textureCount,
const omni::fabric::Token& subidentifier);
void createRasterOverlayResolver(const omni::fabric::Path& path, uint64_t textureCount);
void createClippingRasterOverlayResolver(const omni::fabric::Path& path, uint64_t textureCount);
void createFeatureIdIndex(const omni::fabric::Path& path);
void createFeatureIdAttribute(const omni::fabric::Path& path);
void createFeatureIdTexture(const omni::fabric::Path& path);
void createPropertyAttributePropertyInt(
const omni::fabric::Path& path,
const omni::fabric::Token& subidentifier,
const omni::fabric::Type& noDataType,
const omni::fabric::Type& defaultValueType);
void createPropertyAttributePropertyNormalizedInt(
const omni::fabric::Path& path,
const omni::fabric::Token& subidentifier,
const omni::fabric::Type& noDataType,
const omni::fabric::Type& defaultValueType,
const omni::fabric::Type& offsetType,
const omni::fabric::Type& scaleType,
const omni::fabric::Type& maximumValueType);
void createPropertyAttributePropertyFloat(
const omni::fabric::Path& path,
const omni::fabric::Token& subidentifier,
const omni::fabric::Type& noDataType,
const omni::fabric::Type& defaultValueType,
const omni::fabric::Type& offsetType,
const omni::fabric::Type& scaleType);
void createPropertyAttributeProperty(const omni::fabric::Path& path, MdlInternalPropertyType type);
void createPropertyTexturePropertyInt(
const omni::fabric::Path& path,
const omni::fabric::Token& subidentifier,
const omni::fabric::Type& noDataType,
const omni::fabric::Type& defaultValueType);
void createPropertyTexturePropertyNormalizedInt(
const omni::fabric::Path& path,
const omni::fabric::Token& subidentifier,
const omni::fabric::Type& noDataType,
const omni::fabric::Type& defaultValueType,
const omni::fabric::Type& offsetType,
const omni::fabric::Type& scaleType,
const omni::fabric::Type& maximumValueType);
void createPropertyTextureProperty(const omni::fabric::Path& path, MdlInternalPropertyType type);
void createPropertyTablePropertyInt(
const omni::fabric::Path& path,
const omni::fabric::Token& subidentifier,
const omni::fabric::Type& noDataType,
const omni::fabric::Type& defaultValueType);
void createPropertyTablePropertyNormalizedInt(
const omni::fabric::Path& path,
const omni::fabric::Token& subidentifier,
const omni::fabric::Type& noDataType,
const omni::fabric::Type& defaultValueType,
const omni::fabric::Type& offsetType,
const omni::fabric::Type& scaleType,
const omni::fabric::Type& maximumValueType);
void createPropertyTablePropertyFloat(
const omni::fabric::Path& path,
const omni::fabric::Token& subidentifier,
const omni::fabric::Type& noDataType,
const omni::fabric::Type& defaultValueType,
const omni::fabric::Type& offsetType,
const omni::fabric::Type& scaleType);
void createPropertyTableProperty(const omni::fabric::Path& path, MdlInternalPropertyType type);
void reset();
void setShaderValues(
const omni::fabric::Path& path,
const FabricMaterialInfo& materialInfo,
const glm::dvec3& displayColor,
double displayOpacity);
void setTextureValues(
const omni::fabric::Path& path,
const pxr::TfToken& textureAssetPathToken,
const FabricTextureInfo& textureInfo,
uint64_t texcoordIndex);
void setRasterOverlayValues(
const omni::fabric::Path& path,
const pxr::TfToken& textureAssetPathToken,
const FabricTextureInfo& textureInfo,
uint64_t texcoordIndex,
double alpha);
void setRasterOverlayAlphaValue(const omni::fabric::Path& path, double alpha);
void setFeatureIdIndexValues(const omni::fabric::Path& path, int nullFeatureId);
void setFeatureIdAttributeValues(const omni::fabric::Path& path, const std::string& primvarName, int nullFeatureId);
void setFeatureIdTextureValues(
const omni::fabric::Path& path,
const pxr::TfToken& textureAssetPathToken,
const FabricTextureInfo& textureInfo,
uint64_t texcoordIndex,
int nullFeatureId);
void createConnectionsToCopiedPaths();
void destroyConnectionsToCopiedPaths();
void createConnectionsToProperties();
void destroyConnectionsToProperties();
bool stageDestroyed();
Context* _pContext;
omni::fabric::Path _materialPath;
FabricMaterialDescriptor _materialDescriptor;
pxr::TfToken _defaultWhiteTextureAssetPathToken;
pxr::TfToken _defaultTransparentTextureAssetPathToken;
bool _debugRandomColors;
int64_t _poolId;
int64_t _stageId;
bool _usesDefaultMaterial;
FabricAlphaMode _alphaMode{FabricAlphaMode::OPAQUE};
glm::dvec3 _debugColor{1.0, 1.0, 1.0};
omni::fabric::Path _shaderPath;
omni::fabric::Path _baseColorTexturePath;
std::vector<omni::fabric::Path> _rasterOverlayPaths;
omni::fabric::Path _overlayRasterOverlayResolverPath;
omni::fabric::Path _clippingRasterOverlayResolverPath;
std::vector<omni::fabric::Path> _featureIdPaths;
std::vector<omni::fabric::Path> _featureIdIndexPaths;
std::vector<omni::fabric::Path> _featureIdAttributePaths;
std::vector<omni::fabric::Path> _featureIdTexturePaths;
std::vector<omni::fabric::Path> _propertyPaths;
std::unordered_map<MdlInternalPropertyType, std::vector<omni::fabric::Path>> _propertyAttributePropertyPaths;
std::unordered_map<MdlInternalPropertyType, std::vector<omni::fabric::Path>> _propertyTexturePropertyPaths;
std::unordered_map<MdlInternalPropertyType, std::vector<omni::fabric::Path>> _propertyTablePropertyPaths;
std::vector<omni::fabric::Path> _copiedBaseColorTexturePaths;
std::vector<omni::fabric::Path> _copiedRasterOverlayPaths;
std::vector<omni::fabric::Path> _copiedFeatureIdPaths;
std::vector<omni::fabric::Path> _copiedPropertyPaths;
std::vector<omni::fabric::Path> _allPaths;
};
} // namespace cesium::omniverse
| 9,803 | C | 41.626087 | 120 | 0.714373 |
CesiumGS/cesium-omniverse/src/core/include/cesium/omniverse/SetDefaultTokenResult.h | #pragma once
#include <string>
namespace cesium::omniverse {
enum SetDefaultTokenResultCode {
NOT_SET_IN_SESSION = -1,
OK = 0,
NOT_CONNECTED_TO_ION = 1,
CREATE_FAILED = 2,
};
namespace SetDefaultTokenResultMessages {
inline const std::string_view NOT_SET_IN_SESSION_MESSAGE = "Default token has not been set this session.";
inline const std::string_view OK_MESSAGE = "OK";
inline const std::string_view NOT_CONNECTED_TO_ION_MESSAGE = "Not connected to ion.";
inline const std::string_view CREATE_FAILED_MESSAGE_BASE = "Create failed: {1} ({2})";
} // namespace SetDefaultTokenResultMessages
/**
* Stores information about the last action to set the default token. A code and a relevant user
* friendly message are stored.
*/
struct SetDefaultTokenResult {
int code{SetDefaultTokenResultCode::NOT_SET_IN_SESSION};
std::string message{SetDefaultTokenResultMessages::NOT_SET_IN_SESSION_MESSAGE};
};
} // namespace cesium::omniverse
| 961 | C | 31.066666 | 106 | 0.738814 |
CesiumGS/cesium-omniverse/src/core/include/cesium/omniverse/FabricUtil.h | #pragma once
#include <glm/fwd.hpp>
#include <pxr/usd/usd/common.h>
#include <string>
namespace omni::fabric {
class StageReaderWriter;
class Path;
class Token;
struct Type;
} // namespace omni::fabric
namespace cesium::omniverse {
enum class DataType;
enum class MdlExternalPropertyType;
enum class MdlInternalPropertyType;
struct FabricStatistics;
} // namespace cesium::omniverse
namespace cesium::omniverse::FabricUtil {
// -1 means the prim is not associated with a tileset yet
const int64_t NO_TILESET_ID{-1};
std::string printFabricStage(omni::fabric::StageReaderWriter& fabricStage);
FabricStatistics getStatistics(omni::fabric::StageReaderWriter& fabricStage);
void destroyPrim(omni::fabric::StageReaderWriter& fabricStage, const omni::fabric::Path& path);
void setTilesetTransform(
omni::fabric::StageReaderWriter& fabricStage,
int64_t tilesetId,
const glm::dmat4& ecefToPrimWorldTransform);
omni::fabric::Path toFabricPath(const pxr::SdfPath& path);
omni::fabric::Token toFabricToken(const pxr::TfToken& token);
omni::fabric::Path joinPaths(const omni::fabric::Path& absolutePath, const omni::fabric::Token& relativePath);
omni::fabric::Path getCopiedShaderPath(const omni::fabric::Path& materialPath, const omni::fabric::Path& shaderPath);
std::vector<omni::fabric::Path> copyMaterial(
omni::fabric::StageReaderWriter& fabricStage,
const omni::fabric::Path& srcMaterialPath,
const omni::fabric::Path& dstMaterialPath);
bool materialHasCesiumNodes(omni::fabric::StageReaderWriter& fabricStage, const omni::fabric::Path& materialPath);
bool isCesiumNode(const omni::fabric::Token& mdlIdentifier);
bool isCesiumPropertyNode(const omni::fabric::Token& mdlIdentifier);
bool isShaderConnectedToMaterial(
omni::fabric::StageReaderWriter& fabricStage,
const omni::fabric::Path& materialPath,
const omni::fabric::Path& shaderPath);
omni::fabric::Token getMdlIdentifier(omni::fabric::StageReaderWriter& fabricStage, const omni::fabric::Path& path);
omni::fabric::Type getPrimvarType(DataType type);
MdlExternalPropertyType getMdlExternalPropertyType(const omni::fabric::Token& mdlIdentifier);
bool typesCompatible(MdlExternalPropertyType externalType, MdlInternalPropertyType internalType);
} // namespace cesium::omniverse::FabricUtil
| 2,284 | C | 39.087719 | 117 | 0.788529 |
CesiumGS/cesium-omniverse/src/core/include/cesium/omniverse/FilesystemUtil.h | #pragma once
#include <filesystem>
namespace cesium::omniverse::FilesystemUtil {
std::filesystem::path getCesiumCacheDirectory();
std::filesystem::path getUserHomeDirectory();
} // namespace cesium::omniverse::FilesystemUtil
| 227 | C | 24.333331 | 48 | 0.792952 |
CesiumGS/cesium-omniverse/src/core/include/cesium/omniverse/UsdTokens.h | #pragma once
#include <omni/fabric/FabricUSD.h>
#include <pxr/base/tf/staticTokens.h>
// clang-format off
PXR_NAMESPACE_OPEN_SCOPE
#ifdef CESIUM_OMNI_MSVC
__pragma(warning(push)) __pragma(warning(disable : 4003))
#endif
// Note: variable names should match the USD token names as closely as possible, with special characters converted to underscores
#define USD_TOKENS \
(base_color_texture) \
(cesium_base_color_texture_float4) \
(cesium_feature_id_int) \
(cesium_raster_overlay_float4) \
(cesium_internal_clipping_raster_overlay_resolver) \
(cesium_internal_feature_id_attribute_lookup) \
(cesium_internal_feature_id_texture_lookup) \
(cesium_internal_raster_overlay_lookup) \
(cesium_internal_raster_overlay_resolver) \
(cesium_internal_material) \
(cesium_internal_property_attribute_float_lookup) \
(cesium_internal_property_attribute_float2_lookup) \
(cesium_internal_property_attribute_float3_lookup) \
(cesium_internal_property_attribute_float4_lookup) \
(cesium_internal_property_attribute_int_lookup) \
(cesium_internal_property_attribute_int2_lookup) \
(cesium_internal_property_attribute_int3_lookup) \
(cesium_internal_property_attribute_int4_lookup) \
(cesium_internal_property_attribute_normalized_int_lookup) \
(cesium_internal_property_attribute_normalized_int2_lookup) \
(cesium_internal_property_attribute_normalized_int3_lookup) \
(cesium_internal_property_attribute_normalized_int4_lookup) \
(cesium_internal_property_table_float_lookup) \
(cesium_internal_property_table_float2_lookup) \
(cesium_internal_property_table_float3_lookup) \
(cesium_internal_property_table_float4_lookup) \
(cesium_internal_property_table_int_lookup) \
(cesium_internal_property_table_int2_lookup) \
(cesium_internal_property_table_int3_lookup) \
(cesium_internal_property_table_int4_lookup) \
(cesium_internal_property_table_normalized_int_lookup) \
(cesium_internal_property_table_normalized_int2_lookup) \
(cesium_internal_property_table_normalized_int3_lookup) \
(cesium_internal_property_table_normalized_int4_lookup) \
(cesium_internal_property_texture_int_lookup) \
(cesium_internal_property_texture_int2_lookup) \
(cesium_internal_property_texture_int3_lookup) \
(cesium_internal_property_texture_int4_lookup) \
(cesium_internal_property_texture_normalized_int_lookup) \
(cesium_internal_property_texture_normalized_int2_lookup) \
(cesium_internal_property_texture_normalized_int3_lookup) \
(cesium_internal_property_texture_normalized_int4_lookup) \
(cesium_internal_texture_lookup) \
(cesium_property_float) \
(cesium_property_float2) \
(cesium_property_float3) \
(cesium_property_float4) \
(cesium_property_int) \
(cesium_property_int2) \
(cesium_property_int3) \
(cesium_property_int4) \
(clipping_raster_overlay_resolver) \
(doubleSided) \
(extent) \
(faceVertexCounts) \
(faceVertexIndices) \
(raster_overlay) \
(raster_overlay_resolver) \
(Material) \
(Mesh) \
(none) \
(points) \
(primvarInterpolations) \
(primvars) \
(Shader) \
(sourceAsset) \
(subdivisionScheme) \
(vertex) \
(vertexId) \
(_cesium_gltfLocalToEcefTransform) \
(_cesium_tilesetId) \
(_deletedPrims) \
(_materialSource) \
(_paramColorSpace) \
(_sdrMetadata) \
(_worldExtent) \
(_worldOrientation) \
(_worldPosition) \
(_worldScale) \
(_worldVisibility) \
((info_implementationSource, "info:implementationSource")) \
((info_mdl_sourceAsset, "info:mdl:sourceAsset")) \
((info_mdl_sourceAsset_subIdentifier, "info:mdl:sourceAsset:subIdentifier")) \
((inputs_alpha, "inputs:alpha")) \
((inputs_alpha_clip, "inputs:alpha_clip")) \
((inputs_alpha_cutoff, "inputs:alpha_cutoff")) \
((inputs_alpha_mode, "inputs:alpha_mode")) \
((inputs_base_alpha, "inputs:base_alpha")) \
((inputs_base_color_factor, "inputs:base_color_factor")) \
((inputs_base_color_texture, "inputs:base_color_texture")) \
((inputs_channels, "inputs:channels")) \
((inputs_channel_count, "inputs:channel_count")) \
((inputs_default_value, "inputs:default_value")) \
((inputs_emissive_factor, "inputs:emissive_factor")) \
((inputs_excludeFromWhiteMode, "inputs:excludeFromWhiteMode")) \
((inputs_feature_id, "inputs:feature_id")) \
((inputs_feature_id_set_index, "inputs:feature_id_set_index")) \
((inputs_has_no_data, "inputs:has_no_data")) \
((inputs_raster_overlay, "inputs:raster_overlay")) \
((inputs_raster_overlay_count, "inputs:raster_overlay_count")) \
((inputs_raster_overlay_index, "inputs:raster_overlay_index")) \
((inputs_maximum_value, "inputs:maximum_value")) \
((inputs_metallic_factor, "inputs:metallic_factor")) \
((inputs_no_data, "inputs:no_data")) \
((inputs_null_feature_id, "inputs:null_feature_id")) \
((inputs_offset, "inputs:offset")) \
((inputs_primvar_name, "inputs:primvar_name")) \
((inputs_property_id, "inputs:property_id")) \
((inputs_property_table_texture, "inputs:property_table_texture")) \
((inputs_property_value, "inputs:property_value")) \
((inputs_roughness_factor, "inputs:roughness_factor")) \
((inputs_scale, "inputs:scale")) \
((inputs_texture, "inputs:texture")) \
((inputs_tex_coord_index, "inputs:tex_coord_index")) \
((inputs_tex_coord_offset, "inputs:tex_coord_offset")) \
((inputs_tex_coord_rotation, "inputs:tex_coord_rotation")) \
((inputs_tex_coord_scale, "inputs:tex_coord_scale")) \
((inputs_tile_color, "inputs:tile_color")) \
((inputs_wrap_s, "inputs:wrap_s")) \
((inputs_wrap_t, "inputs:wrap_t")) \
((material_binding, "material:binding")) \
((outputs_mdl_displacement, "outputs:mdl:displacement")) \
((outputs_mdl_surface, "outputs:mdl:surface")) \
((outputs_mdl_volume, "outputs:mdl:volume")) \
((outputs_out, "outputs:out")) \
((primvars_COLOR_0, "primvars:COLOR_0")) \
((primvars_displayColor, "primvars:displayColor")) \
((primvars_displayOpacity, "primvars:displayOpacity")) \
((primvars_normals, "primvars:normals")) \
((primvars_vertexId, "primvars:vertexId")) \
((xformOp_orient, "xformOp:orient")) \
((xformOp_rotateXYZ, "xformOp:rotateXYZ")) \
((xformOp_rotateXZY, "xformOp:rotateXZY")) \
((xformOp_rotateYXZ, "xformOp:rotateYXZ")) \
((xformOp_rotateYZX, "xformOp:rotateYZX")) \
((xformOp_rotateZXY, "xformOp:rotateZXY")) \
((xformOp_rotateZYX, "xformOp:rotateZYX")) \
((xformOp_scale, "xformOp:scale")) \
((xformOp_translate, "xformOp:translate")) \
((_auto, "auto"))
#ifdef CESIUM_OMNI_CLANG
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wgnu-zero-variadic-macro-arguments"
#endif
TF_DECLARE_PUBLIC_TOKENS(UsdTokens, USD_TOKENS);
#ifdef CESIUM_OMNI_CLANG
#pragma clang diagnostic pop
#endif
#define FABRIC_DEFINE_TOKEN_ELEM(elem) const omni::fabric::TokenC elem = omni::fabric::asInt(pxr::UsdTokens->elem);
#define FABRIC_DEFINE_TOKEN(r, data, elem) \
BOOST_PP_TUPLE_ELEM(1, 0, BOOST_PP_IIF(TF_PP_IS_TUPLE(elem), \
(FABRIC_DEFINE_TOKEN_ELEM(BOOST_PP_TUPLE_ELEM(2, 0, elem))), \
(FABRIC_DEFINE_TOKEN_ELEM(elem))))
#define FABRIC_DEFINE_TOKENS(seq) BOOST_PP_SEQ_FOR_EACH(FABRIC_DEFINE_TOKEN, ~, seq)
#define FABRIC_DECLARE_TOKEN_ELEM(elem) extern const omni::fabric::TokenC elem;
#define FABRIC_DECLARE_TOKEN(r, data, elem) \
BOOST_PP_TUPLE_ELEM(1, 0, BOOST_PP_IIF(TF_PP_IS_TUPLE(elem), \
(FABRIC_DECLARE_TOKEN_ELEM(BOOST_PP_TUPLE_ELEM(2, 0, elem))), \
(FABRIC_DECLARE_TOKEN_ELEM(elem))))
#define FABRIC_DECLARE_TOKENS(seq) BOOST_PP_SEQ_FOR_EACH(FABRIC_DECLARE_TOKEN, ~, seq)
#ifdef CESIUM_OMNI_MSVC
__pragma(warning(pop))
#endif
PXR_NAMESPACE_CLOSE_SCOPE
namespace cesium::omniverse::FabricTokens {
FABRIC_DECLARE_TOKENS(USD_TOKENS);
const omni::fabric::TokenC feature_id_n(uint64_t index);
const omni::fabric::TokenC raster_overlay_n(uint64_t index);
const omni::fabric::TokenC inputs_raster_overlay_n(uint64_t index);
const omni::fabric::TokenC primvars_st_n(uint64_t index);
const omni::fabric::TokenC property_n(uint64_t index);
}
namespace cesium::omniverse::FabricTypes {
// Due to legacy support the eRelationship type is defined as a scalar value but is secretly an array
const omni::fabric::Type doubleSided(omni::fabric::BaseDataType::eBool, 1, 0, omni::fabric::AttributeRole::eNone);
const omni::fabric::Type extent(omni::fabric::BaseDataType::eDouble, 6, 0, omni::fabric::AttributeRole::eNone);
const omni::fabric::Type faceVertexCounts(omni::fabric::BaseDataType::eInt, 1, 1, omni::fabric::AttributeRole::eNone);
const omni::fabric::Type faceVertexIndices(omni::fabric::BaseDataType::eInt, 1, 1, omni::fabric::AttributeRole::eNone);
const omni::fabric::Type info_implementationSource(omni::fabric::BaseDataType::eToken, 1, 0, omni::fabric::AttributeRole::eNone);
const omni::fabric::Type info_mdl_sourceAsset(omni::fabric::BaseDataType::eAsset, 1, 0, omni::fabric::AttributeRole::eNone);
const omni::fabric::Type info_mdl_sourceAsset_subIdentifier(omni::fabric::BaseDataType::eToken, 1, 0, omni::fabric::AttributeRole::eNone);
const omni::fabric::Type inputs_alpha(omni::fabric::BaseDataType::eFloat, 1, 0, omni::fabric::AttributeRole::eNone);
const omni::fabric::Type inputs_alpha_cutoff(omni::fabric::BaseDataType::eFloat, 1, 0, omni::fabric::AttributeRole::eNone);
const omni::fabric::Type inputs_alpha_mode(omni::fabric::BaseDataType::eInt, 1, 0, omni::fabric::AttributeRole::eNone);
const omni::fabric::Type inputs_base_alpha(omni::fabric::BaseDataType::eFloat, 1, 0, omni::fabric::AttributeRole::eNone);
const omni::fabric::Type inputs_base_color_factor(omni::fabric::BaseDataType::eFloat, 3, 0, omni::fabric::AttributeRole::eColor);
const omni::fabric::Type inputs_channels(omni::fabric::BaseDataType::eInt, 4, 0, omni::fabric::AttributeRole::eNone);
const omni::fabric::Type inputs_channel_count(omni::fabric::BaseDataType::eInt, 1, 0, omni::fabric::AttributeRole::eNone);
const omni::fabric::Type inputs_default_value_float(omni::fabric::BaseDataType::eFloat, 1, 0, omni::fabric::AttributeRole::eNone);
const omni::fabric::Type inputs_default_value_float2(omni::fabric::BaseDataType::eFloat, 2, 0, omni::fabric::AttributeRole::eNone);
const omni::fabric::Type inputs_default_value_float3(omni::fabric::BaseDataType::eFloat, 3, 0, omni::fabric::AttributeRole::eNone);
const omni::fabric::Type inputs_default_value_float4(omni::fabric::BaseDataType::eFloat, 4, 0, omni::fabric::AttributeRole::eNone);
const omni::fabric::Type inputs_default_value_int(omni::fabric::BaseDataType::eInt, 1, 0, omni::fabric::AttributeRole::eNone);
const omni::fabric::Type inputs_default_value_int2(omni::fabric::BaseDataType::eInt, 2, 0, omni::fabric::AttributeRole::eNone);
const omni::fabric::Type inputs_default_value_int3(omni::fabric::BaseDataType::eInt, 3, 0, omni::fabric::AttributeRole::eNone);
const omni::fabric::Type inputs_default_value_int4(omni::fabric::BaseDataType::eInt, 4, 0, omni::fabric::AttributeRole::eNone);
const omni::fabric::Type inputs_emissive_factor(omni::fabric::BaseDataType::eFloat, 3, 0, omni::fabric::AttributeRole::eColor);
const omni::fabric::Type inputs_excludeFromWhiteMode(omni::fabric::BaseDataType::eBool, 1, 0, omni::fabric::AttributeRole::eNone);
const omni::fabric::Type inputs_has_no_data(omni::fabric::BaseDataType::eBool, 1, 0, omni::fabric::AttributeRole::eNone);
const omni::fabric::Type inputs_raster_overlay_count(omni::fabric::BaseDataType::eInt, 1, 0, omni::fabric::AttributeRole::eNone);
const omni::fabric::Type inputs_maximum_value_int(omni::fabric::BaseDataType::eInt, 1, 0, omni::fabric::AttributeRole::eNone);
const omni::fabric::Type inputs_maximum_value_int2(omni::fabric::BaseDataType::eInt, 2, 0, omni::fabric::AttributeRole::eNone);
const omni::fabric::Type inputs_maximum_value_int3(omni::fabric::BaseDataType::eInt, 3, 0, omni::fabric::AttributeRole::eNone);
const omni::fabric::Type inputs_maximum_value_int4(omni::fabric::BaseDataType::eInt, 4, 0, omni::fabric::AttributeRole::eNone);
const omni::fabric::Type inputs_metallic_factor(omni::fabric::BaseDataType::eFloat, 1, 0, omni::fabric::AttributeRole::eNone);
const omni::fabric::Type inputs_no_data_float(omni::fabric::BaseDataType::eFloat, 1, 0, omni::fabric::AttributeRole::eNone);
const omni::fabric::Type inputs_no_data_float2(omni::fabric::BaseDataType::eFloat, 2, 0, omni::fabric::AttributeRole::eNone);
const omni::fabric::Type inputs_no_data_float3(omni::fabric::BaseDataType::eFloat, 3, 0, omni::fabric::AttributeRole::eNone);
const omni::fabric::Type inputs_no_data_float4(omni::fabric::BaseDataType::eFloat, 4, 0, omni::fabric::AttributeRole::eNone);
const omni::fabric::Type inputs_no_data_int(omni::fabric::BaseDataType::eInt, 1, 0, omni::fabric::AttributeRole::eNone);
const omni::fabric::Type inputs_no_data_int2(omni::fabric::BaseDataType::eInt, 2, 0, omni::fabric::AttributeRole::eNone);
const omni::fabric::Type inputs_no_data_int3(omni::fabric::BaseDataType::eInt, 3, 0, omni::fabric::AttributeRole::eNone);
const omni::fabric::Type inputs_no_data_int4(omni::fabric::BaseDataType::eInt, 4, 0, omni::fabric::AttributeRole::eNone);
const omni::fabric::Type inputs_null_feature_id(omni::fabric::BaseDataType::eInt, 1, 0, omni::fabric::AttributeRole::eNone);
const omni::fabric::Type inputs_offset_float(omni::fabric::BaseDataType::eFloat, 1, 0, omni::fabric::AttributeRole::eNone);
const omni::fabric::Type inputs_offset_float2(omni::fabric::BaseDataType::eFloat, 2, 0, omni::fabric::AttributeRole::eNone);
const omni::fabric::Type inputs_offset_float3(omni::fabric::BaseDataType::eFloat, 3, 0, omni::fabric::AttributeRole::eNone);
const omni::fabric::Type inputs_offset_float4(omni::fabric::BaseDataType::eFloat, 4, 0, omni::fabric::AttributeRole::eNone);
const omni::fabric::Type inputs_primvar_name(omni::fabric::BaseDataType::eUChar, 1, 1, omni::fabric::AttributeRole::eText);
const omni::fabric::Type inputs_property_table_texture(omni::fabric::BaseDataType::eAsset, 1, 0, omni::fabric::AttributeRole::eNone);
const omni::fabric::Type inputs_roughness_factor(omni::fabric::BaseDataType::eFloat, 1, 0, omni::fabric::AttributeRole::eNone);
const omni::fabric::Type inputs_scale_float(omni::fabric::BaseDataType::eFloat, 1, 0, omni::fabric::AttributeRole::eNone);
const omni::fabric::Type inputs_scale_float2(omni::fabric::BaseDataType::eFloat, 2, 0, omni::fabric::AttributeRole::eNone);
const omni::fabric::Type inputs_scale_float3(omni::fabric::BaseDataType::eFloat, 3, 0, omni::fabric::AttributeRole::eNone);
const omni::fabric::Type inputs_scale_float4(omni::fabric::BaseDataType::eFloat, 4, 0, omni::fabric::AttributeRole::eNone);
const omni::fabric::Type inputs_texture(omni::fabric::BaseDataType::eAsset, 1, 0, omni::fabric::AttributeRole::eNone);
const omni::fabric::Type inputs_tex_coord_index(omni::fabric::BaseDataType::eInt, 1, 0, omni::fabric::AttributeRole::eNone);
const omni::fabric::Type inputs_tex_coord_offset(omni::fabric::BaseDataType::eFloat, 2, 0, omni::fabric::AttributeRole::eNone);
const omni::fabric::Type inputs_tex_coord_rotation(omni::fabric::BaseDataType::eFloat, 1, 0, omni::fabric::AttributeRole::eNone);
const omni::fabric::Type inputs_tex_coord_scale(omni::fabric::BaseDataType::eFloat, 2, 0, omni::fabric::AttributeRole::eNone);
const omni::fabric::Type inputs_tile_color(omni::fabric::BaseDataType::eFloat, 4, 0, omni::fabric::AttributeRole::eNone);
const omni::fabric::Type inputs_wrap_s(omni::fabric::BaseDataType::eInt, 1, 0, omni::fabric::AttributeRole::eNone);
const omni::fabric::Type inputs_wrap_t(omni::fabric::BaseDataType::eInt, 1, 0, omni::fabric::AttributeRole::eNone);
const omni::fabric::Type Material(omni::fabric::BaseDataType::eTag, 1, 0, omni::fabric::AttributeRole::ePrimTypeName);
const omni::fabric::Type material_binding(omni::fabric::BaseDataType::eRelationship, 1, 0, omni::fabric::AttributeRole::eNone);
const omni::fabric::Type Mesh(omni::fabric::BaseDataType::eTag, 1, 0, omni::fabric::AttributeRole::ePrimTypeName);
const omni::fabric::Type outputs_out(omni::fabric::BaseDataType::eToken, 1, 0, omni::fabric::AttributeRole::eNone);
const omni::fabric::Type points(omni::fabric::BaseDataType::eFloat, 3, 1, omni::fabric::AttributeRole::ePosition);
const omni::fabric::Type primvarInterpolations(omni::fabric::BaseDataType::eToken, 1, 1, omni::fabric::AttributeRole::eNone);
const omni::fabric::Type primvars(omni::fabric::BaseDataType::eToken, 1, 1, omni::fabric::AttributeRole::eNone);
const omni::fabric::Type primvars_COLOR_0(omni::fabric::BaseDataType::eFloat, 4, 1, omni::fabric::AttributeRole::eNone);
const omni::fabric::Type primvars_normals(omni::fabric::BaseDataType::eFloat, 3, 1, omni::fabric::AttributeRole::eNormal);
const omni::fabric::Type primvars_st(omni::fabric::BaseDataType::eFloat, 2, 1, omni::fabric::AttributeRole::eTexCoord);
const omni::fabric::Type primvars_vertexId(omni::fabric::BaseDataType::eFloat, 1, 1, omni::fabric::AttributeRole::eNone);
const omni::fabric::Type Shader(omni::fabric::BaseDataType::eTag, 1, 0, omni::fabric::AttributeRole::ePrimTypeName);
const omni::fabric::Type subdivisionScheme(omni::fabric::BaseDataType::eToken, 1, 0, omni::fabric::AttributeRole::eNone);
const omni::fabric::Type _cesium_gltfLocalToEcefTransform(omni::fabric::BaseDataType::eDouble, 16, 0, omni::fabric::AttributeRole::eMatrix);
const omni::fabric::Type _cesium_tilesetId(omni::fabric::BaseDataType::eInt64, 1, 0, omni::fabric::AttributeRole::eNone);
const omni::fabric::Type _materialSource(omni::fabric::BaseDataType::eRelationship, 1, 0, omni::fabric::AttributeRole::eNone);
const omni::fabric::Type _paramColorSpace(omni::fabric::BaseDataType::eToken, 1, 1, omni::fabric::AttributeRole::eNone);
const omni::fabric::Type _sdrMetadata(omni::fabric::BaseDataType::eToken, 1, 1, omni::fabric::AttributeRole::eNone);
const omni::fabric::Type _worldExtent(omni::fabric::BaseDataType::eDouble, 6, 0, omni::fabric::AttributeRole::eNone);
const omni::fabric::Type _worldOrientation(omni::fabric::BaseDataType::eFloat, 4, 0, omni::fabric::AttributeRole::eQuaternion);
const omni::fabric::Type _worldPosition(omni::fabric::BaseDataType::eDouble, 3, 0, omni::fabric::AttributeRole::eNone);
const omni::fabric::Type _worldScale(omni::fabric::BaseDataType::eFloat, 3, 0, omni::fabric::AttributeRole::eVector);
const omni::fabric::Type _worldVisibility(omni::fabric::BaseDataType::eBool, 1, 0, omni::fabric::AttributeRole::eNone);
}
// clang-format on
| 18,626 | C | 63.453287 | 140 | 0.727102 |
CesiumGS/cesium-omniverse/src/core/include/cesium/omniverse/CesiumIonServerManager.h | #pragma once
#include "cesium/omniverse/AssetTroubleshootingDetails.h"
#include "cesium/omniverse/SetDefaultTokenResult.h"
#include "cesium/omniverse/TokenTroubleshootingDetails.h"
#include <pxr/usd/sdf/path.h>
#include <memory>
namespace CesiumIonClient {
struct Token;
}
namespace cesium::omniverse {
class CesiumIonSession;
class Context;
class OmniIonServer;
class CesiumIonServerManager {
public:
CesiumIonServerManager(Context* pContext);
~CesiumIonServerManager() = default;
CesiumIonServerManager(const CesiumIonServerManager&) = delete;
CesiumIonServerManager& operator=(const CesiumIonServerManager&) = delete;
CesiumIonServerManager(CesiumIonServerManager&&) noexcept = delete;
CesiumIonServerManager& operator=(CesiumIonServerManager&&) noexcept = delete;
void onUpdateFrame();
void setProjectDefaultToken(const CesiumIonClient::Token& token);
void connectToIon();
[[nodiscard]] OmniIonServer* getCurrentIonServer() const;
[[nodiscard]] std::shared_ptr<CesiumIonSession> getCurrentIonSession() const;
[[nodiscard]] std::optional<CesiumIonClient::Token> getDefaultToken() const;
[[nodiscard]] SetDefaultTokenResult getSetDefaultTokenResult() const;
[[nodiscard]] bool isDefaultTokenSet() const;
void createToken(const std::string& name);
void selectToken(const CesiumIonClient::Token& token);
void specifyToken(const std::string& token);
[[nodiscard]] std::optional<AssetTroubleshootingDetails> getAssetTroubleshootingDetails() const;
[[nodiscard]] std::optional<TokenTroubleshootingDetails> getAssetTokenTroubleshootingDetails() const;
[[nodiscard]] std::optional<TokenTroubleshootingDetails> getDefaultTokenTroubleshootingDetails() const;
void updateTroubleshootingDetails(
const pxr::SdfPath& tilesetPath,
int64_t tilesetIonAssetId,
uint64_t tokenEventId,
uint64_t assetEventId);
void updateTroubleshootingDetails(
const pxr::SdfPath& tilesetPath,
[[maybe_unused]] int64_t tilesetIonAssetId,
int64_t rasterOverlayIonAssetId,
uint64_t tokenEventId,
uint64_t assetEventId);
void updateTokenTroubleshootingDetails(
int64_t assetId,
const std::string& token,
uint64_t eventId,
TokenTroubleshootingDetails& details);
void updateAssetTroubleshootingDetails(int64_t assetId, uint64_t eventId, AssetTroubleshootingDetails& details);
private:
Context* _pContext;
SetDefaultTokenResult _lastSetTokenResult;
std::optional<AssetTroubleshootingDetails> _assetTroubleshootingDetails;
std::optional<TokenTroubleshootingDetails> _assetTokenTroubleshootingDetails;
std::optional<TokenTroubleshootingDetails> _defaultTokenTroubleshootingDetails;
};
} // namespace cesium::omniverse
| 2,814 | C | 37.561643 | 116 | 0.762615 |
CesiumGS/cesium-omniverse/src/core/include/cesium/omniverse/FabricStatistics.h | #pragma once
#include <cstdint>
namespace cesium::omniverse {
struct FabricStatistics {
uint64_t materialsCapacity{0};
uint64_t materialsLoaded{0};
uint64_t geometriesCapacity{0};
uint64_t geometriesLoaded{0};
uint64_t geometriesRendered{0};
uint64_t trianglesLoaded{0};
uint64_t trianglesRendered{0};
};
} // namespace cesium::omniverse
| 370 | C | 19.61111 | 35 | 0.718919 |
CesiumGS/cesium-omniverse/src/core/include/cesium/omniverse/OmniRasterOverlay.h | #pragma once
#include "cesium/omniverse/OmniTileset.h"
#include <CesiumRasterOverlays/RasterOverlay.h>
#include <pxr/usd/sdf/path.h>
namespace CesiumRasterOverlays {
class RasterOverlay;
}
namespace cesium::omniverse {
class Context;
class OmniTileset;
enum class FabricOverlayRenderMethod;
class OmniRasterOverlay {
friend void OmniTileset::addRasterOverlayIfExists(const OmniRasterOverlay* pOverlay);
friend pxr::SdfPath
OmniTileset::getRasterOverlayPathIfExists(const CesiumRasterOverlays::RasterOverlay& rasterOverlay);
public:
OmniRasterOverlay(Context* pContext, const pxr::SdfPath& path);
virtual ~OmniRasterOverlay() = default;
OmniRasterOverlay(const OmniRasterOverlay&) = delete;
OmniRasterOverlay& operator=(const OmniRasterOverlay&) = delete;
OmniRasterOverlay(OmniRasterOverlay&&) noexcept = default;
OmniRasterOverlay& operator=(OmniRasterOverlay&&) noexcept = default;
[[nodiscard]] const pxr::SdfPath& getPath() const;
[[nodiscard]] bool getShowCreditsOnScreen() const;
[[nodiscard]] double getAlpha() const;
[[nodiscard]] FabricOverlayRenderMethod getOverlayRenderMethod() const;
[[nodiscard]] float getMaximumScreenSpaceError() const;
[[nodiscard]] int getMaximumTextureSize() const;
[[nodiscard]] int getMaximumSimultaneousTileLoads() const;
[[nodiscard]] int getSubTileCacheBytes() const;
[[nodiscard]] CesiumRasterOverlays::RasterOverlayOptions createRasterOverlayOptions() const;
void updateRasterOverlayOptions() const;
virtual void reload() = 0;
protected:
[[nodiscard]] virtual CesiumRasterOverlays::RasterOverlay* getRasterOverlay() const = 0;
Context* _pContext;
pxr::SdfPath _path;
private:
void setRasterOverlayOptionsFromUsd(CesiumRasterOverlays::RasterOverlayOptions& options) const;
};
} // namespace cesium::omniverse
| 1,865 | C | 33.555555 | 104 | 0.764611 |
CesiumGS/cesium-omniverse/src/core/include/cesium/omniverse/OmniIonRasterOverlay.h | #pragma once
#include "cesium/omniverse/OmniRasterOverlay.h"
#include <CesiumRasterOverlays/IonRasterOverlay.h>
#include <CesiumUtility/IntrusivePointer.h>
namespace CesiumIonClient {
struct Token;
}
namespace cesium::omniverse {
class OmniIonRasterOverlay final : public OmniRasterOverlay {
public:
OmniIonRasterOverlay(Context* pContext, const pxr::SdfPath& path);
~OmniIonRasterOverlay() override = default;
OmniIonRasterOverlay(const OmniIonRasterOverlay&) = delete;
OmniIonRasterOverlay& operator=(const OmniIonRasterOverlay&) = delete;
OmniIonRasterOverlay(OmniIonRasterOverlay&&) noexcept = default;
OmniIonRasterOverlay& operator=(OmniIonRasterOverlay&&) noexcept = default;
[[nodiscard]] int64_t getIonAssetId() const;
[[nodiscard]] CesiumIonClient::Token getIonAccessToken() const;
[[nodiscard]] std::string getIonApiUrl() const;
[[nodiscard]] pxr::SdfPath getResolvedIonServerPath() const;
[[nodiscard]] CesiumRasterOverlays::RasterOverlay* getRasterOverlay() const override;
void reload() override;
private:
CesiumUtility::IntrusivePointer<CesiumRasterOverlays::IonRasterOverlay> _pIonRasterOverlay;
};
} // namespace cesium::omniverse
| 1,212 | C | 33.657142 | 95 | 0.771452 |
CesiumGS/cesium-omniverse/src/core/include/cesium/omniverse/AssetRegistry.h | #pragma once
#include <pxr/usd/usd/common.h>
#include <vector>
#include <gsl/span>
namespace cesium::omniverse {
class Context;
class OmniCartographicPolygon;
class OmniData;
class OmniGeoreference;
class OmniGlobeAnchor;
class OmniRasterOverlay;
class OmniIonRasterOverlay;
class OmniIonServer;
class OmniPolygonRasterOverlay;
class OmniTileset;
class OmniWebMapServiceRasterOverlay;
class OmniTileMapServiceRasterOverlay;
class OmniWebMapTileServiceRasterOverlay;
struct Viewport;
enum AssetType {
DATA,
TILESET,
ION_RASTER_OVERLAY,
POLYGON_RASTER_OVERLAY,
WEB_MAP_SERVICE_RASTER_OVERLAY,
TILE_MAP_SERVICE_RASTER_OVERLAY,
WEB_MAP_TILE_SERVICE_RASTER_OVERLAY,
GEOREFERENCE,
GLOBE_ANCHOR,
ION_SERVER,
CARTOGRAPHIC_POLYGON,
OTHER,
};
class AssetRegistry {
public:
AssetRegistry(Context* pContext);
~AssetRegistry();
AssetRegistry(const AssetRegistry&) = delete;
AssetRegistry& operator=(const AssetRegistry&) = delete;
AssetRegistry(AssetRegistry&&) noexcept = delete;
AssetRegistry& operator=(AssetRegistry&&) noexcept = delete;
void onUpdateFrame(const gsl::span<const Viewport>& viewports, bool waitForLoadingTiles);
OmniData& addData(const pxr::SdfPath& path);
void removeData(const pxr::SdfPath& path);
[[nodiscard]] OmniData* getData(const pxr::SdfPath& path) const;
[[nodiscard]] OmniData* getFirstData() const;
OmniTileset& addTileset(const pxr::SdfPath& path);
void removeTileset(const pxr::SdfPath& path);
[[nodiscard]] OmniTileset* getTileset(const pxr::SdfPath& path) const;
[[nodiscard]] const std::vector<std::unique_ptr<OmniTileset>>& getTilesets() const;
OmniIonRasterOverlay& addIonRasterOverlay(const pxr::SdfPath& path);
void removeIonRasterOverlay(const pxr::SdfPath& path);
[[nodiscard]] OmniIonRasterOverlay* getIonRasterOverlay(const pxr::SdfPath& path) const;
[[nodiscard]] OmniIonRasterOverlay* getIonRasterOverlayByIonAssetId(int64_t ionAssetId) const;
[[nodiscard]] const std::vector<std::unique_ptr<OmniIonRasterOverlay>>& getIonRasterOverlays() const;
OmniPolygonRasterOverlay& addPolygonRasterOverlay(const pxr::SdfPath& path);
void removePolygonRasterOverlay(const pxr::SdfPath& path);
[[nodiscard]] OmniPolygonRasterOverlay* getPolygonRasterOverlay(const pxr::SdfPath& path) const;
[[nodiscard]] const std::vector<std::unique_ptr<OmniPolygonRasterOverlay>>& getPolygonRasterOverlays() const;
OmniWebMapServiceRasterOverlay& addWebMapServiceRasterOverlay(const pxr::SdfPath& path);
void removeWebMapServiceRasterOverlay(const pxr::SdfPath& path);
[[nodiscard]] OmniWebMapServiceRasterOverlay* getWebMapServiceRasterOverlay(const pxr::SdfPath& path) const;
OmniTileMapServiceRasterOverlay& addTileMapServiceRasterOverlay(const pxr::SdfPath& path);
void removeTileMapServiceRasterOverlay(const pxr::SdfPath& path);
[[nodiscard]] OmniTileMapServiceRasterOverlay* getTileMapServiceRasterOverlay(const pxr::SdfPath& path) const;
OmniWebMapTileServiceRasterOverlay& addWebMapTileServiceRasterOverlay(const pxr::SdfPath& path);
void removeWebMapTileServiceRasterOverlay(const pxr::SdfPath& path);
[[nodiscard]] OmniWebMapTileServiceRasterOverlay* getWebMapTileServiceRasterOverlay(const pxr::SdfPath& path) const;
[[nodiscard]] OmniRasterOverlay* getRasterOverlay(const pxr::SdfPath& path) const;
OmniGeoreference& addGeoreference(const pxr::SdfPath& path);
void removeGeoreference(const pxr::SdfPath& path);
[[nodiscard]] OmniGeoreference* getGeoreference(const pxr::SdfPath& path) const;
[[nodiscard]] const std::vector<std::unique_ptr<OmniGeoreference>>& getGeoreferences() const;
[[nodiscard]] OmniGeoreference* getFirstGeoreference() const;
OmniGlobeAnchor& addGlobeAnchor(const pxr::SdfPath& path);
void removeGlobeAnchor(const pxr::SdfPath& path);
[[nodiscard]] OmniGlobeAnchor* getGlobeAnchor(const pxr::SdfPath& path) const;
[[nodiscard]] const std::vector<std::unique_ptr<OmniGlobeAnchor>>& getGlobeAnchors() const;
OmniIonServer& addIonServer(const pxr::SdfPath& path);
void removeIonServer(const pxr::SdfPath& path);
[[nodiscard]] OmniIonServer* getIonServer(const pxr::SdfPath& path) const;
[[nodiscard]] const std::vector<std::unique_ptr<OmniIonServer>>& getIonServers() const;
[[nodiscard]] OmniIonServer* getFirstIonServer() const;
OmniCartographicPolygon& addCartographicPolygon(const pxr::SdfPath& path);
void removeCartographicPolygon(const pxr::SdfPath& path);
[[nodiscard]] OmniCartographicPolygon* getCartographicPolygon(const pxr::SdfPath& path) const;
[[nodiscard]] const std::vector<std::unique_ptr<OmniCartographicPolygon>>& getCartographicPolygons() const;
[[nodiscard]] AssetType getAssetType(const pxr::SdfPath& path) const;
[[nodiscard]] bool hasAsset(const pxr::SdfPath& path) const;
void clear();
private:
Context* _pContext;
std::vector<std::unique_ptr<OmniData>> _datas;
std::vector<std::unique_ptr<OmniTileset>> _tilesets;
std::vector<std::unique_ptr<OmniIonRasterOverlay>> _ionRasterOverlays;
std::vector<std::unique_ptr<OmniPolygonRasterOverlay>> _polygonRasterOverlays;
std::vector<std::unique_ptr<OmniWebMapServiceRasterOverlay>> _webMapServiceRasterOverlays;
std::vector<std::unique_ptr<OmniTileMapServiceRasterOverlay>> _tileMapServiceRasterOverlays;
std::vector<std::unique_ptr<OmniWebMapTileServiceRasterOverlay>> _webMapTileServiceRasterOverlays;
std::vector<std::unique_ptr<OmniGeoreference>> _georeferences;
std::vector<std::unique_ptr<OmniGlobeAnchor>> _globeAnchors;
std::vector<std::unique_ptr<OmniIonServer>> _ionServers;
std::vector<std::unique_ptr<OmniCartographicPolygon>> _cartographicPolygons;
int64_t _tilesetId{0};
};
} // namespace cesium::omniverse
| 5,880 | C | 43.55303 | 120 | 0.763095 |
CesiumGS/cesium-omniverse/src/core/include/cesium/omniverse/MetadataUtil.h | #pragma once
#include "cesium/omniverse/Context.h"
#include "cesium/omniverse/DataType.h"
#include "cesium/omniverse/FabricPropertyInfo.h"
#include "cesium/omniverse/GltfUtil.h"
#include "cesium/omniverse/Logger.h"
#include <CesiumGltf/ExtensionExtMeshFeatures.h>
#include <CesiumGltf/ExtensionMeshPrimitiveExtStructuralMetadata.h>
#include <CesiumGltf/ExtensionModelExtStructuralMetadata.h>
#include <CesiumGltf/PropertyAttribute.h>
#include <CesiumGltf/PropertyAttributeView.h>
#include <CesiumGltf/PropertyTableView.h>
#include <CesiumGltf/PropertyTexture.h>
#include <CesiumGltf/PropertyTextureView.h>
namespace cesium::omniverse {
struct FabricPropertyDescriptor;
struct FabricTextureData;
} // namespace cesium::omniverse
namespace cesium::omniverse::MetadataUtil {
template <typename Callback, typename UnsupportedCallback>
void forEachPropertyAttributeProperty(
const Context& context,
const CesiumGltf::Model& model,
const CesiumGltf::MeshPrimitive& primitive,
Callback&& callback,
const UnsupportedCallback& unsupportedCallback) {
const auto pStructuralMetadataModel = model.getExtension<CesiumGltf::ExtensionModelExtStructuralMetadata>();
if (!pStructuralMetadataModel) {
return;
}
const auto pStructuralMetadataPrimitive =
primitive.getExtension<CesiumGltf::ExtensionMeshPrimitiveExtStructuralMetadata>();
if (!pStructuralMetadataPrimitive) {
return;
}
for (const auto& propertyAttributeIndex : pStructuralMetadataPrimitive->propertyAttributes) {
const auto pPropertyAttribute =
model.getSafe(&pStructuralMetadataModel->propertyAttributes, static_cast<int32_t>(propertyAttributeIndex));
if (!pPropertyAttribute) {
context.getLogger()->warn("Property attribute index {} is out of range.", propertyAttributeIndex);
continue;
}
const auto propertyAttributeView = CesiumGltf::PropertyAttributeView(model, *pPropertyAttribute);
if (propertyAttributeView.status() != CesiumGltf::PropertyAttributeViewStatus::Valid) {
context.getLogger()->warn(
"Property attribute is invalid and will be ignored. Status code: {}",
static_cast<int>(propertyAttributeView.status()));
continue;
}
propertyAttributeView.forEachProperty(
primitive,
[&context,
callback = std::forward<Callback>(callback),
&unsupportedCallback,
&propertyAttributeView,
&pStructuralMetadataModel,
&pPropertyAttribute](const std::string& propertyId, const auto& propertyAttributePropertyView) {
if (propertyAttributePropertyView.status() != CesiumGltf::PropertyAttributePropertyViewStatus::Valid) {
unsupportedCallback(
propertyId,
fmt::format(
"Property \"{}\" is invalid and will be ignored. Status code: {}",
propertyId,
static_cast<int>(propertyAttributePropertyView.status())));
return;
}
const auto& schema = pStructuralMetadataModel->schema;
if (!schema.has_value()) {
unsupportedCallback(
propertyId, fmt::format("No schema found. Property \"{}\" will be ignored.", propertyId));
return;
}
const auto pClassDefinition = propertyAttributeView.getClass();
if (!pClassDefinition) {
unsupportedCallback(
propertyId, fmt::format("No class found. Property \"{}\" will be ignored.", propertyId));
return;
}
const auto pClassProperty = propertyAttributeView.getClassProperty(propertyId);
if (!pClassProperty) {
unsupportedCallback(
propertyId,
fmt::format("No class property found. Property \"{}\" will be ignored.", propertyId));
return;
}
const auto& propertyAttributeProperty = pPropertyAttribute->properties.at(propertyId);
callback(
propertyId,
schema.value(),
*pClassDefinition,
*pClassProperty,
*pPropertyAttribute,
propertyAttributeProperty,
propertyAttributeView,
propertyAttributePropertyView);
});
}
}
template <typename Callback, typename UnsupportedCallback>
void forEachPropertyTextureProperty(
const Context& context,
const CesiumGltf::Model& model,
const CesiumGltf::MeshPrimitive& primitive,
Callback&& callback,
const UnsupportedCallback& unsupportedCallback) {
const auto pStructuralMetadataModel = model.getExtension<CesiumGltf::ExtensionModelExtStructuralMetadata>();
if (!pStructuralMetadataModel) {
return;
}
const auto pStructuralMetadataPrimitive =
primitive.getExtension<CesiumGltf::ExtensionMeshPrimitiveExtStructuralMetadata>();
if (!pStructuralMetadataPrimitive) {
return;
}
for (const auto& propertyTextureIndex : pStructuralMetadataPrimitive->propertyTextures) {
const auto pPropertyTexture =
model.getSafe(&pStructuralMetadataModel->propertyTextures, static_cast<int32_t>(propertyTextureIndex));
if (!pPropertyTexture) {
context.getLogger()->warn(fmt::format("Property texture index {} is out of range.", propertyTextureIndex));
continue;
}
const auto propertyTextureView = CesiumGltf::PropertyTextureView(model, *pPropertyTexture);
if (propertyTextureView.status() != CesiumGltf::PropertyTextureViewStatus::Valid) {
context.getLogger()->warn(
"Property texture is invalid and will be ignored. Status code: {}",
static_cast<int>(propertyTextureView.status()));
continue;
}
propertyTextureView.forEachProperty(
[&context,
callback = std::forward<Callback>(callback),
&unsupportedCallback,
&propertyTextureView,
&pStructuralMetadataModel,
&pPropertyTexture](const std::string& propertyId, const auto& propertyTexturePropertyView) {
if (propertyTexturePropertyView.status() != CesiumGltf::PropertyTexturePropertyViewStatus::Valid) {
unsupportedCallback(
propertyId,
fmt::format(
"Property \"{}\" is invalid and will be ignored. Status code: {}",
propertyId,
static_cast<int>(propertyTexturePropertyView.status())));
return;
}
const auto& schema = pStructuralMetadataModel->schema;
if (!schema.has_value()) {
unsupportedCallback(
propertyId, fmt::format("No schema found. Property \"{}\" will be ignored.", propertyId));
return;
}
const auto pClassDefinition = propertyTextureView.getClass();
if (!pClassDefinition) {
unsupportedCallback(
propertyId, fmt::format("No class found. Property \"{}\" will be ignored.", propertyId));
return;
}
const auto pClassProperty = propertyTextureView.getClassProperty(propertyId);
if (!pClassProperty) {
unsupportedCallback(
propertyId,
fmt::format("No class property found. Property \"{}\" will be ignored.", propertyId));
return;
}
if (!propertyTexturePropertyView.getImage()) {
unsupportedCallback(
propertyId, fmt::format("No image found. Property \"{}\" will be ignored.", propertyId));
return;
}
const auto& propertyTextureProperty = pPropertyTexture->properties.at(propertyId);
callback(
propertyId,
schema.value(),
*pClassDefinition,
*pClassProperty,
*pPropertyTexture,
propertyTextureProperty,
propertyTextureView,
propertyTexturePropertyView);
});
}
}
template <typename Callback, typename UnsupportedCallback>
void forEachPropertyTableProperty(
const Context& context,
const CesiumGltf::Model& model,
const CesiumGltf::MeshPrimitive& primitive,
Callback&& callback,
const UnsupportedCallback& unsupportedCallback) {
const auto pStructuralMetadataModel = model.getExtension<CesiumGltf::ExtensionModelExtStructuralMetadata>();
if (!pStructuralMetadataModel) {
return;
}
const auto pMeshFeatures = primitive.getExtension<CesiumGltf::ExtensionExtMeshFeatures>();
if (!pMeshFeatures) {
return;
}
for (uint64_t i = 0; i < pMeshFeatures->featureIds.size(); ++i) {
const auto featureIdSetIndex = i;
const auto& featureId = pMeshFeatures->featureIds[featureIdSetIndex];
if (featureId.propertyTable.has_value()) {
const auto pPropertyTable = model.getSafe(
&pStructuralMetadataModel->propertyTables, static_cast<int32_t>(featureId.propertyTable.value()));
if (!pPropertyTable) {
context.getLogger()->warn(
fmt::format("Property table index {} is out of range.", featureId.propertyTable.value()));
continue;
}
const auto propertyTableView = CesiumGltf::PropertyTableView(model, *pPropertyTable);
if (propertyTableView.status() != CesiumGltf::PropertyTableViewStatus::Valid) {
context.getLogger()->warn(
"Property table is invalid and will be ignored. Status code: {}",
static_cast<int>(propertyTableView.status()));
continue;
}
propertyTableView.forEachProperty(
[&context,
callback = std::forward<Callback>(callback),
&unsupportedCallback,
&propertyTableView,
&pStructuralMetadataModel,
&pPropertyTable,
featureIdSetIndex](const std::string& propertyId, const auto& propertyTablePropertyView) {
if (propertyTablePropertyView.status() != CesiumGltf::PropertyTablePropertyViewStatus::Valid) {
unsupportedCallback(
propertyId,
fmt::format(
"Property \"{}\" is invalid and will be ignored. Status code: {}",
propertyId,
static_cast<int>(propertyTablePropertyView.status())));
return;
}
const auto& schema = pStructuralMetadataModel->schema;
if (!schema.has_value()) {
unsupportedCallback(
propertyId, fmt::format("No schema found. Property \"{}\" will be ignored.", propertyId));
return;
}
const auto pClassDefinition = propertyTableView.getClass();
if (!pClassDefinition) {
unsupportedCallback(
propertyId, fmt::format("No class found. Property \"{}\" will be ignored.", propertyId));
return;
}
const auto pClassProperty = propertyTableView.getClassProperty(propertyId);
if (!pClassProperty) {
unsupportedCallback(
propertyId,
fmt::format("No class property found. Property \"{}\" will be ignored.", propertyId));
return;
}
const auto& propertyTableProperty = pPropertyTable->properties.at(propertyId);
callback(
propertyId,
schema.value(),
*pClassDefinition,
*pClassProperty,
*pPropertyTable,
propertyTableProperty,
propertyTableView,
propertyTablePropertyView,
featureIdSetIndex);
});
}
}
}
template <typename Callback, typename UnsupportedCallback>
void forEachStyleablePropertyAttributeProperty(
const Context& context,
const CesiumGltf::Model& model,
const CesiumGltf::MeshPrimitive& primitive,
Callback&& callback,
const UnsupportedCallback& unsupportedCallback) {
forEachPropertyAttributeProperty(
context,
model,
primitive,
[&context, callback = std::forward<Callback>(callback), &unsupportedCallback](
const std::string& propertyId,
[[maybe_unused]] const CesiumGltf::Schema& schema,
[[maybe_unused]] const CesiumGltf::Class& classDefinition,
[[maybe_unused]] const CesiumGltf::ClassProperty& classProperty,
[[maybe_unused]] const CesiumGltf::PropertyAttribute& propertyAttribute,
const CesiumGltf::PropertyAttributeProperty& propertyAttributeProperty,
[[maybe_unused]] const CesiumGltf::PropertyAttributeView& propertyAttributeView,
const auto& propertyAttributePropertyView) {
using RawType = decltype(propertyAttributePropertyView.getRaw(0));
using TransformedType = typename std::decay_t<decltype(propertyAttributePropertyView.get(0))>::value_type;
constexpr auto type = DataTypeUtil::getTypeReverse<RawType, TransformedType>();
if constexpr (DataTypeUtil::isMatrix<type>()) {
unsupportedCallback(
propertyId,
fmt::format(
"Matrix properties are not supported for styling. Property \"{}\" will be ignored.",
propertyId));
return;
} else {
const auto& attribute = propertyAttributeProperty.attribute;
// For some reason the static cast is needed in MSVC
const auto propertyInfo = FabricPropertyInfo<static_cast<cesium::omniverse::DataType>(type)>{
propertyAttributePropertyView.offset(),
propertyAttributePropertyView.scale(),
propertyAttributePropertyView.min(),
propertyAttributePropertyView.max(),
propertyAttributePropertyView.required(),
propertyAttributePropertyView.noData(),
propertyAttributePropertyView.defaultValue(),
};
const auto property =
FabricPropertyAttributePropertyInfo<static_cast<cesium::omniverse::DataType>(type)>{
attribute,
propertyInfo,
};
callback(propertyId, propertyAttributePropertyView, property);
}
},
unsupportedCallback);
}
template <typename Callback, typename UnsupportedCallback>
void forEachStyleablePropertyTextureProperty(
const Context& context,
const CesiumGltf::Model& model,
const CesiumGltf::MeshPrimitive& primitive,
Callback&& callback,
const UnsupportedCallback& unsupportedCallback) {
forEachPropertyTextureProperty(
context,
model,
primitive,
[&context, callback = std::forward<Callback>(callback), &unsupportedCallback, &model](
const std::string& propertyId,
[[maybe_unused]] const CesiumGltf::Schema& schema,
[[maybe_unused]] const CesiumGltf::Class& classDefinition,
[[maybe_unused]] const CesiumGltf::ClassProperty& classProperty,
[[maybe_unused]] const CesiumGltf::PropertyTexture& propertyTexture,
const CesiumGltf::PropertyTextureProperty& propertyTextureProperty,
[[maybe_unused]] const CesiumGltf::PropertyTextureView& propertyTextureView,
const auto& propertyTexturePropertyView) {
using RawType = decltype(propertyTexturePropertyView.getRaw(0.0, 0.0));
using TransformedType =
typename std::decay_t<decltype(propertyTexturePropertyView.get(0.0, 0.0))>::value_type;
constexpr auto IsArray = HAS_MEMBER(RawType, size());
if constexpr (IsArray) {
unsupportedCallback(
propertyId,
fmt::format(
"Array properties are not supported for styling. Property \"{}\" will be ignored.",
propertyId));
return;
} else {
constexpr auto type = DataTypeUtil::getTypeReverse<RawType, TransformedType>();
if constexpr (DataTypeUtil::getComponentByteLength<type>() > 1) {
unsupportedCallback(
propertyId,
fmt::format(
"Only 8-bit per-component property texture properties are supported for styling. Property "
"\"{}\" will be ignored.",
propertyId));
return;
} else {
const auto textureInfo = GltfUtil::getPropertyTexturePropertyInfo(model, propertyTextureProperty);
if (textureInfo.channels.size() != DataTypeUtil::getComponentCount<type>()) {
unsupportedCallback(
propertyId,
fmt::format(
"Properties with components that are packed across multiple texture channels are not "
"supported for styling. Property \"{}\" will be ignored.",
propertyId));
return;
}
if (textureInfo.channels.size() > 4) {
unsupportedCallback(
propertyId,
fmt::format(
"Properties with more than four channels are not supported for styling. Property "
"\"{}\" will be ignored.",
propertyId));
return;
}
const auto propertyInfo = FabricPropertyInfo<static_cast<cesium::omniverse::DataType>(type)>{
propertyTexturePropertyView.offset(),
propertyTexturePropertyView.scale(),
propertyTexturePropertyView.min(),
propertyTexturePropertyView.max(),
propertyTexturePropertyView.required(),
propertyTexturePropertyView.noData(),
propertyTexturePropertyView.defaultValue(),
};
const auto property =
FabricPropertyTexturePropertyInfo<static_cast<cesium::omniverse::DataType>(type)>{
textureInfo,
static_cast<uint64_t>(propertyTextureProperty.index),
propertyInfo,
};
callback(propertyId, propertyTexturePropertyView, property);
}
}
},
unsupportedCallback);
}
template <typename Callback, typename UnsupportedCallback>
void forEachStyleablePropertyTableProperty(
const Context& context,
const CesiumGltf::Model& model,
const CesiumGltf::MeshPrimitive& primitive,
Callback&& callback,
const UnsupportedCallback& unsupportedCallback) {
forEachPropertyTableProperty(
context,
model,
primitive,
[&context, callback = std::forward<Callback>(callback), &unsupportedCallback](
const std::string& propertyId,
[[maybe_unused]] const CesiumGltf::Schema& schema,
[[maybe_unused]] const CesiumGltf::Class& classDefinition,
[[maybe_unused]] const CesiumGltf::ClassProperty& classProperty,
[[maybe_unused]] const CesiumGltf::PropertyTable& propertyTable,
[[maybe_unused]] const CesiumGltf::PropertyTableProperty& propertyTableProperty,
[[maybe_unused]] const CesiumGltf::PropertyTableView& propertyTableView,
const auto& propertyTablePropertyView,
uint64_t featureIdSetIndex) {
using RawType = decltype(propertyTablePropertyView.getRaw(0));
using TransformedType = typename std::decay_t<decltype(propertyTablePropertyView.get(0))>::value_type;
constexpr auto IsArray = HAS_MEMBER(RawType, size());
constexpr auto IsBoolean = std::is_same_v<RawType, bool>;
constexpr auto IsString = std::is_same_v<RawType, std::string_view>;
if constexpr (IsArray) {
unsupportedCallback(
propertyId,
fmt::format(
"Array properties are not supported for styling. Property \"{}\" will be ignored.",
propertyId));
return;
} else if constexpr (IsBoolean) {
unsupportedCallback(
propertyId,
fmt::format(
"Boolean properties are not supported for styling. Property \"{}\" will be ignored.",
propertyId));
return;
} else if constexpr (IsString) {
unsupportedCallback(
propertyId,
fmt::format(
"String properties are not supported for styling. Property \"{}\" will be ignored.",
propertyId));
return;
} else {
constexpr auto type = DataTypeUtil::getTypeReverse<RawType, TransformedType>();
constexpr auto unnormalizedComponentType = DataTypeUtil::getUnnormalizedComponentType<type>();
if constexpr (DataTypeUtil::isMatrix<type>()) {
unsupportedCallback(
propertyId,
fmt::format(
"Matrix properties are not supported for styling. Property \"{}\" will be ignored.",
propertyId));
return;
} else if constexpr (unnormalizedComponentType == DataType::UINT32) {
unsupportedCallback(
propertyId,
fmt::format(
"UINT32 properties are not supported for styling due to potential precision loss. Property "
"\"{}\" will be ignored.",
propertyId));
return;
} else if constexpr (unnormalizedComponentType == DataType::UINT64) {
unsupportedCallback(
propertyId,
fmt::format(
"UINT64 properties are not supported for styling due to potential precision loss. Property "
"\"{}\" will be ignored.",
propertyId));
return;
} else if constexpr (unnormalizedComponentType == DataType::INT64) {
unsupportedCallback(
propertyId,
fmt::format(
"INT64 properties are not supported for styling due to potential precision loss. Property "
"\"{}\" will be ignored.",
propertyId));
return;
} else {
if constexpr (unnormalizedComponentType == DataType::FLOAT64) {
unsupportedCallback(
propertyId,
fmt::format(
"64-bit float properties are converted to 32-bit floats for styling. Some precision "
"loss "
"may occur for property \"{}\".",
propertyId));
}
const auto propertyInfo = FabricPropertyInfo<static_cast<cesium::omniverse::DataType>(type)>{
propertyTablePropertyView.offset(),
propertyTablePropertyView.scale(),
propertyTablePropertyView.min(),
propertyTablePropertyView.max(),
propertyTablePropertyView.required(),
propertyTablePropertyView.noData(),
propertyTablePropertyView.defaultValue(),
};
const auto property =
FabricPropertyTablePropertyInfo<static_cast<cesium::omniverse::DataType>(type)>{
featureIdSetIndex,
propertyInfo,
};
callback(propertyId, propertyTablePropertyView, property);
}
}
},
unsupportedCallback);
}
std::tuple<std::vector<FabricPropertyDescriptor>, std::map<std::string, std::string>> getStyleableProperties(
const Context& context,
const CesiumGltf::Model& model,
const CesiumGltf::MeshPrimitive& primitive);
std::vector<const CesiumGltf::ImageCesium*> getPropertyTextureImages(
const Context& context,
const CesiumGltf::Model& model,
const CesiumGltf::MeshPrimitive& primitive);
std::unordered_map<uint64_t, uint64_t> getPropertyTextureIndexMapping(
const Context& context,
const CesiumGltf::Model& model,
const CesiumGltf::MeshPrimitive& primitive);
std::vector<FabricTextureData> encodePropertyTables(
const Context& context,
const CesiumGltf::Model& model,
const CesiumGltf::MeshPrimitive& primitive);
uint64_t getPropertyTableTextureCount(
const Context& context,
const CesiumGltf::Model& model,
const CesiumGltf::MeshPrimitive& primitive);
} // namespace cesium::omniverse::MetadataUtil
| 26,987 | C | 44.130435 | 120 | 0.561974 |
CesiumGS/cesium-omniverse/src/core/include/cesium/omniverse/SettingsWrapper.h | #pragma once
#include <cstdint>
#include <string>
#include <vector>
namespace cesium::omniverse::Settings {
struct AccessToken {
std::string ionApiUrl;
std::string accessToken;
};
std::vector<AccessToken> getAccessTokens();
void setAccessToken(const AccessToken& accessToken);
void removeAccessToken(const std::string& ionApiUrl);
void clearTokens();
uint64_t getMaxCacheItems();
} // namespace cesium::omniverse::Settings
| 437 | C | 18.90909 | 53 | 0.757437 |
CesiumGS/cesium-omniverse/src/core/include/cesium/omniverse/FabricRenderResources.h | #pragma once
#include <glm/glm.hpp>
#include <vector>
namespace cesium::omniverse {
struct FabricMesh;
struct FabricRenderResources {
FabricRenderResources() = default;
~FabricRenderResources() = default;
FabricRenderResources(const FabricRenderResources&) = delete;
FabricRenderResources& operator=(const FabricRenderResources&) = delete;
FabricRenderResources(FabricRenderResources&&) noexcept = default;
FabricRenderResources& operator=(FabricRenderResources&&) noexcept = default;
std::vector<FabricMesh> fabricMeshes;
};
} // namespace cesium::omniverse
| 594 | C | 24.869564 | 81 | 0.762626 |
CesiumGS/cesium-omniverse/src/core/include/cesium/omniverse/UsdUtil.h | #pragma once
#include "CesiumUsdSchemas/rasterOverlay.h"
#include <glm/fwd.hpp>
#include <pxr/base/gf/declare.h>
#include <pxr/usd/usd/common.h>
#include <pxr/usd/usdGeom/basisCurves.h>
#include <pxr/usd/usdGeom/xformOp.h>
PXR_NAMESPACE_OPEN_SCOPE
class CesiumData;
class CesiumGeoreference;
class CesiumGlobeAnchorAPI;
class CesiumRasterOverlay;
class CesiumIonRasterOverlay;
class CesiumIonServer;
class CesiumPolygonRasterOverlay;
class CesiumSession;
class CesiumTileset;
class CesiumWebMapServiceRasterOverlay;
class CesiumTileMapServiceRasterOverlay;
class CesiumWebMapTileServiceRasterOverlay;
class UsdGeomBasisCurves;
class UsdGeomXformable;
class UsdGeomXformOp;
class UsdShadeShader;
PXR_NAMESPACE_CLOSE_SCOPE
namespace Cesium3DTilesSelection {
class ViewState;
}
namespace CesiumGeospatial {
class Cartographic;
class Ellipsoid;
class LocalHorizontalCoordinateSystem;
} // namespace CesiumGeospatial
namespace cesium::omniverse {
class Context;
struct Viewport;
} // namespace cesium::omniverse
namespace cesium::omniverse::MathUtil {
enum class EulerAngleOrder;
}
namespace cesium::omniverse::UsdUtil {
glm::dvec3 usdToGlmVector(const pxr::GfVec3d& vector);
glm::fvec3 usdToGlmVector(const pxr::GfVec3f& vector);
glm::dmat4 usdToGlmMatrix(const pxr::GfMatrix4d& matrix);
glm::dquat usdToGlmQuat(const pxr::GfQuatd& quat);
glm::fquat usdToGlmQuat(const pxr::GfQuatf& quat);
std::array<glm::dvec3, 2> usdToGlmExtent(const pxr::GfRange3d& extent);
pxr::GfVec3d glmToUsdVector(const glm::dvec3& vector);
pxr::GfVec2f glmToUsdVector(const glm::fvec2& vector);
pxr::GfVec3f glmToUsdVector(const glm::fvec3& vector);
pxr::GfVec4f glmToUsdVector(const glm::fvec4& vector);
pxr::GfRange3d glmToUsdExtent(const std::array<glm::dvec3, 2>& extent);
pxr::GfQuatd glmToUsdQuat(const glm::dquat& quat);
pxr::GfQuatf glmToUsdQuat(const glm::fquat& quat);
pxr::GfMatrix4d glmToUsdMatrix(const glm::dmat4& matrix);
glm::dmat4 computePrimLocalToWorldTransform(const pxr::UsdStageWeakPtr& pStage, const pxr::SdfPath& path);
glm::dmat4 computePrimWorldToLocalTransform(const pxr::UsdStageWeakPtr& pStage, const pxr::SdfPath& path);
glm::dmat4 computeEcefToStageTransform(const Context& context, const pxr::SdfPath& georeferencePath);
glm::dmat4 computeEcefToPrimWorldTransform(
const Context& context,
const pxr::SdfPath& georeferencePath,
const pxr::SdfPath& primPath);
glm::dmat4 computePrimWorldToEcefTransform(
const Context& context,
const pxr::SdfPath& georeferencePath,
const pxr::SdfPath& primPath);
glm::dmat4 computeEcefToPrimLocalTransform(
const Context& context,
const pxr::SdfPath& georeferencePath,
const pxr::SdfPath& primPath);
glm::dmat4 computePrimLocalToEcefTransform(
const Context& context,
const pxr::SdfPath& georeferencePath,
const pxr::SdfPath& primPath);
CesiumGeospatial::LocalHorizontalCoordinateSystem computeLocalCoordinateSystem(
const pxr::UsdStageWeakPtr& pStage,
const CesiumGeospatial::Cartographic& origin,
const CesiumGeospatial::Ellipsoid& ellipsoid);
Cesium3DTilesSelection::ViewState computeViewState(
const Context& context,
const pxr::SdfPath& georeferencePath,
const pxr::SdfPath& primPath,
const Viewport& viewport);
bool primExists(const pxr::UsdStageWeakPtr& pStage, const pxr::SdfPath& path);
bool isSchemaValid(const pxr::UsdSchemaBase& schema);
bool isPrimVisible(const pxr::UsdStageWeakPtr& pStage, const pxr::SdfPath& path);
const std::string& getName(const pxr::UsdStageWeakPtr& pStage, const pxr::SdfPath& path);
pxr::TfToken getUsdUpAxis(const pxr::UsdStageWeakPtr& pStage);
double getUsdMetersPerUnit(const pxr::UsdStageWeakPtr& pStage);
pxr::SdfPath getRootPath(const pxr::UsdStageWeakPtr& pStage);
pxr::SdfPath
makeUniquePath(const pxr::UsdStageWeakPtr& pStage, const pxr::SdfPath& parentPath, const std::string& name);
std::string getSafeName(const std::string& name);
pxr::TfToken getDynamicTextureProviderAssetPathToken(const std::string_view& name);
pxr::CesiumData defineCesiumData(const pxr::UsdStageWeakPtr& pStage, const pxr::SdfPath& path);
pxr::CesiumTileset defineCesiumTileset(const pxr::UsdStageWeakPtr& pStage, const pxr::SdfPath& path);
pxr::CesiumIonRasterOverlay defineCesiumIonRasterOverlay(const pxr::UsdStageWeakPtr& pStage, const pxr::SdfPath& path);
pxr::CesiumPolygonRasterOverlay
defineCesiumPolygonRasterOverlay(const pxr::UsdStageWeakPtr& pStage, const pxr::SdfPath& path);
pxr::CesiumGeoreference defineCesiumGeoreference(const pxr::UsdStageWeakPtr& pStage, const pxr::SdfPath& path);
pxr::CesiumIonServer defineCesiumIonServer(const pxr::UsdStageWeakPtr& pStage, const pxr::SdfPath& path);
pxr::CesiumGlobeAnchorAPI applyCesiumGlobeAnchor(const pxr::UsdStageWeakPtr& pStage, const pxr::SdfPath& path);
pxr::CesiumSession defineCesiumSession(const pxr::UsdStageWeakPtr& pStage, const pxr::SdfPath& path);
pxr::CesiumData getCesiumData(const pxr::UsdStageWeakPtr& pStage, const pxr::SdfPath& path);
pxr::CesiumTileset getCesiumTileset(const pxr::UsdStageWeakPtr& pStage, const pxr::SdfPath& path);
pxr::CesiumRasterOverlay getCesiumRasterOverlay(const pxr::UsdStageWeakPtr& pStage, const pxr::SdfPath& path);
pxr::CesiumIonRasterOverlay getCesiumIonRasterOverlay(const pxr::UsdStageWeakPtr& pStage, const pxr::SdfPath& path);
pxr::CesiumPolygonRasterOverlay
getCesiumPolygonRasterOverlay(const pxr::UsdStageWeakPtr& pStage, const pxr::SdfPath& path);
pxr::CesiumWebMapServiceRasterOverlay
getCesiumWebMapServiceRasterOverlay(const pxr::UsdStageWeakPtr& pStage, const pxr::SdfPath& path);
pxr::CesiumTileMapServiceRasterOverlay
getCesiumTileMapServiceRasterOverlay(const pxr::UsdStageWeakPtr& pStage, const pxr::SdfPath& path);
pxr::CesiumWebMapTileServiceRasterOverlay
getCesiumWebMapTileServiceRasterOverlay(const pxr::UsdStageWeakPtr& pStage, const pxr::SdfPath& path);
pxr::CesiumGeoreference getCesiumGeoreference(const pxr::UsdStageWeakPtr& pStage, const pxr::SdfPath& path);
pxr::CesiumGlobeAnchorAPI getCesiumGlobeAnchor(const pxr::UsdStageWeakPtr& pStage, const pxr::SdfPath& path);
pxr::CesiumIonServer getCesiumIonServer(const pxr::UsdStageWeakPtr& pStage, const pxr::SdfPath& path);
pxr::UsdGeomBasisCurves getCesiumCartographicPolygon(const pxr::UsdStageWeakPtr& pStage, const pxr::SdfPath& path);
pxr::UsdShadeShader getUsdShader(const pxr::UsdStageWeakPtr& pStage, const pxr::SdfPath& path);
pxr::UsdGeomBasisCurves getUsdBasisCurves(const pxr::UsdStageWeakPtr& pStage, const pxr::SdfPath& path);
pxr::CesiumSession getOrCreateCesiumSession(const pxr::UsdStageWeakPtr& pStage);
bool isCesiumData(const pxr::UsdStageWeakPtr& pStage, const pxr::SdfPath& path);
bool isCesiumTileset(const pxr::UsdStageWeakPtr& pStage, const pxr::SdfPath& path);
bool isCesiumRasterOverlay(const pxr::UsdStageWeakPtr& pStage, const pxr::SdfPath& path);
bool isCesiumIonRasterOverlay(const pxr::UsdStageWeakPtr& pStage, const pxr::SdfPath& path);
bool isCesiumPolygonRasterOverlay(const pxr::UsdStageWeakPtr& pStage, const pxr::SdfPath& path);
bool isCesiumWebMapServiceRasterOverlay(const pxr::UsdStageWeakPtr& pStage, const pxr::SdfPath& path);
bool isCesiumTileMapServiceRasterOverlay(const pxr::UsdStageWeakPtr& pStage, const pxr::SdfPath& path);
bool isCesiumWebMapTileServiceRasterOverlay(const pxr::UsdStageWeakPtr& pStage, const pxr::SdfPath& path);
bool isCesiumGeoreference(const pxr::UsdStageWeakPtr& pStage, const pxr::SdfPath& path);
bool isCesiumIonServer(const pxr::UsdStageWeakPtr& pStage, const pxr::SdfPath& path);
bool isCesiumCartographicPolygon(const pxr::UsdStageWeakPtr& pStage, const pxr::SdfPath& path);
bool isCesiumSession(const pxr::UsdStageWeakPtr& pStage, const pxr::SdfPath& path);
bool hasCesiumGlobeAnchor(const pxr::UsdStageWeakPtr& pStage, const pxr::SdfPath& path);
bool isUsdShader(const pxr::UsdStageWeakPtr& pStage, const pxr::SdfPath& path);
bool isUsdMaterial(const pxr::UsdStageWeakPtr& pStage, const pxr::SdfPath& path);
glm::dvec3 getTranslate(const pxr::UsdGeomXformOp& translateOp);
glm::dvec3 getRotate(const pxr::UsdGeomXformOp& rotateOp);
glm::dquat getOrient(const pxr::UsdGeomXformOp& orientOp);
glm::dvec3 getScale(const pxr::UsdGeomXformOp& scaleOp);
void setTranslate(pxr::UsdGeomXformOp& translateOp, const glm::dvec3& translate);
void setRotate(pxr::UsdGeomXformOp& rotateOp, const glm::dvec3& rotate);
void setOrient(pxr::UsdGeomXformOp& orientOp, const glm::dquat& orient);
void setScale(pxr::UsdGeomXformOp& scaleOp, const glm::dvec3& scale);
struct TranslateRotateScaleOps {
pxr::UsdGeomXformOp translateOp;
pxr::UsdGeomXformOp rotateOrOrientOp;
pxr::UsdGeomXformOp scaleOp;
MathUtil::EulerAngleOrder eulerAngleOrder;
};
std::optional<TranslateRotateScaleOps> getOrCreateTranslateRotateScaleOps(const pxr::UsdGeomXformable& xformable);
}; // namespace cesium::omniverse::UsdUtil
| 8,823 | C | 48.853107 | 119 | 0.808682 |
CesiumGS/cesium-omniverse/src/core/include/cesium/omniverse/OmniWebMapServiceRasterOverlay.h | #pragma once
#include "cesium/omniverse/OmniRasterOverlay.h"
#include <CesiumRasterOverlays/WebMapServiceRasterOverlay.h>
#include <CesiumUtility/IntrusivePointer.h>
#include <string>
namespace cesium::omniverse {
class OmniWebMapServiceRasterOverlay final : public OmniRasterOverlay {
public:
OmniWebMapServiceRasterOverlay(Context* pContext, const pxr::SdfPath& path);
~OmniWebMapServiceRasterOverlay() override = default;
OmniWebMapServiceRasterOverlay(const OmniWebMapServiceRasterOverlay&) = delete;
OmniWebMapServiceRasterOverlay& operator=(const OmniWebMapServiceRasterOverlay&) = delete;
OmniWebMapServiceRasterOverlay(OmniWebMapServiceRasterOverlay&&) noexcept = default;
OmniWebMapServiceRasterOverlay& operator=(OmniWebMapServiceRasterOverlay&&) noexcept = default;
[[nodiscard]] CesiumRasterOverlays::RasterOverlay* getRasterOverlay() const override;
[[nodiscard]] std::string getBaseUrl() const;
[[nodiscard]] int getMinimumLevel() const;
[[nodiscard]] int getMaximumLevel() const;
[[nodiscard]] int getTileWidth() const;
[[nodiscard]] int getTileHeight() const;
[[nodiscard]] std::string getLayers() const;
void reload() override;
private:
CesiumUtility::IntrusivePointer<CesiumRasterOverlays::WebMapServiceRasterOverlay> _pWebMapServiceRasterOverlay;
};
} // namespace cesium::omniverse
| 1,373 | C | 39.411764 | 115 | 0.782229 |
CesiumGS/cesium-omniverse/src/core/include/cesium/omniverse/OmniData.h | #pragma once
#include <pxr/usd/sdf/path.h>
namespace cesium::omniverse {
class Context;
class OmniData {
public:
OmniData(Context* pContext, const pxr::SdfPath& path);
~OmniData() = default;
OmniData(const OmniData&) = delete;
OmniData& operator=(const OmniData&) = delete;
OmniData(OmniData&&) noexcept = default;
OmniData& operator=(OmniData&&) noexcept = default;
[[nodiscard]] const pxr::SdfPath& getPath() const;
[[nodiscard]] pxr::SdfPath getSelectedIonServerPath() const;
[[nodiscard]] bool getDebugDisableMaterials() const;
[[nodiscard]] bool getDebugDisableTextures() const;
[[nodiscard]] bool getDebugDisableGeometryPool() const;
[[nodiscard]] bool getDebugDisableMaterialPool() const;
[[nodiscard]] bool getDebugDisableTexturePool() const;
[[nodiscard]] uint64_t getDebugGeometryPoolInitialCapacity() const;
[[nodiscard]] uint64_t getDebugMaterialPoolInitialCapacity() const;
[[nodiscard]] uint64_t getDebugTexturePoolInitialCapacity() const;
[[nodiscard]] bool getDebugRandomColors() const;
[[nodiscard]] bool getDebugDisableGeoreferencing() const;
private:
Context* _pContext;
pxr::SdfPath _path;
};
} // namespace cesium::omniverse
| 1,236 | C | 33.36111 | 71 | 0.718447 |
CesiumGS/cesium-omniverse/src/core/include/cesium/omniverse/FabricFeaturesInfo.h | #pragma once
#include "cesium/omniverse/FabricTextureInfo.h"
#include <optional>
#include <variant>
#include <vector>
namespace cesium::omniverse {
enum class FabricFeatureIdType {
INDEX,
ATTRIBUTE,
TEXTURE,
};
struct FabricFeatureId {
std::optional<uint64_t> nullFeatureId;
uint64_t featureCount;
std::variant<std::monostate, uint64_t, FabricTextureInfo> featureIdStorage;
};
struct FabricFeaturesInfo {
std::vector<FabricFeatureId> featureIds;
};
} // namespace cesium::omniverse
| 517 | C | 17.499999 | 79 | 0.73501 |
CesiumGS/cesium-omniverse/src/core/include/cesium/omniverse/TaskProcessor.h | #pragma once
#include <CesiumAsync/ITaskProcessor.h>
#include <pxr/base/work/dispatcher.h>
namespace cesium::omniverse {
class TaskProcessor final : public CesiumAsync::ITaskProcessor {
public:
TaskProcessor() = default;
~TaskProcessor() override = default;
TaskProcessor(const TaskProcessor&) = delete;
TaskProcessor& operator=(const TaskProcessor&) = delete;
TaskProcessor(TaskProcessor&&) noexcept = delete;
TaskProcessor& operator=(TaskProcessor&&) noexcept = delete;
void startTask(std::function<void()> f) override;
private:
// TODO: should we being using something in Carbonite instead?
pxr::WorkDispatcher _dispatcher;
};
} // namespace cesium::omniverse
| 709 | C | 27.399999 | 66 | 0.730606 |
CesiumGS/cesium-omniverse/src/core/include/cesium/omniverse/FabricTextureData.h | #pragma once
#include <carb/RenderingTypes.h>
#include <vector>
namespace cesium::omniverse {
struct FabricTextureData {
std::vector<std::byte> bytes;
uint64_t width;
uint64_t height;
carb::Format format;
};
} // namespace cesium::omniverse
| 262 | C | 14.470587 | 33 | 0.694656 |
CesiumGS/cesium-omniverse/src/core/include/cesium/omniverse/FabricTextureInfo.h | #pragma once
#include <glm/glm.hpp>
#include <vector>
namespace cesium::omniverse {
struct FabricTextureInfo {
glm::dvec2 offset;
double rotation;
glm::dvec2 scale;
uint64_t setIndex;
int32_t wrapS;
int32_t wrapT;
bool flipVertical;
std::vector<uint8_t> channels;
// Make sure to update this function when adding new fields to the struct
// In C++ 20 we can use the default equality comparison (= default)
// clang-format off
bool operator==(const FabricTextureInfo& other) const {
return offset == other.offset &&
rotation == other.rotation &&
scale == other.scale &&
setIndex == other.setIndex &&
wrapS == other.wrapS &&
wrapT == other.wrapT &&
flipVertical == other.flipVertical &&
channels == other.channels;
}
// clang-format on
};
} // namespace cesium::omniverse
| 945 | C | 25.277777 | 77 | 0.596825 |
CesiumGS/cesium-omniverse/src/core/include/cesium/omniverse/FabricMaterialDescriptor.h | #pragma once
#include <pxr/usd/sdf/path.h>
namespace CesiumGltf {
struct Model;
struct MeshPrimitive;
} // namespace CesiumGltf
namespace cesium::omniverse {
class Context;
enum class FabricFeatureIdType;
enum class FabricOverlayRenderMethod;
struct FabricFeaturesInfo;
struct FabricRasterOverlaysInfo;
struct FabricMaterialInfo;
struct FabricPropertyDescriptor;
/**
* @brief A descriptor used to initialize a {@link FabricMaterial} and {@link FabricMaterialPool}.
*
* The descriptor uniquely identifies the topology of a {@link FabricMaterial} i.e. what Fabric prims
* need to be created and how they're connected. It is distinct from {@FabricMaterialInfo} which
* supplies the actual material values.
*
* Materials that have the same material descriptor will be assigned to the same material pool.
* To reduce the number of material pools that are needed the list of member variables should be
* as limited as possible.
*/
class FabricMaterialDescriptor {
public:
FabricMaterialDescriptor(
const Context& context,
const CesiumGltf::Model& model,
const CesiumGltf::MeshPrimitive& primitive,
const FabricMaterialInfo& materialInfo,
const FabricFeaturesInfo& featuresInfo,
const FabricRasterOverlaysInfo& rasterOverlaysInfo,
const pxr::SdfPath& tilesetMaterialPath);
[[nodiscard]] bool hasVertexColors() const;
[[nodiscard]] bool hasBaseColorTexture() const;
[[nodiscard]] const std::vector<FabricFeatureIdType>& getFeatureIdTypes() const;
[[nodiscard]] const std::vector<FabricOverlayRenderMethod>& getRasterOverlayRenderMethods() const;
[[nodiscard]] bool hasTilesetMaterial() const;
[[nodiscard]] const pxr::SdfPath& getTilesetMaterialPath() const;
[[nodiscard]] const std::vector<FabricPropertyDescriptor>& getStyleableProperties() const;
[[nodiscard]] const std::map<std::string, std::string>& getUnsupportedPropertyWarnings() const;
bool operator==(const FabricMaterialDescriptor& other) const;
private:
bool _hasVertexColors;
bool _hasBaseColorTexture;
std::vector<FabricFeatureIdType> _featureIdTypes;
std::vector<FabricOverlayRenderMethod> _rasterOverlayRenderMethods;
pxr::SdfPath _tilesetMaterialPath;
std::vector<FabricPropertyDescriptor> _styleableProperties;
std::map<std::string, std::string> _unsupportedPropertyWarnings;
};
} // namespace cesium::omniverse
| 2,410 | C | 36.671874 | 102 | 0.763071 |
CesiumGS/cesium-omniverse/src/core/include/cesium/omniverse/CesiumIonSession.h | #pragma once
#include <CesiumAsync/AsyncSystem.h>
#include <CesiumAsync/SharedFuture.h>
#include <CesiumIonClient/Connection.h>
#include <memory>
#include <optional>
#include <vector>
namespace CesiumAsync {
class IAssetAccessor;
}
namespace cesium::omniverse {
class CesiumIonSession {
public:
CesiumIonSession(
const CesiumAsync::AsyncSystem& asyncSystem,
std::shared_ptr<CesiumAsync::IAssetAccessor> pAssetAccessor,
std::string ionServerUrl,
std::string ionApiUrl,
int64_t ionApplicationId);
~CesiumIonSession() = default;
CesiumIonSession(const CesiumIonSession&) = delete;
CesiumIonSession& operator=(const CesiumIonSession&) = delete;
CesiumIonSession(CesiumIonSession&&) noexcept = default;
CesiumIonSession& operator=(CesiumIonSession&&) noexcept = default;
[[nodiscard]] std::shared_ptr<CesiumAsync::IAssetAccessor> getAssetAccessor() const {
return this->_pAssetAccessor;
}
[[nodiscard]] const CesiumAsync::AsyncSystem& getAsyncSystem() const {
return this->_asyncSystem;
}
CesiumAsync::AsyncSystem& getAsyncSystem() {
return this->_asyncSystem;
}
[[nodiscard]] bool isConnected() const {
return this->_connection.has_value();
}
[[nodiscard]] bool isConnecting() const {
return this->_isConnecting;
}
[[nodiscard]] bool isResuming() const {
return this->_isResuming;
}
[[nodiscard]] bool isProfileLoaded() const {
return this->_profile.has_value();
}
[[nodiscard]] bool isLoadingProfile() const {
return this->_isLoadingProfile;
}
[[nodiscard]] bool isAssetListLoaded() const {
return this->_assets.has_value();
}
[[nodiscard]] bool isLoadingAssetList() const {
return this->_isLoadingAssets;
}
[[nodiscard]] bool isTokenListLoaded() const {
return this->_tokens.has_value();
}
[[nodiscard]] bool isLoadingTokenList() const {
return this->_isLoadingTokens;
}
void connect();
void resume();
void disconnect();
void tick();
void refreshProfile();
void refreshAssets();
void refreshTokens();
[[nodiscard]] const std::optional<CesiumIonClient::Connection>& getConnection() const;
const CesiumIonClient::Profile& getProfile();
const CesiumIonClient::Assets& getAssets();
const std::vector<CesiumIonClient::Token>& getTokens();
[[nodiscard]] const std::string& getAuthorizeUrl() const {
return this->_authorizeUrl;
}
bool refreshProfileIfNeeded();
bool refreshAssetsIfNeeded();
bool refreshTokensIfNeeded();
/**
* Finds the details of the specified token in the user's account.
*
* If this session is not connected, returns std::nullopt.
*
* Even if the list of tokens is already loaded, this method does a new query
* in order get the most up-to-date information about the token.
*
* @param token The token.
* @return The details of the token, or an error response if the token does
* not exist in the signed-in user account.
*/
[[nodiscard]] CesiumAsync::Future<CesiumIonClient::Response<CesiumIonClient::Token>>
findToken(const std::string& token) const;
private:
CesiumAsync::AsyncSystem _asyncSystem;
std::shared_ptr<CesiumAsync::IAssetAccessor> _pAssetAccessor;
std::optional<CesiumIonClient::Connection> _connection;
std::optional<CesiumIonClient::Profile> _profile;
std::optional<CesiumIonClient::Assets> _assets;
std::optional<std::vector<CesiumIonClient::Token>> _tokens;
std::optional<CesiumAsync::SharedFuture<CesiumIonClient::Token>> _projectDefaultTokenDetailsFuture;
bool _isConnecting;
bool _isResuming;
bool _isLoadingProfile;
bool _isLoadingAssets;
bool _isLoadingTokens;
bool _loadProfileQueued;
bool _loadAssetsQueued;
bool _loadTokensQueued;
std::string _authorizeUrl;
std::string _ionServerUrl;
std::string _ionApiUrl;
int64_t _ionApplicationId;
};
} // namespace cesium::omniverse
| 4,107 | C | 28.768116 | 103 | 0.679815 |
CesiumGS/cesium-omniverse/src/core/include/cesium/omniverse/FabricPrepareRenderResources.h | #pragma once
#ifdef CESIUM_OMNI_MSVC
#pragma push_macro("OPAQUE")
#undef OPAQUE
#endif
#include <Cesium3DTilesSelection/IPrepareRendererResources.h>
namespace cesium::omniverse {
class Context;
struct FabricMesh;
class OmniTileset;
class FabricPrepareRenderResources final : public Cesium3DTilesSelection::IPrepareRendererResources {
public:
FabricPrepareRenderResources(Context* pContext, OmniTileset* pTileset);
~FabricPrepareRenderResources() override = default;
FabricPrepareRenderResources(const FabricPrepareRenderResources&) = delete;
FabricPrepareRenderResources& operator=(const FabricPrepareRenderResources&) = delete;
FabricPrepareRenderResources(FabricPrepareRenderResources&&) noexcept = default;
FabricPrepareRenderResources& operator=(FabricPrepareRenderResources&&) noexcept = default;
CesiumAsync::Future<Cesium3DTilesSelection::TileLoadResultAndRenderResources> prepareInLoadThread(
const CesiumAsync::AsyncSystem& asyncSystem,
Cesium3DTilesSelection::TileLoadResult&& tileLoadResult,
const glm::dmat4& tileToEcefTransform,
const std::any& rendererOptions) override;
void* prepareInMainThread(Cesium3DTilesSelection::Tile& tile, void* pLoadThreadResult) override;
void free(Cesium3DTilesSelection::Tile& tile, void* pLoadThreadResult, void* pMainThreadResult) noexcept override;
void* prepareRasterInLoadThread(CesiumGltf::ImageCesium& image, const std::any& rendererOptions) override;
void*
prepareRasterInMainThread(CesiumRasterOverlays::RasterOverlayTile& rasterTile, void* pLoadThreadResult) override;
void freeRaster(
const CesiumRasterOverlays::RasterOverlayTile& rasterTile,
void* pLoadThreadResult,
void* pMainThreadResult) noexcept override;
void attachRasterInMainThread(
const Cesium3DTilesSelection::Tile& tile,
int32_t overlayTextureCoordinateID,
const CesiumRasterOverlays::RasterOverlayTile& rasterTile,
void* pMainThreadRendererResources,
const glm::dvec2& translation,
const glm::dvec2& scale) override;
void detachRasterInMainThread(
const Cesium3DTilesSelection::Tile& tile,
int32_t overlayTextureCoordinateID,
const CesiumRasterOverlays::RasterOverlayTile& rasterTile,
void* pMainThreadRendererResources) noexcept override;
[[nodiscard]] bool tilesetExists() const;
void detachTileset();
private:
Context* _pContext;
OmniTileset* _pTileset;
};
} // namespace cesium::omniverse
| 2,547 | C | 36.470588 | 118 | 0.769533 |
CesiumGS/cesium-omniverse/src/core/include/cesium/omniverse/CppUtil.h | #pragma once
#include <algorithm>
#include <array>
#include <cstdint>
#include <functional>
#include <map>
#include <optional>
#include <set>
#include <unordered_set>
#include <vector>
namespace cesium::omniverse::CppUtil {
template <typename T, typename L, uint64_t... I> const auto& dispatchImpl(std::index_sequence<I...>, L lambda) {
static std::array<decltype(lambda(std::integral_constant<T, T(0)>{})), sizeof...(I)> array = {
{lambda(std::integral_constant<T, T(I)>{})...}};
return array;
}
template <uint64_t T_COUNT, typename T, typename L, typename... P> auto dispatch(L lambda, T n, P&&... p) {
const auto& array = dispatchImpl<T>(std::make_index_sequence<T_COUNT>{}, lambda);
return array[static_cast<uint64_t>(n)](std::forward<P>(p)...);
}
template <typename T> const T& defaultValue(const T* pValue, const T& defaultValue) {
return pValue ? *pValue : defaultValue;
}
template <typename T, typename U> T defaultValue(const std::optional<U>& optional, const T& defaultValue) {
return optional.has_value() ? static_cast<T>(optional.value()) : defaultValue;
}
template <typename T> uint64_t getIndexFromRef(const std::vector<T>& vector, const T& item) {
return static_cast<uint64_t>(&item - vector.data());
};
template <typename T, typename U> std::optional<T> castOptional(const std::optional<U>& optional) {
return optional.has_value() ? std::make_optional(static_cast<T>(optional.value())) : std::nullopt;
}
template <typename T, typename U> uint64_t indexOf(const std::vector<T>& vector, const U& value) {
return static_cast<uint64_t>(std::distance(vector.begin(), std::find(vector.begin(), vector.end(), value)));
}
template <typename T, typename U> uint64_t indexOfByMember(const std::vector<T>& vector, U T::*member, const U& value) {
return static_cast<uint64_t>(
std::distance(vector.begin(), std::find_if(vector.begin(), vector.end(), [&value, &member](const auto& item) {
return item.*member == value;
})));
}
template <typename T, typename U> bool contains(const std::vector<T>& vector, const U& value) {
return std::find(vector.begin(), vector.end(), value) != vector.end();
}
// In C++ 20 we can use std::ranges::common_range instead of having a separate version for std::array
template <typename T, size_t C, typename U> bool contains(const std::array<T, C>& array, const U& value) {
return std::find(array.begin(), array.end(), value) != array.end();
}
template <typename T, typename U> bool contains(const std::unordered_set<T>& set, const U& value) {
return set.find(value) != set.end();
}
template <typename T, typename U> bool contains(const std::map<T, U>& map, const U& value) {
return map.find(value) != map.end();
}
template <typename T, typename U> bool containsByMember(const std::vector<T>& vector, U T::*member, const U& value) {
return indexOfByMember(vector, member, value) != vector.size();
}
template <typename T, typename F> bool containsIf(const std::vector<T>& vector, const F& condition) {
return std::find_if(vector.begin(), vector.end(), condition) != vector.end();
}
template <typename T, typename F> void eraseIf(std::vector<T>& vector, const F& condition) {
vector.erase(std::remove_if(vector.begin(), vector.end(), condition), vector.end());
}
template <typename T, typename F> uint64_t countIf(const std::vector<T>& vector, const F& condition) {
return static_cast<uint64_t>(std::count_if(vector.begin(), vector.end(), condition));
}
template <typename T> const T& getElementByIndex(const std::set<T>& set, uint64_t index) {
assert(index < set.size());
return *std::next(set.begin(), static_cast<int>(index));
}
template <typename T, typename F> void sort(std::vector<T>& vector, const F& comparison) {
std::sort(vector.begin(), vector.end(), comparison);
}
template <typename T> void append(std::vector<T>& vector, const std::vector<T>& append) {
vector.insert(vector.end(), append.begin(), append.end());
}
template <typename T, typename F> constexpr auto hasMemberImpl(F&& f) -> decltype(f(std::declval<T>()), true) {
return true;
}
template <typename> constexpr bool hasMemberImpl(...) {
return false;
}
#define HAS_MEMBER(T, EXPR) CppUtil::hasMemberImpl<T>([](auto&& obj) -> decltype(obj.EXPR) {})
} // namespace cesium::omniverse::CppUtil
| 4,382 | C | 38.845454 | 120 | 0.67435 |
CesiumGS/cesium-omniverse/src/core/include/cesium/omniverse/Logger.h | #pragma once
#include "cesium/omniverse/CppUtil.h"
#include <spdlog/logger.h>
#include <unordered_set>
namespace cesium::omniverse {
class Logger final : public spdlog::logger {
public:
Logger();
template <typename T> void oneTimWarning(const T& warning) {
if (CppUtil::contains(_oneTimeWarnings, warning)) {
return;
}
_oneTimeWarnings.insert(warning);
warn(warning);
}
template <typename... Args> void oneTimeWarning(spdlog::format_string_t<Args...> fmt, Args&&... args) {
const auto warning = fmt::format(fmt, std::forward<Args>(args)...);
if (CppUtil::contains(_oneTimeWarnings, warning)) {
return;
}
_oneTimeWarnings.insert(warning);
warn(warning);
}
private:
std::unordered_set<std::string> _oneTimeWarnings;
};
} // namespace cesium::omniverse
| 886 | C | 21.174999 | 107 | 0.623025 |
CesiumGS/cesium-omniverse/src/core/include/cesium/omniverse/UrlAssetAccessor.h | /* <editor-fold desc="MIT License">
Copyright(c) 2023 Timothy Moore
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
</editor-fold> */
#pragma once
#include "CesiumAsync/AsyncSystem.h"
#include "CesiumAsync/IAssetAccessor.h"
#include <curl/curl.h>
#include <cstddef>
#include <filesystem>
#include <memory>
#include <mutex>
#include <vector>
namespace cesium::omniverse {
// A cache that permits reuse of CURL handles. This is extremely important for performance
// because libcurl will keep existing connections open if a curl handle is not destroyed
// ("cleaned up").
struct CurlCache {
struct CacheEntry {
CacheEntry()
: curl(nullptr)
, free(false) {}
CacheEntry(CURL* curl_, bool free_)
: curl(curl_)
, free(free_) {}
CURL* curl;
bool free;
};
std::mutex cacheMutex;
std::vector<CacheEntry> cache;
CURL* get() {
std::lock_guard<std::mutex> lock(cacheMutex);
for (auto& entry : cache) {
if (entry.free) {
entry.free = false;
return entry.curl;
}
}
cache.emplace_back(curl_easy_init(), false);
return cache.back().curl;
}
void release(CURL* curl) {
std::lock_guard<std::mutex> lock(cacheMutex);
for (auto& entry : cache) {
if (curl == entry.curl) {
curl_easy_reset(curl);
entry.free = true;
return;
}
}
throw std::logic_error("releasing a curl handle that is not in the cache");
}
};
// Simple implementation of AssetAcessor that can make network and local requests
class UrlAssetAccessor final : public CesiumAsync::IAssetAccessor {
public:
UrlAssetAccessor(const std::filesystem::path& certificatePath = {});
~UrlAssetAccessor() override;
CesiumAsync::Future<std::shared_ptr<CesiumAsync::IAssetRequest>>
get(const CesiumAsync::AsyncSystem& asyncSystem,
const std::string& url,
const std::vector<CesiumAsync::IAssetAccessor::THeader>& headers) override;
CesiumAsync::Future<std::shared_ptr<CesiumAsync::IAssetRequest>> request(
const CesiumAsync::AsyncSystem& asyncSystem,
const std::string& verb,
const std::string& url,
const std::vector<CesiumAsync::IAssetAccessor::THeader>& headers,
const gsl::span<const std::byte>& contentPayload) override;
void tick() noexcept override;
friend class CurlHandle;
private:
CurlCache curlCache;
std::string userAgent;
curl_slist* setCommonOptions(CURL* curl, const std::string& url, const CesiumAsync::HttpHeaders& headers);
std::string _certificatePath;
};
} // namespace cesium::omniverse
| 3,738 | C | 33.62037 | 110 | 0.68031 |
CesiumGS/cesium-omniverse/src/core/include/cesium/omniverse/OmniTileset.h | #pragma once
#include <glm/glm.hpp>
#include <pxr/usd/sdf/path.h>
#include <optional>
#include <gsl/span>
namespace Cesium3DTilesSelection {
class Tileset;
class ViewState;
class ViewUpdateResult;
} // namespace Cesium3DTilesSelection
namespace CesiumRasterOverlays {
class RasterOverlay;
}
namespace CesiumGltf {
struct Model;
}
namespace CesiumIonClient {
struct Token;
}
namespace cesium::omniverse {
class Context;
class FabricPrepareRenderResources;
class OmniRasterOverlay;
struct TilesetStatistics;
struct Viewport;
enum TilesetSourceType {
ION,
URL,
};
class OmniTileset {
public:
OmniTileset(Context* pContext, const pxr::SdfPath& path, int64_t tilesetId);
~OmniTileset();
OmniTileset(const OmniTileset&) = delete;
OmniTileset& operator=(const OmniTileset&) = delete;
OmniTileset(OmniTileset&&) noexcept = default;
OmniTileset& operator=(OmniTileset&&) noexcept = default;
[[nodiscard]] const pxr::SdfPath& getPath() const;
[[nodiscard]] int64_t getTilesetId() const;
[[nodiscard]] TilesetStatistics getStatistics() const;
[[nodiscard]] TilesetSourceType getSourceType() const;
[[nodiscard]] std::string getUrl() const;
[[nodiscard]] int64_t getIonAssetId() const;
[[nodiscard]] CesiumIonClient::Token getIonAccessToken() const;
[[nodiscard]] std::string getIonApiUrl() const;
[[nodiscard]] pxr::SdfPath getResolvedIonServerPath() const;
[[nodiscard]] double getMaximumScreenSpaceError() const;
[[nodiscard]] bool getPreloadAncestors() const;
[[nodiscard]] bool getPreloadSiblings() const;
[[nodiscard]] bool getForbidHoles() const;
[[nodiscard]] uint32_t getMaximumSimultaneousTileLoads() const;
[[nodiscard]] uint64_t getMaximumCachedBytes() const;
[[nodiscard]] uint32_t getLoadingDescendantLimit() const;
[[nodiscard]] bool getEnableFrustumCulling() const;
[[nodiscard]] bool getEnableFogCulling() const;
[[nodiscard]] bool getEnforceCulledScreenSpaceError() const;
[[nodiscard]] double getMainThreadLoadingTimeLimit() const;
[[nodiscard]] double getCulledScreenSpaceError() const;
[[nodiscard]] bool getSuspendUpdate() const;
[[nodiscard]] bool getSmoothNormals() const;
[[nodiscard]] bool getShowCreditsOnScreen() const;
[[nodiscard]] pxr::SdfPath getResolvedGeoreferencePath() const;
[[nodiscard]] pxr::SdfPath getMaterialPath() const;
[[nodiscard]] glm::dvec3 getDisplayColor() const;
[[nodiscard]] double getDisplayOpacity() const;
[[nodiscard]] std::vector<pxr::SdfPath> getRasterOverlayPaths() const;
void updateTilesetOptions();
void reload();
[[nodiscard]] pxr::SdfPath getRasterOverlayPathIfExists(const CesiumRasterOverlays::RasterOverlay& rasterOverlay);
void updateRasterOverlayAlpha(const pxr::SdfPath& rasterOverlayPath);
void updateShaderInput(const pxr::SdfPath& shaderPath, const pxr::TfToken& attributeName);
void updateDisplayColorAndOpacity();
void addRasterOverlayIfExists(const OmniRasterOverlay* overlay);
void onUpdateFrame(const gsl::span<const Viewport>& viewports, bool waitForLoadingTiles);
private:
void updateTransform();
void updateView(const gsl::span<const Viewport>& viewports, bool waitForLoadingTiles);
[[nodiscard]] bool updateExtent();
void updateLoadStatus();
void destroyNativeTileset();
std::unique_ptr<Cesium3DTilesSelection::Tileset> _pTileset;
std::shared_ptr<FabricPrepareRenderResources> _pRenderResourcesPreparer;
const Cesium3DTilesSelection::ViewUpdateResult* _pViewUpdateResult;
Context* _pContext;
pxr::SdfPath _path;
int64_t _tilesetId;
glm::dmat4 _ecefToPrimWorldTransform{};
std::vector<Cesium3DTilesSelection::ViewState> _viewStates;
bool _extentSet{false};
bool _activeLoading{false};
};
} // namespace cesium::omniverse
| 3,856 | C | 32.833333 | 118 | 0.739108 |
CesiumGS/cesium-omniverse/src/core/include/cesium/omniverse/DataType.h | #pragma once
namespace cesium::omniverse {
enum class DataType {
UINT8,
INT8,
UINT16,
INT16,
UINT32,
INT32,
UINT64,
INT64,
FLOAT32,
FLOAT64,
UINT8_NORM,
INT8_NORM,
UINT16_NORM,
INT16_NORM,
UINT32_NORM,
INT32_NORM,
UINT64_NORM,
INT64_NORM,
VEC2_UINT8,
VEC2_INT8,
VEC2_UINT16,
VEC2_INT16,
VEC2_UINT32,
VEC2_INT32,
VEC2_UINT64,
VEC2_INT64,
VEC2_FLOAT32,
VEC2_FLOAT64,
VEC2_UINT8_NORM,
VEC2_INT8_NORM,
VEC2_UINT16_NORM,
VEC2_INT16_NORM,
VEC2_UINT32_NORM,
VEC2_INT32_NORM,
VEC2_UINT64_NORM,
VEC2_INT64_NORM,
VEC3_UINT8,
VEC3_INT8,
VEC3_UINT16,
VEC3_INT16,
VEC3_UINT32,
VEC3_INT32,
VEC3_UINT64,
VEC3_INT64,
VEC3_FLOAT32,
VEC3_FLOAT64,
VEC3_UINT8_NORM,
VEC3_INT8_NORM,
VEC3_UINT16_NORM,
VEC3_INT16_NORM,
VEC3_UINT32_NORM,
VEC3_INT32_NORM,
VEC3_UINT64_NORM,
VEC3_INT64_NORM,
VEC4_UINT8,
VEC4_INT8,
VEC4_UINT16,
VEC4_INT16,
VEC4_UINT32,
VEC4_INT32,
VEC4_UINT64,
VEC4_INT64,
VEC4_FLOAT32,
VEC4_FLOAT64,
VEC4_UINT8_NORM,
VEC4_INT8_NORM,
VEC4_UINT16_NORM,
VEC4_INT16_NORM,
VEC4_UINT32_NORM,
VEC4_INT32_NORM,
VEC4_UINT64_NORM,
VEC4_INT64_NORM,
MAT2_UINT8,
MAT2_INT8,
MAT2_UINT16,
MAT2_INT16,
MAT2_UINT32,
MAT2_INT32,
MAT2_UINT64,
MAT2_INT64,
MAT2_FLOAT32,
MAT2_FLOAT64,
MAT2_UINT8_NORM,
MAT2_INT8_NORM,
MAT2_UINT16_NORM,
MAT2_INT16_NORM,
MAT2_UINT32_NORM,
MAT2_INT32_NORM,
MAT2_UINT64_NORM,
MAT2_INT64_NORM,
MAT3_UINT8,
MAT3_INT8,
MAT3_UINT16,
MAT3_INT16,
MAT3_UINT32,
MAT3_INT32,
MAT3_UINT64,
MAT3_INT64,
MAT3_FLOAT32,
MAT3_FLOAT64,
MAT3_UINT8_NORM,
MAT3_INT8_NORM,
MAT3_UINT16_NORM,
MAT3_INT16_NORM,
MAT3_UINT32_NORM,
MAT3_INT32_NORM,
MAT3_UINT64_NORM,
MAT3_INT64_NORM,
MAT4_UINT8,
MAT4_INT8,
MAT4_UINT16,
MAT4_INT16,
MAT4_UINT32,
MAT4_INT32,
MAT4_UINT64,
MAT4_INT64,
MAT4_FLOAT32,
MAT4_FLOAT64,
MAT4_UINT8_NORM,
MAT4_INT8_NORM,
MAT4_UINT16_NORM,
MAT4_INT16_NORM,
MAT4_UINT32_NORM,
MAT4_INT32_NORM,
MAT4_UINT64_NORM,
MAT4_INT64_NORM,
};
enum class MdlInternalPropertyType {
INT32,
FLOAT32,
INT32_NORM,
VEC2_INT32,
VEC2_FLOAT32,
VEC2_INT32_NORM,
VEC3_INT32,
VEC3_FLOAT32,
VEC3_INT32_NORM,
VEC4_INT32,
VEC4_FLOAT32,
VEC4_INT32_NORM,
MAT2_INT32,
MAT2_FLOAT32,
MAT2_INT32_NORM,
MAT3_INT32,
MAT3_FLOAT32,
MAT3_INT32_NORM,
MAT4_INT32,
MAT4_FLOAT32,
MAT4_INT32_NORM,
};
enum class MdlExternalPropertyType {
INT32,
FLOAT32,
VEC2_INT32,
VEC2_FLOAT32,
VEC3_INT32,
VEC3_FLOAT32,
VEC4_INT32,
VEC4_FLOAT32,
MAT2_FLOAT32,
MAT3_FLOAT32,
MAT4_FLOAT32,
};
} // namespace cesium::omniverse
| 2,998 | C | 16.33526 | 36 | 0.602068 |
CesiumGS/cesium-omniverse/src/core/include/cesium/omniverse/FabricVertexAttributeAccessors.h | #pragma once
#include "cesium/omniverse/DataType.h"
#include "cesium/omniverse/DataTypeUtil.h"
#ifdef CESIUM_OMNI_MSVC
#pragma push_macro("OPAQUE")
#undef OPAQUE
#endif
#include <CesiumGltf/AccessorView.h>
#include <glm/fwd.hpp>
#include <gsl/span>
namespace cesium::omniverse {
class PositionsAccessor {
public:
PositionsAccessor();
PositionsAccessor(const CesiumGltf::AccessorView<glm::fvec3>& view);
void fill(const gsl::span<glm::fvec3>& values) const;
[[nodiscard]] const glm::fvec3& get(uint64_t index) const;
[[nodiscard]] uint64_t size() const;
private:
CesiumGltf::AccessorView<glm::fvec3> _view;
uint64_t _size;
};
class IndicesAccessor {
public:
IndicesAccessor();
IndicesAccessor(uint64_t size);
IndicesAccessor(const CesiumGltf::AccessorView<uint8_t>& uint8View);
IndicesAccessor(const CesiumGltf::AccessorView<uint16_t>& uint16View);
IndicesAccessor(const CesiumGltf::AccessorView<uint32_t>& uint32View);
template <typename T> static IndicesAccessor FromTriangleStrips(const CesiumGltf::AccessorView<T>& view);
template <typename T> static IndicesAccessor FromTriangleFans(const CesiumGltf::AccessorView<T>& view);
void fill(const gsl::span<int>& values) const;
[[nodiscard]] uint32_t get(uint64_t index) const;
[[nodiscard]] uint64_t size() const;
private:
std::vector<uint32_t> _computed;
CesiumGltf::AccessorView<uint8_t> _uint8View;
CesiumGltf::AccessorView<uint16_t> _uint16View;
CesiumGltf::AccessorView<uint32_t> _uint32View;
uint64_t _size;
};
class NormalsAccessor {
public:
NormalsAccessor();
NormalsAccessor(const CesiumGltf::AccessorView<glm::fvec3>& view);
static NormalsAccessor GenerateSmooth(const PositionsAccessor& positions, const IndicesAccessor& indices);
void fill(const gsl::span<glm::fvec3>& values) const;
[[nodiscard]] uint64_t size() const;
private:
std::vector<glm::fvec3> _computed;
CesiumGltf::AccessorView<glm::fvec3> _view;
uint64_t _size;
};
class TexcoordsAccessor {
public:
TexcoordsAccessor();
TexcoordsAccessor(const CesiumGltf::AccessorView<glm::fvec2>& view, bool flipVertical);
void fill(const gsl::span<glm::fvec2>& values) const;
[[nodiscard]] uint64_t size() const;
private:
CesiumGltf::AccessorView<glm::fvec2> _view;
bool _flipVertical;
uint64_t _size;
};
class VertexColorsAccessor {
public:
VertexColorsAccessor();
VertexColorsAccessor(const CesiumGltf::AccessorView<glm::u8vec3>& uint8Vec3View);
VertexColorsAccessor(const CesiumGltf::AccessorView<glm::u8vec4>& uint8Vec4View);
VertexColorsAccessor(const CesiumGltf::AccessorView<glm::u16vec3>& uint16Vec3View);
VertexColorsAccessor(const CesiumGltf::AccessorView<glm::u16vec4>& uint16Vec4View);
VertexColorsAccessor(const CesiumGltf::AccessorView<glm::fvec3>& float32Vec3View);
VertexColorsAccessor(const CesiumGltf::AccessorView<glm::fvec4>& float32Vec4View);
/**
* @brief Copy accessor values to the given output values, including any data transformations.
*
* @param values The output values.
* @param repeat Indicates how many times each value in the accessor should be repeated in the output. Typically repeat is 1, but for voxel point clouds repeat is 8.
*/
void fill(const gsl::span<glm::fvec4>& values, uint64_t repeat = 1) const;
[[nodiscard]] uint64_t size() const;
private:
CesiumGltf::AccessorView<glm::u8vec3> _uint8Vec3View;
CesiumGltf::AccessorView<glm::u8vec4> _uint8Vec4View;
CesiumGltf::AccessorView<glm::u16vec3> _uint16Vec3View;
CesiumGltf::AccessorView<glm::u16vec4> _uint16Vec4View;
CesiumGltf::AccessorView<glm::fvec3> _float32Vec3View;
CesiumGltf::AccessorView<glm::fvec4> _float32Vec4View;
uint64_t _size;
};
class VertexIdsAccessor {
public:
VertexIdsAccessor();
VertexIdsAccessor(uint64_t size);
void fill(const gsl::span<float>& values, uint64_t repeat = 1) const;
[[nodiscard]] uint64_t size() const;
private:
uint64_t _size;
};
class FaceVertexCountsAccessor {
public:
FaceVertexCountsAccessor();
FaceVertexCountsAccessor(uint64_t size);
void fill(const gsl::span<int>& values) const;
[[nodiscard]] uint64_t size() const;
private:
uint64_t _size;
};
template <DataType T> class VertexAttributeAccessor {
public:
VertexAttributeAccessor()
: _size(0){};
VertexAttributeAccessor(const CesiumGltf::AccessorView<DataTypeUtil::GetNativeType<T>>& view)
: _view(view)
, _size(static_cast<uint64_t>(view.size())) {}
void fill(
const gsl::span<DataTypeUtil::GetNativeType<DataTypeUtil::getPrimvarType<T>()>>& values,
uint64_t repeat = 1) const {
const auto size = values.size();
assert(size == _size * repeat);
for (uint64_t i = 0; i < size; ++i) {
values[i] = static_cast<DataTypeUtil::GetNativeType<DataTypeUtil::getPrimvarType<T>()>>(
_view[static_cast<int64_t>(i / repeat)]);
}
}
[[nodiscard]] uint64_t size() const {
return _size;
}
private:
CesiumGltf::AccessorView<DataTypeUtil::GetNativeType<T>> _view;
uint64_t _size;
};
} // namespace cesium::omniverse
| 5,285 | C | 30.094117 | 169 | 0.70123 |
CesiumGS/cesium-omniverse/src/core/include/cesium/omniverse/FabricGeometryPool.h | #pragma once
#include "cesium/omniverse/FabricGeometry.h"
#include "cesium/omniverse/FabricGeometryDescriptor.h"
#include "cesium/omniverse/ObjectPool.h"
namespace cesium::omniverse {
class FabricGeometryPool final : public ObjectPool<FabricGeometry> {
public:
FabricGeometryPool(
Context* pContext,
int64_t poolId,
const FabricGeometryDescriptor& geometryDescriptor,
uint64_t initialCapacity);
~FabricGeometryPool() override = default;
FabricGeometryPool(const FabricGeometryPool&) = delete;
FabricGeometryPool& operator=(const FabricGeometryPool&) = delete;
FabricGeometryPool(FabricGeometryPool&&) noexcept = default;
FabricGeometryPool& operator=(FabricGeometryPool&&) noexcept = default;
[[nodiscard]] const FabricGeometryDescriptor& getGeometryDescriptor() const;
[[nodiscard]] int64_t getPoolId() const;
protected:
[[nodiscard]] std::shared_ptr<FabricGeometry> createObject(uint64_t objectId) const override;
void setActive(FabricGeometry* pGeometry, bool active) const override;
private:
Context* _pContext;
int64_t _poolId;
FabricGeometryDescriptor _geometryDescriptor;
};
} // namespace cesium::omniverse
| 1,212 | C | 32.694444 | 97 | 0.750825 |
CesiumGS/cesium-omniverse/src/core/include/cesium/omniverse/FabricGeometryDescriptor.h | #pragma once
#include <cstdint>
#include <set>
namespace CesiumGltf {
struct MeshPrimitive;
struct Model;
} // namespace CesiumGltf
namespace cesium::omniverse {
struct FabricFeaturesInfo;
struct FabricVertexAttributeDescriptor;
/**
* @brief A descriptor used to initialize a {@link FabricGeometry} and {@link FabricGeometryPool}.
*
* The descriptor uniquely identifies the topology of a {@link FabricGeometry} i.e. what Fabric
* attributes are added to the prim, but not the actual values.
*
* Geometries that have the same geometry descriptor will be assigned to the same geometry pool.
* To reduce the number of geometry pools that are needed the list of member variables should be
* as limited as possible.
*/
class FabricGeometryDescriptor {
public:
FabricGeometryDescriptor(
const CesiumGltf::Model& model,
const CesiumGltf::MeshPrimitive& primitive,
const FabricFeaturesInfo& featuresInfo,
bool smoothNormals);
[[nodiscard]] bool hasNormals() const;
[[nodiscard]] bool hasVertexColors() const;
[[nodiscard]] bool hasVertexIds() const;
[[nodiscard]] uint64_t getTexcoordSetCount() const;
[[nodiscard]] const std::set<FabricVertexAttributeDescriptor>& getCustomVertexAttributes() const;
bool operator==(const FabricGeometryDescriptor& other) const;
private:
bool _hasNormals{false};
bool _hasVertexColors{false};
bool _hasVertexIds{false};
uint64_t _texcoordSetCount{0};
// std::set is sorted which is important for checking FabricGeometryDescriptor equality
// Note that features ids are treated as custom vertex attributes since they don't have specific parsing behavior
std::set<FabricVertexAttributeDescriptor> _customVertexAttributes;
};
} // namespace cesium::omniverse
| 1,783 | C | 32.037036 | 117 | 0.751542 |
CesiumGS/cesium-omniverse/src/core/include/cesium/omniverse/FabricPropertyInfo.h | #pragma once
#include "cesium/omniverse/DataType.h"
#include "cesium/omniverse/DataTypeUtil.h"
#include "cesium/omniverse/FabricTextureInfo.h"
namespace cesium::omniverse {
template <DataType T> struct FabricPropertyInfo {
std::optional<DataTypeUtil::GetNativeType<DataTypeUtil::getTransformedType<T>()>> offset;
std::optional<DataTypeUtil::GetNativeType<DataTypeUtil::getTransformedType<T>()>> scale;
std::optional<DataTypeUtil::GetNativeType<DataTypeUtil::getTransformedType<T>()>> min;
std::optional<DataTypeUtil::GetNativeType<DataTypeUtil::getTransformedType<T>()>> max;
bool required;
std::optional<DataTypeUtil::GetNativeType<T>> noData;
std::optional<DataTypeUtil::GetNativeType<DataTypeUtil::getTransformedType<T>()>> defaultValue;
};
template <DataType T> struct FabricPropertyAttributePropertyInfo {
static constexpr auto Type = T;
std::string attribute;
FabricPropertyInfo<T> propertyInfo;
};
template <DataType T> struct FabricPropertyTexturePropertyInfo {
static constexpr auto Type = T;
FabricTextureInfo textureInfo;
uint64_t textureIndex;
FabricPropertyInfo<T> propertyInfo;
};
template <DataType T> struct FabricPropertyTablePropertyInfo {
static constexpr auto Type = T;
uint64_t featureIdSetIndex;
FabricPropertyInfo<T> propertyInfo;
};
} // namespace cesium::omniverse
| 1,365 | C | 34.02564 | 99 | 0.7663 |
CesiumGS/cesium-omniverse/src/core/include/cesium/omniverse/FabricAttributesBuilder.h | #pragma once
#include <omni/fabric/AttrNameAndType.h>
namespace omni::fabric {
class StageReaderWriter;
}
namespace cesium::omniverse {
class Context;
class FabricAttributesBuilder {
public:
FabricAttributesBuilder(Context* pContext);
~FabricAttributesBuilder() = default;
FabricAttributesBuilder(const FabricAttributesBuilder&) = delete;
FabricAttributesBuilder& operator=(const FabricAttributesBuilder&) = delete;
FabricAttributesBuilder(FabricAttributesBuilder&&) noexcept = default;
FabricAttributesBuilder& operator=(FabricAttributesBuilder&&) noexcept = default;
void addAttribute(const omni::fabric::Type& type, const omni::fabric::Token& name);
void createAttributes(const omni::fabric::Path& path) const;
private:
static const uint64_t MAX_ATTRIBUTES{30};
uint64_t _size{0};
std::array<omni::fabric::AttrNameAndType, MAX_ATTRIBUTES> _attributes;
Context* _pContext;
};
} // namespace cesium::omniverse
| 971 | C | 28.454545 | 87 | 0.753862 |
CesiumGS/cesium-omniverse/src/core/include/cesium/omniverse/OmniPolygonRasterOverlay.h | #pragma once
#include "cesium/omniverse/OmniRasterOverlay.h"
#include <Cesium3DTilesSelection/RasterizedPolygonsTileExcluder.h>
#include <CesiumRasterOverlays/RasterizedPolygonsOverlay.h>
#include <CesiumUtility/IntrusivePointer.h>
namespace cesium::omniverse {
class OmniPolygonRasterOverlay final : public OmniRasterOverlay {
public:
OmniPolygonRasterOverlay(Context* pContext, const pxr::SdfPath& path);
~OmniPolygonRasterOverlay() override = default;
OmniPolygonRasterOverlay(const OmniPolygonRasterOverlay&) = delete;
OmniPolygonRasterOverlay& operator=(const OmniPolygonRasterOverlay&) = delete;
OmniPolygonRasterOverlay(OmniPolygonRasterOverlay&&) noexcept = default;
OmniPolygonRasterOverlay& operator=(OmniPolygonRasterOverlay&&) noexcept = default;
[[nodiscard]] std::vector<pxr::SdfPath> getCartographicPolygonPaths() const;
[[nodiscard]] CesiumRasterOverlays::RasterOverlay* getRasterOverlay() const override;
[[nodiscard]] bool getInvertSelection() const;
[[nodiscard]] bool getExcludeSelectedTiles() const;
[[nodiscard]] std::shared_ptr<Cesium3DTilesSelection::RasterizedPolygonsTileExcluder> getExcluder();
void reload() override;
private:
CesiumUtility::IntrusivePointer<CesiumRasterOverlays::RasterizedPolygonsOverlay> _pPolygonRasterOverlay;
std::shared_ptr<Cesium3DTilesSelection::RasterizedPolygonsTileExcluder> _pExcluder;
};
} // namespace cesium::omniverse
| 1,446 | C | 44.218749 | 108 | 0.797372 |
CesiumGS/cesium-omniverse/src/core/include/cesium/omniverse/Broadcast.h | #pragma once
// clang-format off
// carb/events/IObject.h should include this
#include <utility>
// clang-format on
#include <carb/events/IEvents.h>
#include <pxr/usd/usd/common.h>
namespace cesium::omniverse::Broadcast {
void assetsUpdated();
void connectionUpdated();
void profileUpdated();
void tokensUpdated();
void showTroubleshooter(
const pxr::SdfPath& tilesetPath,
int64_t tilesetIonAssetId,
const std::string& tilesetName,
int64_t rasterOverlayIonAssetId,
const std::string& rasterOverlayName,
const std::string& message);
void setDefaultTokenComplete();
void tilesetLoaded(const pxr::SdfPath& tilesetPath);
void sendMessageToBus(carb::events::EventType eventType);
void sendMessageToBus(const std::string_view& eventKey);
} // namespace cesium::omniverse::Broadcast
| 805 | C | 25.866666 | 57 | 0.762733 |
CesiumGS/cesium-omniverse/src/core/include/cesium/omniverse/FabricTexture.h | #pragma once
#include <carb/RenderingTypes.h>
#include <pxr/base/tf/token.h>
#include <memory>
#include <string>
namespace omni::ui {
class DynamicTextureProvider;
}
namespace CesiumGltf {
struct ImageCesium;
}
namespace cesium::omniverse {
class Context;
enum class TransferFunction {
LINEAR,
SRGB,
};
class FabricTexture {
public:
FabricTexture(Context* pContext, const std::string& name, int64_t poolId);
~FabricTexture();
FabricTexture(const FabricTexture&) = delete;
FabricTexture& operator=(const FabricTexture&) = delete;
FabricTexture(FabricTexture&&) noexcept = default;
FabricTexture& operator=(FabricTexture&&) noexcept = default;
void setImage(const CesiumGltf::ImageCesium& image, TransferFunction transferFunction);
void setBytes(const std::vector<std::byte>& bytes, uint64_t width, uint64_t height, carb::Format format);
void setActive(bool active);
[[nodiscard]] const pxr::TfToken& getAssetPathToken() const;
[[nodiscard]] int64_t getPoolId() const;
private:
void reset();
Context* _pContext;
std::unique_ptr<omni::ui::DynamicTextureProvider> _pTexture;
pxr::TfToken _assetPathToken;
int64_t _poolId;
};
} // namespace cesium::omniverse
| 1,243 | C | 22.923076 | 109 | 0.716814 |
CesiumGS/cesium-omniverse/src/core/include/cesium/omniverse/ObjectPool.h | #pragma once
#include <cassert>
#include <memory>
#include <queue>
namespace cesium::omniverse {
template <typename T> class ObjectPool {
public:
ObjectPool() = default;
virtual ~ObjectPool() = default;
std::shared_ptr<T> acquire() {
const auto percentActive = computePercentActive();
if (percentActive > _doublingThreshold) {
// Capacity is initially 0, so make sure the new capacity is at least 1
const auto newCapacity = std::max(_capacity * 2, uint64_t(1));
setCapacity(newCapacity);
}
auto pObject = _queue.front();
_queue.pop_front();
setActive(pObject.get(), true);
return pObject;
}
void release(std::shared_ptr<T> pObject) {
_queue.push_back(pObject);
setActive(pObject.get(), false);
}
[[nodiscard]] uint64_t getCapacity() const {
return _capacity;
}
[[nodiscard]] uint64_t getNumberActive() const {
return getCapacity() - getNumberInactive();
}
[[nodiscard]] uint64_t getNumberInactive() const {
return _queue.size();
}
[[nodiscard]] bool isEmpty() const {
return getNumberInactive() == getCapacity();
}
[[nodiscard]] double computePercentActive() const {
const auto numberActive = static_cast<double>(getNumberActive());
const auto capacity = static_cast<double>(getCapacity());
if (capacity == 0) {
return 1.0;
}
return numberActive / capacity;
}
void setCapacity(uint64_t capacity) {
const auto oldCapacity = _capacity;
const auto newCapacity = capacity;
assert(newCapacity >= oldCapacity);
if (newCapacity <= oldCapacity) {
// We can't shrink capacity because it would mean destroying objects currently in use
return;
}
const auto count = newCapacity - oldCapacity;
for (uint64_t i = 0; i < count; ++i) {
_queue.push_back(createObject(_objectId++));
++_capacity;
}
}
protected:
virtual std::shared_ptr<T> createObject(uint64_t objectId) const = 0;
virtual void setActive(T* pObject, bool active) const = 0;
const std::deque<std::shared_ptr<T>>& getQueue() {
return _queue;
}
private:
std::deque<std::shared_ptr<T>> _queue;
uint64_t _objectId{0};
uint64_t _capacity{0};
double _doublingThreshold{0.75};
};
} // namespace cesium::omniverse
| 2,500 | C | 24.520408 | 97 | 0.5976 |
CesiumGS/cesium-omniverse/src/core/include/cesium/omniverse/OmniGlobeAnchor.h | #pragma once
#include <CesiumGeospatial/Cartographic.h>
#include <glm/glm.hpp>
#include <glm/gtc/quaternion.hpp>
#include <pxr/usd/sdf/path.h>
namespace CesiumGeospatial {
class GlobeAnchor;
class Ellipsoid;
} // namespace CesiumGeospatial
namespace cesium::omniverse {
class Context;
class OmniGlobeAnchor {
public:
OmniGlobeAnchor(Context* pContext, const pxr::SdfPath& path);
~OmniGlobeAnchor();
OmniGlobeAnchor(const OmniGlobeAnchor&) = delete;
OmniGlobeAnchor& operator=(const OmniGlobeAnchor&) = delete;
OmniGlobeAnchor(OmniGlobeAnchor&&) noexcept = default;
OmniGlobeAnchor& operator=(OmniGlobeAnchor&&) noexcept = default;
[[nodiscard]] const pxr::SdfPath& getPath() const;
[[nodiscard]] bool getDetectTransformChanges() const;
[[nodiscard]] bool getAdjustOrientation() const;
[[nodiscard]] pxr::SdfPath getResolvedGeoreferencePath() const;
void updateByEcefPosition();
void updateByGeographicCoordinates();
void updateByPrimLocalTransform(bool resetOrientation);
void updateByGeoreference();
private:
[[nodiscard]] bool isAnchorValid() const;
void initialize();
void finalize();
[[nodiscard]] glm::dvec3 getPrimLocalToEcefTranslation() const;
[[nodiscard]] CesiumGeospatial::Cartographic getGeographicCoordinates() const;
[[nodiscard]] glm::dvec3 getPrimLocalTranslation() const;
[[nodiscard]] glm::dvec3 getPrimLocalRotation() const;
[[nodiscard]] glm::dquat getPrimLocalOrientation() const;
[[nodiscard]] glm::dvec3 getPrimLocalScale() const;
void savePrimLocalToEcefTranslation();
void saveGeographicCoordinates();
void savePrimLocalTransform();
Context* _pContext;
pxr::SdfPath _path;
std::unique_ptr<CesiumGeospatial::GlobeAnchor> _pAnchor;
// These are used for quick comparisons, so we can short circuit successive updates.
glm::dvec3 _cachedPrimLocalToEcefTranslation{0.0};
glm::dvec3 _cachedPrimLocalToEcefRotation{0.0};
glm::dvec3 _cachedPrimLocalToEcefScale{1.0};
CesiumGeospatial::Cartographic _cachedGeographicCoordinates{0.0, 0.0, 0.0};
glm::dvec3 _cachedPrimLocalTranslation{0.0};
glm::dvec3 _cachedPrimLocalRotation{0.0, 0.0, 0.0};
glm::dquat _cachedPrimLocalOrientation{1.0, 0.0, 0.0, 0.0};
glm::dvec3 _cachedPrimLocalScale{1.0};
};
} // namespace cesium::omniverse
| 2,361 | C | 33.735294 | 88 | 0.733587 |
CesiumGS/cesium-omniverse/src/core/include/cesium/omniverse/Viewport.h | #pragma once
#include <glm/glm.hpp>
namespace cesium::omniverse {
struct Viewport {
glm::dmat4 viewMatrix;
glm::dmat4 projMatrix;
double width;
double height;
};
} // namespace cesium::omniverse
| 215 | C | 13.399999 | 32 | 0.683721 |
CesiumGS/cesium-omniverse/src/core/include/cesium/omniverse/MathUtil.h | #pragma once
#include <glm/glm.hpp>
#include <glm/gtc/quaternion.hpp>
#include <array>
namespace CesiumGeospatial {
class Cartographic;
}
namespace cesium::omniverse::MathUtil {
enum class EulerAngleOrder {
XYZ,
XZY,
YXZ,
YZX,
ZXY,
ZYX,
};
struct DecomposedEuler {
glm::dvec3 translation;
glm::dvec3 rotation;
glm::dvec3 scale;
};
struct Decomposed {
glm::dvec3 translation;
glm::dquat rotation;
glm::dvec3 scale;
};
EulerAngleOrder getReversedEulerAngleOrder(EulerAngleOrder eulerAngleOrder);
DecomposedEuler decomposeEuler(const glm::dmat4& matrix, EulerAngleOrder eulerAngleOrder);
Decomposed decompose(const glm::dmat4& matrix);
glm::dmat4 composeEuler(
const glm::dvec3& translation,
const glm::dvec3& rotation,
const glm::dvec3& scale,
EulerAngleOrder eulerAngleOrder);
glm::dmat4 compose(const glm::dvec3& translation, const glm::dquat& rotation, const glm::dvec3& scale);
bool equal(const CesiumGeospatial::Cartographic& a, const CesiumGeospatial::Cartographic& b);
bool epsilonEqual(const CesiumGeospatial::Cartographic& a, const CesiumGeospatial::Cartographic& b, double epsilon);
bool epsilonEqual(const glm::dmat4& a, const glm::dmat4& b, double epsilon);
bool epsilonEqual(const glm::dvec3& a, const glm::dvec3& b, double epsilon);
bool epsilonEqual(const glm::dquat& a, const glm::dquat& b, double epsilon);
glm::dvec3 getCorner(const std::array<glm::dvec3, 2>& extent, uint64_t index);
std::array<glm::dvec3, 2> transformExtent(const std::array<glm::dvec3, 2>& extent, const glm::dmat4& transform);
} // namespace cesium::omniverse::MathUtil
| 1,635 | C | 27.206896 | 116 | 0.738226 |
CesiumGS/cesium-omniverse/src/core/include/cesium/omniverse/FabricTexturePool.h | #pragma once
#include "cesium/omniverse/FabricTexture.h"
#include "cesium/omniverse/ObjectPool.h"
namespace cesium::omniverse {
class FabricTexturePool final : public ObjectPool<FabricTexture> {
public:
FabricTexturePool(Context* pContext, int64_t poolId, uint64_t initialCapacity);
~FabricTexturePool() override = default;
FabricTexturePool(const FabricTexturePool&) = delete;
FabricTexturePool& operator=(const FabricTexturePool&) = delete;
FabricTexturePool(FabricTexturePool&&) noexcept = default;
FabricTexturePool& operator=(FabricTexturePool&&) noexcept = default;
[[nodiscard]] int64_t getPoolId() const;
protected:
[[nodiscard]] std::shared_ptr<FabricTexture> createObject(uint64_t objectId) const override;
void setActive(FabricTexture* pTexture, bool active) const override;
private:
Context* _pContext;
int64_t _poolId;
};
} // namespace cesium::omniverse
| 925 | C | 30.931033 | 96 | 0.75027 |
CesiumGS/cesium-omniverse/src/core/include/cesium/omniverse/OmniCartographicPolygon.h | #pragma once
#include <glm/fwd.hpp>
#include <pxr/usd/sdf/path.h>
namespace CesiumGeospatial {
class Cartographic;
}
namespace cesium::omniverse {
class Context;
class OmniCartographicPolygon {
public:
OmniCartographicPolygon(Context* pContext, const pxr::SdfPath& path);
~OmniCartographicPolygon() = default;
OmniCartographicPolygon(const OmniCartographicPolygon&) = delete;
OmniCartographicPolygon& operator=(const OmniCartographicPolygon&) = delete;
OmniCartographicPolygon(OmniCartographicPolygon&&) noexcept = default;
OmniCartographicPolygon& operator=(OmniCartographicPolygon&&) noexcept = default;
[[nodiscard]] const pxr::SdfPath& getPath() const;
[[nodiscard]] std::vector<CesiumGeospatial::Cartographic> getCartographics() const;
private:
Context* _pContext;
pxr::SdfPath _path;
};
} // namespace cesium::omniverse
| 877 | C | 27.32258 | 87 | 0.753706 |
CesiumGS/cesium-omniverse/src/core/include/cesium/omniverse/LoggerSink.h | #pragma once
// clang-format off
// Needs to go above Omniverse headers
#include <cctype>
// clang-format on
#include <omni/log/ILog.h>
#include <spdlog/details/null_mutex.h>
#include <spdlog/sinks/base_sink.h>
#include <mutex>
#include <string>
namespace cesium::omniverse {
class LoggerSink final : public spdlog::sinks::base_sink<spdlog::details::null_mutex> {
public:
LoggerSink(omni::log::Level logLevel);
protected:
void sink_it_(const spdlog::details::log_msg& msg) override;
void flush_() override;
private:
std::string formatMessage(const spdlog::details::log_msg& msg);
std::mutex _formatMutex;
omni::log::Level _logLevel;
};
} // namespace cesium::omniverse
| 709 | C | 19.882352 | 87 | 0.702398 |
CesiumGS/cesium-omniverse/src/core/include/cesium/omniverse/FabricPropertyDescriptor.h | #pragma once
#include "cesium/omniverse/DataType.h"
#include <string>
namespace cesium::omniverse {
enum class FabricPropertyStorageType {
ATTRIBUTE,
TEXTURE,
TABLE,
};
struct FabricPropertyDescriptor {
FabricPropertyStorageType storageType;
MdlInternalPropertyType type;
std::string propertyId;
uint64_t featureIdSetIndex; // Only relevant for property tables
// Make sure to update this function when adding new fields to the struct
// In C++ 20 we can use the default equality comparison (= default)
// clang-format off
bool operator==(const FabricPropertyDescriptor& other) const {
return storageType == other.storageType &&
type == other.type &&
propertyId == other.propertyId &&
featureIdSetIndex == other.featureIdSetIndex;
}
// clang-format on
};
} // namespace cesium::omniverse
| 900 | C | 25.499999 | 77 | 0.684444 |
CesiumGS/cesium-omniverse/src/core/include/cesium/omniverse/OmniWebMapTileServiceRasterOverlay.h | #pragma once
#include "cesium/omniverse/OmniRasterOverlay.h"
#include <CesiumRasterOverlays/WebMapTileServiceRasterOverlay.h>
#include <CesiumUtility/IntrusivePointer.h>
#include <string>
namespace cesium::omniverse {
class OmniWebMapTileServiceRasterOverlay final : public OmniRasterOverlay {
public:
OmniWebMapTileServiceRasterOverlay(Context* pContext, const pxr::SdfPath& path);
~OmniWebMapTileServiceRasterOverlay() override = default;
OmniWebMapTileServiceRasterOverlay(const OmniWebMapTileServiceRasterOverlay&) = delete;
OmniWebMapTileServiceRasterOverlay& operator=(const OmniWebMapTileServiceRasterOverlay&) = delete;
OmniWebMapTileServiceRasterOverlay(OmniWebMapTileServiceRasterOverlay&&) noexcept = default;
OmniWebMapTileServiceRasterOverlay& operator=(OmniWebMapTileServiceRasterOverlay&&) noexcept = default;
[[nodiscard]] CesiumRasterOverlays::RasterOverlay* getRasterOverlay() const override;
[[nodiscard]] std::string getUrl() const;
[[nodiscard]] std::string getLayer() const;
[[nodiscard]] std::string getTileMatrixSetId() const;
[[nodiscard]] std::string getStyle() const;
[[nodiscard]] std::string getFormat() const;
[[nodiscard]] int getMinimumZoomLevel() const;
[[nodiscard]] int getMaximumZoomLevel() const;
[[nodiscard]] bool getSpecifyZoomLevels() const;
[[nodiscard]] bool getUseWebMercatorProjection() const;
[[nodiscard]] bool getSpecifyTilingScheme() const;
[[nodiscard]] double getNorth() const;
[[nodiscard]] double getSouth() const;
[[nodiscard]] double getEast() const;
[[nodiscard]] double getWest() const;
[[nodiscard]] bool getSpecifyTileMatrixSetLabels() const;
[[nodiscard]] std::string getTileMatrixSetLabelPrefix() const;
[[nodiscard]] std::vector<std::string> getTileMatrixSetLabels() const;
[[nodiscard]] int getRootTilesX() const;
[[nodiscard]] int getRootTilesY() const;
void reload() override;
private:
CesiumUtility::IntrusivePointer<CesiumRasterOverlays::WebMapTileServiceRasterOverlay>
_pWebMapTileServiceRasterOverlay;
};
} // namespace cesium::omniverse
| 2,139 | C | 42.673469 | 107 | 0.758298 |
CesiumGS/cesium-omniverse/src/core/include/cesium/omniverse/RenderStatistics.h | #pragma once
#include <cstdint>
namespace cesium::omniverse {
struct RenderStatistics {
uint64_t materialsCapacity{0};
uint64_t materialsLoaded{0};
uint64_t geometriesCapacity{0};
uint64_t geometriesLoaded{0};
uint64_t geometriesRendered{0};
uint64_t trianglesLoaded{0};
uint64_t trianglesRendered{0};
uint64_t tilesetCachedBytes{0};
uint64_t tilesVisited{0};
uint64_t culledTilesVisited{0};
uint64_t tilesRendered{0};
uint64_t tilesCulled{0};
uint64_t maxDepthVisited{0};
uint64_t tilesLoadingWorker{0};
uint64_t tilesLoadingMain{0};
uint64_t tilesLoaded{0};
};
} // namespace cesium::omniverse
| 664 | C | 23.629629 | 35 | 0.707831 |
CesiumGS/cesium-omniverse/src/core/include/cesium/omniverse/FabricMesh.h | #pragma once
#include "cesium/omniverse/FabricFeaturesInfo.h"
#include "cesium/omniverse/FabricMaterialInfo.h"
#include <memory>
#include <unordered_map>
#include <vector>
namespace cesium::omniverse {
class FabricGeometry;
class FabricMaterial;
class FabricTexture;
struct FabricMesh {
FabricMesh() = default;
~FabricMesh() = default;
FabricMesh(const FabricMesh&) = delete;
FabricMesh& operator=(const FabricMesh&) = delete;
FabricMesh(FabricMesh&&) noexcept = default;
FabricMesh& operator=(FabricMesh&&) noexcept = default;
std::shared_ptr<FabricGeometry> pGeometry;
std::shared_ptr<FabricMaterial> pMaterial;
std::shared_ptr<FabricTexture> pBaseColorTexture;
std::vector<std::shared_ptr<FabricTexture>> featureIdTextures;
std::vector<std::shared_ptr<FabricTexture>> propertyTextures;
std::vector<std::shared_ptr<FabricTexture>> propertyTableTextures;
FabricMaterialInfo materialInfo;
FabricFeaturesInfo featuresInfo;
std::unordered_map<uint64_t, uint64_t> texcoordIndexMapping;
std::unordered_map<uint64_t, uint64_t> rasterOverlayTexcoordIndexMapping;
std::vector<uint64_t> featureIdIndexSetIndexMapping;
std::vector<uint64_t> featureIdAttributeSetIndexMapping;
std::vector<uint64_t> featureIdTextureSetIndexMapping;
std::unordered_map<uint64_t, uint64_t> propertyTextureIndexMapping;
};
} // namespace cesium::omniverse
| 1,413 | C | 33.487804 | 77 | 0.760793 |
CesiumGS/cesium-omniverse/src/core/include/cesium/omniverse/FabricMaterialInfo.h | #pragma once
#include "cesium/omniverse/FabricTextureInfo.h"
#include <glm/glm.hpp>
#include <optional>
#ifdef CESIUM_OMNI_MSVC
#pragma push_macro("OPAQUE")
#undef OPAQUE
#endif
namespace cesium::omniverse {
/**
* @brief Matches gltf_alpha_mode in gltf/pbr.mdl.
*/
enum class FabricAlphaMode : int {
OPAQUE = 0,
MASK = 1,
BLEND = 2,
};
/**
* @brief Material values parsed from a glTF material passed to {@link FabricMaterial::setMaterial}.
*/
struct FabricMaterialInfo {
double alphaCutoff;
FabricAlphaMode alphaMode;
double baseAlpha;
glm::dvec3 baseColorFactor;
glm::dvec3 emissiveFactor;
double metallicFactor;
double roughnessFactor;
bool doubleSided;
bool hasVertexColors;
std::optional<FabricTextureInfo> baseColorTexture;
// Make sure to update this function when adding new fields to the struct
// In C++ 20 we can use the default equality comparison (= default)
// clang-format off
bool operator==(const FabricMaterialInfo& other) const {
return alphaCutoff == other.alphaCutoff &&
alphaMode == other.alphaMode &&
baseAlpha == other.baseAlpha &&
baseColorFactor == other.baseColorFactor &&
emissiveFactor == other.emissiveFactor &&
metallicFactor == other.metallicFactor &&
roughnessFactor == other.roughnessFactor &&
doubleSided == other.doubleSided &&
hasVertexColors == other.hasVertexColors &&
baseColorTexture == other.baseColorTexture;
}
// clang-format on
};
} // namespace cesium::omniverse
| 1,636 | C | 26.745762 | 99 | 0.661369 |
CesiumGS/cesium-omniverse/src/core/include/cesium/omniverse/OmniIonServer.h | #pragma once
#include <pxr/usd/sdf/path.h>
namespace CesiumIonClient {
struct Token;
}
namespace cesium::omniverse {
class CesiumIonSession;
class Context;
class OmniIonServer {
public:
OmniIonServer(Context* pContext, const pxr::SdfPath& path);
~OmniIonServer() = default;
OmniIonServer(const OmniIonServer&) = delete;
OmniIonServer& operator=(const OmniIonServer&) = delete;
OmniIonServer(OmniIonServer&&) noexcept = default;
OmniIonServer& operator=(OmniIonServer&&) noexcept = default;
[[nodiscard]] const pxr::SdfPath& getPath() const;
[[nodiscard]] std::string getIonServerUrl() const;
[[nodiscard]] std::string getIonServerApiUrl() const;
[[nodiscard]] int64_t getIonServerApplicationId() const;
[[nodiscard]] CesiumIonClient::Token getToken() const;
void setToken(const CesiumIonClient::Token& token);
[[nodiscard]] std::shared_ptr<CesiumIonSession> getSession() const;
private:
Context* _pContext;
pxr::SdfPath _path;
std::shared_ptr<CesiumIonSession> _session;
};
} // namespace cesium::omniverse
| 1,084 | C | 26.820512 | 71 | 0.71679 |
CesiumGS/cesium-omniverse/src/core/include/cesium/omniverse/FabricRasterOverlaysInfo.h | #pragma once
#include <vector>
namespace cesium::omniverse {
enum class FabricOverlayRenderMethod {
OVERLAY = 0,
CLIPPING = 1,
};
struct FabricRasterOverlaysInfo {
std::vector<FabricOverlayRenderMethod> overlayRenderMethods;
};
} // namespace cesium::omniverse
| 278 | C | 15.411764 | 64 | 0.741007 |
CesiumGS/cesium-omniverse/src/core/include/cesium/omniverse/FabricResourceManager.h | #pragma once
#include "cesium/omniverse/FabricMaterialInfo.h"
#include <pxr/usd/usd/common.h>
#include <atomic>
#include <mutex>
#include <vector>
namespace CesiumGltf {
struct ImageCesium;
struct MeshPrimitive;
struct Model;
} // namespace CesiumGltf
namespace omni::ui {
class DynamicTextureProvider;
}
namespace cesium::omniverse {
class Context;
class FabricGeometry;
class FabricGeometryPool;
class FabricMaterial;
class FabricMaterialPool;
class FabricGeometryDescriptor;
class FabricMaterialDescriptor;
class FabricTexture;
class FabricTexturePool;
struct FabricFeaturesInfo;
struct FabricRasterOverlaysInfo;
class FabricResourceManager {
public:
FabricResourceManager(Context* pContext);
~FabricResourceManager();
FabricResourceManager(const FabricResourceManager&) = delete;
FabricResourceManager& operator=(const FabricResourceManager&) = delete;
FabricResourceManager(FabricResourceManager&&) noexcept = delete;
FabricResourceManager& operator=(FabricResourceManager&&) noexcept = delete;
bool shouldAcquireMaterial(
const CesiumGltf::MeshPrimitive& primitive,
bool hasRasterOverlay,
const pxr::SdfPath& tilesetMaterialPath) const;
bool getDisableTextures() const;
std::shared_ptr<FabricGeometry> acquireGeometry(
const CesiumGltf::Model& model,
const CesiumGltf::MeshPrimitive& primitive,
const FabricFeaturesInfo& featuresInfo,
bool smoothNormals);
std::shared_ptr<FabricMaterial> acquireMaterial(
const CesiumGltf::Model& model,
const CesiumGltf::MeshPrimitive& primitive,
const FabricMaterialInfo& materialInfo,
const FabricFeaturesInfo& featuresInfo,
const FabricRasterOverlaysInfo& rasterOverlaysInfo,
int64_t tilesetId,
const pxr::SdfPath& tilesetMaterialPath);
std::shared_ptr<FabricTexture> acquireTexture();
void releaseGeometry(std::shared_ptr<FabricGeometry> pGeometry);
void releaseMaterial(std::shared_ptr<FabricMaterial> pMaterial);
void releaseTexture(std::shared_ptr<FabricTexture> pTexture);
void setDisableMaterials(bool disableMaterials);
void setDisableTextures(bool disableTextures);
void setDisableGeometryPool(bool disableGeometryPool);
void setDisableMaterialPool(bool disableMaterialPool);
void setDisableTexturePool(bool disableTexturePool);
void setGeometryPoolInitialCapacity(uint64_t geometryPoolInitialCapacity);
void setMaterialPoolInitialCapacity(uint64_t materialPoolInitialCapacity);
void setTexturePoolInitialCapacity(uint64_t texturePoolInitialCapacity);
void setDebugRandomColors(bool debugRandomColors);
void updateShaderInput(
const pxr::SdfPath& materialPath,
const pxr::SdfPath& shaderPath,
const pxr::TfToken& attributeName) const;
void clear();
private:
struct SharedMaterial {
SharedMaterial() = default;
~SharedMaterial() = default;
SharedMaterial(const SharedMaterial&) = delete;
SharedMaterial& operator=(const SharedMaterial&) = delete;
SharedMaterial(SharedMaterial&&) noexcept = default;
SharedMaterial& operator=(SharedMaterial&&) noexcept = default;
std::shared_ptr<FabricMaterial> pMaterial;
FabricMaterialInfo materialInfo;
int64_t tilesetId;
uint64_t referenceCount;
};
std::shared_ptr<FabricMaterial> createMaterial(const FabricMaterialDescriptor& materialDescriptor);
std::shared_ptr<FabricMaterial> acquireSharedMaterial(
const FabricMaterialInfo& materialInfo,
const FabricMaterialDescriptor& materialDescriptor,
int64_t tilesetId);
void releaseSharedMaterial(const FabricMaterial& material);
bool isSharedMaterial(const FabricMaterial& material) const;
std::shared_ptr<FabricGeometry> acquireGeometryFromPool(const FabricGeometryDescriptor& geometryDescriptor);
std::shared_ptr<FabricMaterial> acquireMaterialFromPool(const FabricMaterialDescriptor& materialDescriptor);
std::shared_ptr<FabricTexture> acquireTextureFromPool();
FabricGeometryPool* getGeometryPool(const FabricGeometry& geometry) const;
FabricMaterialPool* getMaterialPool(const FabricMaterial& material) const;
FabricTexturePool* getTexturePool(const FabricTexture& texture) const;
int64_t getNextGeometryId();
int64_t getNextMaterialId();
int64_t getNextTextureId();
int64_t getNextGeometryPoolId();
int64_t getNextMaterialPoolId();
int64_t getNextTexturePoolId();
std::vector<std::unique_ptr<FabricGeometryPool>> _geometryPools;
std::vector<std::unique_ptr<FabricMaterialPool>> _materialPools;
std::vector<std::unique_ptr<FabricTexturePool>> _texturePools;
bool _disableMaterials{false};
bool _disableTextures{false};
bool _disableGeometryPool{false};
bool _disableMaterialPool{false};
bool _disableTexturePool{false};
uint64_t _geometryPoolInitialCapacity{0};
uint64_t _materialPoolInitialCapacity{0};
uint64_t _texturePoolInitialCapacity{0};
bool _debugRandomColors{false};
std::atomic<int64_t> _geometryId{0};
std::atomic<int64_t> _materialId{0};
std::atomic<int64_t> _textureId{0};
std::atomic<int64_t> _geometryPoolId{0};
std::atomic<int64_t> _materialPoolId{0};
std::atomic<int64_t> _texturePoolId{0};
std::mutex _poolMutex;
Context* _pContext;
std::unique_ptr<omni::ui::DynamicTextureProvider> _defaultWhiteTexture;
std::unique_ptr<omni::ui::DynamicTextureProvider> _defaultTransparentTexture;
pxr::TfToken _defaultWhiteTextureAssetPathToken;
pxr::TfToken _defaultTransparentTextureAssetPathToken;
std::vector<SharedMaterial> _sharedMaterials;
};
} // namespace cesium::omniverse
| 5,777 | C | 34.447853 | 112 | 0.752986 |
CesiumGS/cesium-omniverse/src/core/include/cesium/omniverse/GltfUtil.h | #pragma once
#include "cesium/omniverse/DataType.h"
#include "cesium/omniverse/FabricVertexAttributeAccessors.h"
#include <CesiumGltf/Accessor.h>
#include <glm/fwd.hpp>
#include <set>
namespace CesiumGltf {
struct ImageCesium;
struct Material;
struct Model;
struct MeshPrimitive;
struct Texture;
struct PropertyTextureProperty;
} // namespace CesiumGltf
namespace cesium::omniverse {
struct FabricFeaturesInfo;
struct FabricMaterialInfo;
struct FabricTextureInfo;
struct FabricVertexAttributeDescriptor;
} // namespace cesium::omniverse
namespace cesium::omniverse::GltfUtil {
PositionsAccessor getPositions(const CesiumGltf::Model& model, const CesiumGltf::MeshPrimitive& primitive);
std::optional<std::array<glm::dvec3, 2>>
getExtent(const CesiumGltf::Model& model, const CesiumGltf::MeshPrimitive& primitive);
IndicesAccessor getIndices(
const CesiumGltf::Model& model,
const CesiumGltf::MeshPrimitive& primitive,
const PositionsAccessor& positions);
FaceVertexCountsAccessor getFaceVertexCounts(const IndicesAccessor& indices);
NormalsAccessor getNormals(
const CesiumGltf::Model& model,
const CesiumGltf::MeshPrimitive& primitive,
const PositionsAccessor& positionsAccessor,
const IndicesAccessor& indices,
bool smoothNormals);
TexcoordsAccessor
getTexcoords(const CesiumGltf::Model& model, const CesiumGltf::MeshPrimitive& primitive, uint64_t setIndex);
TexcoordsAccessor getRasterOverlayTexcoords(
const CesiumGltf::Model& model,
const CesiumGltf::MeshPrimitive& primitive,
uint64_t setIndex);
VertexColorsAccessor
getVertexColors(const CesiumGltf::Model& model, const CesiumGltf::MeshPrimitive& primitive, uint64_t setIndex);
VertexIdsAccessor getVertexIds(const PositionsAccessor& positionsAccessor);
const CesiumGltf::ImageCesium*
getBaseColorTextureImage(const CesiumGltf::Model& model, const CesiumGltf::MeshPrimitive& primitive);
const CesiumGltf::ImageCesium* getFeatureIdTextureImage(
const CesiumGltf::Model& model,
const CesiumGltf::MeshPrimitive& primitive,
uint64_t featureIdSetIndex);
FabricMaterialInfo getMaterialInfo(const CesiumGltf::Model& model, const CesiumGltf::MeshPrimitive& primitive);
FabricFeaturesInfo getFeaturesInfo(const CesiumGltf::Model& model, const CesiumGltf::MeshPrimitive& primitive);
std::set<FabricVertexAttributeDescriptor>
getCustomVertexAttributes(const CesiumGltf::Model& model, const CesiumGltf::MeshPrimitive& primitive);
const FabricMaterialInfo& getDefaultMaterialInfo();
const FabricTextureInfo& getDefaultTextureInfo();
FabricTextureInfo getPropertyTexturePropertyInfo(
const CesiumGltf::Model& model,
const CesiumGltf::PropertyTextureProperty& propertyTextureProperty);
bool hasNormals(const CesiumGltf::Model& model, const CesiumGltf::MeshPrimitive& primitive, bool smoothNormals);
bool hasTexcoords(const CesiumGltf::Model& model, const CesiumGltf::MeshPrimitive& primitive, uint64_t setIndex);
bool hasRasterOverlayTexcoords(
const CesiumGltf::Model& model,
const CesiumGltf::MeshPrimitive& primitive,
uint64_t setIndex);
bool hasVertexColors(const CesiumGltf::Model& model, const CesiumGltf::MeshPrimitive& primitive, uint64_t setIndex);
bool hasMaterial(const CesiumGltf::MeshPrimitive& primitive);
std::vector<uint64_t> getTexcoordSetIndexes(const CesiumGltf::Model& model, const CesiumGltf::MeshPrimitive& primitive);
std::vector<uint64_t>
getRasterOverlayTexcoordSetIndexes(const CesiumGltf::Model& model, const CesiumGltf::MeshPrimitive& primitive);
CesiumGltf::Ktx2TranscodeTargets getKtx2TranscodeTargets();
template <DataType T>
VertexAttributeAccessor<T> getVertexAttributeValues(
const CesiumGltf::Model& model,
const CesiumGltf::MeshPrimitive& primitive,
const std::string& attributeName) {
const auto it = primitive.attributes.find(attributeName);
if (it == primitive.attributes.end()) {
return {};
}
const auto pAccessor = model.getSafe(&model.accessors, it->second);
if (!pAccessor) {
return {};
}
const auto view = CesiumGltf::AccessorView<DataTypeUtil::GetNativeType<T>>(model, *pAccessor);
if (view.status() != CesiumGltf::AccessorViewStatus::Valid) {
return {};
}
return VertexAttributeAccessor<T>(view);
}
} // namespace cesium::omniverse::GltfUtil
| 4,312 | C | 34.06504 | 120 | 0.790584 |
CesiumGS/cesium-omniverse/src/core/include/cesium/omniverse/OmniGeoreference.h | #pragma once
#include <CesiumGeospatial/Ellipsoid.h>
#include <CesiumGeospatial/LocalHorizontalCoordinateSystem.h>
#include <pxr/usd/sdf/path.h>
namespace CesiumGeospatial {
class Cartographic;
class LocalHorizontalCoordinateSystem;
} // namespace CesiumGeospatial
namespace cesium::omniverse {
class Context;
class OmniGeoreference {
public:
OmniGeoreference(Context* pContext, const pxr::SdfPath& path);
~OmniGeoreference() = default;
OmniGeoreference(const OmniGeoreference&) = delete;
OmniGeoreference& operator=(const OmniGeoreference&) = delete;
OmniGeoreference(OmniGeoreference&&) noexcept = default;
OmniGeoreference& operator=(OmniGeoreference&&) noexcept = default;
[[nodiscard]] const pxr::SdfPath& getPath() const;
[[nodiscard]] CesiumGeospatial::Cartographic getOrigin() const;
[[nodiscard]] const CesiumGeospatial::Ellipsoid& getEllipsoid() const;
[[nodiscard]] CesiumGeospatial::LocalHorizontalCoordinateSystem getLocalCoordinateSystem() const;
private:
Context* _pContext;
pxr::SdfPath _path;
CesiumGeospatial::Ellipsoid _ellipsoid;
};
} // namespace cesium::omniverse
| 1,149 | C | 30.944444 | 101 | 0.762402 |
CesiumGS/cesium-omniverse/src/core/include/cesium/omniverse/TilesetStatistics.h | #pragma once
#include <cstdint>
namespace cesium::omniverse {
struct TilesetStatistics {
uint64_t tilesetCachedBytes{0};
uint64_t tilesVisited{0};
uint64_t culledTilesVisited{0};
uint64_t tilesRendered{0};
uint64_t tilesCulled{0};
uint64_t maxDepthVisited{0};
uint64_t tilesLoadingWorker{0};
uint64_t tilesLoadingMain{0};
uint64_t tilesLoaded{0};
};
} // namespace cesium::omniverse
| 423 | C | 20.199999 | 35 | 0.706856 |
CesiumGS/cesium-omniverse/src/bindings/PythonBindings.cpp | #include "cesium/omniverse/CesiumIonSession.h"
#include "cesium/omniverse/CesiumOmniverse.h"
#include <CesiumUtility/CreditSystem.h>
#include <carb/BindingsPythonUtils.h>
#include <pxr/base/gf/matrix4d.h>
#include <pxr/base/gf/vec4d.h>
#include <pxr/usd/sdf/path.h>
// Needs to go after carb
#include "pyboost11.h"
namespace pybind11::detail {
PYBOOST11_TYPE_CASTER(pxr::GfMatrix4d, _("Matrix4d"));
}
#ifdef CESIUM_OMNI_CLANG
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wgnu-zero-variadic-macro-arguments"
#endif
CARB_BINDINGS("cesium.omniverse.python")
#ifdef CESIUM_OMNI_CLANG
#pragma clang diagnostic pop
#endif
DISABLE_PYBIND11_DYNAMIC_CAST(cesium::omniverse::ICesiumOmniverseInterface)
struct ViewportPythonBinding {
pxr::GfMatrix4d viewMatrix;
pxr::GfMatrix4d projMatrix;
double width;
double height;
};
PYBIND11_MODULE(CesiumOmniversePythonBindings, m) {
using namespace cesium::omniverse;
m.doc() = "pybind11 cesium.omniverse bindings";
// clang-format off
carb::defineInterfaceClass<ICesiumOmniverseInterface>(
m, "ICesiumOmniverseInterface", "acquire_cesium_omniverse_interface", "release_cesium_omniverse_interface")
.def("on_startup", &ICesiumOmniverseInterface::onStartup)
.def("on_shutdown", &ICesiumOmniverseInterface::onShutdown)
.def("reload_tileset", &ICesiumOmniverseInterface::reloadTileset)
.def("on_update_frame", [](ICesiumOmniverseInterface& interface, const std::vector<ViewportPythonBinding>& viewports, bool waitForLoadingTiles) {
return interface.onUpdateFrame(reinterpret_cast<const ViewportApi*>(viewports.data()), viewports.size(), waitForLoadingTiles);
})
.def("on_stage_change", &ICesiumOmniverseInterface::onUsdStageChanged)
.def("connect_to_ion", &ICesiumOmniverseInterface::connectToIon)
.def("get_session", &ICesiumOmniverseInterface::getSession)
.def("get_server_path", &ICesiumOmniverseInterface::getServerPath)
.def("get_sessions", &ICesiumOmniverseInterface::getSessions)
.def("get_server_paths", &ICesiumOmniverseInterface::getServerPaths)
.def("get_set_default_token_result", &ICesiumOmniverseInterface::getSetDefaultTokenResult)
.def("is_default_token_set", &ICesiumOmniverseInterface::isDefaultTokenSet)
.def("create_token", &ICesiumOmniverseInterface::createToken)
.def("select_token", &ICesiumOmniverseInterface::selectToken)
.def("specify_token", &ICesiumOmniverseInterface::specifyToken)
.def("get_asset_troubleshooting_details", &ICesiumOmniverseInterface::getAssetTroubleshootingDetails)
.def("get_asset_token_troubleshooting_details", &ICesiumOmniverseInterface::getAssetTokenTroubleshootingDetails)
.def("get_default_token_troubleshooting_details", &ICesiumOmniverseInterface::getDefaultTokenTroubleshootingDetails)
.def("update_troubleshooting_details", py::overload_cast<const char*, int64_t, uint64_t, uint64_t>(&ICesiumOmniverseInterface::updateTroubleshootingDetails))
.def("update_troubleshooting_details", py::overload_cast<const char*, int64_t, int64_t, uint64_t, uint64_t>(&ICesiumOmniverseInterface::updateTroubleshootingDetails))
.def("print_fabric_stage", &ICesiumOmniverseInterface::printFabricStage)
.def("get_render_statistics", &ICesiumOmniverseInterface::getRenderStatistics)
.def("credits_available", &ICesiumOmniverseInterface::creditsAvailable)
.def("get_credits", &ICesiumOmniverseInterface::getCredits)
.def("credits_start_next_frame", &ICesiumOmniverseInterface::creditsStartNextFrame)
.def("is_tracing_enabled", &ICesiumOmniverseInterface::isTracingEnabled)
.def("clear_accessor_cache", &ICesiumOmniverseInterface::clearAccessorCache);
// clang-format on
py::class_<CesiumIonSession, std::shared_ptr<CesiumIonSession>>(m, "CesiumIonSession")
.def("is_connected", &CesiumIonSession::isConnected)
.def("is_connecting", &CesiumIonSession::isConnecting)
.def("is_resuming", &CesiumIonSession::isResuming)
.def("is_profile_loaded", &CesiumIonSession::isProfileLoaded)
.def("is_loading_profile", &CesiumIonSession::isLoadingProfile)
.def("is_asset_list_loaded", &CesiumIonSession::isAssetListLoaded)
.def("is_loading_asset_list", &CesiumIonSession::isLoadingAssetList)
.def("is_token_list_loaded", &CesiumIonSession::isTokenListLoaded)
.def("is_loading_token_list", &CesiumIonSession::isLoadingTokenList)
.def("get_authorize_url", &CesiumIonSession::getAuthorizeUrl)
.def("get_connection", &CesiumIonSession::getConnection)
.def("get_profile", &CesiumIonSession::getProfile)
.def("get_assets", &CesiumIonSession::getAssets)
.def("get_tokens", &CesiumIonSession::getTokens)
.def("refresh_tokens", &CesiumIonSession::refreshTokens)
.def("refresh_profile", &CesiumIonSession::refreshProfile)
.def("refresh_assets", &CesiumIonSession::refreshAssets)
.def("disconnect", &CesiumIonSession::disconnect);
py::class_<SetDefaultTokenResult>(m, "SetDefaultTokenResult")
.def_readonly("code", &SetDefaultTokenResult::code)
.def_readonly("message", &SetDefaultTokenResult::message);
py::class_<CesiumIonClient::Assets>(m, "Assets")
.def_readonly("link", &CesiumIonClient::Assets::link)
.def_readonly("items", &CesiumIonClient::Assets::items);
py::class_<CesiumIonClient::Asset>(m, "Asset")
.def_readonly("asset_id", &CesiumIonClient::Asset::id)
.def_readonly("name", &CesiumIonClient::Asset::name)
.def_readonly("description", &CesiumIonClient::Asset::description)
.def_readonly("attribution", &CesiumIonClient::Asset::attribution)
.def_readonly("asset_type", &CesiumIonClient::Asset::type)
.def_readonly("bytes", &CesiumIonClient::Asset::bytes)
.def_readonly("date_added", &CesiumIonClient::Asset::dateAdded)
.def_readonly("status", &CesiumIonClient::Asset::status)
.def_readonly("percent_complete", &CesiumIonClient::Asset::percentComplete);
py::class_<CesiumIonClient::Connection>(m, "Connection")
// Wrap non-static member function in lambda. May be able to use py::overload_cast<> in C++ 20
.def("get_api_uri", [](CesiumIonClient::Connection& connection) { return connection.getApiUrl(); })
.def("get_access_token", &CesiumIonClient::Connection::getAccessToken);
py::class_<CesiumIonClient::Profile>(m, "Profile")
.def_readonly("id", &CesiumIonClient::Profile::id)
.def_readonly("username", &CesiumIonClient::Profile::username);
py::class_<CesiumIonClient::Token>(m, "Token")
.def_readonly("id", &CesiumIonClient::Token::id)
.def_readonly("name", &CesiumIonClient::Token::name)
.def_readonly("token", &CesiumIonClient::Token::token)
.def_readonly("is_default", &CesiumIonClient::Token::isDefault);
py::class_<TokenTroubleshootingDetails>(m, "TokenTroubleshootingDetails")
.def_readonly("token", &TokenTroubleshootingDetails::token)
.def_readonly("is_valid", &TokenTroubleshootingDetails::isValid)
.def_readonly("allows_access_to_asset", &TokenTroubleshootingDetails::allowsAccessToAsset)
.def_readonly("associated_with_user_account", &TokenTroubleshootingDetails::associatedWithUserAccount)
.def_readonly("show_details", &TokenTroubleshootingDetails::showDetails);
py::class_<AssetTroubleshootingDetails>(m, "AssetTroubleshootingDetails")
.def_readonly("asset_id", &AssetTroubleshootingDetails::assetId)
.def_readonly("asset_exists_in_user_account", &AssetTroubleshootingDetails::assetExistsInUserAccount);
py::class_<RenderStatistics>(m, "RenderStatistics")
.def_readonly("materials_capacity", &RenderStatistics::materialsCapacity)
.def_readonly("materials_loaded", &RenderStatistics::materialsLoaded)
.def_readonly("geometries_capacity", &RenderStatistics::geometriesCapacity)
.def_readonly("geometries_loaded", &RenderStatistics::geometriesLoaded)
.def_readonly("geometries_rendered", &RenderStatistics::geometriesRendered)
.def_readonly("triangles_loaded", &RenderStatistics::trianglesLoaded)
.def_readonly("triangles_rendered", &RenderStatistics::trianglesRendered)
.def_readonly("tileset_cached_bytes", &RenderStatistics::tilesetCachedBytes)
.def_readonly("tiles_visited", &RenderStatistics::tilesVisited)
.def_readonly("culled_tiles_visited", &RenderStatistics::culledTilesVisited)
.def_readonly("tiles_rendered", &RenderStatistics::tilesRendered)
.def_readonly("tiles_culled", &RenderStatistics::tilesCulled)
.def_readonly("max_depth_visited", &RenderStatistics::maxDepthVisited)
.def_readonly("tiles_loading_worker", &RenderStatistics::tilesLoadingWorker)
.def_readonly("tiles_loading_main", &RenderStatistics::tilesLoadingMain)
.def_readonly("tiles_loaded", &RenderStatistics::tilesLoaded);
py::class_<ViewportPythonBinding>(m, "Viewport")
.def(py::init())
.def_readwrite("viewMatrix", &ViewportPythonBinding::viewMatrix)
.def_readwrite("projMatrix", &ViewportPythonBinding::projMatrix)
.def_readwrite("width", &ViewportPythonBinding::width)
.def_readwrite("height", &ViewportPythonBinding::height);
}
| 9,489 | C++ | 55.153846 | 174 | 0.720413 |
CesiumGS/cesium-omniverse/src/bindings/pyboost11.h | // From https://yyc.solvcon.net/en/latest/writing/2021/pyboost11/code.html
// clang-format off
/*
* Copyright (c) 2021, Yung-Yu Chen <[email protected]>
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* - Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* - Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* - Neither the name of the copyright holder nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
#pragma once
#include <pybind11/pybind11.h>
#ifdef CESIUM_OMNI_GCC
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wmissing-field-initializers"
#pragma GCC diagnostic ignored "-Wunused-parameter"
#endif
#include <boost/python.hpp>
#ifdef CESIUM_OMNI_GCC
#pragma GCC diagnostic pop
#endif
namespace pyboost11
{
// Pybind11 cast by using boost.python.
template <typename T> struct caster
{
caster(pybind11::handle src)
: obj(boost::python::handle<>(boost::python::borrowed(src.ptr())))
, ext(obj)
{}
bool check() const { return ext.check(); }
// From-Python conversion.
operator T() { return ext(); }
T operator()() { return ext(); }
// To-Python conversion.
static pybind11::handle to_python(T & src)
{
namespace bpy = boost::python;
return bpy::incref(bpy::object(src).ptr());
}
boost::python::object obj;
boost::python::extract<T> ext;
};
} // end namespace pyboost11
namespace pybind11
{
namespace detail
{
template <typename type> struct pyboost11_type_caster
{
// Expanded from PYBIND11_TYPE_CASTER.
protected:
type value;
public:
template <typename T_, enable_if_t<std::is_same<type, remove_cv_t<T_>>::value, int> = 0>
static handle cast(T_ *src, return_value_policy policy, handle parent) {
if (!src) return none().release();
if (policy == return_value_policy::take_ownership) {
auto h = cast(std::move(*src), policy, parent); delete src; return h;
} else {
return cast(*src, policy, parent);
}
}
operator type*() { return &value; }
operator type&() { return value; }
operator type&&() && { return std::move(value); }
template <typename T_> using cast_op_type = pybind11::detail::movable_cast_op_type<T_>;
// Boilerplate.
bool load(handle src, bool)
{
if (!src)
{
return false;
}
pyboost11::caster<type> ext(src);
if (!ext.check())
{
return false;
}
value = ext();
return true;
}
static handle cast(type * src, return_value_policy /* policy */, handle /* parent */)
{
return pyboost11::caster<type>::to_python(src);
}
static handle cast(type src, return_value_policy /* policy */, handle /* parent */)
{
return pyboost11::caster<type>::to_python(src);
}
};
#define PYBOOST11_TYPE_CASTER(type, py_name) \
template <> struct type_caster<type> : public pyboost11_type_caster<type> \
{ static constexpr auto name = py_name; }
} // end namespace detail
} // end namespace pybind11
namespace pyboost11
{
// Boost.python convert by using pybind11.
template <typename T> struct converter
{
public:
converter() { init(); }
void init()
{
static bool initialized = false;
if (!initialized)
{
namespace bpy = boost::python;
// From-Python conversion.
bpy::converter::registry::push_back
(
&convertible
, &construct
, bpy::type_id<T>()
);
// To-Python conversion.
bpy::to_python_converter<T, converter>();
initialized = true;
}
}
// From-Python convertibility.
static void * convertible(PyObject * objptr)
{
namespace pyb = pybind11;
try
{
pyb::handle(objptr).cast<T>();
return objptr;
}
catch (pyb::cast_error const &)
{
return nullptr;
}
}
// From-Python conversion.
static void construct
(
PyObject * objptr
, boost::python::converter::rvalue_from_python_stage1_data * data
)
{
namespace pyb = pybind11;
void * storage = reinterpret_cast
<
boost::python::converter::rvalue_from_python_storage<T> *
>(data)->storage.bytes;
new (storage) T(pyb::handle(objptr).cast<T>());
data->convertible = storage;
}
// To-Python conversion.
static PyObject * convert(T const & t)
{
return pybind11::cast(t).inc_ref().ptr();
}
};
} // end namespace pyboost11
// vim: set ff=unix fenc=utf8 et sw=4 ts=4 sts=4:
// clang-format on
| 5,974 | C | 26.790698 | 92 | 0.629227 |
CesiumGS/cesium-omniverse/src/plugins/CesiumUsdSchemas/src/CesiumUsdSchemas/wrapSession.cpp | #include ".//session.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
_CreateEcefToUsdTransformAttr(CesiumSession &self,
object defaultVal, bool writeSparsely) {
return self.CreateEcefToUsdTransformAttr(
UsdPythonToSdfType(defaultVal, SdfValueTypeNames->Matrix4d), writeSparsely);
}
static std::string
_Repr(const CesiumSession &self)
{
std::string primRepr = TfPyRepr(self.GetPrim());
return TfStringPrintf(
"CesiumUsdSchemas.Session(%s)",
primRepr.c_str());
}
} // anonymous namespace
void wrapCesiumSession()
{
typedef CesiumSession This;
class_<This, bases<UsdTyped> >
cls("Session");
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("GetEcefToUsdTransformAttr",
&This::GetEcefToUsdTransformAttr)
.def("CreateEcefToUsdTransformAttr",
&_CreateEcefToUsdTransformAttr,
(arg("defaultValue")=object(),
arg("writeSparsely")=false))
.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 {
}
}
| 2,983 | C++ | 24.724138 | 84 | 0.588669 |
CesiumGS/cesium-omniverse/src/plugins/CesiumUsdSchemas/src/CesiumUsdSchemas/wrapTileset.cpp | #include ".//tileset.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
_CreateSourceTypeAttr(CesiumTileset &self,
object defaultVal, bool writeSparsely) {
return self.CreateSourceTypeAttr(
UsdPythonToSdfType(defaultVal, SdfValueTypeNames->Token), writeSparsely);
}
static UsdAttribute
_CreateUrlAttr(CesiumTileset &self,
object defaultVal, bool writeSparsely) {
return self.CreateUrlAttr(
UsdPythonToSdfType(defaultVal, SdfValueTypeNames->String), writeSparsely);
}
static UsdAttribute
_CreateIonAssetIdAttr(CesiumTileset &self,
object defaultVal, bool writeSparsely) {
return self.CreateIonAssetIdAttr(
UsdPythonToSdfType(defaultVal, SdfValueTypeNames->Int64), writeSparsely);
}
static UsdAttribute
_CreateIonAccessTokenAttr(CesiumTileset &self,
object defaultVal, bool writeSparsely) {
return self.CreateIonAccessTokenAttr(
UsdPythonToSdfType(defaultVal, SdfValueTypeNames->String), writeSparsely);
}
static UsdAttribute
_CreateMaximumScreenSpaceErrorAttr(CesiumTileset &self,
object defaultVal, bool writeSparsely) {
return self.CreateMaximumScreenSpaceErrorAttr(
UsdPythonToSdfType(defaultVal, SdfValueTypeNames->Float), writeSparsely);
}
static UsdAttribute
_CreatePreloadAncestorsAttr(CesiumTileset &self,
object defaultVal, bool writeSparsely) {
return self.CreatePreloadAncestorsAttr(
UsdPythonToSdfType(defaultVal, SdfValueTypeNames->Bool), writeSparsely);
}
static UsdAttribute
_CreatePreloadSiblingsAttr(CesiumTileset &self,
object defaultVal, bool writeSparsely) {
return self.CreatePreloadSiblingsAttr(
UsdPythonToSdfType(defaultVal, SdfValueTypeNames->Bool), writeSparsely);
}
static UsdAttribute
_CreateForbidHolesAttr(CesiumTileset &self,
object defaultVal, bool writeSparsely) {
return self.CreateForbidHolesAttr(
UsdPythonToSdfType(defaultVal, SdfValueTypeNames->Bool), writeSparsely);
}
static UsdAttribute
_CreateMaximumSimultaneousTileLoadsAttr(CesiumTileset &self,
object defaultVal, bool writeSparsely) {
return self.CreateMaximumSimultaneousTileLoadsAttr(
UsdPythonToSdfType(defaultVal, SdfValueTypeNames->UInt), writeSparsely);
}
static UsdAttribute
_CreateMaximumCachedBytesAttr(CesiumTileset &self,
object defaultVal, bool writeSparsely) {
return self.CreateMaximumCachedBytesAttr(
UsdPythonToSdfType(defaultVal, SdfValueTypeNames->UInt64), writeSparsely);
}
static UsdAttribute
_CreateLoadingDescendantLimitAttr(CesiumTileset &self,
object defaultVal, bool writeSparsely) {
return self.CreateLoadingDescendantLimitAttr(
UsdPythonToSdfType(defaultVal, SdfValueTypeNames->UInt), writeSparsely);
}
static UsdAttribute
_CreateEnableFrustumCullingAttr(CesiumTileset &self,
object defaultVal, bool writeSparsely) {
return self.CreateEnableFrustumCullingAttr(
UsdPythonToSdfType(defaultVal, SdfValueTypeNames->Bool), writeSparsely);
}
static UsdAttribute
_CreateEnableFogCullingAttr(CesiumTileset &self,
object defaultVal, bool writeSparsely) {
return self.CreateEnableFogCullingAttr(
UsdPythonToSdfType(defaultVal, SdfValueTypeNames->Bool), writeSparsely);
}
static UsdAttribute
_CreateEnforceCulledScreenSpaceErrorAttr(CesiumTileset &self,
object defaultVal, bool writeSparsely) {
return self.CreateEnforceCulledScreenSpaceErrorAttr(
UsdPythonToSdfType(defaultVal, SdfValueTypeNames->Bool), writeSparsely);
}
static UsdAttribute
_CreateCulledScreenSpaceErrorAttr(CesiumTileset &self,
object defaultVal, bool writeSparsely) {
return self.CreateCulledScreenSpaceErrorAttr(
UsdPythonToSdfType(defaultVal, SdfValueTypeNames->Float), writeSparsely);
}
static UsdAttribute
_CreateSuspendUpdateAttr(CesiumTileset &self,
object defaultVal, bool writeSparsely) {
return self.CreateSuspendUpdateAttr(
UsdPythonToSdfType(defaultVal, SdfValueTypeNames->Bool), writeSparsely);
}
static UsdAttribute
_CreateSmoothNormalsAttr(CesiumTileset &self,
object defaultVal, bool writeSparsely) {
return self.CreateSmoothNormalsAttr(
UsdPythonToSdfType(defaultVal, SdfValueTypeNames->Bool), writeSparsely);
}
static UsdAttribute
_CreateShowCreditsOnScreenAttr(CesiumTileset &self,
object defaultVal, bool writeSparsely) {
return self.CreateShowCreditsOnScreenAttr(
UsdPythonToSdfType(defaultVal, SdfValueTypeNames->Bool), writeSparsely);
}
static UsdAttribute
_CreateMainThreadLoadingTimeLimitAttr(CesiumTileset &self,
object defaultVal, bool writeSparsely) {
return self.CreateMainThreadLoadingTimeLimitAttr(
UsdPythonToSdfType(defaultVal, SdfValueTypeNames->Float), writeSparsely);
}
static std::string
_Repr(const CesiumTileset &self)
{
std::string primRepr = TfPyRepr(self.GetPrim());
return TfStringPrintf(
"CesiumUsdSchemas.Tileset(%s)",
primRepr.c_str());
}
} // anonymous namespace
void wrapCesiumTileset()
{
typedef CesiumTileset This;
class_<This, bases<UsdGeomGprim> >
cls("Tileset");
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("GetSourceTypeAttr",
&This::GetSourceTypeAttr)
.def("CreateSourceTypeAttr",
&_CreateSourceTypeAttr,
(arg("defaultValue")=object(),
arg("writeSparsely")=false))
.def("GetUrlAttr",
&This::GetUrlAttr)
.def("CreateUrlAttr",
&_CreateUrlAttr,
(arg("defaultValue")=object(),
arg("writeSparsely")=false))
.def("GetIonAssetIdAttr",
&This::GetIonAssetIdAttr)
.def("CreateIonAssetIdAttr",
&_CreateIonAssetIdAttr,
(arg("defaultValue")=object(),
arg("writeSparsely")=false))
.def("GetIonAccessTokenAttr",
&This::GetIonAccessTokenAttr)
.def("CreateIonAccessTokenAttr",
&_CreateIonAccessTokenAttr,
(arg("defaultValue")=object(),
arg("writeSparsely")=false))
.def("GetMaximumScreenSpaceErrorAttr",
&This::GetMaximumScreenSpaceErrorAttr)
.def("CreateMaximumScreenSpaceErrorAttr",
&_CreateMaximumScreenSpaceErrorAttr,
(arg("defaultValue")=object(),
arg("writeSparsely")=false))
.def("GetPreloadAncestorsAttr",
&This::GetPreloadAncestorsAttr)
.def("CreatePreloadAncestorsAttr",
&_CreatePreloadAncestorsAttr,
(arg("defaultValue")=object(),
arg("writeSparsely")=false))
.def("GetPreloadSiblingsAttr",
&This::GetPreloadSiblingsAttr)
.def("CreatePreloadSiblingsAttr",
&_CreatePreloadSiblingsAttr,
(arg("defaultValue")=object(),
arg("writeSparsely")=false))
.def("GetForbidHolesAttr",
&This::GetForbidHolesAttr)
.def("CreateForbidHolesAttr",
&_CreateForbidHolesAttr,
(arg("defaultValue")=object(),
arg("writeSparsely")=false))
.def("GetMaximumSimultaneousTileLoadsAttr",
&This::GetMaximumSimultaneousTileLoadsAttr)
.def("CreateMaximumSimultaneousTileLoadsAttr",
&_CreateMaximumSimultaneousTileLoadsAttr,
(arg("defaultValue")=object(),
arg("writeSparsely")=false))
.def("GetMaximumCachedBytesAttr",
&This::GetMaximumCachedBytesAttr)
.def("CreateMaximumCachedBytesAttr",
&_CreateMaximumCachedBytesAttr,
(arg("defaultValue")=object(),
arg("writeSparsely")=false))
.def("GetLoadingDescendantLimitAttr",
&This::GetLoadingDescendantLimitAttr)
.def("CreateLoadingDescendantLimitAttr",
&_CreateLoadingDescendantLimitAttr,
(arg("defaultValue")=object(),
arg("writeSparsely")=false))
.def("GetEnableFrustumCullingAttr",
&This::GetEnableFrustumCullingAttr)
.def("CreateEnableFrustumCullingAttr",
&_CreateEnableFrustumCullingAttr,
(arg("defaultValue")=object(),
arg("writeSparsely")=false))
.def("GetEnableFogCullingAttr",
&This::GetEnableFogCullingAttr)
.def("CreateEnableFogCullingAttr",
&_CreateEnableFogCullingAttr,
(arg("defaultValue")=object(),
arg("writeSparsely")=false))
.def("GetEnforceCulledScreenSpaceErrorAttr",
&This::GetEnforceCulledScreenSpaceErrorAttr)
.def("CreateEnforceCulledScreenSpaceErrorAttr",
&_CreateEnforceCulledScreenSpaceErrorAttr,
(arg("defaultValue")=object(),
arg("writeSparsely")=false))
.def("GetCulledScreenSpaceErrorAttr",
&This::GetCulledScreenSpaceErrorAttr)
.def("CreateCulledScreenSpaceErrorAttr",
&_CreateCulledScreenSpaceErrorAttr,
(arg("defaultValue")=object(),
arg("writeSparsely")=false))
.def("GetSuspendUpdateAttr",
&This::GetSuspendUpdateAttr)
.def("CreateSuspendUpdateAttr",
&_CreateSuspendUpdateAttr,
(arg("defaultValue")=object(),
arg("writeSparsely")=false))
.def("GetSmoothNormalsAttr",
&This::GetSmoothNormalsAttr)
.def("CreateSmoothNormalsAttr",
&_CreateSmoothNormalsAttr,
(arg("defaultValue")=object(),
arg("writeSparsely")=false))
.def("GetShowCreditsOnScreenAttr",
&This::GetShowCreditsOnScreenAttr)
.def("CreateShowCreditsOnScreenAttr",
&_CreateShowCreditsOnScreenAttr,
(arg("defaultValue")=object(),
arg("writeSparsely")=false))
.def("GetMainThreadLoadingTimeLimitAttr",
&This::GetMainThreadLoadingTimeLimitAttr)
.def("CreateMainThreadLoadingTimeLimitAttr",
&_CreateMainThreadLoadingTimeLimitAttr,
(arg("defaultValue")=object(),
arg("writeSparsely")=false))
.def("GetGeoreferenceBindingRel",
&This::GetGeoreferenceBindingRel)
.def("CreateGeoreferenceBindingRel",
&This::CreateGeoreferenceBindingRel)
.def("GetIonServerBindingRel",
&This::GetIonServerBindingRel)
.def("CreateIonServerBindingRel",
&This::CreateIonServerBindingRel)
.def("GetRasterOverlayBindingRel",
&This::GetRasterOverlayBindingRel)
.def("CreateRasterOverlayBindingRel",
&This::CreateRasterOverlayBindingRel)
.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 {
}
}
| 13,615 | C++ | 34.550914 | 82 | 0.617481 |
CesiumGS/cesium-omniverse/src/plugins/CesiumUsdSchemas/src/CesiumUsdSchemas/api.h | #ifndef CESIUMUSDSCHEMAS_API_H
#define CESIUMUSDSCHEMAS_API_H
#include "pxr/base/arch/export.h"
#if defined(PXR_STATIC)
# define CESIUMUSDSCHEMAS_API
# define CESIUMUSDSCHEMAS_API_TEMPLATE_CLASS(...)
# define CESIUMUSDSCHEMAS_API_TEMPLATE_STRUCT(...)
# define CESIUMUSDSCHEMAS_LOCAL
#else
# if defined(CESIUMUSDSCHEMAS_EXPORTS)
# define CESIUMUSDSCHEMAS_API ARCH_EXPORT
# define CESIUMUSDSCHEMAS_API_TEMPLATE_CLASS(...) ARCH_EXPORT_TEMPLATE(class, __VA_ARGS__)
# define CESIUMUSDSCHEMAS_API_TEMPLATE_STRUCT(...) ARCH_EXPORT_TEMPLATE(struct, __VA_ARGS__)
# else
# define CESIUMUSDSCHEMAS_API ARCH_IMPORT
# define CESIUMUSDSCHEMAS_API_TEMPLATE_CLASS(...) ARCH_IMPORT_TEMPLATE(class, __VA_ARGS__)
# define CESIUMUSDSCHEMAS_API_TEMPLATE_STRUCT(...) ARCH_IMPORT_TEMPLATE(struct, __VA_ARGS__)
# endif
# define CESIUMUSDSCHEMAS_LOCAL ARCH_HIDDEN
#endif
#endif
| 908 | C | 35.359999 | 98 | 0.72467 |
CesiumGS/cesium-omniverse/src/plugins/CesiumUsdSchemas/src/CesiumUsdSchemas/polygonRasterOverlay.h | #ifndef CESIUMUSDSCHEMAS_GENERATED_POLYGONRASTEROVERLAY_H
#define CESIUMUSDSCHEMAS_GENERATED_POLYGONRASTEROVERLAY_H
/// \file CesiumUsdSchemas/polygonRasterOverlay.h
#include "pxr/pxr.h"
#include ".//api.h"
#include ".//rasterOverlay.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;
// -------------------------------------------------------------------------- //
// CESIUMPOLYGONRASTEROVERLAYPRIM //
// -------------------------------------------------------------------------- //
/// \class CesiumPolygonRasterOverlay
///
/// Adds a prim for representing a polygon raster overlay.
///
/// For any described attribute \em Fallback \em Value or \em Allowed \em Values below
/// that are text/tokens, the actual token is published and defined in \ref CesiumTokens.
/// So to set an attribute to the value "rightHanded", use CesiumTokens->rightHanded
/// as the value.
///
class CesiumPolygonRasterOverlay : public CesiumRasterOverlay
{
public:
/// Compile time constant representing what kind of schema this class is.
///
/// \sa UsdSchemaKind
static const UsdSchemaKind schemaKind = UsdSchemaKind::ConcreteTyped;
/// Construct a CesiumPolygonRasterOverlay on UsdPrim \p prim .
/// Equivalent to CesiumPolygonRasterOverlay::Get(prim.GetStage(), prim.GetPath())
/// for a \em valid \p prim, but will not immediately throw an error for
/// an invalid \p prim
explicit CesiumPolygonRasterOverlay(const UsdPrim& prim=UsdPrim())
: CesiumRasterOverlay(prim)
{
}
/// Construct a CesiumPolygonRasterOverlay on the prim held by \p schemaObj .
/// Should be preferred over CesiumPolygonRasterOverlay(schemaObj.GetPrim()),
/// as it preserves SchemaBase state.
explicit CesiumPolygonRasterOverlay(const UsdSchemaBase& schemaObj)
: CesiumRasterOverlay(schemaObj)
{
}
/// Destructor.
CESIUMUSDSCHEMAS_API
virtual ~CesiumPolygonRasterOverlay();
/// 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 CesiumPolygonRasterOverlay 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
/// CesiumPolygonRasterOverlay(stage->GetPrimAtPath(path));
/// \endcode
///
CESIUMUSDSCHEMAS_API
static CesiumPolygonRasterOverlay
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 CesiumPolygonRasterOverlay
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:
// --------------------------------------------------------------------- //
// INVERTSELECTION
// --------------------------------------------------------------------- //
/// Whether to invert the selection specified by the polygons. If this is true, only the areas outside of the polygons will be rasterized.
///
/// | ||
/// | -- | -- |
/// | Declaration | `bool cesium:invertSelection = 0` |
/// | C++ Type | bool |
/// | \ref Usd_Datatypes "Usd Type" | SdfValueTypeNames->Bool |
CESIUMUSDSCHEMAS_API
UsdAttribute GetInvertSelectionAttr() const;
/// See GetInvertSelectionAttr(), 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 CreateInvertSelectionAttr(VtValue const &defaultValue = VtValue(), bool writeSparsely=false) const;
public:
// --------------------------------------------------------------------- //
// EXCLUDESELECTEDTILES
// --------------------------------------------------------------------- //
/// Whether tiles that fall entirely within the rasterized selection should be excluded from loading and rendering. For better performance, this should be enabled when this overlay will be used for clipping. But when this overlay is used for other effects, this option should be disabled to avoid missing tiles. Note that if InvertSelection is true, this will cull tiles that are outside of all the polygons. If it is false, this will cull tiles that are completely inside at least one polygon.
///
/// | ||
/// | -- | -- |
/// | Declaration | `bool cesium:excludeSelectedTiles = 1` |
/// | C++ Type | bool |
/// | \ref Usd_Datatypes "Usd Type" | SdfValueTypeNames->Bool |
CESIUMUSDSCHEMAS_API
UsdAttribute GetExcludeSelectedTilesAttr() const;
/// See GetExcludeSelectedTilesAttr(), 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 CreateExcludeSelectedTilesAttr(VtValue const &defaultValue = VtValue(), bool writeSparsely=false) const;
public:
// --------------------------------------------------------------------- //
// CESIUMOVERLAYRENDERMETHOD
// --------------------------------------------------------------------- //
///
///
/// | ||
/// | -- | -- |
/// | Declaration | `uniform token cesium:overlayRenderMethod = "clip"` |
/// | C++ Type | TfToken |
/// | \ref Usd_Datatypes "Usd Type" | SdfValueTypeNames->Token |
/// | \ref SdfVariability "Variability" | SdfVariabilityUniform |
CESIUMUSDSCHEMAS_API
UsdAttribute GetCesiumOverlayRenderMethodAttr() const;
/// See GetCesiumOverlayRenderMethodAttr(), 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 CreateCesiumOverlayRenderMethodAttr(VtValue const &defaultValue = VtValue(), bool writeSparsely=false) const;
public:
// --------------------------------------------------------------------- //
// CARTOGRAPHICPOLYGONBINDING
// --------------------------------------------------------------------- //
/// Specifies which Cartographic Polygons to use in the raster overlay
///
CESIUMUSDSCHEMAS_API
UsdRelationship GetCartographicPolygonBindingRel() const;
/// See GetCartographicPolygonBindingRel(), and also
/// \ref Usd_Create_Or_Get_Property for when to use Get vs Create
CESIUMUSDSCHEMAS_API
UsdRelationship CreateCartographicPolygonBindingRel() 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
| 9,686 | C | 41.117391 | 498 | 0.626574 |
CesiumGS/cesium-omniverse/src/plugins/CesiumUsdSchemas/src/CesiumUsdSchemas/webMapTileServiceRasterOverlay.h | #ifndef CESIUMUSDSCHEMAS_GENERATED_WEBMAPTILESERVICERASTEROVERLAY_H
#define CESIUMUSDSCHEMAS_GENERATED_WEBMAPTILESERVICERASTEROVERLAY_H
/// \file CesiumUsdSchemas/webMapTileServiceRasterOverlay.h
#include "pxr/pxr.h"
#include ".//api.h"
#include ".//rasterOverlay.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;
// -------------------------------------------------------------------------- //
// CESIUMWEBMAPTILESERVICERASTEROVERLAYPRIM //
// -------------------------------------------------------------------------- //
/// \class CesiumWebMapTileServiceRasterOverlay
///
/// Adds a prim for representing a Web Map Tile Service (WMTS) raster overlay.
///
class CesiumWebMapTileServiceRasterOverlay : public CesiumRasterOverlay
{
public:
/// Compile time constant representing what kind of schema this class is.
///
/// \sa UsdSchemaKind
static const UsdSchemaKind schemaKind = UsdSchemaKind::ConcreteTyped;
/// Construct a CesiumWebMapTileServiceRasterOverlay on UsdPrim \p prim .
/// Equivalent to CesiumWebMapTileServiceRasterOverlay::Get(prim.GetStage(), prim.GetPath())
/// for a \em valid \p prim, but will not immediately throw an error for
/// an invalid \p prim
explicit CesiumWebMapTileServiceRasterOverlay(const UsdPrim& prim=UsdPrim())
: CesiumRasterOverlay(prim)
{
}
/// Construct a CesiumWebMapTileServiceRasterOverlay on the prim held by \p schemaObj .
/// Should be preferred over CesiumWebMapTileServiceRasterOverlay(schemaObj.GetPrim()),
/// as it preserves SchemaBase state.
explicit CesiumWebMapTileServiceRasterOverlay(const UsdSchemaBase& schemaObj)
: CesiumRasterOverlay(schemaObj)
{
}
/// Destructor.
CESIUMUSDSCHEMAS_API
virtual ~CesiumWebMapTileServiceRasterOverlay();
/// 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 CesiumWebMapTileServiceRasterOverlay 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
/// CesiumWebMapTileServiceRasterOverlay(stage->GetPrimAtPath(path));
/// \endcode
///
CESIUMUSDSCHEMAS_API
static CesiumWebMapTileServiceRasterOverlay
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 CesiumWebMapTileServiceRasterOverlay
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:
// --------------------------------------------------------------------- //
// URL
// --------------------------------------------------------------------- //
/// The base url of the Web Map Tile Service (WMTS).
///
/// | ||
/// | -- | -- |
/// | Declaration | `string cesium:url = ""` |
/// | C++ Type | std::string |
/// | \ref Usd_Datatypes "Usd Type" | SdfValueTypeNames->String |
CESIUMUSDSCHEMAS_API
UsdAttribute GetUrlAttr() const;
/// See GetUrlAttr(), 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 CreateUrlAttr(VtValue const &defaultValue = VtValue(), bool writeSparsely=false) const;
public:
// --------------------------------------------------------------------- //
// LAYER
// --------------------------------------------------------------------- //
/// Layer name.
///
/// | ||
/// | -- | -- |
/// | Declaration | `string cesium:layer = ""` |
/// | C++ Type | std::string |
/// | \ref Usd_Datatypes "Usd Type" | SdfValueTypeNames->String |
CESIUMUSDSCHEMAS_API
UsdAttribute GetLayerAttr() const;
/// See GetLayerAttr(), 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 CreateLayerAttr(VtValue const &defaultValue = VtValue(), bool writeSparsely=false) const;
public:
// --------------------------------------------------------------------- //
// STYLE
// --------------------------------------------------------------------- //
/// Style.
///
/// | ||
/// | -- | -- |
/// | Declaration | `string cesium:style = ""` |
/// | C++ Type | std::string |
/// | \ref Usd_Datatypes "Usd Type" | SdfValueTypeNames->String |
CESIUMUSDSCHEMAS_API
UsdAttribute GetStyleAttr() const;
/// See GetStyleAttr(), 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 CreateStyleAttr(VtValue const &defaultValue = VtValue(), bool writeSparsely=false) const;
public:
// --------------------------------------------------------------------- //
// FORMAT
// --------------------------------------------------------------------- //
/// Format.
///
/// | ||
/// | -- | -- |
/// | Declaration | `string cesium:format = "image/jpeg"` |
/// | C++ Type | std::string |
/// | \ref Usd_Datatypes "Usd Type" | SdfValueTypeNames->String |
CESIUMUSDSCHEMAS_API
UsdAttribute GetFormatAttr() const;
/// See GetFormatAttr(), 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 CreateFormatAttr(VtValue const &defaultValue = VtValue(), bool writeSparsely=false) const;
public:
// --------------------------------------------------------------------- //
// TILEMATRIXSETID
// --------------------------------------------------------------------- //
/// Tile Matrix Set ID
///
/// | ||
/// | -- | -- |
/// | Declaration | `string cesium:tileMatrixSetId = ""` |
/// | C++ Type | std::string |
/// | \ref Usd_Datatypes "Usd Type" | SdfValueTypeNames->String |
CESIUMUSDSCHEMAS_API
UsdAttribute GetTileMatrixSetIdAttr() const;
/// See GetTileMatrixSetIdAttr(), 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 CreateTileMatrixSetIdAttr(VtValue const &defaultValue = VtValue(), bool writeSparsely=false) const;
public:
// --------------------------------------------------------------------- //
// SPECIFYTILEMATRIXSETLABELS
// --------------------------------------------------------------------- //
/// True to specify tile matrix set labels manually, or false to automatically determine from level and prefix.
///
/// | ||
/// | -- | -- |
/// | Declaration | `bool cesium:specifyTileMatrixSetLabels = 0` |
/// | C++ Type | bool |
/// | \ref Usd_Datatypes "Usd Type" | SdfValueTypeNames->Bool |
CESIUMUSDSCHEMAS_API
UsdAttribute GetSpecifyTileMatrixSetLabelsAttr() const;
/// See GetSpecifyTileMatrixSetLabelsAttr(), 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 CreateSpecifyTileMatrixSetLabelsAttr(VtValue const &defaultValue = VtValue(), bool writeSparsely=false) const;
public:
// --------------------------------------------------------------------- //
// TILEMATRIXSETLABELPREFIX
// --------------------------------------------------------------------- //
/// Prefix for tile matrix set labels. For instance, setting "EPSG:4326:" as prefix generates label list ["EPSG:4326:0", "EPSG:4326:1", "EPSG:4326:2", ...]
///
/// | ||
/// | -- | -- |
/// | Declaration | `string cesium:tileMatrixSetLabelPrefix = ""` |
/// | C++ Type | std::string |
/// | \ref Usd_Datatypes "Usd Type" | SdfValueTypeNames->String |
CESIUMUSDSCHEMAS_API
UsdAttribute GetTileMatrixSetLabelPrefixAttr() const;
/// See GetTileMatrixSetLabelPrefixAttr(), 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 CreateTileMatrixSetLabelPrefixAttr(VtValue const &defaultValue = VtValue(), bool writeSparsely=false) const;
public:
// --------------------------------------------------------------------- //
// TILEMATRIXSETLABELS
// --------------------------------------------------------------------- //
/// Comma-separated tile matrix set labels
///
/// | ||
/// | -- | -- |
/// | Declaration | `string cesium:tileMatrixSetLabels` |
/// | C++ Type | std::string |
/// | \ref Usd_Datatypes "Usd Type" | SdfValueTypeNames->String |
CESIUMUSDSCHEMAS_API
UsdAttribute GetTileMatrixSetLabelsAttr() const;
/// See GetTileMatrixSetLabelsAttr(), 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 CreateTileMatrixSetLabelsAttr(VtValue const &defaultValue = VtValue(), bool writeSparsely=false) const;
public:
// --------------------------------------------------------------------- //
// USEWEBMERCATORPROJECTION
// --------------------------------------------------------------------- //
/// False to use geographic projection, true to use webmercator projection. For instance, EPSG:4326 uses geographic and EPSG:3857 uses webmercator.
///
/// | ||
/// | -- | -- |
/// | Declaration | `bool cesium:useWebMercatorProjection = 1` |
/// | C++ Type | bool |
/// | \ref Usd_Datatypes "Usd Type" | SdfValueTypeNames->Bool |
CESIUMUSDSCHEMAS_API
UsdAttribute GetUseWebMercatorProjectionAttr() const;
/// See GetUseWebMercatorProjectionAttr(), 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 CreateUseWebMercatorProjectionAttr(VtValue const &defaultValue = VtValue(), bool writeSparsely=false) const;
public:
// --------------------------------------------------------------------- //
// SPECIFYTILINGSCHEME
// --------------------------------------------------------------------- //
/// True to specify quadtree tiling scheme according to projection and bounding rectangle, or false to automatically determine from projection.
///
/// | ||
/// | -- | -- |
/// | Declaration | `bool cesium:specifyTilingScheme = 0` |
/// | C++ Type | bool |
/// | \ref Usd_Datatypes "Usd Type" | SdfValueTypeNames->Bool |
CESIUMUSDSCHEMAS_API
UsdAttribute GetSpecifyTilingSchemeAttr() const;
/// See GetSpecifyTilingSchemeAttr(), 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 CreateSpecifyTilingSchemeAttr(VtValue const &defaultValue = VtValue(), bool writeSparsely=false) const;
public:
// --------------------------------------------------------------------- //
// ROOTTILESX
// --------------------------------------------------------------------- //
/// Tile number corresponding to TileCol, also known as TileMatrixWidth
///
/// | ||
/// | -- | -- |
/// | Declaration | `int cesium:rootTilesX = 1` |
/// | C++ Type | int |
/// | \ref Usd_Datatypes "Usd Type" | SdfValueTypeNames->Int |
CESIUMUSDSCHEMAS_API
UsdAttribute GetRootTilesXAttr() const;
/// See GetRootTilesXAttr(), 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 CreateRootTilesXAttr(VtValue const &defaultValue = VtValue(), bool writeSparsely=false) const;
public:
// --------------------------------------------------------------------- //
// ROOTTILESY
// --------------------------------------------------------------------- //
/// Tile number corresponding to TileRow, also known as TileMatrixHeight
///
/// | ||
/// | -- | -- |
/// | Declaration | `int cesium:rootTilesY = 1` |
/// | C++ Type | int |
/// | \ref Usd_Datatypes "Usd Type" | SdfValueTypeNames->Int |
CESIUMUSDSCHEMAS_API
UsdAttribute GetRootTilesYAttr() const;
/// See GetRootTilesYAttr(), 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 CreateRootTilesYAttr(VtValue const &defaultValue = VtValue(), bool writeSparsely=false) const;
public:
// --------------------------------------------------------------------- //
// WEST
// --------------------------------------------------------------------- //
/// The longitude of the west boundary on globe in degrees, in the range [-180, 180]
///
/// | ||
/// | -- | -- |
/// | Declaration | `double cesium:west = -180` |
/// | C++ Type | double |
/// | \ref Usd_Datatypes "Usd Type" | SdfValueTypeNames->Double |
CESIUMUSDSCHEMAS_API
UsdAttribute GetWestAttr() const;
/// See GetWestAttr(), 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 CreateWestAttr(VtValue const &defaultValue = VtValue(), bool writeSparsely=false) const;
public:
// --------------------------------------------------------------------- //
// EAST
// --------------------------------------------------------------------- //
/// The longitude of the east boundary on globe in degrees, in the range [-180, 180]
///
/// | ||
/// | -- | -- |
/// | Declaration | `double cesium:east = 180` |
/// | C++ Type | double |
/// | \ref Usd_Datatypes "Usd Type" | SdfValueTypeNames->Double |
CESIUMUSDSCHEMAS_API
UsdAttribute GetEastAttr() const;
/// See GetEastAttr(), 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 CreateEastAttr(VtValue const &defaultValue = VtValue(), bool writeSparsely=false) const;
public:
// --------------------------------------------------------------------- //
// SOUTH
// --------------------------------------------------------------------- //
/// The longitude of the south boundary on globe in degrees, in the range [-90, 90]
///
/// | ||
/// | -- | -- |
/// | Declaration | `double cesium:south = -90` |
/// | C++ Type | double |
/// | \ref Usd_Datatypes "Usd Type" | SdfValueTypeNames->Double |
CESIUMUSDSCHEMAS_API
UsdAttribute GetSouthAttr() const;
/// See GetSouthAttr(), 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 CreateSouthAttr(VtValue const &defaultValue = VtValue(), bool writeSparsely=false) const;
public:
// --------------------------------------------------------------------- //
// NORTH
// --------------------------------------------------------------------- //
/// The longitude of the north boundary on globe in degrees, in the range [-90, 90]
///
/// | ||
/// | -- | -- |
/// | Declaration | `double cesium:north = 90` |
/// | C++ Type | double |
/// | \ref Usd_Datatypes "Usd Type" | SdfValueTypeNames->Double |
CESIUMUSDSCHEMAS_API
UsdAttribute GetNorthAttr() const;
/// See GetNorthAttr(), 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 CreateNorthAttr(VtValue const &defaultValue = VtValue(), bool writeSparsely=false) const;
public:
// --------------------------------------------------------------------- //
// SPECIFYZOOMLEVELS
// --------------------------------------------------------------------- //
/// True to directly specify minum and maximum zoom levels available from the server, or false to automatically determine the minimum and maximum zoom levels from the server's tilemapresource.xml file.
///
/// | ||
/// | -- | -- |
/// | Declaration | `bool cesium:specifyZoomLevels = 0` |
/// | C++ Type | bool |
/// | \ref Usd_Datatypes "Usd Type" | SdfValueTypeNames->Bool |
CESIUMUSDSCHEMAS_API
UsdAttribute GetSpecifyZoomLevelsAttr() const;
/// See GetSpecifyZoomLevelsAttr(), 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 CreateSpecifyZoomLevelsAttr(VtValue const &defaultValue = VtValue(), bool writeSparsely=false) const;
public:
// --------------------------------------------------------------------- //
// MINIMUMZOOMLEVEL
// --------------------------------------------------------------------- //
/// Minimum zoom level
///
/// | ||
/// | -- | -- |
/// | Declaration | `int cesium:minimumZoomLevel = 0` |
/// | C++ Type | int |
/// | \ref Usd_Datatypes "Usd Type" | SdfValueTypeNames->Int |
CESIUMUSDSCHEMAS_API
UsdAttribute GetMinimumZoomLevelAttr() const;
/// See GetMinimumZoomLevelAttr(), 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 CreateMinimumZoomLevelAttr(VtValue const &defaultValue = VtValue(), bool writeSparsely=false) const;
public:
// --------------------------------------------------------------------- //
// MAXIMUMZOOMLEVEL
// --------------------------------------------------------------------- //
/// Maximum zoom level
///
/// | ||
/// | -- | -- |
/// | Declaration | `int cesium:maximumZoomLevel = 25` |
/// | C++ Type | int |
/// | \ref Usd_Datatypes "Usd Type" | SdfValueTypeNames->Int |
CESIUMUSDSCHEMAS_API
UsdAttribute GetMaximumZoomLevelAttr() const;
/// See GetMaximumZoomLevelAttr(), 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 CreateMaximumZoomLevelAttr(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
| 24,500 | C | 42.596085 | 205 | 0.572571 |
CesiumGS/cesium-omniverse/src/plugins/CesiumUsdSchemas/src/CesiumUsdSchemas/wrapIonServer.cpp | #include ".//ionServer.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
_CreateDisplayNameAttr(CesiumIonServer &self,
object defaultVal, bool writeSparsely) {
return self.CreateDisplayNameAttr(
UsdPythonToSdfType(defaultVal, SdfValueTypeNames->String), writeSparsely);
}
static UsdAttribute
_CreateIonServerUrlAttr(CesiumIonServer &self,
object defaultVal, bool writeSparsely) {
return self.CreateIonServerUrlAttr(
UsdPythonToSdfType(defaultVal, SdfValueTypeNames->String), writeSparsely);
}
static UsdAttribute
_CreateIonServerApiUrlAttr(CesiumIonServer &self,
object defaultVal, bool writeSparsely) {
return self.CreateIonServerApiUrlAttr(
UsdPythonToSdfType(defaultVal, SdfValueTypeNames->String), writeSparsely);
}
static UsdAttribute
_CreateIonServerApplicationIdAttr(CesiumIonServer &self,
object defaultVal, bool writeSparsely) {
return self.CreateIonServerApplicationIdAttr(
UsdPythonToSdfType(defaultVal, SdfValueTypeNames->Int64), writeSparsely);
}
static UsdAttribute
_CreateProjectDefaultIonAccessTokenAttr(CesiumIonServer &self,
object defaultVal, bool writeSparsely) {
return self.CreateProjectDefaultIonAccessTokenAttr(
UsdPythonToSdfType(defaultVal, SdfValueTypeNames->String), writeSparsely);
}
static UsdAttribute
_CreateProjectDefaultIonAccessTokenIdAttr(CesiumIonServer &self,
object defaultVal, bool writeSparsely) {
return self.CreateProjectDefaultIonAccessTokenIdAttr(
UsdPythonToSdfType(defaultVal, SdfValueTypeNames->String), writeSparsely);
}
static std::string
_Repr(const CesiumIonServer &self)
{
std::string primRepr = TfPyRepr(self.GetPrim());
return TfStringPrintf(
"CesiumUsdSchemas.IonServer(%s)",
primRepr.c_str());
}
} // anonymous namespace
void wrapCesiumIonServer()
{
typedef CesiumIonServer This;
class_<This, bases<UsdTyped> >
cls("IonServer");
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("GetDisplayNameAttr",
&This::GetDisplayNameAttr)
.def("CreateDisplayNameAttr",
&_CreateDisplayNameAttr,
(arg("defaultValue")=object(),
arg("writeSparsely")=false))
.def("GetIonServerUrlAttr",
&This::GetIonServerUrlAttr)
.def("CreateIonServerUrlAttr",
&_CreateIonServerUrlAttr,
(arg("defaultValue")=object(),
arg("writeSparsely")=false))
.def("GetIonServerApiUrlAttr",
&This::GetIonServerApiUrlAttr)
.def("CreateIonServerApiUrlAttr",
&_CreateIonServerApiUrlAttr,
(arg("defaultValue")=object(),
arg("writeSparsely")=false))
.def("GetIonServerApplicationIdAttr",
&This::GetIonServerApplicationIdAttr)
.def("CreateIonServerApplicationIdAttr",
&_CreateIonServerApplicationIdAttr,
(arg("defaultValue")=object(),
arg("writeSparsely")=false))
.def("GetProjectDefaultIonAccessTokenAttr",
&This::GetProjectDefaultIonAccessTokenAttr)
.def("CreateProjectDefaultIonAccessTokenAttr",
&_CreateProjectDefaultIonAccessTokenAttr,
(arg("defaultValue")=object(),
arg("writeSparsely")=false))
.def("GetProjectDefaultIonAccessTokenIdAttr",
&This::GetProjectDefaultIonAccessTokenIdAttr)
.def("CreateProjectDefaultIonAccessTokenIdAttr",
&_CreateProjectDefaultIonAccessTokenIdAttr,
(arg("defaultValue")=object(),
arg("writeSparsely")=false))
.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 {
}
}
| 5,889 | C++ | 30.666667 | 82 | 0.614196 |
CesiumGS/cesium-omniverse/src/plugins/CesiumUsdSchemas/src/CesiumUsdSchemas/session.cpp | #include ".//session.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<CesiumSession,
TfType::Bases< UsdTyped > >();
// Register the usd prim typename as an alias under UsdSchemaBase. This
// enables one to call
// TfType::Find<UsdSchemaBase>().FindDerivedByName("CesiumSessionPrim")
// to find TfType<CesiumSession>, which is how IsA queries are
// answered.
TfType::AddAlias<UsdSchemaBase, CesiumSession>("CesiumSessionPrim");
}
/* virtual */
CesiumSession::~CesiumSession()
{
}
/* static */
CesiumSession
CesiumSession::Get(const UsdStagePtr &stage, const SdfPath &path)
{
if (!stage) {
TF_CODING_ERROR("Invalid stage");
return CesiumSession();
}
return CesiumSession(stage->GetPrimAtPath(path));
}
/* static */
CesiumSession
CesiumSession::Define(
const UsdStagePtr &stage, const SdfPath &path)
{
static TfToken usdPrimTypeName("CesiumSessionPrim");
if (!stage) {
TF_CODING_ERROR("Invalid stage");
return CesiumSession();
}
return CesiumSession(
stage->DefinePrim(path, usdPrimTypeName));
}
/* virtual */
UsdSchemaKind CesiumSession::_GetSchemaKind() const
{
return CesiumSession::schemaKind;
}
/* static */
const TfType &
CesiumSession::_GetStaticTfType()
{
static TfType tfType = TfType::Find<CesiumSession>();
return tfType;
}
/* static */
bool
CesiumSession::_IsTypedSchema()
{
static bool isTyped = _GetStaticTfType().IsA<UsdTyped>();
return isTyped;
}
/* virtual */
const TfType &
CesiumSession::_GetTfType() const
{
return _GetStaticTfType();
}
UsdAttribute
CesiumSession::GetEcefToUsdTransformAttr() const
{
return GetPrim().GetAttribute(CesiumTokens->cesiumEcefToUsdTransform);
}
UsdAttribute
CesiumSession::CreateEcefToUsdTransformAttr(VtValue const &defaultValue, bool writeSparsely) const
{
return UsdSchemaBase::_CreateAttr(CesiumTokens->cesiumEcefToUsdTransform,
SdfValueTypeNames->Matrix4d,
/* custom = */ false,
SdfVariabilityVarying,
defaultValue,
writeSparsely);
}
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&
CesiumSession::GetSchemaAttributeNames(bool includeInherited)
{
static TfTokenVector localNames = {
CesiumTokens->cesiumEcefToUsdTransform,
};
static TfTokenVector allNames =
_ConcatenateAttributeNames(
UsdTyped::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)--
| 3,568 | C++ | 24.492857 | 98 | 0.654989 |
CesiumGS/cesium-omniverse/src/plugins/CesiumUsdSchemas/src/CesiumUsdSchemas/ionServer.cpp | #include ".//ionServer.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<CesiumIonServer,
TfType::Bases< UsdTyped > >();
// Register the usd prim typename as an alias under UsdSchemaBase. This
// enables one to call
// TfType::Find<UsdSchemaBase>().FindDerivedByName("CesiumIonServerPrim")
// to find TfType<CesiumIonServer>, which is how IsA queries are
// answered.
TfType::AddAlias<UsdSchemaBase, CesiumIonServer>("CesiumIonServerPrim");
}
/* virtual */
CesiumIonServer::~CesiumIonServer()
{
}
/* static */
CesiumIonServer
CesiumIonServer::Get(const UsdStagePtr &stage, const SdfPath &path)
{
if (!stage) {
TF_CODING_ERROR("Invalid stage");
return CesiumIonServer();
}
return CesiumIonServer(stage->GetPrimAtPath(path));
}
/* static */
CesiumIonServer
CesiumIonServer::Define(
const UsdStagePtr &stage, const SdfPath &path)
{
static TfToken usdPrimTypeName("CesiumIonServerPrim");
if (!stage) {
TF_CODING_ERROR("Invalid stage");
return CesiumIonServer();
}
return CesiumIonServer(
stage->DefinePrim(path, usdPrimTypeName));
}
/* virtual */
UsdSchemaKind CesiumIonServer::_GetSchemaKind() const
{
return CesiumIonServer::schemaKind;
}
/* static */
const TfType &
CesiumIonServer::_GetStaticTfType()
{
static TfType tfType = TfType::Find<CesiumIonServer>();
return tfType;
}
/* static */
bool
CesiumIonServer::_IsTypedSchema()
{
static bool isTyped = _GetStaticTfType().IsA<UsdTyped>();
return isTyped;
}
/* virtual */
const TfType &
CesiumIonServer::_GetTfType() const
{
return _GetStaticTfType();
}
UsdAttribute
CesiumIonServer::GetDisplayNameAttr() const
{
return GetPrim().GetAttribute(CesiumTokens->cesiumDisplayName);
}
UsdAttribute
CesiumIonServer::CreateDisplayNameAttr(VtValue const &defaultValue, bool writeSparsely) const
{
return UsdSchemaBase::_CreateAttr(CesiumTokens->cesiumDisplayName,
SdfValueTypeNames->String,
/* custom = */ false,
SdfVariabilityVarying,
defaultValue,
writeSparsely);
}
UsdAttribute
CesiumIonServer::GetIonServerUrlAttr() const
{
return GetPrim().GetAttribute(CesiumTokens->cesiumIonServerUrl);
}
UsdAttribute
CesiumIonServer::CreateIonServerUrlAttr(VtValue const &defaultValue, bool writeSparsely) const
{
return UsdSchemaBase::_CreateAttr(CesiumTokens->cesiumIonServerUrl,
SdfValueTypeNames->String,
/* custom = */ false,
SdfVariabilityVarying,
defaultValue,
writeSparsely);
}
UsdAttribute
CesiumIonServer::GetIonServerApiUrlAttr() const
{
return GetPrim().GetAttribute(CesiumTokens->cesiumIonServerApiUrl);
}
UsdAttribute
CesiumIonServer::CreateIonServerApiUrlAttr(VtValue const &defaultValue, bool writeSparsely) const
{
return UsdSchemaBase::_CreateAttr(CesiumTokens->cesiumIonServerApiUrl,
SdfValueTypeNames->String,
/* custom = */ false,
SdfVariabilityVarying,
defaultValue,
writeSparsely);
}
UsdAttribute
CesiumIonServer::GetIonServerApplicationIdAttr() const
{
return GetPrim().GetAttribute(CesiumTokens->cesiumIonServerApplicationId);
}
UsdAttribute
CesiumIonServer::CreateIonServerApplicationIdAttr(VtValue const &defaultValue, bool writeSparsely) const
{
return UsdSchemaBase::_CreateAttr(CesiumTokens->cesiumIonServerApplicationId,
SdfValueTypeNames->Int64,
/* custom = */ false,
SdfVariabilityVarying,
defaultValue,
writeSparsely);
}
UsdAttribute
CesiumIonServer::GetProjectDefaultIonAccessTokenAttr() const
{
return GetPrim().GetAttribute(CesiumTokens->cesiumProjectDefaultIonAccessToken);
}
UsdAttribute
CesiumIonServer::CreateProjectDefaultIonAccessTokenAttr(VtValue const &defaultValue, bool writeSparsely) const
{
return UsdSchemaBase::_CreateAttr(CesiumTokens->cesiumProjectDefaultIonAccessToken,
SdfValueTypeNames->String,
/* custom = */ false,
SdfVariabilityVarying,
defaultValue,
writeSparsely);
}
UsdAttribute
CesiumIonServer::GetProjectDefaultIonAccessTokenIdAttr() const
{
return GetPrim().GetAttribute(CesiumTokens->cesiumProjectDefaultIonAccessTokenId);
}
UsdAttribute
CesiumIonServer::CreateProjectDefaultIonAccessTokenIdAttr(VtValue const &defaultValue, bool writeSparsely) const
{
return UsdSchemaBase::_CreateAttr(CesiumTokens->cesiumProjectDefaultIonAccessTokenId,
SdfValueTypeNames->String,
/* custom = */ false,
SdfVariabilityVarying,
defaultValue,
writeSparsely);
}
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&
CesiumIonServer::GetSchemaAttributeNames(bool includeInherited)
{
static TfTokenVector localNames = {
CesiumTokens->cesiumDisplayName,
CesiumTokens->cesiumIonServerUrl,
CesiumTokens->cesiumIonServerApiUrl,
CesiumTokens->cesiumIonServerApplicationId,
CesiumTokens->cesiumProjectDefaultIonAccessToken,
CesiumTokens->cesiumProjectDefaultIonAccessTokenId,
};
static TfTokenVector allNames =
_ConcatenateAttributeNames(
UsdTyped::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)--
| 6,697 | C++ | 28.121739 | 112 | 0.662386 |
CesiumGS/cesium-omniverse/src/plugins/CesiumUsdSchemas/src/CesiumUsdSchemas/module.cpp | #include "pxr/pxr.h"
#include "pxr/base/tf/pyModule.h"
PXR_NAMESPACE_USING_DIRECTIVE
TF_WRAP_MODULE
{
TF_WRAP(CesiumData);
TF_WRAP(CesiumGeoreference);
TF_WRAP(CesiumGlobeAnchorAPI);
TF_WRAP(CesiumIonServer);
TF_WRAP(CesiumRasterOverlay);
TF_WRAP(CesiumIonRasterOverlay);
TF_WRAP(CesiumPolygonRasterOverlay);
TF_WRAP(CesiumSession);
TF_WRAP(CesiumTileMapServiceRasterOverlay);
TF_WRAP(CesiumTileset);
TF_WRAP(CesiumTokens);
TF_WRAP(CesiumWebMapServiceRasterOverlay);
TF_WRAP(CesiumWebMapTileServiceRasterOverlay);
}
| 544 | C++ | 23.772726 | 48 | 0.779412 |
CesiumGS/cesium-omniverse/src/plugins/CesiumUsdSchemas/src/CesiumUsdSchemas/webMapServiceRasterOverlay.cpp | #include ".//webMapServiceRasterOverlay.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<CesiumWebMapServiceRasterOverlay,
TfType::Bases< CesiumRasterOverlay > >();
// Register the usd prim typename as an alias under UsdSchemaBase. This
// enables one to call
// TfType::Find<UsdSchemaBase>().FindDerivedByName("CesiumWebMapServiceRasterOverlayPrim")
// to find TfType<CesiumWebMapServiceRasterOverlay>, which is how IsA queries are
// answered.
TfType::AddAlias<UsdSchemaBase, CesiumWebMapServiceRasterOverlay>("CesiumWebMapServiceRasterOverlayPrim");
}
/* virtual */
CesiumWebMapServiceRasterOverlay::~CesiumWebMapServiceRasterOverlay()
{
}
/* static */
CesiumWebMapServiceRasterOverlay
CesiumWebMapServiceRasterOverlay::Get(const UsdStagePtr &stage, const SdfPath &path)
{
if (!stage) {
TF_CODING_ERROR("Invalid stage");
return CesiumWebMapServiceRasterOverlay();
}
return CesiumWebMapServiceRasterOverlay(stage->GetPrimAtPath(path));
}
/* static */
CesiumWebMapServiceRasterOverlay
CesiumWebMapServiceRasterOverlay::Define(
const UsdStagePtr &stage, const SdfPath &path)
{
static TfToken usdPrimTypeName("CesiumWebMapServiceRasterOverlayPrim");
if (!stage) {
TF_CODING_ERROR("Invalid stage");
return CesiumWebMapServiceRasterOverlay();
}
return CesiumWebMapServiceRasterOverlay(
stage->DefinePrim(path, usdPrimTypeName));
}
/* virtual */
UsdSchemaKind CesiumWebMapServiceRasterOverlay::_GetSchemaKind() const
{
return CesiumWebMapServiceRasterOverlay::schemaKind;
}
/* static */
const TfType &
CesiumWebMapServiceRasterOverlay::_GetStaticTfType()
{
static TfType tfType = TfType::Find<CesiumWebMapServiceRasterOverlay>();
return tfType;
}
/* static */
bool
CesiumWebMapServiceRasterOverlay::_IsTypedSchema()
{
static bool isTyped = _GetStaticTfType().IsA<UsdTyped>();
return isTyped;
}
/* virtual */
const TfType &
CesiumWebMapServiceRasterOverlay::_GetTfType() const
{
return _GetStaticTfType();
}
UsdAttribute
CesiumWebMapServiceRasterOverlay::GetBaseUrlAttr() const
{
return GetPrim().GetAttribute(CesiumTokens->cesiumBaseUrl);
}
UsdAttribute
CesiumWebMapServiceRasterOverlay::CreateBaseUrlAttr(VtValue const &defaultValue, bool writeSparsely) const
{
return UsdSchemaBase::_CreateAttr(CesiumTokens->cesiumBaseUrl,
SdfValueTypeNames->String,
/* custom = */ false,
SdfVariabilityVarying,
defaultValue,
writeSparsely);
}
UsdAttribute
CesiumWebMapServiceRasterOverlay::GetLayersAttr() const
{
return GetPrim().GetAttribute(CesiumTokens->cesiumLayers);
}
UsdAttribute
CesiumWebMapServiceRasterOverlay::CreateLayersAttr(VtValue const &defaultValue, bool writeSparsely) const
{
return UsdSchemaBase::_CreateAttr(CesiumTokens->cesiumLayers,
SdfValueTypeNames->String,
/* custom = */ false,
SdfVariabilityVarying,
defaultValue,
writeSparsely);
}
UsdAttribute
CesiumWebMapServiceRasterOverlay::GetTileWidthAttr() const
{
return GetPrim().GetAttribute(CesiumTokens->cesiumTileWidth);
}
UsdAttribute
CesiumWebMapServiceRasterOverlay::CreateTileWidthAttr(VtValue const &defaultValue, bool writeSparsely) const
{
return UsdSchemaBase::_CreateAttr(CesiumTokens->cesiumTileWidth,
SdfValueTypeNames->Int,
/* custom = */ false,
SdfVariabilityVarying,
defaultValue,
writeSparsely);
}
UsdAttribute
CesiumWebMapServiceRasterOverlay::GetTileHeightAttr() const
{
return GetPrim().GetAttribute(CesiumTokens->cesiumTileHeight);
}
UsdAttribute
CesiumWebMapServiceRasterOverlay::CreateTileHeightAttr(VtValue const &defaultValue, bool writeSparsely) const
{
return UsdSchemaBase::_CreateAttr(CesiumTokens->cesiumTileHeight,
SdfValueTypeNames->Int,
/* custom = */ false,
SdfVariabilityVarying,
defaultValue,
writeSparsely);
}
UsdAttribute
CesiumWebMapServiceRasterOverlay::GetMinimumLevelAttr() const
{
return GetPrim().GetAttribute(CesiumTokens->cesiumMinimumLevel);
}
UsdAttribute
CesiumWebMapServiceRasterOverlay::CreateMinimumLevelAttr(VtValue const &defaultValue, bool writeSparsely) const
{
return UsdSchemaBase::_CreateAttr(CesiumTokens->cesiumMinimumLevel,
SdfValueTypeNames->Int,
/* custom = */ false,
SdfVariabilityVarying,
defaultValue,
writeSparsely);
}
UsdAttribute
CesiumWebMapServiceRasterOverlay::GetMaximumLevelAttr() const
{
return GetPrim().GetAttribute(CesiumTokens->cesiumMaximumLevel);
}
UsdAttribute
CesiumWebMapServiceRasterOverlay::CreateMaximumLevelAttr(VtValue const &defaultValue, bool writeSparsely) const
{
return UsdSchemaBase::_CreateAttr(CesiumTokens->cesiumMaximumLevel,
SdfValueTypeNames->Int,
/* custom = */ false,
SdfVariabilityVarying,
defaultValue,
writeSparsely);
}
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&
CesiumWebMapServiceRasterOverlay::GetSchemaAttributeNames(bool includeInherited)
{
static TfTokenVector localNames = {
CesiumTokens->cesiumBaseUrl,
CesiumTokens->cesiumLayers,
CesiumTokens->cesiumTileWidth,
CesiumTokens->cesiumTileHeight,
CesiumTokens->cesiumMinimumLevel,
CesiumTokens->cesiumMaximumLevel,
};
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)--
| 7,010 | C++ | 29.482609 | 111 | 0.677461 |