Merge branch 'dev' of github.com:syoyo/tinyusdz into dev

 Conflicts:
	src/ascii-parser.cc
This commit is contained in:
Syoyo Fujita
2022-10-16 01:04:30 +09:00
34 changed files with 5267 additions and 3805 deletions

View File

@@ -238,6 +238,9 @@ set(TINYUSDZ_SOURCES
${PROJECT_SOURCE_DIR}/src/xform.cc
${PROJECT_SOURCE_DIR}/src/performance.cc
${PROJECT_SOURCE_DIR}/src/ascii-parser.cc
${PROJECT_SOURCE_DIR}/src/ascii-parser-basetype.cc
${PROJECT_SOURCE_DIR}/src/ascii-parser-timesamples.cc
${PROJECT_SOURCE_DIR}/src/ascii-parser-timesamples-array.cc
${PROJECT_SOURCE_DIR}/src/audio-loader.cc
${PROJECT_SOURCE_DIR}/src/usda-reader.cc
${PROJECT_SOURCE_DIR}/src/usdc-reader.cc
@@ -267,6 +270,7 @@ set(TINYUSDZ_SOURCES
${PROJECT_SOURCE_DIR}/src/image-loader.cc
${PROJECT_SOURCE_DIR}/src/pprinter.cc
${PROJECT_SOURCE_DIR}/src/stage.cc
${PROJECT_SOURCE_DIR}/src/tydra/scene-access.cc
${PROJECT_SOURCE_DIR}/src/tydra/render-data.cc)
if(TINYUSDZ_WITH_PXR_COMPAT_API)
@@ -513,10 +517,11 @@ endif()
#
foreach(TINYUSDZ_LIB_TARGET ${TINYUSDZ_LIBS})
# /bigobj is required to avoid : fatal error C1128: number of sections exceeded object file format limit: compile with /bigobj
if(MSVC)
target_compile_options(${TINYUSDZ_LIB_TARGET} PRIVATE /bigobj)
endif()
# Current TinyUSDZ now should compile well without /bigobj flag.
# Uncommend if you encounter the following errror: fatal error C1128: number of sections exceeded object file format limit: compile with /bigobj
#if(MSVC)
# target_compile_options(${TINYUSDZ_LIB_TARGET} PRIVATE /bigobj)
#endif()
if(TINYUSDZ_PRODUCTION_BUILD)
target_compile_definitions(${TINYUSDZ_LIB_TARGET}

View File

@@ -108,18 +108,17 @@ If you need commercial support, eco-system development(e.g. plug-ins, DCC tools
* [x] Can be compiled with standalone MSVC compilers(Build Tools for Visual Studio 2019)
* [x] clang 3.4 or later https://clang.llvm.org/cxx_status.html
* [x] llvm-mingw(clang) supported
## USDZ file format
USDZ is actually an uncompressed zip file.
USDZ(ZIP) contains usd(binary or ascii) and resources(e.g. image/auduo files)
* [x] MinGW gcc supported, but not recommended(You may got compilation failure depending on your build configuration: https://github.com/syoyo/tinyusdz/issues/33 , and linking takes too much time if you use default bfd linker.). If you want to compile TinyUSDZ in MinGW environment, llvm-mingw(clang) is recommended to use.
## Build
### Integrate to your app
Recomended way is simply copy `src` and `include` folder to your app, and add `*.cc` files to your app's build system.
If you are using CMake, just include tinyusdz repo with `add_subdirectory`.
Another way is simply copy `src` folder to your app, and add `*.cc` files to your app's build system.
All include paths are set relative from `src` folder, so you can just add include directory to `src` folder.
See `<tinyusdz>/CMakeLists.txt` and [examples/sdlviewer/CMakeLists.txt](examples/sdlviewer/CMakeLists.txt) for details.
It may not be recommend to use tinyusdz as a git submodule, since the repo contains lots of codes required to build TinyUSDZ examples but these are not required for your app.
@@ -130,9 +129,9 @@ Please see `CMake build options` and `CMakeLists.txt`. In most case same identif
### CMake
cmake build is still provided for CI build. `CMakeSettings.json` is provided for Visual Studio 2019.
Cmake build is provided.
Cmake project is not recommended for embedding TinyUSDZ to your app.
#### Linux and macOS
```
$ mkdir build
@@ -141,6 +140,15 @@ $ cmake ..
$ make
```
Please take a look at `scripts/bootstrap-cmake-*.sh` for some build configuraions.
#### Visual Studio
Visual Studio 2019 and 2022 are supported.
`CMakeSettings.json` is provided for Visual Studio 2019, but reccommended way is to invoke `vcsetup.bat`.
(Edit VS version in `vcsetup.bat` as you with)
#### LLVM-MinGW build
MinGW native and cross-compiling example using llvm-mingw(clang) is provided.
@@ -281,7 +289,7 @@ then build TinyUSDZ by linking with this local Python build.
## License
TinyUSDZ is licensed under MIT license and Apache 2.0 license.
(Doing relicensing. Will be relicensed to Apache 2.0)
(Doing relicensing from MIT to Apache 2.0. Will be fully relicensed to Apache 2.0 at some point)
### Third party licenses

View File

@@ -3,76 +3,85 @@ cmake_minimum_required(VERSION 3.4.1)
option(TINYUSDZ_USE_USDOBJ "Build with built-in .obj support" On)
set(TINYUSDZ_SOURCES
${PROJECT_SOURCE_DIR}/../../../../../src/tinyusdz.cc
${PROJECT_SOURCE_DIR}/../../../../../src/prim-types.cc
${PROJECT_SOURCE_DIR}/../../../../../src/ascii-parser.cc
${PROJECT_SOURCE_DIR}/../../../../../src/usda-reader.cc
${PROJECT_SOURCE_DIR}/../../../../../src/usdc-reader.cc
${PROJECT_SOURCE_DIR}/../../../../../src/usdc-writer.cc
${PROJECT_SOURCE_DIR}/../../../../../src/crate-reader.cc
${PROJECT_SOURCE_DIR}/../../../../../src/crate-format.cc
${PROJECT_SOURCE_DIR}/../../../../../src/crate-pprint.cc
${PROJECT_SOURCE_DIR}/../../../../../src/io-util.cc
${PROJECT_SOURCE_DIR}/../../../../../src/pprinter.cc
${PROJECT_SOURCE_DIR}/../../../../../src/value-types.cc
${PROJECT_SOURCE_DIR}/../../../../../src/value-pprint.cc
${PROJECT_SOURCE_DIR}/../../../../../src/primvar.cc
${PROJECT_SOURCE_DIR}/../../../../../src/image-loader.cc
${PROJECT_SOURCE_DIR}/../../../../../src/usda-writer.cc)
${PROJECT_SOURCE_DIR}/../../../../../src/tinyusdz.cc
${PROJECT_SOURCE_DIR}/../../../../../src/prim-types.cc
${PROJECT_SOURCE_DIR}/../../../../../src/ascii-parser.cc
${PROJECT_SOURCE_DIR}/../../../../../src/ascii-parser-basetype.cc
${PROJECT_SOURCE_DIR}/../../../../../src/ascii-parser-timesamples.cc
${PROJECT_SOURCE_DIR}/../../../../../src/ascii-parser-timesamples-array.cc
${PROJECT_SOURCE_DIR}/../../../../../src/usda-reader.cc
${PROJECT_SOURCE_DIR}/../../../../../src/usdc-reader.cc
${PROJECT_SOURCE_DIR}/../../../../../src/usdc-writer.cc
${PROJECT_SOURCE_DIR}/../../../../../src/crate-reader.cc
${PROJECT_SOURCE_DIR}/../../../../../src/crate-format.cc
${PROJECT_SOURCE_DIR}/../../../../../src/crate-pprint.cc
${PROJECT_SOURCE_DIR}/../../../../../src/io-util.cc
${PROJECT_SOURCE_DIR}/../../../../../src/pprinter.cc
${PROJECT_SOURCE_DIR}/../../../../../src/tiny-format.cc
${PROJECT_SOURCE_DIR}/../../../../../src/value-types.cc
${PROJECT_SOURCE_DIR}/../../../../../src/value-pprint.cc
${PROJECT_SOURCE_DIR}/../../../../../src/primvar.cc
${PROJECT_SOURCE_DIR}/../../../../../src/prim-reconstruct.cc
${PROJECT_SOURCE_DIR}/../../../../../src/prim-composition.cc
${PROJECT_SOURCE_DIR}/../../../../../src/image-loader.cc
${PROJECT_SOURCE_DIR}/../../../../../src/usda-writer.cc
${PROJECT_SOURCE_DIR}/../../../../../src/usdGeom.cc
${PROJECT_SOURCE_DIR}/../../../../../src/xform.cc
${PROJECT_SOURCE_DIR}/../../../../../src/stage.cc
${PROJECT_SOURCE_DIR}/../../../../../src/tydra/scene-access.cc
${PROJECT_SOURCE_DIR}/../../../../../src/tydra/render-data.cc
)
if(TINYUSDZ_USE_USDOBJ)
list(APPEND TINYUSDZ_SOURCES
${PROJECT_SOURCE_DIR}/../../../../../src/usdObj.cc)
list(APPEND TINYUSDZ_SOURCES
${PROJECT_SOURCE_DIR}/../../../../../src/external/tiny_obj_loader.cc)
endif()
if (TINYUSDZ_USE_USDOBJ)
list(APPEND TINYUSDZ_SOURCES
${PROJECT_SOURCE_DIR}/../../../../../src/usdObj.cc)
list(APPEND TINYUSDZ_SOURCES
${PROJECT_SOURCE_DIR}/../../../../../src/external/tiny_obj_loader.cc)
endif ()
set(TINYUSDZ_DEP_SOURCES
${PROJECT_SOURCE_DIR}/../../../../../src/integerCoding.cpp
${PROJECT_SOURCE_DIR}/../../../../../src/lz4-compression.cc
${PROJECT_SOURCE_DIR}/../../../../../src/lz4/lz4.c
${PROJECT_SOURCE_DIR}/../../../../../src/external/string_id/database.cpp
${PROJECT_SOURCE_DIR}/../../../../../src/external/string_id/string_id.cpp
${PROJECT_SOURCE_DIR}/../../../../../src/external/string_id/error.cpp
${PROJECT_SOURCE_DIR}/../../../../../src/external/fpng.cpp
${PROJECT_SOURCE_DIR}/../../../../../src/external/staticstruct.cc
${PROJECT_SOURCE_DIR}/../../../../../src/external/tinyxml2/tinyxml2.cpp
${PROJECT_SOURCE_DIR}/../../../../../src/external/ryu/ryu/s2d.c
${PROJECT_SOURCE_DIR}/../../../../../src/external/ryu/ryu/s2f.c)
${PROJECT_SOURCE_DIR}/../../../../../src/integerCoding.cpp
${PROJECT_SOURCE_DIR}/../../../../../src/lz4-compression.cc
${PROJECT_SOURCE_DIR}/../../../../../src/lz4/lz4.c
#${PROJECT_SOURCE_DIR}/../../../../../src/external/string_id/database.cpp
#${PROJECT_SOURCE_DIR}/../../../../../src/external/string_id/string_id.cpp
#${PROJECT_SOURCE_DIR}/../../../../../src/external/string_id/error.cpp
${PROJECT_SOURCE_DIR}/../../../../../src/external/fpng.cpp
#${PROJECT_SOURCE_DIR}/../../../../../src/external/staticstruct.cc
${PROJECT_SOURCE_DIR}/../../../../../src/external/tinyxml2/tinyxml2.cpp
)
# Reuse files from sdlviewer
set(USDVIEW_SOURCES
${PROJECT_SOURCE_DIR}/../../../../../examples/sdlviewer/simple-render.cc
${PROJECT_SOURCE_DIR}/../../../../../examples/common/matrix.cc
${PROJECT_SOURCE_DIR}/../../../../../examples/common/trackball.cc)
${PROJECT_SOURCE_DIR}/../../../../../examples/sdlviewer/simple-render.cc
${PROJECT_SOURCE_DIR}/../../../../../examples/common/matrix.cc
${PROJECT_SOURCE_DIR}/../../../../../examples/common/trackball.cc)
# Build the libhello-oboe library
add_library(
hello-tinyusdz SHARED jni-tinyusdz.cc render-ctx.cc ${TINYUSDZ_SOURCES}
${TINYUSDZ_DEP_SOURCES} ${USDVIEW_SOURCES})
hello-tinyusdz SHARED jni-tinyusdz.cc render-ctx.cc ${TINYUSDZ_SOURCES}
${TINYUSDZ_DEP_SOURCES} ${USDVIEW_SOURCES})
target_link_libraries(hello-tinyusdz jnigraphics android log)
target_include_directories(
hello-tinyusdz
PRIVATE ${PROJECT_SOURCE_DIR}/../../../../../src/
${PROJECT_SOURCE_DIR}/../../../../../src/external/ryu
${PROJECT_SOURCE_DIR}/../../../../../src/external/fast_float/include
# nanort, nanosg, etc
${PROJECT_SOURCE_DIR}/../../../../../examples/common/
# sdlviewer example
${PROJECT_SOURCE_DIR}/../../../../../examples/sdlviewer/)
hello-tinyusdz
PRIVATE ${PROJECT_SOURCE_DIR}/../../../../../src/
# nanort, nanosg, etc
${PROJECT_SOURCE_DIR}/../../../../../examples/common/
# sdlviewer example
${PROJECT_SOURCE_DIR}/../../../../../examples/sdlviewer/)
if(TINYUSDZ_USE_USDOBJ)
target_compile_definitions(hello-tinyusdz PRIVATE "TINYUSDZ_USE_USDOBJ")
endif()
if (TINYUSDZ_USE_USDOBJ)
target_compile_definitions(hello-tinyusdz PRIVATE "TINYUSDZ_USE_USDOBJ")
endif ()
# Required to load .usd files from Android asset for demo purpose
# When you embed TinyUSDZ to your own app, you are better to load .usd files from a memory and turn this define off.
target_compile_definitions(hello-tinyusdz
PRIVATE "TINYUSDZ_ANDROID_LOAD_FROM_ASSETS")
PRIVATE "TINYUSDZ_ANDROID_LOAD_FROM_ASSETS")
# Enable optimization flags: if having problems with source level debugging,
# disable -Ofast ( and debug ), re-enable after done debugging.
target_compile_options(hello-tinyusdz PRIVATE -Wall -Werror
"$<$<CONFIG:RELEASE>:-Ofast>")
"$<$<CONFIG:RELEASE>:-Ofast>")

View File

@@ -67,7 +67,7 @@ void SimpleScene(tinyusdz::Stage *stage)
// primvar is simply an attribute with prefix `primvars:`
//
// texCoord2f[] primvars:uv = [ ... ] ( interpolation = "vertex" )
// int[] primvars:uv:indices = [ ... ]
// int[] primvars:uv:indices = [ ... ]
//
{
tinyusdz::PrimAttrib uvAttr;
@@ -92,7 +92,7 @@ void SimpleScene(tinyusdz::Stage *stage)
mesh.props.emplace("primvars:uv", uvProp);
// ----------------------
tinyusdz::PrimAttrib uvIndexAttr;
std::vector<int> uvIndices;
@@ -121,7 +121,7 @@ void SimpleScene(tinyusdz::Stage *stage)
attrib.set_var(std::move(var));
attrib.variability = tinyusdz::Variability::Uniform;
tinyusdz::AttrMeta meta;
meta.hidden = false;
attrib.meta = meta;
@@ -140,7 +140,7 @@ void SimpleScene(tinyusdz::Stage *stage)
// |
// +- [Mesh]
//
xformPrim.children.emplace_back(std::move(meshPrim));
xformPrim.children().emplace_back(std::move(meshPrim));
stage->GetRootPrims().emplace_back(std::move(xformPrim));
}

View File

@@ -289,6 +289,9 @@ list(
../../src/crate-pprint.cc
../../src/audio-loader.cc
../../src/ascii-parser.cc
../../src/ascii-parser-basetype.cc
../../src/ascii-parser-timesamples.cc
../../src/ascii-parser-timesamples-array.cc
../../src/usdc-reader.cc
../../src/usda-reader.cc
#../../src/usda-writer.cc
@@ -303,6 +306,7 @@ list(
../../src/xform.cc
../../src/stage.cc
../../src/tydra/render-data.cc
../../src/tydra/scene-access.cc
)
set(TINYUSDZ_DEP_SOURCES
@@ -310,11 +314,11 @@ set(TINYUSDZ_DEP_SOURCES
../../src/lz4-compression.cc
../../src/lz4/lz4.c
../../src/external/pystring.cpp
../../src/external/string_id/string_id.cpp
../../src/external/string_id/database.cpp
../../src/external/string_id/error.cpp
#../../src/external/string_id/string_id.cpp
#../../src/external/string_id/database.cpp
#../../src/external/string_id/error.cpp
../../src/external/fpng.cpp
../../src/external/staticstruct.cc
#../../src/external/staticstruct.cc
../../src/external/tinyxml2/tinyxml2.cpp
)

View File

@@ -1,7 +1,303 @@
#include <algorithm>
#include <iostream>
#include <sstream>
#include "tinyusdz.hh"
#include "tydra/render-data.hh"
#include "tydra/scene-access.hh"
#include "usdShade.hh"
#include "pprinter.hh"
#include "prim-pprint.hh"
#include "value-pprint.hh"
static std::string GetFileExtension(const std::string &filename) {
if (filename.find_last_of('.') != std::string::npos)
return filename.substr(filename.find_last_of('.') + 1);
return "";
}
static std::string str_tolower(std::string s) {
std::transform(s.begin(), s.end(), s.begin(),
// static_cast<int(*)(int)>(std::tolower) // wrong
// [](int c){ return std::tolower(c); } // wrong
// [](char c){ return std::tolower(c); } // wrong
[](unsigned char c) { return std::tolower(c); } // correct
);
return s;
}
// key = Full absolute prim path(e.g. `/bora/dora`)
using MaterialMap = std::map<std::string, const tinyusdz::Material *>;
using PreviewSurfaceMap =
std::map<std::string, std::pair<const tinyusdz::Shader *, const tinyusdz::UsdPreviewSurface *>>;
using UVTextureMap = std::map<std::string, std::pair<const tinyusdz::Shader *, const tinyusdz::UsdUVTexture *>>;
using PrimvarReader_float2Map =
std::map<std::string, std::pair<const tinyusdz::Shader *, const tinyusdz::UsdPrimvarReader_float2 *>>;
#if 0
template <typename T>
static bool TraverseRec(const std::string &path_prefix,
const tinyusdz::Prim &prim, uint32_t depth,
std::map<std::string, const T *> &itemmap) {
if (depth > 1024 * 128) {
// Too deep
return false;
}
std::string prim_abs_path = path_prefix + "/" + prim.local_path().full_path_name();
if (prim.is<tinyusdz::Material>()) {
if (const T *pv = prim.as<T>()) {
std::cout << "Path : <" << prim_abs_path << "> is "
<< tinyusdz::value::TypeTraits<T>::type_name() << ".\n";
itemmap[prim_abs_path] = pv;
}
}
for (const auto &child : prim.children()) {
if (!TraverseRec(prim_abs_path, child, depth + 1, itemmap)) {
return false;
}
}
return true;
}
template <typename T>
static bool TraverseShaderRec(const std::string &path_prefix,
const tinyusdz::Prim &prim, uint32_t depth,
std::map<std::string, const T *> &itemmap) {
if (depth > 1024 * 128) {
// Too deep
return false;
}
std::string prim_abs_path = path_prefix + "/" + prim.local_path().full_path_name();
// First test if Shader prim.
if (const tinyusdz::Shader *ps = prim.as<tinyusdz::Shader>()) {
// Concrete Shader object(e.g. UsdUVTexture) is stored in .data.
if (const T *s = ps->value.as<T>()) {
std::cout << "Path : <" << prim_abs_path << "> is "
<< tinyusdz::value::TypeTraits<T>::type_name() << ".\n";
itemmap[prim_abs_path] = s;
}
}
for (const auto &child : prim.children()) {
if (!TraverseShaderRec(prim_abs_path, child, depth + 1, itemmap)) {
return false;
}
}
return true;
}
static void TraverseMaterial(const tinyusdz::Stage &stage, MaterialMap &m) {
for (const auto &prim : stage.GetRootPrims()) {
TraverseRec(/* root */ "", prim, 0, m);
}
}
static void TraversePreviewSurface(const tinyusdz::Stage &stage,
PreviewSurfaceMap &m) {
for (const auto &prim : stage.GetRootPrims()) {
TraverseShaderRec(/* root */ "", prim, 0, m);
}
}
static void TraverseUVTexture(const tinyusdz::Stage &stage, UVTextureMap &m) {
for (const auto &prim : stage.GetRootPrims()) {
TraverseShaderRec(/* root */ "", prim, 0, m);
}
}
static void TraversePrimvarReader_float2(const tinyusdz::Stage &stage,
PrimvarReader_float2Map &m) {
for (const auto &prim : stage.GetRootPrims()) {
TraverseShaderRec(/* root */ "", prim, 0, m);
}
}
#endif
int main(int argc, char **argv) {
if (argc < 2) {
std::cout << "Need input.usdz\n" << std::endl;
return EXIT_FAILURE;
}
std::string filepath = argv[1];
std::string warn;
std::string err;
std::string ext = str_tolower(GetFileExtension(filepath));
tinyusdz::Stage stage;
if (ext.compare("usdc") == 0) {
bool ret = tinyusdz::LoadUSDCFromFile(filepath, &stage, &warn, &err);
if (!warn.empty()) {
std::cerr << "WARN : " << warn << "\n";
}
if (!err.empty()) {
std::cerr << "ERR : " << err << "\n";
// return EXIT_FAILURE;
}
if (!ret) {
std::cerr << "Failed to load USDC file: " << filepath << "\n";
return EXIT_FAILURE;
}
} else if (ext.compare("usda") == 0) {
bool ret = tinyusdz::LoadUSDAFromFile(filepath, &stage, &warn, &err);
if (!warn.empty()) {
std::cerr << "WARN : " << warn << "\n";
}
if (!err.empty()) {
std::cerr << "ERR : " << err << "\n";
// return EXIT_FAILURE;
}
if (!ret) {
std::cerr << "Failed to load USDA file: " << filepath << "\n";
return EXIT_FAILURE;
}
} else if (ext.compare("usdz") == 0) {
// std::cout << "usdz\n";
bool ret = tinyusdz::LoadUSDZFromFile(filepath, &stage, &warn, &err);
if (!warn.empty()) {
std::cerr << "WARN : " << warn << "\n";
}
if (!err.empty()) {
std::cerr << "ERR : " << err << "\n";
// return EXIT_FAILURE;
}
if (!ret) {
std::cerr << "Failed to load USDZ file: " << filepath << "\n";
return EXIT_FAILURE;
}
} else {
// try to auto detect format.
bool ret = tinyusdz::LoadUSDFromFile(filepath, &stage, &warn, &err);
if (!warn.empty()) {
std::cerr << "WARN : " << warn << "\n";
}
if (!err.empty()) {
std::cerr << "ERR : " << err << "\n";
// return EXIT_FAILURE;
}
if (!ret) {
std::cerr << "Failed to load USD file: " << filepath << "\n";
return EXIT_FAILURE;
}
}
std::string s = stage.ExportToString();
std::cout << s << "\n";
std::cout << "--------------------------------------"
<< "\n";
// Mapping hold the pointer to concrete Prim object,
// So stage content should not be changed(no Prim addition/deletion).
MaterialMap matmap;
PreviewSurfaceMap surfacemap;
UVTextureMap texmap;
PrimvarReader_float2Map preadermap;
// Collect and make full path <-> Prim/Shader mapping
tinyusdz::tydra::ListPrims(stage, matmap);
tinyusdz::tydra::ListShaders(stage, surfacemap);
tinyusdz::tydra::ListShaders(stage, texmap);
tinyusdz::tydra::ListShaders(stage, preadermap);
//
// Query example
//
for (const auto &item : matmap) {
nonstd::expected<const tinyusdz::Prim*, std::string> mat = stage.GetPrimAtPath(tinyusdz::Path(item.first, /* prop name */""));
if (mat) {
std::cout << "Found Material <" << item.first << "> from Stage:\n";
if (const tinyusdz::Material *mp = mat.value()->as<tinyusdz::Material>()) { // this should be true though.
std::cout << tinyusdz::to_string(*mp) << "\n";
}
} else {
std::cerr << "Err: " << mat.error() << "\n";
}
}
for (const auto &item : surfacemap) {
// Returned Prim is Shader class
nonstd::expected<const tinyusdz::Prim*, std::string> shader = stage.GetPrimAtPath(tinyusdz::Path(item.first, /* prop name */""));
if (shader) {
std::cout << "Found Shader(UsdPreviewSurface) <" << item.first << "> from Stage:\n";
const tinyusdz::Shader *sp = shader.value()->as<tinyusdz::Shader>();
if (sp) { // this should be true though.
if (const tinyusdz::UsdPreviewSurface *surf = sp->value.as<tinyusdz::UsdPreviewSurface>()) {
// Print Shader
std::cout << tinyusdz::to_string(*sp) << "\n";
}
}
} else {
std::cerr << "Err: " << shader.error() << "\n";
}
}
for (const auto &item : texmap) {
// Returned Prim is Shader class
nonstd::expected<const tinyusdz::Prim*, std::string> shader = stage.GetPrimAtPath(tinyusdz::Path(item.first, /* prop name */""));
if (shader) {
std::cout << "Found Shader(UsdUVTexture) <" << item.first << "> from Stage:\n";
const tinyusdz::Shader *sp = shader.value()->as<tinyusdz::Shader>();
if (sp) { // this should be true though.
if (const tinyusdz::UsdUVTexture *tex = sp->value.as<tinyusdz::UsdUVTexture>()) {
std::cout << tinyusdz::to_string(*sp);
}
}
} else {
std::cerr << "Err: " << shader.error() << "\n";
}
}
for (const auto &item : preadermap) {
// Returned Prim is Shader class
nonstd::expected<const tinyusdz::Prim*, std::string> shader = stage.GetPrimAtPath(tinyusdz::Path(item.first, /* prop name */""));
if (shader) {
std::cout << "Found Shader(UsdPrimvarReader_float2) <" << item.first << "> from Stage:\n";
const tinyusdz::Shader *sp = shader.value()->as<tinyusdz::Shader>();
if (sp) { // this should be true though.
if (const tinyusdz::UsdPrimvarReader_float2 *preader = sp->value.as<tinyusdz::UsdPrimvarReader_float2>()) {
std::cout << tinyusdz::to_string(*sp) << "\n";
}
}
} else {
std::cerr << "Err: " << shader.error() << "\n";
}
}
//
// -- Querying Parent Prim
//
for (const auto &item : surfacemap) {
// Usually Parent is Material
std::string err;
if (const tinyusdz::Prim *p = tinyusdz::tydra::GetParentPrim(stage, tinyusdz::Path(item.first, /* property */""), &err)) {
std::cout << "Input path = " << tinyusdz::to_string(item.first) << "\n";
std::cout << "Parent prim = " << tinyusdz::prim::print_prim(*p) << "\n";
} else {
std::cerr << err;
}
}
int main(int argc, char **argv)
{
return 0;
}

View File

@@ -37,12 +37,16 @@ list(
../../src/crate-writer.cc
../../src/crate-pprint.cc
../../src/ascii-parser.cc
../../src/ascii-parser-basetype.cc
../../src/ascii-parser-timesamples.cc
../../src/ascii-parser-timesamples-array.cc
../../src/usda-reader.cc
../../src/usda-writer.cc
../../src/usdc-reader.cc
../../src/usdc-writer.cc
../../src/image-loader.cc
../../src/prim-reconstruct.cc
../../src/prim-composition.cc
../../src/tiny-format.cc
../../src/xform.cc
../../src/usdGeom.cc
@@ -52,6 +56,8 @@ list(
../../src/usdMtlx.cc
../../src/usdObj.cc
../../src/tydra/render-data.cc
../../src/tydra/scene-access.cc
../../src/stage.cc
)
set(TINYUSDZ_DEP_SOURCES

2950
src/ascii-parser-basetype.cc Normal file

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,396 @@
// SPDX-License-Identifier: MIT
// Copyright 2021 - Present, Syoyo Fujita.
//
// To deal with too many sections in generated .obj error(happens in MinGW and MSVC)
// Split ParseTimeSamples to two .cc files.
//
// TODO
// - [ ] Rewrite code with less C++ template code.
#include <cstdio>
#ifdef _MSC_VER
#ifndef NOMINMAX
#define NOMINMAX
#endif
#endif
#include <algorithm>
#include <atomic>
//#include <cassert>
#include <cstdlib>
#include <fstream>
#include <iostream>
#include <iterator>
#include <map>
#include <set>
#include <sstream>
#include <stack>
#if defined(__wasi__)
#else
#include <mutex>
#include <thread>
#endif
#include <vector>
#include "ascii-parser.hh"
#include "str-util.hh"
#include "tiny-format.hh"
//
#if !defined(TINYUSDZ_DISABLE_MODULE_USDA_READER)
//
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Weverything"
#endif
// external
//#include "external/fast_float/include/fast_float/fast_float.h"
//#include "external/jsteemann/atoi.h"
//#include "external/simple_match/include/simple_match/simple_match.hpp"
#include "nonstd/expected.hpp"
//
#ifdef __clang__
#pragma clang diagnostic pop
#endif
//
// Tentative
#ifdef __clang__
#pragma clang diagnostic ignored "-Wunused-parameter"
#endif
#include "common-macros.inc"
#include "io-util.hh"
#include "pprinter.hh"
#include "prim-types.hh"
#include "str-util.hh"
#include "stream-reader.hh"
#include "tinyusdz.hh"
#include "value-pprint.hh"
#include "value-types.hh"
namespace tinyusdz {
namespace ascii {
extern template bool AsciiParser::ParseBasicTypeArray(std::vector<nonstd::optional<bool>> *result);
extern template bool AsciiParser::ParseBasicTypeArray(std::vector<nonstd::optional<int32_t>> *result);
extern template bool AsciiParser::ParseBasicTypeArray(std::vector<nonstd::optional<uint32_t>> *result);
extern template bool AsciiParser::ParseBasicTypeArray(std::vector<nonstd::optional<int64_t>> *result);
extern template bool AsciiParser::ParseBasicTypeArray(std::vector<nonstd::optional<uint64_t>> *result);
extern template bool AsciiParser::ParseBasicTypeArray(std::vector<nonstd::optional<value::half>> *result);
extern template bool AsciiParser::ParseBasicTypeArray(std::vector<nonstd::optional<value::half2>> *result);
extern template bool AsciiParser::ParseBasicTypeArray(std::vector<nonstd::optional<value::half3>> *result);
extern template bool AsciiParser::ParseBasicTypeArray(std::vector<nonstd::optional<value::half4>> *result);
extern template bool AsciiParser::ParseBasicTypeArray(std::vector<nonstd::optional<float>> *result);
extern template bool AsciiParser::ParseBasicTypeArray(std::vector<nonstd::optional<value::float2>> *result);
extern template bool AsciiParser::ParseBasicTypeArray(std::vector<nonstd::optional<value::float3>> *result);
extern template bool AsciiParser::ParseBasicTypeArray(std::vector<nonstd::optional<value::float4>> *result);
extern template bool AsciiParser::ParseBasicTypeArray(std::vector<nonstd::optional<double>> *result);
extern template bool AsciiParser::ParseBasicTypeArray(std::vector<nonstd::optional<value::double2>> *result);
extern template bool AsciiParser::ParseBasicTypeArray(std::vector<nonstd::optional<value::double3>> *result);
extern template bool AsciiParser::ParseBasicTypeArray(std::vector<nonstd::optional<value::double4>> *result);
extern template bool AsciiParser::ParseBasicTypeArray(std::vector<nonstd::optional<value::texcoord2h>> *result);
extern template bool AsciiParser::ParseBasicTypeArray(std::vector<nonstd::optional<value::texcoord2f>> *result);
extern template bool AsciiParser::ParseBasicTypeArray(std::vector<nonstd::optional<value::texcoord2d>> *result);
extern template bool AsciiParser::ParseBasicTypeArray(std::vector<nonstd::optional<value::texcoord3h>> *result);
extern template bool AsciiParser::ParseBasicTypeArray(std::vector<nonstd::optional<value::texcoord3f>> *result);
extern template bool AsciiParser::ParseBasicTypeArray(std::vector<nonstd::optional<value::texcoord3d>> *result);
extern template bool AsciiParser::ParseBasicTypeArray(std::vector<nonstd::optional<value::point3h>> *result);
extern template bool AsciiParser::ParseBasicTypeArray(std::vector<nonstd::optional<value::point3f>> *result);
extern template bool AsciiParser::ParseBasicTypeArray(std::vector<nonstd::optional<value::point3d>> *result);
extern template bool AsciiParser::ParseBasicTypeArray(std::vector<nonstd::optional<value::normal3h>> *result);
extern template bool AsciiParser::ParseBasicTypeArray(std::vector<nonstd::optional<value::normal3f>> *result);
extern template bool AsciiParser::ParseBasicTypeArray(std::vector<nonstd::optional<value::normal3d>> *result);
extern template bool AsciiParser::ParseBasicTypeArray(std::vector<nonstd::optional<value::vector3h>> *result);
extern template bool AsciiParser::ParseBasicTypeArray(std::vector<nonstd::optional<value::vector3f>> *result);
extern template bool AsciiParser::ParseBasicTypeArray(std::vector<nonstd::optional<value::vector3d>> *result);
extern template bool AsciiParser::ParseBasicTypeArray(std::vector<nonstd::optional<value::color3h>> *result);
extern template bool AsciiParser::ParseBasicTypeArray(std::vector<nonstd::optional<value::color3f>> *result);
extern template bool AsciiParser::ParseBasicTypeArray(std::vector<nonstd::optional<value::color3d>> *result);
extern template bool AsciiParser::ParseBasicTypeArray(std::vector<nonstd::optional<value::color4h>> *result);
extern template bool AsciiParser::ParseBasicTypeArray(std::vector<nonstd::optional<value::color4f>> *result);
extern template bool AsciiParser::ParseBasicTypeArray(std::vector<nonstd::optional<value::color4d>> *result);
extern template bool AsciiParser::ParseBasicTypeArray(std::vector<nonstd::optional<value::matrix2d>> *result);
extern template bool AsciiParser::ParseBasicTypeArray(std::vector<nonstd::optional<value::matrix3d>> *result);
extern template bool AsciiParser::ParseBasicTypeArray(std::vector<nonstd::optional<value::matrix4d>> *result);
extern template bool AsciiParser::ParseBasicTypeArray(std::vector<nonstd::optional<value::quath>> *result);
extern template bool AsciiParser::ParseBasicTypeArray(std::vector<nonstd::optional<value::quatf>> *result);
extern template bool AsciiParser::ParseBasicTypeArray(std::vector<nonstd::optional<value::quatd>> *result);
extern template bool AsciiParser::ParseBasicTypeArray(std::vector<nonstd::optional<value::token>> *result);
extern template bool AsciiParser::ParseBasicTypeArray(std::vector<nonstd::optional<StringData>> *result);
extern template bool AsciiParser::ParseBasicTypeArray(std::vector<nonstd::optional<std::string>> *result);
extern template bool AsciiParser::ParseBasicTypeArray(std::vector<nonstd::optional<Reference>> *result);
extern template bool AsciiParser::ParseBasicTypeArray(std::vector<nonstd::optional<Path>> *result);
extern template bool AsciiParser::ParseBasicTypeArray(std::vector<nonstd::optional<value::AssetPath>> *result);
extern template bool AsciiParser::ParseBasicTypeArray(std::vector<bool> *result);
extern template bool AsciiParser::ParseBasicTypeArray(std::vector<int32_t> *result);
extern template bool AsciiParser::ParseBasicTypeArray(std::vector<uint32_t> *result);
extern template bool AsciiParser::ParseBasicTypeArray(std::vector<int64_t> *result);
extern template bool AsciiParser::ParseBasicTypeArray(std::vector<uint64_t> *result);
extern template bool AsciiParser::ParseBasicTypeArray(std::vector<value::half> *result);
extern template bool AsciiParser::ParseBasicTypeArray(std::vector<value::half2> *result);
extern template bool AsciiParser::ParseBasicTypeArray(std::vector<value::half3> *result);
extern template bool AsciiParser::ParseBasicTypeArray(std::vector<value::half4> *result);
extern template bool AsciiParser::ParseBasicTypeArray(std::vector<float> *result);
extern template bool AsciiParser::ParseBasicTypeArray(std::vector<value::float2> *result);
extern template bool AsciiParser::ParseBasicTypeArray(std::vector<value::float3> *result);
extern template bool AsciiParser::ParseBasicTypeArray(std::vector<value::float4> *result);
extern template bool AsciiParser::ParseBasicTypeArray(std::vector<double> *result);
extern template bool AsciiParser::ParseBasicTypeArray(std::vector<value::double2> *result);
extern template bool AsciiParser::ParseBasicTypeArray(std::vector<value::double3> *result);
extern template bool AsciiParser::ParseBasicTypeArray(std::vector<value::double4> *result);
extern template bool AsciiParser::ParseBasicTypeArray(std::vector<value::texcoord2h> *result);
extern template bool AsciiParser::ParseBasicTypeArray(std::vector<value::texcoord2f> *result);
extern template bool AsciiParser::ParseBasicTypeArray(std::vector<value::texcoord2d> *result);
extern template bool AsciiParser::ParseBasicTypeArray(std::vector<value::texcoord3h> *result);
extern template bool AsciiParser::ParseBasicTypeArray(std::vector<value::texcoord3f> *result);
extern template bool AsciiParser::ParseBasicTypeArray(std::vector<value::texcoord3d> *result);
extern template bool AsciiParser::ParseBasicTypeArray(std::vector<value::point3h> *result);
extern template bool AsciiParser::ParseBasicTypeArray(std::vector<value::point3f> *result);
extern template bool AsciiParser::ParseBasicTypeArray(std::vector<value::point3d> *result);
extern template bool AsciiParser::ParseBasicTypeArray(std::vector<value::normal3h> *result);
extern template bool AsciiParser::ParseBasicTypeArray(std::vector<value::normal3f> *result);
extern template bool AsciiParser::ParseBasicTypeArray(std::vector<value::normal3d> *result);
extern template bool AsciiParser::ParseBasicTypeArray(std::vector<value::vector3h> *result);
extern template bool AsciiParser::ParseBasicTypeArray(std::vector<value::vector3f> *result);
extern template bool AsciiParser::ParseBasicTypeArray(std::vector<value::vector3d> *result);
extern template bool AsciiParser::ParseBasicTypeArray(std::vector<value::color3h> *result);
extern template bool AsciiParser::ParseBasicTypeArray(std::vector<value::color3f> *result);
extern template bool AsciiParser::ParseBasicTypeArray(std::vector<value::color3d> *result);
extern template bool AsciiParser::ParseBasicTypeArray(std::vector<value::color4h> *result);
extern template bool AsciiParser::ParseBasicTypeArray(std::vector<value::color4f> *result);
extern template bool AsciiParser::ParseBasicTypeArray(std::vector<value::color4d> *result);
extern template bool AsciiParser::ParseBasicTypeArray(std::vector<value::matrix2d> *result);
extern template bool AsciiParser::ParseBasicTypeArray(std::vector<value::matrix3d> *result);
extern template bool AsciiParser::ParseBasicTypeArray(std::vector<value::matrix4d> *result);
extern template bool AsciiParser::ParseBasicTypeArray(std::vector<value::quath> *result);
extern template bool AsciiParser::ParseBasicTypeArray(std::vector<value::quatf> *result);
extern template bool AsciiParser::ParseBasicTypeArray(std::vector<value::quatd> *result);
extern template bool AsciiParser::ParseBasicTypeArray(std::vector<value::token> *result);
extern template bool AsciiParser::ParseBasicTypeArray(std::vector<StringData> *result);
extern template bool AsciiParser::ParseBasicTypeArray(std::vector<std::string> *result);
extern template bool AsciiParser::ParseBasicTypeArray(std::vector<Reference> *result);
extern template bool AsciiParser::ParseBasicTypeArray(std::vector<Path> *result);
extern template bool AsciiParser::ParseBasicTypeArray(std::vector<value::AssetPath> *result);
//
// -- impl ParseTimeSampleData
//
// TODO: Share code with array version as much as possible.
template <typename T>
nonstd::optional<AsciiParser::TimeSampleData<std::vector<T>>>
AsciiParser::TryParseTimeSamplesOfArray() {
// timeSamples = '{' ((int : [T]) sep)+ '}'
// sep = ','(may ok to omit for the last element.
TimeSampleData<std::vector<T>> data;
if (!Expect('{')) {
return nonstd::nullopt;
}
if (!SkipWhitespaceAndNewline()) {
return nonstd::nullopt;
}
while (!Eof()) {
char c;
if (!Char1(&c)) {
return nonstd::nullopt;
}
if (c == '}') {
break;
}
Rewind(1);
double timeVal;
// -inf, inf and nan are handled.
if (!ReadBasicType(&timeVal)) {
PushError("Parse time value failed.");
return nonstd::nullopt;
}
if (!SkipWhitespace()) {
return nonstd::nullopt;
}
if (!Expect(':')) {
return nonstd::nullopt;
}
if (!SkipWhitespace()) {
return nonstd::nullopt;
}
// None(nullopt) or T[]
nonstd::optional<std::vector<T>> tsValue;
if (MaybeNone()) {
tsValue = nonstd::nullopt;
} else {
std::vector<T> value;
if (!ParseBasicTypeArray(&value)) {
PushError("Failed to parse array value.");
return nonstd::nullopt;
}
tsValue = value;
}
// The last element may have separator ','
{
// Semicolon ';' is not allowed as a separator for timeSamples array
// values.
if (!SkipWhitespace()) {
return nonstd::nullopt;
}
char sep;
if (!Char1(&sep)) {
return nonstd::nullopt;
}
DCOUT("sep = " << sep);
if (sep == '}') {
// End of item
data.push_back({timeVal, tsValue});
break;
} else if (sep == ',') {
// ok
} else {
Rewind(1);
// Look ahead Newline + '}'
auto loc = CurrLoc();
if (SkipWhitespaceAndNewline()) {
char nc;
if (!Char1(&nc)) {
return nonstd::nullopt;
}
if (nc == '}') {
// End of item
data.push_back({timeVal, tsValue});
break;
}
}
// Rewind and continue parsing.
SeekTo(loc);
}
}
if (!SkipWhitespaceAndNewline()) {
return nonstd::nullopt;
}
data.push_back({timeVal, tsValue});
}
DCOUT(
"Parse TimeSamples of array type success. # of items = " << data.size());
return std::move(data);
}
template <typename T>
value::TimeSamples AsciiParser::ConvertToTimeSamples(
const TimeSampleData<T> &ts) {
value::TimeSamples dst;
for (const auto &item : ts) {
dst.times.push_back(std::get<0>(item));
if (item.second) {
dst.values.push_back(item.second.value());
} else {
// Blocked.
dst.values.push_back(value::ValueBlock());
}
}
return dst;
}
bool AsciiParser::ParseTimeSamplesOfArray(const std::string &type_name,
value::TimeSamples *ts_out) {
// 1D and scalar
#define PARSE_TYPE(__tyname, __type, __ts) \
if ((__tyname == value::TypeTraits<__type>::type_name())) { \
if (auto pv = TryParseTimeSamplesOfArray<__type>()) { \
__ts = ConvertToTimeSamples<std::vector<__type>>(pv.value()); \
} else { \
PUSH_ERROR_AND_RETURN("Failed to parse timeSample data with type `" \
<< value::TypeTraits<__type>::type_name() \
<< "[]`"); \
} \
} else
value::TimeSamples ts;
// NOTE: `string` does not support multi-line string.
PARSE_TYPE(type_name, value::AssetPath, ts)
PARSE_TYPE(type_name, value::token, ts)
PARSE_TYPE(type_name, std::string, ts)
PARSE_TYPE(type_name, float, ts)
PARSE_TYPE(type_name, int, ts)
PARSE_TYPE(type_name, uint32_t, ts)
PARSE_TYPE(type_name, int64_t, ts)
PARSE_TYPE(type_name, uint64_t, ts)
PARSE_TYPE(type_name, value::half, ts)
PARSE_TYPE(type_name, value::half2, ts)
PARSE_TYPE(type_name, value::half3, ts)
PARSE_TYPE(type_name, value::half4, ts)
PARSE_TYPE(type_name, float, ts)
PARSE_TYPE(type_name, value::float2, ts)
PARSE_TYPE(type_name, value::float3, ts)
PARSE_TYPE(type_name, value::float4, ts)
PARSE_TYPE(type_name, double, ts)
PARSE_TYPE(type_name, value::double2, ts)
PARSE_TYPE(type_name, value::double3, ts)
PARSE_TYPE(type_name, value::double4, ts)
PARSE_TYPE(type_name, value::quath, ts)
PARSE_TYPE(type_name, value::quatf, ts)
PARSE_TYPE(type_name, value::quatd, ts)
PARSE_TYPE(type_name, value::color3f, ts)
PARSE_TYPE(type_name, value::color4f, ts)
PARSE_TYPE(type_name, value::color3d, ts)
PARSE_TYPE(type_name, value::color4d, ts)
PARSE_TYPE(type_name, value::vector3f, ts)
PARSE_TYPE(type_name, value::normal3f, ts)
PARSE_TYPE(type_name, value::point3f, ts)
PARSE_TYPE(type_name, value::texcoord2f, ts)
PARSE_TYPE(type_name, value::texcoord3f, ts)
PARSE_TYPE(type_name, value::matrix4d, ts) {
PUSH_ERROR_AND_RETURN(" : TODO: timeSamples type " + type_name);
}
#undef PARSE_TYPE
if (ts_out) {
(*ts_out) = std::move(ts);
}
return true;
}
} // namespace ascii
} // namespace tinyusdz
#else // TINYUSDZ_DISABLE_MODULE_USDA_READER
#endif // TINYUSDZ_DISABLE_MODULE_USDA_READER

View File

@@ -0,0 +1,385 @@
// SPDX-License-Identifier: MIT
// Copyright 2021 - Present, Syoyo Fujita.
//
// To deal with too many sections in generated .obj error(happens in MinGW and MSVC)
// Split ParseTimeSamples to two .cc files.
//
// TODO
// - [ ] Rewrite code with less C++ template code.
#include <cstdio>
#ifdef _MSC_VER
#ifndef NOMINMAX
#define NOMINMAX
#endif
#endif
#include <algorithm>
#include <atomic>
//#include <cassert>
#include <cstdlib>
#include <fstream>
#include <iostream>
#include <iterator>
#include <map>
#include <set>
#include <sstream>
#include <stack>
#if defined(__wasi__)
#else
#include <mutex>
#include <thread>
#endif
#include <vector>
#include "ascii-parser.hh"
#include "str-util.hh"
#include "tiny-format.hh"
//
#if !defined(TINYUSDZ_DISABLE_MODULE_USDA_READER)
//
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Weverything"
#endif
// external
//#include "external/fast_float/include/fast_float/fast_float.h"
//#include "external/jsteemann/atoi.h"
//#include "external/simple_match/include/simple_match/simple_match.hpp"
#include "nonstd/expected.hpp"
//
#ifdef __clang__
#pragma clang diagnostic pop
#endif
//
// Tentative
#ifdef __clang__
#pragma clang diagnostic ignored "-Wunused-parameter"
#endif
#include "common-macros.inc"
#include "io-util.hh"
#include "pprinter.hh"
#include "prim-types.hh"
#include "str-util.hh"
#include "stream-reader.hh"
#include "tinyusdz.hh"
#include "value-pprint.hh"
#include "value-types.hh"
namespace tinyusdz {
namespace ascii {
extern template bool AsciiParser::ParseBasicTypeArray(std::vector<nonstd::optional<bool>> *result);
extern template bool AsciiParser::ParseBasicTypeArray(std::vector<nonstd::optional<int32_t>> *result);
extern template bool AsciiParser::ParseBasicTypeArray(std::vector<nonstd::optional<uint32_t>> *result);
extern template bool AsciiParser::ParseBasicTypeArray(std::vector<nonstd::optional<int64_t>> *result);
extern template bool AsciiParser::ParseBasicTypeArray(std::vector<nonstd::optional<uint64_t>> *result);
extern template bool AsciiParser::ParseBasicTypeArray(std::vector<nonstd::optional<value::half>> *result);
extern template bool AsciiParser::ParseBasicTypeArray(std::vector<nonstd::optional<value::half2>> *result);
extern template bool AsciiParser::ParseBasicTypeArray(std::vector<nonstd::optional<value::half3>> *result);
extern template bool AsciiParser::ParseBasicTypeArray(std::vector<nonstd::optional<value::half4>> *result);
extern template bool AsciiParser::ParseBasicTypeArray(std::vector<nonstd::optional<float>> *result);
extern template bool AsciiParser::ParseBasicTypeArray(std::vector<nonstd::optional<value::float2>> *result);
extern template bool AsciiParser::ParseBasicTypeArray(std::vector<nonstd::optional<value::float3>> *result);
extern template bool AsciiParser::ParseBasicTypeArray(std::vector<nonstd::optional<value::float4>> *result);
extern template bool AsciiParser::ParseBasicTypeArray(std::vector<nonstd::optional<double>> *result);
extern template bool AsciiParser::ParseBasicTypeArray(std::vector<nonstd::optional<value::double2>> *result);
extern template bool AsciiParser::ParseBasicTypeArray(std::vector<nonstd::optional<value::double3>> *result);
extern template bool AsciiParser::ParseBasicTypeArray(std::vector<nonstd::optional<value::double4>> *result);
extern template bool AsciiParser::ParseBasicTypeArray(std::vector<nonstd::optional<value::texcoord2h>> *result);
extern template bool AsciiParser::ParseBasicTypeArray(std::vector<nonstd::optional<value::texcoord2f>> *result);
extern template bool AsciiParser::ParseBasicTypeArray(std::vector<nonstd::optional<value::texcoord2d>> *result);
extern template bool AsciiParser::ParseBasicTypeArray(std::vector<nonstd::optional<value::texcoord3h>> *result);
extern template bool AsciiParser::ParseBasicTypeArray(std::vector<nonstd::optional<value::texcoord3f>> *result);
extern template bool AsciiParser::ParseBasicTypeArray(std::vector<nonstd::optional<value::texcoord3d>> *result);
extern template bool AsciiParser::ParseBasicTypeArray(std::vector<nonstd::optional<value::point3h>> *result);
extern template bool AsciiParser::ParseBasicTypeArray(std::vector<nonstd::optional<value::point3f>> *result);
extern template bool AsciiParser::ParseBasicTypeArray(std::vector<nonstd::optional<value::point3d>> *result);
extern template bool AsciiParser::ParseBasicTypeArray(std::vector<nonstd::optional<value::normal3h>> *result);
extern template bool AsciiParser::ParseBasicTypeArray(std::vector<nonstd::optional<value::normal3f>> *result);
extern template bool AsciiParser::ParseBasicTypeArray(std::vector<nonstd::optional<value::normal3d>> *result);
extern template bool AsciiParser::ParseBasicTypeArray(std::vector<nonstd::optional<value::vector3h>> *result);
extern template bool AsciiParser::ParseBasicTypeArray(std::vector<nonstd::optional<value::vector3f>> *result);
extern template bool AsciiParser::ParseBasicTypeArray(std::vector<nonstd::optional<value::vector3d>> *result);
extern template bool AsciiParser::ParseBasicTypeArray(std::vector<nonstd::optional<value::color3h>> *result);
extern template bool AsciiParser::ParseBasicTypeArray(std::vector<nonstd::optional<value::color3f>> *result);
extern template bool AsciiParser::ParseBasicTypeArray(std::vector<nonstd::optional<value::color3d>> *result);
extern template bool AsciiParser::ParseBasicTypeArray(std::vector<nonstd::optional<value::color4h>> *result);
extern template bool AsciiParser::ParseBasicTypeArray(std::vector<nonstd::optional<value::color4f>> *result);
extern template bool AsciiParser::ParseBasicTypeArray(std::vector<nonstd::optional<value::color4d>> *result);
extern template bool AsciiParser::ParseBasicTypeArray(std::vector<nonstd::optional<value::matrix2d>> *result);
extern template bool AsciiParser::ParseBasicTypeArray(std::vector<nonstd::optional<value::matrix3d>> *result);
extern template bool AsciiParser::ParseBasicTypeArray(std::vector<nonstd::optional<value::matrix4d>> *result);
extern template bool AsciiParser::ParseBasicTypeArray(std::vector<nonstd::optional<value::quath>> *result);
extern template bool AsciiParser::ParseBasicTypeArray(std::vector<nonstd::optional<value::quatf>> *result);
extern template bool AsciiParser::ParseBasicTypeArray(std::vector<nonstd::optional<value::quatd>> *result);
extern template bool AsciiParser::ParseBasicTypeArray(std::vector<nonstd::optional<value::token>> *result);
extern template bool AsciiParser::ParseBasicTypeArray(std::vector<nonstd::optional<StringData>> *result);
extern template bool AsciiParser::ParseBasicTypeArray(std::vector<nonstd::optional<std::string>> *result);
extern template bool AsciiParser::ParseBasicTypeArray(std::vector<nonstd::optional<Reference>> *result);
extern template bool AsciiParser::ParseBasicTypeArray(std::vector<nonstd::optional<Path>> *result);
extern template bool AsciiParser::ParseBasicTypeArray(std::vector<nonstd::optional<value::AssetPath>> *result);
extern template bool AsciiParser::ParseBasicTypeArray(std::vector<bool> *result);
extern template bool AsciiParser::ParseBasicTypeArray(std::vector<int32_t> *result);
extern template bool AsciiParser::ParseBasicTypeArray(std::vector<uint32_t> *result);
extern template bool AsciiParser::ParseBasicTypeArray(std::vector<int64_t> *result);
extern template bool AsciiParser::ParseBasicTypeArray(std::vector<uint64_t> *result);
extern template bool AsciiParser::ParseBasicTypeArray(std::vector<value::half> *result);
extern template bool AsciiParser::ParseBasicTypeArray(std::vector<value::half2> *result);
extern template bool AsciiParser::ParseBasicTypeArray(std::vector<value::half3> *result);
extern template bool AsciiParser::ParseBasicTypeArray(std::vector<value::half4> *result);
extern template bool AsciiParser::ParseBasicTypeArray(std::vector<float> *result);
extern template bool AsciiParser::ParseBasicTypeArray(std::vector<value::float2> *result);
extern template bool AsciiParser::ParseBasicTypeArray(std::vector<value::float3> *result);
extern template bool AsciiParser::ParseBasicTypeArray(std::vector<value::float4> *result);
extern template bool AsciiParser::ParseBasicTypeArray(std::vector<double> *result);
extern template bool AsciiParser::ParseBasicTypeArray(std::vector<value::double2> *result);
extern template bool AsciiParser::ParseBasicTypeArray(std::vector<value::double3> *result);
extern template bool AsciiParser::ParseBasicTypeArray(std::vector<value::double4> *result);
extern template bool AsciiParser::ParseBasicTypeArray(std::vector<value::texcoord2h> *result);
extern template bool AsciiParser::ParseBasicTypeArray(std::vector<value::texcoord2f> *result);
extern template bool AsciiParser::ParseBasicTypeArray(std::vector<value::texcoord2d> *result);
extern template bool AsciiParser::ParseBasicTypeArray(std::vector<value::texcoord3h> *result);
extern template bool AsciiParser::ParseBasicTypeArray(std::vector<value::texcoord3f> *result);
extern template bool AsciiParser::ParseBasicTypeArray(std::vector<value::texcoord3d> *result);
extern template bool AsciiParser::ParseBasicTypeArray(std::vector<value::point3h> *result);
extern template bool AsciiParser::ParseBasicTypeArray(std::vector<value::point3f> *result);
extern template bool AsciiParser::ParseBasicTypeArray(std::vector<value::point3d> *result);
extern template bool AsciiParser::ParseBasicTypeArray(std::vector<value::normal3h> *result);
extern template bool AsciiParser::ParseBasicTypeArray(std::vector<value::normal3f> *result);
extern template bool AsciiParser::ParseBasicTypeArray(std::vector<value::normal3d> *result);
extern template bool AsciiParser::ParseBasicTypeArray(std::vector<value::vector3h> *result);
extern template bool AsciiParser::ParseBasicTypeArray(std::vector<value::vector3f> *result);
extern template bool AsciiParser::ParseBasicTypeArray(std::vector<value::vector3d> *result);
extern template bool AsciiParser::ParseBasicTypeArray(std::vector<value::color3h> *result);
extern template bool AsciiParser::ParseBasicTypeArray(std::vector<value::color3f> *result);
extern template bool AsciiParser::ParseBasicTypeArray(std::vector<value::color3d> *result);
extern template bool AsciiParser::ParseBasicTypeArray(std::vector<value::color4h> *result);
extern template bool AsciiParser::ParseBasicTypeArray(std::vector<value::color4f> *result);
extern template bool AsciiParser::ParseBasicTypeArray(std::vector<value::color4d> *result);
extern template bool AsciiParser::ParseBasicTypeArray(std::vector<value::matrix2d> *result);
extern template bool AsciiParser::ParseBasicTypeArray(std::vector<value::matrix3d> *result);
extern template bool AsciiParser::ParseBasicTypeArray(std::vector<value::matrix4d> *result);
extern template bool AsciiParser::ParseBasicTypeArray(std::vector<value::quath> *result);
extern template bool AsciiParser::ParseBasicTypeArray(std::vector<value::quatf> *result);
extern template bool AsciiParser::ParseBasicTypeArray(std::vector<value::quatd> *result);
extern template bool AsciiParser::ParseBasicTypeArray(std::vector<value::token> *result);
extern template bool AsciiParser::ParseBasicTypeArray(std::vector<StringData> *result);
extern template bool AsciiParser::ParseBasicTypeArray(std::vector<std::string> *result);
extern template bool AsciiParser::ParseBasicTypeArray(std::vector<Reference> *result);
extern template bool AsciiParser::ParseBasicTypeArray(std::vector<Path> *result);
extern template bool AsciiParser::ParseBasicTypeArray(std::vector<value::AssetPath> *result);
//
// -- impl ParseTimeSampleData
//
// TODO: Share code with array version as much as possible.
template <typename T>
nonstd::optional<AsciiParser::TimeSampleData<T>>
AsciiParser::TryParseTimeSamples() {
// timeSamples = '{' ((int : T) sep)+ '}'
// sep = ','(may ok to omit for the last element.
TimeSampleData<T> data;
if (!Expect('{')) {
return nonstd::nullopt;
}
if (!SkipWhitespaceAndNewline()) {
return nonstd::nullopt;
}
while (!Eof()) {
char c;
if (!Char1(&c)) {
return nonstd::nullopt;
}
if (c == '}') {
break;
}
Rewind(1);
double timeVal;
// -inf, inf and nan are handled.
if (!ReadBasicType(&timeVal)) {
PushError("Parse time value failed.");
return nonstd::nullopt;
}
if (!SkipWhitespace()) {
return nonstd::nullopt;
}
if (!Expect(':')) {
return nonstd::nullopt;
}
if (!SkipWhitespace()) {
return nonstd::nullopt;
}
nonstd::optional<T> value;
if (!ReadBasicType(&value)) {
return nonstd::nullopt;
}
// The last element may have separator ','
{
// Semicolon ';' is not allowed as a separator for timeSamples array
// values.
if (!SkipWhitespace()) {
return nonstd::nullopt;
}
char sep;
if (!Char1(&sep)) {
return nonstd::nullopt;
}
DCOUT("sep = " << sep);
if (sep == '}') {
// End of item
data.push_back({timeVal, value});
break;
} else if (sep == ',') {
// ok
} else {
Rewind(1);
// Look ahead Newline + '}'
auto loc = CurrLoc();
if (SkipWhitespaceAndNewline()) {
char nc;
if (!Char1(&nc)) {
return nonstd::nullopt;
}
if (nc == '}') {
// End of item
data.push_back({timeVal, value});
break;
}
}
// Rewind and continue parsing.
SeekTo(loc);
}
}
if (!SkipWhitespaceAndNewline()) {
return nonstd::nullopt;
}
data.push_back({timeVal, value});
}
DCOUT("Parse TimeSamples success. # of items = " << data.size());
return std::move(data);
}
template <typename T>
value::TimeSamples AsciiParser::ConvertToTimeSamples(
const TimeSampleData<T> &ts) {
value::TimeSamples dst;
for (const auto &item : ts) {
dst.times.push_back(std::get<0>(item));
if (item.second) {
dst.values.push_back(item.second.value());
} else {
// Blocked.
dst.values.push_back(value::ValueBlock());
}
}
return dst;
}
bool AsciiParser::ParseTimeSamples(const std::string &type_name,
value::TimeSamples *ts_out) {
// 1D and scalar
#define PARSE_TYPE(__tyname, __type, __ts) \
if (__tyname == value::TypeTraits<__type>::type_name()) { \
if (auto pv = TryParseTimeSamples<__type>()) { \
__ts = ConvertToTimeSamples<__type>(pv.value()); \
} else { \
PUSH_ERROR_AND_RETURN("Failed to parse timeSample data with type `" \
<< value::TypeTraits<__type>::type_name() << "`"); \
} \
} else
value::TimeSamples ts;
// NOTE: `string` does not support multi-line string.
PARSE_TYPE(type_name, value::AssetPath, ts)
PARSE_TYPE(type_name, value::token, ts)
PARSE_TYPE(type_name, std::string, ts)
PARSE_TYPE(type_name, float, ts)
PARSE_TYPE(type_name, int, ts)
PARSE_TYPE(type_name, uint32_t, ts)
PARSE_TYPE(type_name, int64_t, ts)
PARSE_TYPE(type_name, uint64_t, ts)
PARSE_TYPE(type_name, value::half, ts)
PARSE_TYPE(type_name, value::half2, ts)
PARSE_TYPE(type_name, value::half3, ts)
PARSE_TYPE(type_name, value::half4, ts)
PARSE_TYPE(type_name, float, ts)
PARSE_TYPE(type_name, value::float2, ts)
PARSE_TYPE(type_name, value::float3, ts)
PARSE_TYPE(type_name, value::float4, ts)
PARSE_TYPE(type_name, double, ts)
PARSE_TYPE(type_name, value::double2, ts)
PARSE_TYPE(type_name, value::double3, ts)
PARSE_TYPE(type_name, value::double4, ts)
PARSE_TYPE(type_name, value::quath, ts)
PARSE_TYPE(type_name, value::quatf, ts)
PARSE_TYPE(type_name, value::quatd, ts)
PARSE_TYPE(type_name, value::color3f, ts)
PARSE_TYPE(type_name, value::color4f, ts)
PARSE_TYPE(type_name, value::color3d, ts)
PARSE_TYPE(type_name, value::color4d, ts)
PARSE_TYPE(type_name, value::vector3f, ts)
PARSE_TYPE(type_name, value::normal3f, ts)
PARSE_TYPE(type_name, value::point3f, ts)
PARSE_TYPE(type_name, value::texcoord2f, ts)
PARSE_TYPE(type_name, value::texcoord3f, ts)
PARSE_TYPE(type_name, value::matrix4d, ts) {
PUSH_ERROR_AND_RETURN(" : TODO: timeSamples type " + type_name);
}
#undef PARSE_TYPE
if (ts_out) {
(*ts_out) = std::move(ts);
}
return true;
}
} // namespace ascii
} // namespace tinyusdz
#else // TINYUSDZ_DISABLE_MODULE_USDA_READER
#endif // TINYUSDZ_DISABLE_MODULE_USDA_READER

File diff suppressed because it is too large Load Diff

View File

@@ -40,6 +40,15 @@ constexpr auto kToken = "token";
constexpr auto kKind = "kind";
constexpr auto kInterpolation = "interpolation";
struct Identifier : std::string {
// using std::string;
};
// FIXME: Not used? remove.
struct PathIdentifier : std::string {
// using std::string;
};
enum class LoadState {
TOPLEVEL, // toplevel .usda input
SUBLAYER, // .usda is read by 'subLayers'
@@ -303,11 +312,129 @@ class AsciiParser {
///
/// Return true but `value` is set to nullopt for `None`(Attribute Blocked)
///
template <typename T>
bool ReadBasicType(nonstd::optional<T> *value);
// template <typename T>
// bool ReadBasicType(nonstd::optional<T> *value);
template <typename T>
bool ReadBasicType(T *value);
bool ReadBasicType(nonstd::optional<bool> *value);
bool ReadBasicType(nonstd::optional<value::half> *value);
bool ReadBasicType(nonstd::optional<value::half2> *value);
bool ReadBasicType(nonstd::optional<value::half3> *value);
bool ReadBasicType(nonstd::optional<value::half4> *value);
bool ReadBasicType(nonstd::optional<int32_t> *value);
bool ReadBasicType(nonstd::optional<value::int2> *value);
bool ReadBasicType(nonstd::optional<value::int3> *value);
bool ReadBasicType(nonstd::optional<value::int4> *value);
bool ReadBasicType(nonstd::optional<uint32_t> *value);
bool ReadBasicType(nonstd::optional<value::uint2> *value);
bool ReadBasicType(nonstd::optional<value::uint3> *value);
bool ReadBasicType(nonstd::optional<value::uint4> *value);
bool ReadBasicType(nonstd::optional<int64_t> *value);
bool ReadBasicType(nonstd::optional<uint64_t> *value);
bool ReadBasicType(nonstd::optional<float> *value);
bool ReadBasicType(nonstd::optional<value::float2> *value);
bool ReadBasicType(nonstd::optional<value::float3> *value);
bool ReadBasicType(nonstd::optional<value::float4> *value);
bool ReadBasicType(nonstd::optional<double> *value);
bool ReadBasicType(nonstd::optional<value::double2> *value);
bool ReadBasicType(nonstd::optional<value::double3> *value);
bool ReadBasicType(nonstd::optional<value::double4> *value);
bool ReadBasicType(nonstd::optional<value::quath> *value);
bool ReadBasicType(nonstd::optional<value::quatf> *value);
bool ReadBasicType(nonstd::optional<value::quatd> *value);
bool ReadBasicType(nonstd::optional<value::point3h> *value);
bool ReadBasicType(nonstd::optional<value::point3f> *value);
bool ReadBasicType(nonstd::optional<value::point3d> *value);
bool ReadBasicType(nonstd::optional<value::vector3h> *value);
bool ReadBasicType(nonstd::optional<value::vector3f> *value);
bool ReadBasicType(nonstd::optional<value::vector3d> *value);
bool ReadBasicType(nonstd::optional<value::normal3h> *value);
bool ReadBasicType(nonstd::optional<value::normal3f> *value);
bool ReadBasicType(nonstd::optional<value::normal3d> *value);
bool ReadBasicType(nonstd::optional<value::color3h> *value);
bool ReadBasicType(nonstd::optional<value::color3f> *value);
bool ReadBasicType(nonstd::optional<value::color3d> *value);
bool ReadBasicType(nonstd::optional<value::color4h> *value);
bool ReadBasicType(nonstd::optional<value::color4f> *value);
bool ReadBasicType(nonstd::optional<value::color4d> *value);
bool ReadBasicType(nonstd::optional<value::matrix2d> *value);
bool ReadBasicType(nonstd::optional<value::matrix3d> *value);
bool ReadBasicType(nonstd::optional<value::matrix4d> *value);
bool ReadBasicType(nonstd::optional<value::texcoord2h> *value);
bool ReadBasicType(nonstd::optional<value::texcoord2f> *value);
bool ReadBasicType(nonstd::optional<value::texcoord2d> *value);
bool ReadBasicType(nonstd::optional<value::texcoord3h> *value);
bool ReadBasicType(nonstd::optional<value::texcoord3f> *value);
bool ReadBasicType(nonstd::optional<value::texcoord3d> *value);
bool ReadBasicType(nonstd::optional<StringData> *value);
bool ReadBasicType(nonstd::optional<std::string> *value);
bool ReadBasicType(nonstd::optional<value::token> *value);
bool ReadBasicType(nonstd::optional<Path> *value);
bool ReadBasicType(nonstd::optional<value::AssetPath> *value);
bool ReadBasicType(nonstd::optional<Reference> *value);
bool ReadBasicType(nonstd::optional<Identifier> *value);
bool ReadBasicType(nonstd::optional<PathIdentifier> *value);
// template <typename T>
// bool ReadBasicType(T *value);
bool ReadBasicType(bool *value);
bool ReadBasicType(value::half *value);
bool ReadBasicType(value::half2 *value);
bool ReadBasicType(value::half3 *value);
bool ReadBasicType(value::half4 *value);
bool ReadBasicType(int32_t *value);
bool ReadBasicType(value::int2 *value);
bool ReadBasicType(value::int3 *value);
bool ReadBasicType(value::int4 *value);
bool ReadBasicType(uint32_t *value);
bool ReadBasicType(value::uint2 *value);
bool ReadBasicType(value::uint3 *value);
bool ReadBasicType(value::uint4 *value);
bool ReadBasicType(int64_t *value);
bool ReadBasicType(uint64_t *value);
bool ReadBasicType(float *value);
bool ReadBasicType(value::float2 *value);
bool ReadBasicType(value::float3 *value);
bool ReadBasicType(value::float4 *value);
bool ReadBasicType(double *value);
bool ReadBasicType(value::double2 *value);
bool ReadBasicType(value::double3 *value);
bool ReadBasicType(value::double4 *value);
bool ReadBasicType(value::quath *value);
bool ReadBasicType(value::quatf *value);
bool ReadBasicType(value::quatd *value);
bool ReadBasicType(value::point3h *value);
bool ReadBasicType(value::point3f *value);
bool ReadBasicType(value::point3d *value);
bool ReadBasicType(value::vector3h *value);
bool ReadBasicType(value::vector3f *value);
bool ReadBasicType(value::vector3d *value);
bool ReadBasicType(value::normal3h *value);
bool ReadBasicType(value::normal3f *value);
bool ReadBasicType(value::normal3d *value);
bool ReadBasicType(value::color3h *value);
bool ReadBasicType(value::color3f *value);
bool ReadBasicType(value::color3d *value);
bool ReadBasicType(value::color4h *value);
bool ReadBasicType(value::color4f *value);
bool ReadBasicType(value::color4d *value);
bool ReadBasicType(value::texcoord2h *value);
bool ReadBasicType(value::texcoord2f *value);
bool ReadBasicType(value::texcoord2d *value);
bool ReadBasicType(value::texcoord3h *value);
bool ReadBasicType(value::texcoord3f *value);
bool ReadBasicType(value::texcoord3d *value);
bool ReadBasicType(value::matrix2d *value);
bool ReadBasicType(value::matrix3d *value);
bool ReadBasicType(value::matrix4d *value);
bool ReadBasicType(StringData *value);
bool ReadBasicType(std::string *value);
bool ReadBasicType(value::token *value);
bool ReadBasicType(Path *value);
bool ReadBasicType(value::AssetPath *value);
bool ReadBasicType(Reference *value);
bool ReadBasicType(Identifier *value);
bool ReadBasicType(PathIdentifier *value);
template <typename T>
bool ReadBasicType(nonstd::optional<std::vector<T>> *value);
@@ -315,8 +442,10 @@ class AsciiParser {
template <typename T>
bool ReadBasicType(std::vector<T> *value);
template <typename T>
bool ParseMatrix(T *result);
// Apprently, No float precision matrix in USDA
bool ParseMatrix(value::matrix2d *result);
bool ParseMatrix(value::matrix3d *result);
bool ParseMatrix(value::matrix4d *result);
///
/// Parse '(', Sep1By(','), ')'
@@ -334,6 +463,15 @@ class AsciiParser {
template <typename T, size_t N>
bool ParseTupleArray(std::vector<std::array<T, N>> *result);
#if 0
template<> bool ParseTupleArray(std::vector<std::array<float, 2>> *result);
template<> bool ParseTupleArray(std::vector<std::array<float, 3>> *result);
template<> bool ParseTupleArray(std::vector<std::array<float, 4>> *result);
template<> bool ParseTupleArray(std::vector<std::array<double, 2>> *result);
template<> bool ParseTupleArray(std::vector<std::array<double, 3>> *result);
template<> bool ParseTupleArray(std::vector<std::array<double, 4>> *result);
#endif
///
/// Parse the array of tuple. some may be None(e.g. `float3`: [(0, 1, 2),
/// None, (2, 3, 4), ...] )
@@ -341,6 +479,15 @@ class AsciiParser {
template <typename T, size_t N>
bool ParseTupleArray(std::vector<nonstd::optional<std::array<T, N>>> *result);
#if 0
template<> bool ParseTupleArray(std::vector<nonstd::optional<std::array<float, 2>>> *result);
template<> bool ParseTupleArray(std::vector<nonstd::optional<std::array<float, 3>>> *result);
template<> bool ParseTupleArray(std::vector<nonstd::optional<std::array<float, 4>>> *result);
template<> bool ParseTupleArray(std::vector<nonstd::optional<std::array<double, 2>>> *result);
template<> bool ParseTupleArray(std::vector<nonstd::optional<std::array<double, 3>>> *result);
template<> bool ParseTupleArray(std::vector<nonstd::optional<std::array<double, 4>>> *result);
#endif
template <typename T>
bool SepBy1BasicType(const char sep, std::vector<T> *result);
@@ -349,7 +496,8 @@ class AsciiParser {
/// (e.g. `[1, 2, 3,]`)
///
template <typename T>
bool SepBy1BasicType(const char sep, const char end_symbol, std::vector<T> *result);
bool SepBy1BasicType(const char sep, const char end_symbol,
std::vector<T> *result);
///
/// Parse '[', Sep1By(','), ']'
@@ -363,6 +511,56 @@ class AsciiParser {
template <typename T>
bool ParseBasicTypeArray(std::vector<T> *result);
#if 0
template<> bool ParseBasicTypeArray(std::vector<bool> *result);
template<> bool ParseBasicTypeArray(std::vector<int32_t> *result);
template<> bool ParseBasicTypeArray(std::vector<uint32_t> *result);
template<> bool ParseBasicTypeArray(std::vector<int64_t> *result);
template<> bool ParseBasicTypeArray(std::vector<uint64_t> *result);
template<> bool ParseBasicTypeArray(std::vector<value::half> *result);
template<> bool ParseBasicTypeArray(std::vector<value::half2> *result);
template<> bool ParseBasicTypeArray(std::vector<value::half3> *result);
template<> bool ParseBasicTypeArray(std::vector<value::half4> *result);
template<> bool ParseBasicTypeArray(std::vector<float> *result);
template<> bool ParseBasicTypeArray(std::vector<value::float2> *result);
template<> bool ParseBasicTypeArray(std::vector<value::float3> *result);
template<> bool ParseBasicTypeArray(std::vector<value::float4> *result);
template<> bool ParseBasicTypeArray(std::vector<double> *result);
template<> bool ParseBasicTypeArray(std::vector<value::double2> *result);
template<> bool ParseBasicTypeArray(std::vector<value::double3> *result);
template<> bool ParseBasicTypeArray(std::vector<value::double4> *result);
template<> bool ParseBasicTypeArray(std::vector<value::texcoord2h> *result);
template<> bool ParseBasicTypeArray(std::vector<value::texcoord2f> *result);
template<> bool ParseBasicTypeArray(std::vector<value::texcoord2d> *result);
template<> bool ParseBasicTypeArray(std::vector<value::texcoord3h> *result);
template<> bool ParseBasicTypeArray(std::vector<value::texcoord3f> *result);
template<> bool ParseBasicTypeArray(std::vector<value::texcoord3d> *result);
template<> bool ParseBasicTypeArray(std::vector<value::point3h> *result);
template<> bool ParseBasicTypeArray(std::vector<value::point3f> *result);
template<> bool ParseBasicTypeArray(std::vector<value::point3d> *result);
template<> bool ParseBasicTypeArray(std::vector<value::normal3h> *result);
template<> bool ParseBasicTypeArray(std::vector<value::normal3f> *result);
template<> bool ParseBasicTypeArray(std::vector<value::normal3d> *result);
template<> bool ParseBasicTypeArray(std::vector<value::vector3h> *result);
template<> bool ParseBasicTypeArray(std::vector<value::vector3f> *result);
template<> bool ParseBasicTypeArray(std::vector<value::vector3d> *result);
template<> bool ParseBasicTypeArray(std::vector<value::color3h> *result);
template<> bool ParseBasicTypeArray(std::vector<value::color3f> *result);
template<> bool ParseBasicTypeArray(std::vector<value::color3d> *result);
template<> bool ParseBasicTypeArray(std::vector<value::color4h> *result);
template<> bool ParseBasicTypeArray(std::vector<value::color4f> *result);
template<> bool ParseBasicTypeArray(std::vector<value::color4d> *result);
template<> bool ParseBasicTypeArray(std::vector<value::matrix2d> *result);
template<> bool ParseBasicTypeArray(std::vector<value::matrix3d> *result);
template<> bool ParseBasicTypeArray(std::vector<value::matrix4d> *result);
template<> bool ParseBasicTypeArray(std::vector<value::token> *result);
template<> bool ParseBasicTypeArray(std::vector<StringData> *result);
template<> bool ParseBasicTypeArray(std::vector<std::string> *result);
template<> bool ParseBasicTypeArray(std::vector<Reference> *result);
template<> bool ParseBasicTypeArray(std::vector<Path> *result);
template<> bool ParseBasicTypeArray(std::vector<value::AssetPath> *result);
#endif
///
/// Parses 1 or more occurences of value with basic type 'T', separated by
/// `sep`
@@ -389,6 +587,25 @@ class AsciiParser {
bool ParseDictElement(std::string *out_key, MetaVariable *out_var);
bool ParseDict(std::map<std::string, MetaVariable> *out_dict);
///
/// Parse TimeSample data(scalar type) and store it to type-erased data
/// structure value::TimeSamples.
///
/// @param[in] type_name Name of TimeSamples type(seen in .usda file. e.g.
/// "float" for `float var.timeSamples = ..`)
///
bool ParseTimeSamples(const std::string &type_name, value::TimeSamples *ts);
///
/// Parse TimeSample data(array type) and store it to type-erased data
/// structure value::TimeSamples.
///
/// @param[in] type_name Name of TimeSamples type(seen in .usda file. array
/// suffix `[]` is omitted. e.g. "float" for `float[] var.timeSamples = ..`)
///
bool ParseTimeSamplesOfArray(const std::string &type_name,
value::TimeSamples *ts);
///
/// `variants` in Prim meta.
///
@@ -570,6 +787,8 @@ class AsciiParser {
// template<typename T>
// bool ParseTimeSampleData(nonstd::optional<T> *out_value);
// -- [TimeSamples] -------------------
template <typename T>
using TimeSampleData = std::vector<std::pair<double, nonstd::optional<T>>>;
@@ -595,6 +814,8 @@ class AsciiParser {
template <typename T>
nonstd::optional<TimeSampleData<std::vector<T>>> TryParseTimeSamplesOfArray();
// ---------------------------------------
nonstd::optional<std::pair<ListEditQual, MetaVariable>> ParsePrimMeta();
bool ParsePrimProps(std::map<std::string, Property> *props);
@@ -619,7 +840,6 @@ class AsciiParser {
const tinyusdz::StreamReader *_sr = nullptr;
// "class" defs
// std::map<std::string, Klass> _klasses;
std::stack<std::string> _path_stack;

View File

@@ -3837,7 +3837,7 @@ bool CrateReader::BuildDecompressedPathsImpl(
// Assume single root node in the scene.
DCOUT("paths[" << pathIndexes[thisIndex]
<< "] is parent. name = " << parentPath.full_path_name());
parentPath = Path::RootPath();
parentPath = Path::make_root_path();
if (thisIndex >= pathIndexes.size()) {
PUSH_ERROR("Index exceeds pathIndexes.size()");
@@ -3849,7 +3849,7 @@ bool CrateReader::BuildDecompressedPathsImpl(
PUSH_ERROR("Index is out-of-range");
return false;
}
_paths[pathIndexes[thisIndex]] = parentPath;
} else {
if (thisIndex >= elementTokenIndexes.size()) {
@@ -4198,15 +4198,26 @@ bool CrateReader::ReadCompressedPaths(const uint64_t maxNumPaths) {
#ifdef TINYUSDZ_LOCAL_DEBUG_PRINT
for (size_t i = 0; i < pathIndexes.size(); i++) {
std::cout << "pathIndexes[" << i << "] = " << pathIndexes[i] << "\n";
DCOUT("pathIndexes[" << i << "] = " << pathIndexes[i]);
}
for (auto item : elementTokenIndexes) {
std::cout << "elementTokenIndexes " << item << "\n";
for (size_t i = 0; i < elementTokenIndexes.size(); i++) {
std::stringstream ss;
ss << "elementTokenIndexes[" << i << "] = " << elementTokenIndexes[i];
int32_t tokIdx = elementTokenIndexes[i];
if (tokIdx < 0) {
// Property Path. Need to negate it.
tokIdx = -tokIdx;
}
if (auto tokv = GetToken(crate::Index(uint32_t(tokIdx)))) {
ss << "(" << tokv.value() << ")";
}
ss << "\n";
DCOUT(ss.str());
}
for (auto item : jumps) {
std::cout << "jumps " << item << "\n";
for (size_t i = 0; i < jumps.size(); i++) {
DCOUT(fmt::format("jumps[{}] = {}", i, jumps[i]));
}
#endif
@@ -4983,10 +4994,10 @@ bool CrateReader::ReadPaths() {
}
#ifdef TINYUSDZ_LOCAL_DEBUG_PRINT
std::cout << "# of paths " << _paths.size() << "\n";
DCOUT("# of paths " << _paths.size());
for (size_t i = 0; i < _paths.size(); i++) {
std::cout << "path[" << i << "] = " << _paths[i].full_path_name() << "\n";
DCOUT("path[" << i << "] = " << _paths[i].full_path_name());
}
#endif

View File

@@ -305,7 +305,7 @@ bool ReadFileHeader(std::vector<uint8_t> *out, std::string *err,
return false;
}
size = (std::min)(max_read_bytes, size);
size = (std::min)(size_t(max_read_bytes), size);
out->resize(size);
AAsset_read(asset, reinterpret_cast<char *>(&out->at(0)), size);
AAsset_close(asset);

View File

@@ -22,13 +22,6 @@
// language governing permissions and limitations under the Apache License.
//
#ifdef _MSC_VER
#ifndef _USE_MATH_DEFINES
#define _USE_MATH_DEFINES
#endif
#endif
#include "../far/catmarkPatchBuilder.h"
#include "../vtr/stackBuffer.h"
@@ -45,8 +38,11 @@ using Vtr::internal::StackBuffer;
namespace Far {
constexpr auto kPI = 3.14159265358979323846;
constexpr auto kPI_2 = kPI/2.0;
//
// Core functions for computing Catmark limit properties that are used
// Core functions for computing Catmark limit properties that are used
// in the conversion to multiple patch types.
//
// This struct/class is just a means of grouping common functions.
@@ -62,7 +58,7 @@ namespace Far {
//
// Regarding support for multiple precision, like Sdc, some intermediate
// calculations are performed in double and cast to float. Historically
// this conversion code has been purely float and later extended to
// this conversion code has been purely float and later extended to
// support template <typename REAL>. For math functions such as cos(),
// sin(), etc., we rely on overloading via <cmath> through the use of
// std::cos(), std::sin(), etc.
@@ -92,7 +88,7 @@ inline double
CatmarkLimits<REAL>::computeCoefficient(int valence) {
static double const efTable[] = {
0.0, 0.0, 0.0,
0.0, 0.0, 0.0,
8.1281572906372312e-01, 0.5, 3.6364406329142801e-01,
2.8751379706077085e-01, 2.3868786685851678e-01, 2.0454364190756097e-01,
1.7922903958061159e-01, 1.5965737079986253e-01, 1.4404233443011302e-01,
@@ -107,7 +103,7 @@ CatmarkLimits<REAL>::computeCoefficient(int valence) {
if (valence < 30) return efTable[valence];
double invValence = 1.0 / valence;
double cosT = std::cos(2.0 * M_PI * invValence);
double cosT = std::cos(2.0 * kPI * invValence);
double divisor = (cosT + 5.0) + std::sqrt((cosT + 9.0) * (cosT + 1.0));
return (16.0 * invValence / divisor);
@@ -149,7 +145,7 @@ CatmarkLimits<REAL>::ComputeInteriorPointWeights(int valence, int faceInRing,
double pCoeff = oneOverValence * oneOverValPlus5;
double tanCoeff = computeCoefficient(valence) * 0.5f * oneOverValPlus5;
double faceAngle = 2.0 * M_PI * oneOverValence;
double faceAngle = 2.0 * kPI * oneOverValence;
//
// Assign position weights directly while accumulating an intermediate set
@@ -211,7 +207,7 @@ CatmarkLimits<REAL>::ComputeBoundaryPointWeights(int valence, int faceInRing,
Weight* pWeights, Weight* epWeights, Weight* emWeights) {
int numFaces = valence - 1;
double faceAngle = M_PI / numFaces;
double faceAngle = kPI / numFaces;
int weightWidth = 2 * valence;
@@ -472,7 +468,7 @@ namespace {
template <typename REAL>
void
_matrixPrintDensity(const char* prefix, SparseMatrix<REAL> const & M) {
int fullSize = M.GetNumRows() * M.GetNumColumns();
int sparseSize = M.GetNumElements();
@@ -766,12 +762,12 @@ GregoryConverter<REAL>::Initialize(SourcePatch const & sourcePatch) {
corner.isRegular = ((corner.numFaces << corner.isBoundary) == 4)
&& !corner.isSharp;
if (corner.isRegular) {
corner.faceAngle = REAL(M_PI_2);
corner.faceAngle = REAL(kPI_2);
corner.cosFaceAngle = 0.0f;
corner.sinFaceAngle = 1.0f;
} else {
corner.faceAngle =
(corner.isBoundary ? REAL(M_PI) : (2.0f * REAL(M_PI)))
(corner.isBoundary ? REAL(kPI) : (2.0f * REAL(kPI)))
/ REAL(corner.numFaces);
corner.cosFaceAngle = std::cos(corner.faceAngle);
corner.sinFaceAngle = std::sin(corner.faceAngle);
@@ -1609,7 +1605,7 @@ BSplineConverter<REAL>::convertIrregularCorner(int irregularCorner,
// (P5) P4----P15---P14 X0----X2----X4----X6
// . | | | | | | |
// . | | | | | | |
// P6----P0*---P3----P13 X1----P0*---P3----P13
// P6----P0*---P3----P13 X1----P0*---P3----P13
// | |P' Em| | ---> | | | |
// | |Ep | | | | | |
// P7----P1----P2----P12 X3----P1----P2----P12
@@ -1959,7 +1955,7 @@ CatmarkPatchBuilder::convertSourcePatch(SourcePatch const & sourcePatch,
// with the additional corner information that it initializes. That
// can then be used for conversion to all destination patch types...
//
if (patchType == PatchDescriptor::GREGORY_BASIS) {
GregoryConverter<REAL>(sourcePatch, matrix);
} else if (patchType == PatchDescriptor::REGULAR) {

View File

@@ -45,6 +45,8 @@ using Vtr::internal::StackBuffer;
namespace Far {
constexpr auto kPI = 3.14159265358979323846;
//
// A simple struct with methods to compute Loop limit points (following
// the pattern established for Catmull-Clark limit points)
@@ -180,7 +182,7 @@ LoopLimits<REAL>::ComputeInteriorPointWeights(int valence, int faceInRing,
// t2. Combine the weights for the point in a single set for t2 and
// then copy it into the appropriate orientation for ep and em:
//
double theta = 2.0 * M_PI / (double) valence;
double theta = 2.0 * kPI / (double) valence;
REAL tanScale = (REAL) ((3.0 + 2.0 * std::cos(theta)) / (6.0 * valence));
@@ -258,7 +260,7 @@ LoopLimits<REAL>::ComputeBoundaryPointWeights(int valence, int faceInRing,
epWeights[1] = (REAL) (1.0 / 3.0);
} else {
int iEdgeNext = faceInRing;
REAL faceAngle = (REAL) (M_PI / (double)(valence - 1));
REAL faceAngle = (REAL) (kPI / (double)(valence - 1));
REAL faceAngleNext = faceAngle * (REAL)iEdgeNext;
REAL cosAngleNext = std::cos(faceAngleNext);
REAL sinAngleNext = std::sin(faceAngleNext);
@@ -278,7 +280,7 @@ LoopLimits<REAL>::ComputeBoundaryPointWeights(int valence, int faceInRing,
emWeights[valence] = (REAL) (1.0 / 3.0);
} else {
int iEdgePrev = (faceInRing + 1) % valence;
REAL faceAngle = (REAL) (M_PI / (double)(valence - 1));
REAL faceAngle = (REAL) (kPI / (double)(valence - 1));
REAL faceAnglePrev = faceAngle * (REAL)iEdgePrev;
REAL cosAnglePrev = std::cos(faceAnglePrev);
REAL sinAnglePrev = std::sin(faceAnglePrev);
@@ -743,11 +745,11 @@ GregoryTriConverter<REAL>::Initialize(SourcePatch const & sourcePatch) {
corner.isRegular = ((corner.numFaces << corner.isBoundary) == 6)
&& !corner.isSharp;
if (corner.isRegular) {
corner.faceAngle = (REAL)(M_PI / 3.0);
corner.faceAngle = (REAL)(kPI / 3.0);
corner.cosFaceAngle = 0.5f;
} else {
corner.faceAngle =
(corner.isBoundary ? REAL(M_PI) : REAL(2.0 * M_PI))
(corner.isBoundary ? REAL(kPI) : REAL(2.0 * kPI))
/ REAL(corner.numFaces);
corner.cosFaceAngle = std::cos(corner.faceAngle);
}

View File

@@ -334,6 +334,8 @@ inline void
Scheme<SCHEME_CATMARK>::assignCreaseLimitTangentMasks(VERTEX const& vertex,
MASK& tan1Mask, MASK& tan2Mask, int const creaseEnds[2]) const {
constexpr auto kPI = 3.14159265358979323846;
typedef typename MASK::Weight Weight;
//
@@ -399,7 +401,7 @@ Scheme<SCHEME_CATMARK>::assignCreaseLimitTangentMasks(VERTEX const& vertex,
// The irregular case -- formulae from Biermann et al:
double k = (double) (interiorEdgeCount + 1);
double theta = M_PI / k;
double theta = kPI / k;
double cosTheta = std::cos(theta);
double sinTheta = std::sin(theta);
@@ -453,6 +455,7 @@ inline void
Scheme<SCHEME_CATMARK>::assignSmoothLimitTangentMasks(VERTEX const& vertex,
MASK& tan1Mask, MASK& tan2Mask) const {
constexpr auto kPI = 3.14159265358979323846;
typedef typename MASK::Weight Weight;
int valence = vertex.GetNumFaces();
@@ -480,7 +483,7 @@ Scheme<SCHEME_CATMARK>::assignSmoothLimitTangentMasks(VERTEX const& vertex,
tan1Mask.FaceWeight(2) = -1.0f;
tan1Mask.FaceWeight(3) = 1.0f;
} else {
double theta = 2.0f * M_PI / (double)valence;
double theta = 2.0f * kPI / (double)valence;
double cosTheta = std::cos(theta);
double cosHalfTheta = std::cos(theta * 0.5f);

View File

@@ -35,6 +35,8 @@ namespace OpenSubdiv {
namespace OPENSUBDIV_VERSION {
namespace Sdc {
constexpr auto kPI = 3.14159265358979323846;
//constexpr auto kPI_2 = kPI/2.0;
//
// Specializations for Sdc::Scheme<SCHEME_LOOP>:
@@ -199,7 +201,7 @@ Scheme<SCHEME_LOOP>::assignSmoothMaskForVertex(VERTEX const& vertex, MASK& mask)
double dValence = (double) valence;
double invValence = 1.0f / dValence;
double cosTheta = std::cos(M_PI * 2.0f * invValence);
double cosTheta = std::cos(kPI * 2.0f * invValence);
double beta = 0.25f * cosTheta + 0.375f;
@@ -298,7 +300,7 @@ Scheme<SCHEME_LOOP>::assignSmoothLimitMask(VERTEX const& vertex, MASK& posMask)
} else {
double dValence = (double) valence;
double invValence = 1.0f / dValence;
double cosTheta = std::cos(M_PI * 2.0f * invValence);
double cosTheta = std::cos(kPI * 2.0f * invValence);
double beta = 0.25f * cosTheta + 0.375f;
double gamma = (0.625f - (beta * beta)) * invValence;
@@ -492,7 +494,7 @@ Scheme<SCHEME_LOOP>::assignCreaseLimitTangentMasks(VERTEX const& vertex,
// 2.0 for considering the region as a half-disk, and 1.5 in keeping
// with the crease tangent):
double theta = M_PI / (interiorEdgeCount + 1);
double theta = kPI / (interiorEdgeCount + 1);
tan2Mask.VertexWeight(0) = 0.0f;
@@ -566,7 +568,7 @@ Scheme<SCHEME_LOOP>::assignSmoothLimitTangentMasks(VERTEX const& vertex,
tan2Mask.EdgeWeight(4) = -Root3by2;
tan2Mask.EdgeWeight(5) = -Root3by2;
} else {
double alpha = 2.0f * M_PI / valence;
double alpha = 2.0f * kPI / valence;
for (int i = 0; i < valence; ++i) {
double alphaI = alpha * i;
tan1Mask.EdgeWeight(i) = (Weight) std::cos(alphaI);

View File

@@ -2278,8 +2278,48 @@ std::string to_string(const Shader &shader, const uint32_t indent, bool closing_
}
std::string to_string(const UsdPreviewSurface &surf, const uint32_t indent, bool closing_brace) {
// TODO: Print spec and meta?
std::stringstream ss;
std::string to_string(const LuxSphereLight &light, const uint32_t indent, bool closing_brace) {
ss << pprint::Indent(indent) << "{\n";
ss << print_shader_params(surf, indent);
if (closing_brace) {
ss << pprint::Indent(indent) << "}\n";
}
return ss.str();
}
std::string to_string(const UsdUVTexture &tex, const uint32_t indent, bool closing_brace) {
// TODO: Print spec and meta?
std::stringstream ss;
ss << pprint::Indent(indent) << "{\n";
ss << print_shader_params(tex, indent);
if (closing_brace) {
ss << pprint::Indent(indent) << "}\n";
}
return ss.str();
}
std::string to_string(const UsdPrimvarReader_float2 &preader, const uint32_t indent, bool closing_brace) {
// TODO: Print spec and meta?
std::stringstream ss;
ss << pprint::Indent(indent) << "{\n";
ss << print_shader_params(preader, indent);
if (closing_brace) {
ss << pprint::Indent(indent) << "}\n";
}
return ss.str();
}
std::string to_string(const SphereLight &light, const uint32_t indent, bool closing_brace) {
std::stringstream ss;
ss << pprint::Indent(indent) << to_string(light.spec) << " SphereLight \"" << light.name << "\"\n";
@@ -2303,7 +2343,7 @@ std::string to_string(const LuxSphereLight &light, const uint32_t indent, bool c
return ss.str();
}
std::string to_string(const LuxDistantLight &light, const uint32_t indent, bool closing_brace) {
std::string to_string(const DistantLight &light, const uint32_t indent, bool closing_brace) {
std::stringstream ss;
ss << pprint::Indent(indent) << to_string(light.spec) << " DistantLight \"" << light.name << "\"\n";
@@ -2328,7 +2368,7 @@ std::string to_string(const LuxDistantLight &light, const uint32_t indent, bool
return ss.str();
}
std::string to_string(const LuxCylinderLight &light, const uint32_t indent, bool closing_brace) {
std::string to_string(const CylinderLight &light, const uint32_t indent, bool closing_brace) {
std::stringstream ss;
ss << pprint::Indent(indent) << to_string(light.spec) << " CylinderLight \"" << light.name << "\"\n";
@@ -2355,7 +2395,7 @@ std::string to_string(const LuxCylinderLight &light, const uint32_t indent, bool
return ss.str();
}
std::string to_string(const LuxDiskLight &light, const uint32_t indent, bool closing_brace) {
std::string to_string(const DiskLight &light, const uint32_t indent, bool closing_brace) {
std::stringstream ss;
ss << pprint::Indent(indent) << to_string(light.spec) << " DiskLight \"" << light.name << "\"\n";
@@ -2381,7 +2421,7 @@ std::string to_string(const LuxDiskLight &light, const uint32_t indent, bool clo
return ss.str();
}
std::string to_string(const LuxDomeLight &light, const uint32_t indent, bool closing_brace) {
std::string to_string(const DomeLight &light, const uint32_t indent, bool closing_brace) {
std::stringstream ss;
ss << pprint::Indent(indent) << to_string(light.spec) << " DomeLight \"" << light.name << "\"\n";
@@ -2480,7 +2520,7 @@ std::string dump_path(const Path &path) {
std::stringstream ss;
ss << "Path: Prim part = " << path.GetPrimPart();
ss << ", Prop part = " << path.GetPropPart();
ss << ", elementName = " << path.GetElementName();
ss << ", elementName = " << path.element_name();
ss << ", isValid = " << path.IsValid();
ss << ", isAbsolute = " << path.IsAbsolutePath();
ss << ", isRelative = " << path.IsRelativePath();
@@ -2489,5 +2529,19 @@ std::string dump_path(const Path &path) {
}
// prim-pprint.hh
namespace prim {
std::string print_prim(const Prim &prim, const uint32_t indent) {
std::stringstream ss;
ss << pprint::Indent(indent) << value::pprint_value(prim.data());
return ss.str();
}
} // namespace prim
} // tinyusdz

View File

@@ -143,18 +143,17 @@ std::string to_string(const Skeleton &skel, const uint32_t indent = 0, bool clos
std::string to_string(const SkelAnimation &anim, const uint32_t indent = 0, bool closing_brace = true);
std::string to_string(const BlendShape &bs, const uint32_t indent = 0, bool closing_brace = true);
std::string to_string(const LuxSphereLight &light, const uint32_t indent = 0, bool closing_brace = true);
std::string to_string(const LuxDomeLight &light, const uint32_t indent = 0, bool closing_brace = true);
std::string to_string(const LuxDiskLight &light, const uint32_t indent = 0, bool closing_brace = true);
std::string to_string(const LuxDistantLight &light, const uint32_t indent = 0, bool closing_brace = true);
std::string to_string(const LuxCylinderLight &light, const uint32_t indent = 0, bool closing_brace = true);
std::string to_string(const SphereLight &light, const uint32_t indent = 0, bool closing_brace = true);
std::string to_string(const DomeLight &light, const uint32_t indent = 0, bool closing_brace = true);
std::string to_string(const DiskLight &light, const uint32_t indent = 0, bool closing_brace = true);
std::string to_string(const DistantLight &light, const uint32_t indent = 0, bool closing_brace = true);
std::string to_string(const CylinderLight &light, const uint32_t indent = 0, bool closing_brace = true);
std::string to_string(const Material &material, const uint32_t indent = 0, bool closing_brace = true);
// It will delegate to to_string() of concrete Shader type(e.g. UsdPreviewSurface)
std::string to_string(const Shader &shader, const uint32_t indent = 0, bool closing_brace = true);
std::string to_string(const APISchemas::APIName &name);
#if 0
std::string to_string(const UsdPreviewSurface &shader, const uint32_t indent = 0, bool closing_brace = true);
std::string to_string(const UsdUVTexture &shader, const uint32_t indent = 0, bool closing_brace = true);
std::string to_string(const UsdPrimvarReader_float &shader, const uint32_t indent = 0, bool closing_brace = true);
@@ -162,7 +161,6 @@ std::string to_string(const UsdPrimvarReader_float2 &shader, const uint32_t inde
std::string to_string(const UsdPrimvarReader_float3 &shader, const uint32_t indent = 0, bool closing_brace = true);
std::string to_string(const UsdPrimvarReader_float4 &shader, const uint32_t indent = 0, bool closing_brace = true);
std::string to_string(const UsdPrimvarReader_int &shader, const uint32_t indent = 0, bool closing_brace = true);
#endif
std::string to_string(const UsdUVTexture::SourceColorSpace v);
std::string to_string(const UsdUVTexture::Wrap v);
@@ -172,6 +170,7 @@ std::string to_string(const GeomCamera::StereoRole &role);
std::string to_string(const tinyusdz::Animatable<Visibility> &v, const uint32_t indent = 0, bool closing_brace = true);
std::string to_string(const APISchemas::APIName &name);
std::string print_xformOpOrder(const std::vector<XformOp> &xformOps, const uint32_t indent);
std::string print_xformOps(const std::vector<XformOp>& xformOps, const uint32_t indent);
std::string print_attr_metas(const AttrMeta &meta, const uint32_t indent);

View File

@@ -11,12 +11,13 @@ namespace tinyusdz {
namespace prim {
//
// Impelemnted in pprinter.cc
// Impelemnted in pprinter.cc at the moment.
//
std::string print_references(const ReferenceList &references, const uint32_t indent);
std::string print_payload(const PayloadList &payload, const uint32_t indent);
std::string print_layeroffset(const LayerOffset &layeroffset, const uint32_t indent);
std::string print_prim(const Prim &prim, const uint32_t indent=0);
} // namespace prim
} // namespace tinyusdz

View File

@@ -2297,10 +2297,10 @@ bool ReconstructPrim(
}
template <>
bool ReconstructPrim<LuxSphereLight>(
bool ReconstructPrim<SphereLight>(
const PropertyMap &properties,
const ReferenceList &references,
LuxSphereLight *light,
SphereLight *light,
std::string *warn,
std::string *err) {
@@ -2314,16 +2314,16 @@ bool ReconstructPrim<LuxSphereLight>(
for (const auto &prop : properties) {
// PARSE_PROPERTY(prop, "inputs:colorTemperature", light->colorTemperature)
PARSE_TYPED_ATTRIBUTE(table, prop, "inputs:color", LuxSphereLight, light->color)
PARSE_TYPED_ATTRIBUTE(table, prop, "inputs:radius", LuxSphereLight, light->radius)
PARSE_TYPED_ATTRIBUTE(table, prop, "inputs:intensity", LuxSphereLight,
PARSE_TYPED_ATTRIBUTE(table, prop, "inputs:color", SphereLight, light->color)
PARSE_TYPED_ATTRIBUTE(table, prop, "inputs:radius", SphereLight, light->radius)
PARSE_TYPED_ATTRIBUTE(table, prop, "inputs:intensity", SphereLight,
light->intensity)
PARSE_ENUM_PROPETY(table, prop, "visibility", VisibilityEnumHandler, LuxSphereLight,
PARSE_ENUM_PROPETY(table, prop, "visibility", VisibilityEnumHandler, SphereLight,
light->visibility)
PARSE_ENUM_PROPETY(table, prop, "purpose", PurposeEnumHandler, LuxSphereLight,
PARSE_ENUM_PROPETY(table, prop, "purpose", PurposeEnumHandler, SphereLight,
light->purpose)
PARSE_EXTENT_ATTRIBUTE(table, prop, "extent", LuxSphereLight, light->extent)
ADD_PROPERTY(table, prop, LuxSphereLight, light->props)
PARSE_EXTENT_ATTRIBUTE(table, prop, "extent", SphereLight, light->extent)
ADD_PROPERTY(table, prop, SphereLight, light->props)
PARSE_PROPERTY_END_MAKE_WARN(table, prop)
}
@@ -2331,10 +2331,10 @@ bool ReconstructPrim<LuxSphereLight>(
}
template <>
bool ReconstructPrim<LuxRectLight>(
bool ReconstructPrim<RectLight>(
const PropertyMap &properties,
const ReferenceList &references,
LuxRectLight *light,
RectLight *light,
std::string *warn,
std::string *err) {
@@ -2349,15 +2349,15 @@ bool ReconstructPrim<LuxRectLight>(
for (const auto &prop : properties) {
// PARSE_PROPERTY(prop, "inputs:colorTemperature", light->colorTemperature)
PARSE_TYPED_ATTRIBUTE(table, prop, "inputs:texture:file", UsdUVTexture, light->file)
PARSE_TYPED_ATTRIBUTE(table, prop, "inputs:color", LuxRectLight, light->color)
PARSE_TYPED_ATTRIBUTE(table, prop, "inputs:height", LuxRectLight, light->height)
PARSE_TYPED_ATTRIBUTE(table, prop, "inputs:width", LuxRectLight, light->width)
PARSE_TYPED_ATTRIBUTE(table, prop, "inputs:intensity", LuxRectLight,
PARSE_TYPED_ATTRIBUTE(table, prop, "inputs:color", RectLight, light->color)
PARSE_TYPED_ATTRIBUTE(table, prop, "inputs:height", RectLight, light->height)
PARSE_TYPED_ATTRIBUTE(table, prop, "inputs:width", RectLight, light->width)
PARSE_TYPED_ATTRIBUTE(table, prop, "inputs:intensity", RectLight,
light->intensity)
PARSE_EXTENT_ATTRIBUTE(table, prop, "extent", LuxRectLight, light->extent)
PARSE_ENUM_PROPETY(table, prop, "purpose", PurposeEnumHandler, LuxRectLight,
PARSE_EXTENT_ATTRIBUTE(table, prop, "extent", RectLight, light->extent)
PARSE_ENUM_PROPETY(table, prop, "purpose", PurposeEnumHandler, RectLight,
light->purpose)
ADD_PROPERTY(table, prop, LuxSphereLight, light->props)
ADD_PROPERTY(table, prop, SphereLight, light->props)
PARSE_PROPERTY_END_MAKE_WARN(table, prop)
}
@@ -2365,10 +2365,10 @@ bool ReconstructPrim<LuxRectLight>(
}
template <>
bool ReconstructPrim<LuxDiskLight>(
bool ReconstructPrim<DiskLight>(
const PropertyMap &properties,
const ReferenceList &references,
LuxDiskLight *light,
DiskLight *light,
std::string *warn,
std::string *err) {
@@ -2382,11 +2382,11 @@ bool ReconstructPrim<LuxDiskLight>(
for (const auto &prop : properties) {
// PARSE_PROPERTY(prop, "inputs:colorTemperature", light->colorTemperature)
PARSE_TYPED_ATTRIBUTE(table, prop, "inputs:radius", LuxDiskLight, light->radius)
PARSE_EXTENT_ATTRIBUTE(table, prop, "extent", LuxDiskLight, light->extent)
PARSE_ENUM_PROPETY(table, prop, "purpose", PurposeEnumHandler, LuxDiskLight,
PARSE_TYPED_ATTRIBUTE(table, prop, "inputs:radius", DiskLight, light->radius)
PARSE_EXTENT_ATTRIBUTE(table, prop, "extent", DiskLight, light->extent)
PARSE_ENUM_PROPETY(table, prop, "purpose", PurposeEnumHandler, DiskLight,
light->purpose)
ADD_PROPERTY(table, prop, LuxDiskLight, light->props)
ADD_PROPERTY(table, prop, DiskLight, light->props)
PARSE_PROPERTY_END_MAKE_WARN(table, prop)
}
@@ -2394,10 +2394,10 @@ bool ReconstructPrim<LuxDiskLight>(
}
template <>
bool ReconstructPrim<LuxCylinderLight>(
bool ReconstructPrim<CylinderLight>(
const PropertyMap &properties,
const ReferenceList &references,
LuxCylinderLight *light,
CylinderLight *light,
std::string *warn,
std::string *err) {
@@ -2411,12 +2411,12 @@ bool ReconstructPrim<LuxCylinderLight>(
for (const auto &prop : properties) {
// PARSE_PROPERTY(prop, "inputs:colorTemperature", light->colorTemperature)
PARSE_TYPED_ATTRIBUTE(table, prop, "inputs:length", LuxCylinderLight, light->length)
PARSE_TYPED_ATTRIBUTE(table, prop, "inputs:radius", LuxCylinderLight, light->radius)
PARSE_EXTENT_ATTRIBUTE(table, prop, "extent", LuxCylinderLight, light->extent)
PARSE_ENUM_PROPETY(table, prop, "purpose", PurposeEnumHandler, LuxCylinderLight,
PARSE_TYPED_ATTRIBUTE(table, prop, "inputs:length", CylinderLight, light->length)
PARSE_TYPED_ATTRIBUTE(table, prop, "inputs:radius", CylinderLight, light->radius)
PARSE_EXTENT_ATTRIBUTE(table, prop, "extent", CylinderLight, light->extent)
PARSE_ENUM_PROPETY(table, prop, "purpose", PurposeEnumHandler, CylinderLight,
light->purpose)
ADD_PROPERTY(table, prop, LuxSphereLight, light->props)
ADD_PROPERTY(table, prop, SphereLight, light->props)
PARSE_PROPERTY_END_MAKE_WARN(table, prop)
}
@@ -2424,10 +2424,10 @@ bool ReconstructPrim<LuxCylinderLight>(
}
template <>
bool ReconstructPrim<LuxDistantLight>(
bool ReconstructPrim<DistantLight>(
const PropertyMap &properties,
const ReferenceList &references,
LuxDistantLight *light,
DistantLight *light,
std::string *warn,
std::string *err) {
@@ -2441,10 +2441,10 @@ bool ReconstructPrim<LuxDistantLight>(
for (const auto &prop : properties) {
// PARSE_PROPERTY(prop, "inputs:colorTemperature", light->colorTemperature)
PARSE_TYPED_ATTRIBUTE(table, prop, "inputs:angle", LuxDistantLight, light->angle)
PARSE_ENUM_PROPETY(table, prop, "purpose", PurposeEnumHandler, LuxDistantLight,
PARSE_TYPED_ATTRIBUTE(table, prop, "inputs:angle", DistantLight, light->angle)
PARSE_ENUM_PROPETY(table, prop, "purpose", PurposeEnumHandler, DistantLight,
light->purpose)
ADD_PROPERTY(table, prop, LuxSphereLight, light->props)
ADD_PROPERTY(table, prop, SphereLight, light->props)
PARSE_PROPERTY_END_MAKE_WARN(table, prop)
}
@@ -2452,10 +2452,10 @@ bool ReconstructPrim<LuxDistantLight>(
}
template <>
bool ReconstructPrim<LuxDomeLight>(
bool ReconstructPrim<DomeLight>(
const PropertyMap &properties,
const ReferenceList &references,
LuxDomeLight *light,
DomeLight *light,
std::string *warn,
std::string *err) {
@@ -2468,18 +2468,18 @@ bool ReconstructPrim<LuxDomeLight>(
}
for (const auto &prop : properties) {
PARSE_TYPED_ATTRIBUTE(table, prop, "guideRadius", LuxDomeLight, light->guideRadius)
PARSE_TYPED_ATTRIBUTE(table, prop, "inputs:diffuse", LuxDomeLight, light->diffuse)
PARSE_TYPED_ATTRIBUTE(table, prop, "inputs:specular", LuxDomeLight,
PARSE_TYPED_ATTRIBUTE(table, prop, "guideRadius", DomeLight, light->guideRadius)
PARSE_TYPED_ATTRIBUTE(table, prop, "inputs:diffuse", DomeLight, light->diffuse)
PARSE_TYPED_ATTRIBUTE(table, prop, "inputs:specular", DomeLight,
light->specular)
PARSE_TYPED_ATTRIBUTE(table, prop, "inputs:colorTemperature", LuxDomeLight,
PARSE_TYPED_ATTRIBUTE(table, prop, "inputs:colorTemperature", DomeLight,
light->colorTemperature)
PARSE_TYPED_ATTRIBUTE(table, prop, "inputs:color", LuxDomeLight, light->color)
PARSE_TYPED_ATTRIBUTE(table, prop, "inputs:intensity", LuxDomeLight,
PARSE_TYPED_ATTRIBUTE(table, prop, "inputs:color", DomeLight, light->color)
PARSE_TYPED_ATTRIBUTE(table, prop, "inputs:intensity", DomeLight,
light->intensity)
PARSE_ENUM_PROPETY(table, prop, "purpose", PurposeEnumHandler, LuxDomeLight,
PARSE_ENUM_PROPETY(table, prop, "purpose", PurposeEnumHandler, DomeLight,
light->purpose)
ADD_PROPERTY(table, prop, LuxDomeLight, light->props)
ADD_PROPERTY(table, prop, DomeLight, light->props)
PARSE_PROPERTY_END_MAKE_WARN(table, prop)
}

View File

@@ -193,7 +193,7 @@ Path Path::AppendProperty(const std::string &elem) {
return p;
}
if (!tokenize_variantElement(elem)) {
if (tokenize_variantElement(elem)) {
// variant chars are not supported yet.
p.valid = false;
return p;
@@ -297,7 +297,7 @@ Path Path::AppendElement(const std::string &elem) {
}
}
Path Path::GetParentPrim() const {
Path Path::GetParentPrimPath() const {
if (!valid) {
return Path();
}

View File

@@ -148,19 +148,21 @@ struct StringData {
int line_col{0};
};
///
/// Simlar to SdfPath.
/// NOTE: We are doging refactoring of Path class, so the following comment may not be correct.
///
/// We don't need the performance for USDZ, so use naiive implementation
/// to represent Path.
/// Path is something like Unix path, delimited by `/`, ':' and '.'
/// Square brackets('<', '>' is not included)
///
/// Root path is represented as prim path "/" and elementPath ""(empty).
///
/// Example:
///
/// - `/muda/bora.dora` : prim_part is `/muda/bora`, prop_part is `.dora`.
/// - `bora` : Relative path
/// - `bora` : Could be Element(leaf) path or Relative path
///
/// ':' is a namespce delimiter(example `input:muda`).
///
@@ -168,14 +170,13 @@ struct StringData {
///
/// - Relational attribute path(`[` `]`. e.g. `/muda/bora[/ari].dora`) is not
/// supported.
/// - Variant chars('{' '}') is not supported.
/// - Variant chars('{' '}') is not supported(yet0.
/// - '../' is TODO
///
/// and have more limitatons.
///
class Path {
public:
// Similar to SdfPathNode
enum class PathType {
Prim,
@@ -191,6 +192,14 @@ class Path {
Path() : valid(false) {}
static Path make_root_path() {
Path p = Path("/", "");
// elementPath is empty for root.
p.element_ = "";
p.valid = true;
return p;
}
// `p` is split into prim_part and prop_part
// Path(const std::string &p);
Path(const std::string &prim, const std::string &prop);
@@ -206,6 +215,7 @@ class Path {
this->prim_part = rhs.prim_part;
this->prop_part = rhs.prop_part;
this->element_ = rhs.element_;
return (*this);
}
@@ -229,19 +239,15 @@ class Path {
std::string GetPrimPart() const { return prim_part; }
std::string GetPropPart() const { return prop_part; }
void set_path_type(const PathType ty) {
path_type_ = ty;
}
void set_path_type(const PathType ty) { path_type_ = ty; }
nonstd::optional<PathType> get_path_type() const {
return path_type_;
}
nonstd::optional<PathType> get_path_type() const { return path_type_; }
// IsPropertyPath: PrimProperty or RelationalAttribute
bool IsPropertyPath() const {
if (path_type_) {
if ((path_type_.value() == PathType::PrimProperty ||
(path_type_.value() == PathType::RelationalAttribute))) {
(path_type_.value() == PathType::RelationalAttribute))) {
return true;
}
}
@@ -259,7 +265,7 @@ class Path {
}
// Is Prim's property path?
// True when both PrimPart and PropPart are not empty.
// True when both PrimPart and PropPart are not empty.
bool IsPrimPropertyPath() const {
if (prim_part.empty()) {
return false;
@@ -274,16 +280,13 @@ class Path {
bool IsEmpty() { return (prim_part.empty() && prop_part.empty()); }
static Path RootPath() { return Path("/", ""); }
// static Path RelativePath() { return Path("."); }
Path AppendProperty(const std::string &elem);
Path AppendElement(const std::string &elem);
std::string GetElementName() const {
return element_;
}
std::string element_name() const { return element_; }
///
/// Split a path to the root(common ancestor) and its siblings
@@ -299,7 +302,7 @@ class Path {
///
std::pair<Path, Path> SplitAtRoot() const;
Path GetParentPrim() const;
Path GetParentPrimPath() const;
///
/// @returns true if a path is '/' only
@@ -379,10 +382,10 @@ class Path {
private:
std::string prim_part; // e.g. /Model/MyMesh, MySphere
std::string prop_part; // e.g. .visibility
std::string element_; // Element name
std::string element_; // Element name
nonstd::optional<PathType> path_type_; // Currently optional.
nonstd::optional<PathType> path_type_; // Currently optional.
bool valid{false};
};
@@ -612,11 +615,10 @@ struct APISchemas {
// SdfLayerOffset
struct LayerOffset {
double _offset;
double _scale;
double _offset{0.0};
double _scale{1.0};
};
// SdfReference
struct Reference {
value::AssetPath asset_path;
@@ -627,9 +629,9 @@ struct Reference {
// SdfPayload
struct Payload {
value::AssetPath asset_path; // std::string in SdfPayload
value::AssetPath asset_path; // std::string in SdfPayload
Path _prim_path;
LayerOffset _layer_offset; // from 0.8.0
LayerOffset _layer_offset; // from 0.8.0
// No customData for Payload
};
@@ -649,13 +651,16 @@ struct PrimMeta {
//
nonstd::optional<std::pair<ListEditQual, std::vector<Reference>>> references;
nonstd::optional<std::pair<ListEditQual, std::vector<Payload>>> payload;
nonstd::optional<std::pair<ListEditQual, std::vector<Path>>> inherits; // 'inherits'
nonstd::optional<std::pair<ListEditQual, std::vector<Path>>>
inherits; // 'inherits'
nonstd::optional<std::pair<ListEditQual, std::vector<std::string>>>
variantSets; // 'variantSets'. Could be `token` but treat as `string`(Crate format uses `string`)
variantSets; // 'variantSets'. Could be `token` but treat as
// `string`(Crate format uses `string`)
nonstd::optional<VariantSelectionMap> variants; // `variants`
nonstd::optional<std::pair<ListEditQual, std::vector<Path>>> specializes; // 'specializes'
nonstd::optional<std::pair<ListEditQual, std::vector<Path>>>
specializes; // 'specializes'
// USDZ extensions
nonstd::optional<std::string> sceneName; // 'sceneName'
@@ -690,7 +695,7 @@ struct AttrMeta {
// nullopt = not specified in USD data
nonstd::optional<Interpolation> interpolation; // 'interpolation'
nonstd::optional<uint32_t> elementSize; // usdSkel 'elementSize'
nonstd::optional<bool> hidden; // 'hidden'
nonstd::optional<bool> hidden; // 'hidden'
nonstd::optional<StringData> comment; // `comment`
nonstd::optional<CustomDataType> customData; // `customData`
@@ -701,8 +706,8 @@ struct AttrMeta {
std::vector<StringData> stringData;
bool authored() const {
return (interpolation || elementSize || hidden || customData || meta.size() ||
stringData.size());
return (interpolation || elementSize || hidden || customData ||
meta.size() || stringData.size());
}
};
@@ -1707,7 +1712,7 @@ struct XformOp {
// ":blender:pivot" for "xformOp:translate:blender:pivot". Suffix
// will be empty for "xformOp:translate"
// XformOpValueType value_type;
//std::string type_name;
// std::string type_name;
value::TimeSamples var;
@@ -1732,22 +1737,22 @@ struct XformOp {
var.values.clear();
var.values.push_back(v);
//type_name = value::TypeTraits<T>::type_name();
// type_name = value::TypeTraits<T>::type_name();
}
void set_timesamples(const value::TimeSamples &v) {
var = v;
//if (var.values.size()) {
// type_name = var.values[0].type_name();
//}
// if (var.values.size()) {
// type_name = var.values[0].type_name();
// }
}
void set_timesamples(value::TimeSamples &&v) {
var = std::move(v);
//if (var.values.size()) {
// type_name = var.values[0].type_name();
//}
// if (var.values.size()) {
// type_name = var.values[0].type_name();
// }
}
bool is_timesamples() const {
@@ -1850,8 +1855,7 @@ struct TimeSamples {
#endif
// Prim metas, Prim tree and properties.
struct VariantSet
{
struct VariantSet {
PrimMeta metas;
std::vector<int64_t> primIndices;
std::map<std::string, Property> props;
@@ -2043,33 +2047,98 @@ struct Scope {
//
// For `Stage` scene graph.
// Similar to `Prim` in pxrUSD.
// This class uses tree-representation of `Prim`. Easy to use, but may not be performant.
// This class uses tree-representation of `Prim`. Easy to use, but may not be
// performant than flattened Prim array + index representation of Prim tree(Index-based scene graph such like glTF).
//
class Prim {
public:
Path path;
Path elementPath;
Specifier specifier{Specifier::Invalid};
Prim(const value::Value &rhs);
Prim(value::Value &&rhs);
value::Value data; // GPrim, Xform, ...
template<typename T>
Prim(const T &prim) {
// Check if T is Prim class type.
static_assert((value::TypeId::TYPE_ID_MODEL_BEGIN <= value::TypeTraits<T>::type_id) && (value::TypeId::TYPE_ID_MODEL_END > value::TypeTraits<T>::type_id), "T is not a Prim class type");
_data = prim;
}
std::vector<Prim> children; // child nodes
std::vector<Prim> &children() {
return _children;
}
const std::vector<Prim> &children() const {
return _children;
}
const value::Value &data() const {
return _data;
}
Specifier &specifier() {
return _specifier;
}
Specifier specifier() const {
return _specifier;
}
Path &local_path() {
return _path;
}
const Path &local_path() const {
return _path;
}
Path &element_path() {
return _elementPath;
}
const Path &element_path() const {
return _elementPath;
}
template<typename T>
bool is() const {
return (_data.type_id() == value::TypeTraits<T>::type_id);
}
// Return a pointer of a concrete Prim class(Xform, Material, ...)
// Return nullptr when failed to cast or T is not a Prim type.
template<typename T>
const T* as() const {
// Check if T is Prim type. e.g. Xform, Material, ...
if ((value::TypeId::TYPE_ID_MODEL_BEGIN <= value::TypeTraits<T>::type_id) &&
(value::TypeId::TYPE_ID_MODEL_END > value::TypeTraits<T>::type_id)) {
return _data.as<T>();
}
return nullptr;
}
private:
Path _path; // Prim's local path name. May contain Property, Relation and
// other infos, but do not include parent's path. To get fully absolute path of a Prim(e.g. "/xform0/mymesh0", You need to traverse Prim tree and concatename `elementPath` or use ***(T.B.D>) method in `Stage` class
Path _elementPath; // leaf("terminal") Prim name.(e.g. "myxform" for `def
// Xform "myform"`). For root node, elementPath name is
// empty string("").
Specifier _specifier{
Specifier::Invalid}; // `def`, `over` or `class`. Usually `def`
value::Value _data; // Generic container for concrete Prim object. GPrim, Xform, ...
std::vector<Prim> _children; // child Prim nodes
};
///
/// Contains concrete Prim object and composition elements.
///
/// PrimNode is near to final state of `Prim`.
/// Doing one further step(Composition, Flatten, select Variant) to get `Prim`.
/// PrimNode is near to the final state of `Prim`.
/// Doing one further step(Composition, Flatten, select Variant) to get `Prim`.
///
/// Similar to `PrimIndex` in pxrUSD
///
class PrimNode {
Path path;
Path elementPath;
@@ -2077,15 +2146,15 @@ class PrimNode {
PrimNode(value::Value &&rhs);
value::Value prim; // GPrim, Xform, ...
value::Value prim; // GPrim, Xform, ...
std::vector<PrimNode> children; // child nodes
///
/// Select variant.
///
bool select_variant(const std::string &target_name, const std::string &variant_name) {
bool select_variant(const std::string &target_name,
const std::string &variant_name) {
const auto m = vsmap.find(target_name);
if (m != vsmap.end()) {
current_vsmap[target_name] = variant_name;
@@ -2100,9 +2169,7 @@ class PrimNode {
/// key = variant prim name
/// value = variats
///
const VariantSelectionMap &get_variant_selection_map() const {
return vsmap;
}
const VariantSelectionMap &get_variant_selection_map() const { return vsmap; }
///
/// Variants
@@ -2112,8 +2179,8 @@ class PrimNode {
using PropertyMap = std::map<std::string, Property>;
using PrimNodeMap = std::map<std::string, PrimNode>;
VariantSelectionMap vsmap; // Original variant selections
VariantSelectionMap current_vsmap; // Currently selected variants
VariantSelectionMap vsmap; // Original variant selections
VariantSelectionMap current_vsmap; // Currently selected variants
// key = variant_name
std::map<std::string, PropertyMap> variantAttributeMap;
@@ -2124,10 +2191,9 @@ class PrimNode {
///
std::vector<value::token> primChildren;
std::vector<value::token> variantChildren;
};
#if 0 // TODO: Remove
#if 0 // TODO: Remove
//
// For low-level scene graph representation, something like Vulkan.
// Less abstraction, and scene graph is representated by indices.
@@ -2271,17 +2337,14 @@ struct StringAndIdMap {
std::map<std::string, int32_t> _s_to_i; // string -> index
};
struct NodeIndex {
std::string name;
// TypeTraits<T>::type_id
value::TypeId type_id{value::TypeId::TYPE_ID_INVALID};
int64_t
index{-1}; // array index to `Scene::xforms`, `Scene::geom_cameras`, ...
// -1 = invlid(or not set)
int64_t index{-1}; // array index to `Scene::xforms`, `Scene::geom_cameras`,
// ... -1 = invlid(or not set)
};
nonstd::optional<Interpolation> InterpolationFromString(const std::string &v);
@@ -2300,7 +2363,8 @@ DEFINE_TYPE_TRAIT(Specifier, "specifier", TYPE_ID_SPECIFIER, 1);
DEFINE_TYPE_TRAIT(Permission, "permission", TYPE_ID_PERMISSION, 1);
DEFINE_TYPE_TRAIT(Variability, "variability", TYPE_ID_VARIABILITY, 1);
DEFINE_TYPE_TRAIT(VariantSelectionMap, "variants", TYPE_ID_VARIANT_SELECION_MAP, 0);
DEFINE_TYPE_TRAIT(VariantSelectionMap, "variants", TYPE_ID_VARIANT_SELECION_MAP,
0);
DEFINE_TYPE_TRAIT(Payload, "payload", TYPE_ID_PAYLOAD, 1);
DEFINE_TYPE_TRAIT(LayerOffset, "LayerOffset", TYPE_ID_LAYER_OFFSET, 1);

View File

@@ -145,7 +145,7 @@ class Node {
namespace {
nonstd::optional<Path> GetPath(const value::Value &v) {
nonstd::optional<Path> GetPrimElementName(const value::Value &v) {
// Since multiple get_value() call consumes lots of stack size(depends on
// sizeof(T)?), Following code would produce 100KB of stack in debug build. So
// use as() instead(as() => roughly 2000 bytes for stack size).
@@ -193,14 +193,14 @@ nonstd::optional<Path> GetPath(const value::Value &v) {
return Path(pv.value().name, "");
}
if (auto pv = v.get_value<LuxDomeLight>()) {
if (auto pv = v.get_value<DomeLight>()) {
return Path(pv.value().name, "");
}
if (auto pv = v.get_value<LuxSphereLight>()) {
if (auto pv = v.get_value<SphereLight>()) {
return Path(pv.value().name, "");
}
// if (auto pv = v.get_value<LuxCylinderLight>()) { return
// Path(pv.value().name); } if (auto pv = v.get_value<LuxDiskLight>()) {
// if (auto pv = v.get_value<CylinderLight>()) { return
// Path(pv.value().name); } if (auto pv = v.get_value<DiskLight>()) {
// return Path(pv.value().name); }
if (auto pv = v.get_value<Material>()) {
@@ -214,9 +214,13 @@ nonstd::optional<Path> GetPath(const value::Value &v) {
// }
#else
// Lookup name field of Prim class
#define EXTRACT_NAME_AND_RETURN_PATH(__ty) \
if (v.as<__ty>()) { \
return Path(v.as<__ty>()->name, ""); \
Path p(v.as<__ty>()->name, ""); \
p.element_name() = v.as<__ty>()->name; \
return std::move(p); \
}
EXTRACT_NAME_AND_RETURN_PATH(Model)
@@ -233,11 +237,11 @@ nonstd::optional<Path> GetPath(const value::Value &v) {
EXTRACT_NAME_AND_RETURN_PATH(GeomSubset)
EXTRACT_NAME_AND_RETURN_PATH(GeomCamera)
EXTRACT_NAME_AND_RETURN_PATH(GeomBasisCurves)
EXTRACT_NAME_AND_RETURN_PATH(LuxDomeLight)
EXTRACT_NAME_AND_RETURN_PATH(LuxSphereLight)
EXTRACT_NAME_AND_RETURN_PATH(LuxCylinderLight)
EXTRACT_NAME_AND_RETURN_PATH(LuxDiskLight)
EXTRACT_NAME_AND_RETURN_PATH(LuxRectLight)
EXTRACT_NAME_AND_RETURN_PATH(DomeLight)
EXTRACT_NAME_AND_RETURN_PATH(SphereLight)
EXTRACT_NAME_AND_RETURN_PATH(CylinderLight)
EXTRACT_NAME_AND_RETURN_PATH(DiskLight)
EXTRACT_NAME_AND_RETURN_PATH(RectLight)
EXTRACT_NAME_AND_RETURN_PATH(Material)
EXTRACT_NAME_AND_RETURN_PATH(Shader)
EXTRACT_NAME_AND_RETURN_PATH(UsdPreviewSurface)
@@ -256,27 +260,27 @@ nonstd::optional<Path> GetPath(const value::Value &v) {
} // namespace
Prim::Prim(const value::Value &rhs) {
// Check if Prim type is Model(GPrim)
// Check if type is Prim(Model(GPrim), usdShade, usdLux, etc.)
if ((value::TypeId::TYPE_ID_MODEL_BEGIN <= rhs.type_id()) &&
(value::TypeId::TYPE_ID_MODEL_END > rhs.type_id())) {
if (auto pv = GetPath(rhs)) {
path = pv.value();
if (auto pv = GetPrimElementName(rhs)) {
_path = pv.value();
}
data = rhs;
_data = rhs;
} else {
// TODO: Raise an error if rhs is not an Prim
}
}
Prim::Prim(value::Value &&rhs) {
// Check if Prim type is Model(GPrim)
// Check if type is Prim(Model(GPrim), usdShade, usdLux, etc.)
if ((value::TypeId::TYPE_ID_MODEL_BEGIN <= rhs.type_id()) &&
(value::TypeId::TYPE_ID_MODEL_END > rhs.type_id())) {
data = std::move(rhs);
_data = std::move(rhs);
if (auto pv = GetPath(data)) {
path = pv.value();
if (auto pv = GetPrimElementName(_data)) {
_path = pv.value();
}
} else {
@@ -287,19 +291,30 @@ Prim::Prim(value::Value &&rhs) {
namespace {
nonstd::optional<const Prim *> GetPrimAtPathRec(const Prim *parent,
const Path &path) {
//// TODO: Find better way to get path name from any value.
// if (auto pv = parent.get_value<Xform>)
if (auto pv = GetPath(parent->data)) {
DCOUT("Prim Path = " << pv.value());
DCOUT("Given Path = " << path);
if (path == pv.value()) {
const std::string &parent_path,
const Path &path, const uint32_t depth) {
std::string abs_path;
// if (auto pv = GetPrimElementName(parent->data())) {
{
// TODO: Use elementPath
std::string elementName = parent->local_path().GetPrimPart();
DCOUT(pprint::Indent(depth) << "Prim elementName = " << elementName);
DCOUT(pprint::Indent(depth) << "Given Path = " << path);
// fully absolute path
abs_path = parent_path + "/" + elementName;
DCOUT(pprint::Indent(depth) << "abs_path = " << abs_path);
DCOUT(pprint::Indent(depth) << "queriying path = " << path.full_path_name());
if (abs_path == path.full_path_name()) {
DCOUT(pprint::Indent(depth) << "Got it! Found Prim at Path = " << abs_path);
return parent;
}
}
for (const auto &child : parent->children) {
if (auto pv = GetPrimAtPathRec(&child, path)) {
DCOUT(pprint::Indent(depth) << "# of children : " << parent->children().size());
for (const auto &child : parent->children()) {
//const std::string &p = parent->elementPath.full_path_name();
DCOUT(pprint::Indent(depth+1) << "Parent path : " << abs_path);
if (auto pv = GetPrimAtPathRec(&child, abs_path, path, depth+1)) {
return pv.value();
}
}
@@ -310,7 +325,7 @@ nonstd::optional<const Prim *> GetPrimAtPathRec(const Prim *parent,
} // namespace
nonstd::expected<const Prim *, std::string> Stage::GetPrimAtPath(
const Path &path) {
const Path &path) const {
DCOUT("GerPrimAtPath : " << path);
if (_dirty) {
@@ -342,7 +357,7 @@ nonstd::expected<const Prim *, std::string> Stage::GetPrimAtPath(
// Brute-force search.
for (const auto &parent : root_nodes) {
if (auto pv = GetPrimAtPathRec(&parent, path)) {
if (auto pv = GetPrimAtPathRec(&parent, /* root */"", path, /* depth */0)) {
// Add to cache.
// Assume pointer address does not change unless dirty state.
_prim_path_cache[path.GetPrimPart()] = pv.value();
@@ -355,7 +370,8 @@ nonstd::expected<const Prim *, std::string> Stage::GetPrimAtPath(
}
nonstd::expected<const Prim *, std::string> Stage::GetPrimFromRelativePath(
const Prim &root, const Path &path) {
const Prim &root, const Path &path) const {
// TODO: Resolve "../"
// TODO: cache path
if (!path.IsValid()) {
@@ -373,30 +389,35 @@ nonstd::expected<const Prim *, std::string> Stage::GetPrimFromRelativePath(
return nonstd::make_unexpected("Invalid Path.\n");
}
Path abs_path = root.path;
#if 0 // TODO
Path abs_path = root.local_path();
abs_path.AppendElement(path.GetPrimPart());
DCOUT("root path = " << root.path);
DCOUT("root path = " << root.path());
DCOUT("abs path = " << abs_path);
// Brute-force search.
if (auto pv = GetPrimAtPathRec(&root, abs_path)) {
// Brute-force search from Stage root.
if (auto pv = GetPrimAtPathRec(&root, /* root */"", abs_path, /* depth */0)) {
return pv.value();
}
return nonstd::make_unexpected("Cannot find path <" + path.full_path_name() +
"> under Prim: " + to_string(root.path) +
"\n");
#else
(void)root;
return nonstd::make_unexpected("GetPrimFromRelativePath is TODO");
#endif
}
namespace {
void PrimPrintRec(std::stringstream &ss, const Prim &prim, uint32_t indent) {
ss << "\n";
ss << pprint_value(prim.data, indent, /* closing_brace */ false);
ss << pprint_value(prim.data(), indent, /* closing_brace */ false);
DCOUT("num_children = " << prim.children.size());
for (const auto &child : prim.children) {
DCOUT("num_children = " << prim.children().size());
for (const auto &child : prim.children()) {
PrimPrintRec(ss, child, indent + 1);
}

View File

@@ -41,6 +41,7 @@ class Stage {
///
/// Traverse by depth-first order.
/// NOTE: Not yet implementd
///
PrimRange Traverse();
@@ -50,7 +51,7 @@ class Stage {
///
/// @returns pointer to Prim(to avoid a copy). Never return nullptr upon success.
///
nonstd::expected<const Prim *, std::string> GetPrimAtPath(const Path &path);
nonstd::expected<const Prim *, std::string> GetPrimAtPath(const Path &path) const;
///
/// Get Prim from a children of given root Prim.
@@ -58,7 +59,7 @@ class Stage {
///
/// @returns pointer to Prim(to avoid a copy). Never return nullptr upon success.
///
nonstd::expected<const Prim *, std::string> GetPrimFromRelativePath(const Prim &root, const Path &path);
nonstd::expected<const Prim *, std::string> GetPrimFromRelativePath(const Prim &root, const Path &path) const;
///
/// Dump Stage as ASCII(USDA) representation.
@@ -110,9 +111,9 @@ class Stage {
// Cached prim path.
// key : prim_part string (e.g. "/path/bora")
std::map<std::string, const Prim *> _prim_path_cache;
mutable std::map<std::string, const Prim *> _prim_path_cache;
bool _dirty{false}; // True when Stage content changes(addition, deletion, composition/flatten, etc.)
mutable bool _dirty{false}; // True when Stage content changes(addition, deletion, composition/flatten, etc.)
};

View File

@@ -158,7 +158,7 @@ nonstd::expected<VertexAttribute<T>, std::string> GetTextureCoordinate(
/// (length = triangulated faceVertexIndices. indexMap[i] stores array index in original faceVertexIndices.
/// For remapping primvar attributes.)
///
/// Return false when a polygon is degenerated.
/// Return false when a polygon is degenerated.
/// No overlap check at the moment
///
/// T = value::float3 or value::double3
@@ -241,13 +241,13 @@ bool TriangulatePolygon(
vi0_2 = faceVertexIndices[faceIndexOffset + j];
if (vi0 >= points.size()) {
err =
err =
fmt::format("Invalid vertex index.");
return false;
}
if (vi0_2 >= points.size()) {
err =
err =
fmt::format("Invalid vertex index.");
return false;
}
@@ -343,6 +343,40 @@ bool TriangulatePolygon(
return true;
}
#if 0
//
// `Shader` may be nested, so first list up all Shader nodes under Material.
//
struct ShaderNode
{
std::name
};
nonstd::optional<UsdPrimvarReader_float2> FindPrimvarReader_float2Rec(
const Prim &root,
RenderMesh &mesh)
{
if (auto sv = root.data.as<Shader>()) {
const Shader &shader = (*sv);
if (auto pv = shader.value.as<UsdUVTexture>()) {
const UsdUVTexture &tex = (*pv);
(void)tex;
}
}
for (const auto &child : root.children) {
auto ret = ListUpShaderGraphRec(child, mesh);
if (!ret) {
return nonstd::make_unexpected(ret.error());
}
}
return true;
}
#endif
} // namespace
// Currently float2 only
@@ -350,11 +384,11 @@ std::vector<UsdPrimvarReader_float2> ExtractPrimvarReadersFromMaterialNode(
const Prim &node) {
std::vector<UsdPrimvarReader_float2> dst;
if (!node.data.as<Material>()) {
if (!node.is<Material>()) {
return dst;
}
for (const auto &child : node.children) {
for (const auto &child : node.children()) {
(void)child;
}
@@ -481,11 +515,11 @@ nonstd::expected<RenderMesh, std::string> Convert(const Stage &stage,
// TODO: Triangulate.
std::string err;
std::vector<uint32_t> triangulatedFaceVertexCounts;
std::vector<uint32_t> triangulatedFaceVertexIndices;
std::vector<size_t> faceVertexIndexMap;
if (!TriangulatePolygon<value::float3, float>(dst.points, dst.faceVertexCounts, dst.faceVertexIndices,
if (!TriangulatePolygon<value::float3, float>(dst.points, dst.faceVertexCounts, dst.faceVertexIndices,
triangulatedFaceVertexCounts, triangulatedFaceVertexIndices, faceVertexIndexMap, err)) {
return nonstd::make_unexpected("Triangulation failed: " + err);

208
src/tydra/scene-access.cc Normal file
View File

@@ -0,0 +1,208 @@
#include "scene-access.hh"
#include "usdGeom.hh"
#include "usdLux.hh"
#include "usdShade.hh"
#include "usdSkel.hh"
#include "pprinter.hh"
#include "prim-pprint.hh"
#include "value-pprint.hh"
namespace tinyusdz {
namespace tydra {
namespace {
template <typename T>
bool TraverseRec(const std::string &path_prefix,
const tinyusdz::Prim &prim, uint32_t depth,
PathPrimMap<T> &itemmap) {
if (depth > 1024 * 128) {
// Too deep
return false;
}
std::string prim_abs_path = path_prefix + "/" + prim.local_path().full_path_name();
if (prim.is<T>()) {
if (const T *pv = prim.as<T>()) {
std::cout << "Path : <" << prim_abs_path << "> is "
<< tinyusdz::value::TypeTraits<T>::type_name() << ".\n";
itemmap[prim_abs_path] = pv;
}
}
for (const auto &child : prim.children()) {
if (!TraverseRec(prim_abs_path, child, depth + 1, itemmap)) {
return false;
}
}
return true;
}
// Specialization for Shader type.
template <typename ShaderTy>
bool TraverseShaderRec(const std::string &path_prefix,
const tinyusdz::Prim &prim, uint32_t depth,
PathShaderMap<ShaderTy> &itemmap) {
if (depth > 1024 * 128) {
// Too deep
return false;
}
std::string prim_abs_path = path_prefix + "/" + prim.local_path().full_path_name();
// First check if type is Shader Prim.
if (const Shader *ps = prim.as<Shader>()) {
// Then check if wanted Shder type
if (const ShaderTy *s = ps->value.as<ShaderTy>()) {
itemmap[prim_abs_path] = std::make_pair(ps, s);
}
}
for (const auto &child : prim.children()) {
if (!TraverseShaderRec(prim_abs_path, child, depth + 1, itemmap)) {
return false;
}
}
return true;
}
} // namespace local
template<typename T>
bool ListPrims(const tinyusdz::Stage &stage, PathPrimMap<T> &m /* output */) {
// Should report error at compilation stege.
static_assert((value::TypeId::TYPE_ID_MODEL_BEGIN <= value::TypeTraits<T>::type_id) &&
(value::TypeId::TYPE_ID_MODEL_END > value::TypeTraits<T>::type_id), "Not a Prim type.");
// Check at runtime. Just in case...
if ((value::TypeId::TYPE_ID_MODEL_BEGIN <= value::TypeTraits<T>::type_id) &&
(value::TypeId::TYPE_ID_MODEL_END > value::TypeTraits<T>::type_id)) {
// Ok
} else {
return false;
}
for (const auto &root_prim : stage.GetRootPrims()) {
TraverseRec(/* root path is empty */"", root_prim, /* depth */0, m);
}
return true;
}
template<typename T>
bool ListShaders(const tinyusdz::Stage &stage, PathShaderMap<T> &m /* output */) {
// Concrete Shader type(e.g. UsdPreviewSurface) is classified as Imaging
// Should report error at compilation stege.
static_assert((value::TypeId::TYPE_ID_IMAGING_BEGIN <= value::TypeTraits<T>::type_id) &&
(value::TypeId::TYPE_ID_IMAGING_END > value::TypeTraits<T>::type_id), "Not a Shader type.");
// Check at runtime. Just in case...
if ((value::TypeId::TYPE_ID_IMAGING_BEGIN <= value::TypeTraits<T>::type_id) &&
(value::TypeId::TYPE_ID_IMAGING_END > value::TypeTraits<T>::type_id)) {
// Ok
} else {
return false;
}
for (const auto &root_prim : stage.GetRootPrims()) {
TraverseShaderRec(/* root path is empty */"", root_prim, /* depth */0, m);
}
return true;
}
const Prim *GetParentPrim(const tinyusdz::Stage &stage, const tinyusdz::Path &path, std::string *err) {
if (!path.IsValid()) {
if (err) {
(*err) = "Input Path " + tinyusdz::to_string(path) + " is invalid.\n";
}
return nullptr;
}
if (path.IsRootPath()) {
if (err) {
(*err) = "Input Path is root(\"/\").\n";
}
return nullptr;
}
if (path.IsRootPrim()) {
if (err) {
(*err) = "Input Path is root Prim, so no parent Prim exists.\n";
}
return nullptr;
}
if (!path.IsAbsolutePath()) {
if (err) {
(*err) = "Input Path must be absolute path(i.e. starts with \"/\").\n";
}
return nullptr;
}
tinyusdz::Path parentPath = path.GetParentPrimPath();
nonstd::expected<const Prim *, std::string> ret = stage.GetPrimAtPath(parentPath);
if (ret) {
return ret.value();
} else {
if (err) {
(*err) += "Failed to get parent Prim from Path " + tinyusdz::to_string(path) + ". Reason = " + ret.error() + "\n";
}
return nullptr;
}
}
//
// Template Instanciations
//
template bool ListPrims(const tinyusdz::Stage &stage, PathPrimMap<Model> &m);
template bool ListPrims(const tinyusdz::Stage &stage, PathPrimMap<Scope> &m);
template bool ListPrims(const tinyusdz::Stage &stage, PathPrimMap<GPrim> &m);
template bool ListPrims(const tinyusdz::Stage &stage, PathPrimMap<Xform> &m);
template bool ListPrims(const tinyusdz::Stage &stage, PathPrimMap<GeomMesh> &m);
template bool ListPrims(const tinyusdz::Stage &stage, PathPrimMap<GeomBasisCurves> &m);
template bool ListPrims(const tinyusdz::Stage &stage, PathPrimMap<GeomSphere> &m);
template bool ListPrims(const tinyusdz::Stage &stage, PathPrimMap<GeomCone> &m);
template bool ListPrims(const tinyusdz::Stage &stage, PathPrimMap<GeomCylinder> &m);
template bool ListPrims(const tinyusdz::Stage &stage, PathPrimMap<GeomCapsule> &m);
template bool ListPrims(const tinyusdz::Stage &stage, PathPrimMap<GeomCube> &m);
template bool ListPrims(const tinyusdz::Stage &stage, PathPrimMap<GeomPoints> &m);
template bool ListPrims(const tinyusdz::Stage &stage, PathPrimMap<GeomSubset> &m);
template bool ListPrims(const tinyusdz::Stage &stage, PathPrimMap<GeomCamera> &m);
template bool ListPrims(const tinyusdz::Stage &stage, PathPrimMap<DomeLight> &m);
template bool ListPrims(const tinyusdz::Stage &stage, PathPrimMap<CylinderLight> &m);
template bool ListPrims(const tinyusdz::Stage &stage, PathPrimMap<SphereLight> &m);
template bool ListPrims(const tinyusdz::Stage &stage, PathPrimMap<DiskLight> &m);
template bool ListPrims(const tinyusdz::Stage &stage, PathPrimMap<DistantLight> &m);
template bool ListPrims(const tinyusdz::Stage &stage, PathPrimMap<RectLight> &m);
template bool ListPrims(const tinyusdz::Stage &stage, PathPrimMap<GeometryLight> &m);
template bool ListPrims(const tinyusdz::Stage &stage, PathPrimMap<PortalLight> &m);
template bool ListPrims(const tinyusdz::Stage &stage, PathPrimMap<PluginLight> &m);
template bool ListPrims(const tinyusdz::Stage &stage, PathPrimMap<Material> &m);
template bool ListPrims(const tinyusdz::Stage &stage, PathPrimMap<Shader> &m);
template bool ListPrims(const tinyusdz::Stage &stage, PathPrimMap<SkelRoot> &m);
template bool ListPrims(const tinyusdz::Stage &stage, PathPrimMap<Skeleton> &m);
template bool ListPrims(const tinyusdz::Stage &stage, PathPrimMap<SkelAnimation> &m);
template bool ListPrims(const tinyusdz::Stage &stage, PathPrimMap<BlendShape> &m);
template bool ListShaders(const tinyusdz::Stage &stage, PathShaderMap<UsdPreviewSurface> &m);
template bool ListShaders(const tinyusdz::Stage &stage, PathShaderMap<UsdUVTexture> &m);
template bool ListShaders(const tinyusdz::Stage &stage, PathShaderMap<UsdPrimvarReader_int> &m);
template bool ListShaders(const tinyusdz::Stage &stage, PathShaderMap<UsdPrimvarReader_float> &m);
template bool ListShaders(const tinyusdz::Stage &stage, PathShaderMap<UsdPrimvarReader_float2> &m);
template bool ListShaders(const tinyusdz::Stage &stage, PathShaderMap<UsdPrimvarReader_float3> &m);
template bool ListShaders(const tinyusdz::Stage &stage, PathShaderMap<UsdPrimvarReader_float4> &m);
} // namespace tydra
} // namespace tinyusdz

60
src/tydra/scene-access.hh Normal file
View File

@@ -0,0 +1,60 @@
// SPDX-License-Identifier: Apache 2.0
// Copyright 2022-Present Light Transport Entertainment, Inc.
//
// Scene access API
//
// NOTE: Tydra API does not use nonstd::optional and nonstd::expected for easier language bindings.
//
#pragma once
#include <map>
#include "prim-types.hh"
#include "stage.hh"
#include "usdGeom.hh"
#include "usdShade.hh"
#include "usdSkel.hh"
namespace tinyusdz {
namespace tydra {
// key = fully absolute Prim path in string(e.g. "/xform/geom0")
template <typename T>
using PathPrimMap = std::map<std::string, const T *>;
//
// value = pair of Shader Prim which contains the Shader type T("info:id") and
// its concrete Shader type(UsdPreviewSurface)
//
template <typename T>
using PathShaderMap =
std::map<std::string, std::pair<const Shader *, const T *>>;
///
/// List Prim of type T from the Stage.
/// Returns false when unsupported/unimplemented Prim type T is given.
///
template <typename T>
bool ListPrims(const tinyusdz::Stage &stage, PathPrimMap<T> &m /* output */);
///
/// List Shader of shader type T from the Stage.
/// Returns false when unsupported/unimplemented Shader type T is given.
/// TODO: User defined shader type("info:id")
///
template <typename T>
bool ListShaders(const tinyusdz::Stage &stage,
PathShaderMap<T> &m /* output */);
///
/// Get parent Prim from Path.
/// Path must be fully expanded absolute path.
///
/// Example: Return "/xform" Prim for "/xform/mesh0" path
///
/// Returns nullptr when the given Path is a root Prim or invalid Path(`err` will be filled when failed).
///
const Prim *GetParentPrim(const tinyusdz::Stage &stage, const tinyusdz::Path &path, std::string *err);
} // namespace tydra
} // namespace tinyusdz

View File

@@ -9,18 +9,18 @@
namespace tinyusdz {
constexpr auto kLuxSphereLight = "SphereLight";
constexpr auto kLuxCylinderLight = "CylinderLight";
constexpr auto kLuxDomeLight = "DomeLight";
constexpr auto kLuxDiskLight = "DiskLight";
constexpr auto kLuxRectLight = "RectLight";
constexpr auto kLuxDistantLight = "DistantLight";
constexpr auto kLuxGeometryLight = "GeometryLight";
constexpr auto kLuxPortalLight = "PortalLight";
constexpr auto kLuxPluginLight = "PluginLight";
constexpr auto kSphereLight = "SphereLight";
constexpr auto kCylinderLight = "CylinderLight";
constexpr auto kDomeLight = "DomeLight";
constexpr auto kDiskLight = "DiskLight";
constexpr auto kRectLight = "RectLight";
constexpr auto kDistantLight = "DistantLight";
constexpr auto kGeometryLight = "GeometryLight";
constexpr auto kPortalLight = "PortalLight";
constexpr auto kPluginLight = "PluginLight";
struct LuxSphereLight : public Xformable {
struct SphereLight : public Xformable {
std::string name;
Specifier spec{Specifier::Def};
@@ -54,7 +54,7 @@ struct LuxSphereLight : public Xformable {
PrimMeta meta;
};
struct LuxCylinderLight : public Xformable {
struct CylinderLight : public Xformable {
std::string name;
Specifier spec{Specifier::Def};
@@ -92,7 +92,7 @@ struct LuxCylinderLight : public Xformable {
};
struct LuxRectLight : public Xformable {
struct RectLight : public Xformable {
std::string name;
Specifier spec{Specifier::Def};
@@ -130,7 +130,7 @@ struct LuxRectLight : public Xformable {
PrimMeta meta;
};
struct LuxDiskLight : public Xformable {
struct DiskLight : public Xformable {
std::string name;
Specifier spec{Specifier::Def};
@@ -166,7 +166,7 @@ struct LuxDiskLight : public Xformable {
PrimMeta meta;
};
struct LuxDistantLight : public Xformable {
struct DistantLight : public Xformable {
std::string name;
Specifier spec{Specifier::Def};
@@ -202,7 +202,7 @@ struct LuxDistantLight : public Xformable {
PrimMeta meta;
};
struct LuxDomeLight : public Xformable {
struct DomeLight : public Xformable {
std::string name;
Specifier spec{Specifier::Def};
int64_t parent_id{-1}; // Index to xform node
@@ -251,19 +251,19 @@ struct LuxDomeLight : public Xformable {
};
// TODO:
struct LuxGeometryLight : public Xformable {
struct GeometryLight : public Xformable {
Specifier spec{Specifier::Def};
nonstd::optional<Relation> geometry; // `rel geometry`
};
// TODO
struct LuxPortalLight : public Xformable {
struct PortalLight : public Xformable {
Specifier spec{Specifier::Def};
TypedAttribute<Animatable<Extent>> extent; // float3[]
};
// TODO
struct LuxPluginLight : public Xformable {
struct PluginLight : public Xformable {
Specifier spec{Specifier::Def};
};
@@ -278,15 +278,15 @@ struct PluginLightFilter {
namespace value {
DEFINE_TYPE_TRAIT(LuxDomeLight, kLuxDomeLight, TYPE_ID_LUX_DOME, 1);
DEFINE_TYPE_TRAIT(LuxCylinderLight, kLuxCylinderLight, TYPE_ID_LUX_CYLINDER, 1);
DEFINE_TYPE_TRAIT(LuxSphereLight, kLuxSphereLight, TYPE_ID_LUX_SPHERE, 1);
DEFINE_TYPE_TRAIT(LuxDiskLight, kLuxDiskLight, TYPE_ID_LUX_DISK, 1);
DEFINE_TYPE_TRAIT(LuxDistantLight, kLuxDistantLight, TYPE_ID_LUX_DISTANT, 1);
DEFINE_TYPE_TRAIT(LuxRectLight, kLuxRectLight, TYPE_ID_LUX_RECT, 1);
DEFINE_TYPE_TRAIT(LuxGeometryLight, kLuxGeometryLight, TYPE_ID_LUX_GEOMETRY, 1);
DEFINE_TYPE_TRAIT(LuxPortalLight, kLuxPortalLight, TYPE_ID_LUX_PORTAL, 1);
DEFINE_TYPE_TRAIT(LuxPluginLight, kLuxPluginLight, TYPE_ID_LUX_PLUGIN, 1);
DEFINE_TYPE_TRAIT(DomeLight, kDomeLight, TYPE_ID_LUX_DOME, 1);
DEFINE_TYPE_TRAIT(CylinderLight, kCylinderLight, TYPE_ID_LUX_CYLINDER, 1);
DEFINE_TYPE_TRAIT(SphereLight, kSphereLight, TYPE_ID_LUX_SPHERE, 1);
DEFINE_TYPE_TRAIT(DiskLight, kDiskLight, TYPE_ID_LUX_DISK, 1);
DEFINE_TYPE_TRAIT(DistantLight, kDistantLight, TYPE_ID_LUX_DISTANT, 1);
DEFINE_TYPE_TRAIT(RectLight, kRectLight, TYPE_ID_LUX_RECT, 1);
DEFINE_TYPE_TRAIT(GeometryLight, kGeometryLight, TYPE_ID_LUX_GEOMETRY, 1);
DEFINE_TYPE_TRAIT(PortalLight, kPortalLight, TYPE_ID_LUX_PORTAL, 1);
DEFINE_TYPE_TRAIT(PluginLight, kPluginLight, TYPE_ID_LUX_PLUGIN, 1);
#undef DEFINE_TYPE_TRAIT
#undef DEFINE_ROLE_TYPE_TRAIT

View File

@@ -89,11 +89,11 @@ RECONSTRUCT_PRIM_DECL(Skeleton);
RECONSTRUCT_PRIM_DECL(SkelRoot);
RECONSTRUCT_PRIM_DECL(SkelAnimation);
RECONSTRUCT_PRIM_DECL(BlendShape);
RECONSTRUCT_PRIM_DECL(LuxDomeLight);
RECONSTRUCT_PRIM_DECL(LuxSphereLight);
RECONSTRUCT_PRIM_DECL(LuxCylinderLight);
RECONSTRUCT_PRIM_DECL(LuxDiskLight);
RECONSTRUCT_PRIM_DECL(LuxDistantLight);
RECONSTRUCT_PRIM_DECL(DomeLight);
RECONSTRUCT_PRIM_DECL(SphereLight);
RECONSTRUCT_PRIM_DECL(CylinderLight);
RECONSTRUCT_PRIM_DECL(DiskLight);
RECONSTRUCT_PRIM_DECL(DistantLight);
RECONSTRUCT_PRIM_DECL(GeomMesh);
RECONSTRUCT_PRIM_DECL(GeomSphere);
RECONSTRUCT_PRIM_DECL(GeomPoints);
@@ -154,11 +154,11 @@ DEFINE_PRIM_TYPE(GeomCylinder, kGeomCylinder, value::TYPE_ID_GEOM_CYLINDER);
DEFINE_PRIM_TYPE(GeomBasisCurves, kGeomBasisCurves,
value::TYPE_ID_GEOM_BASIS_CURVES);
DEFINE_PRIM_TYPE(GeomSubset, kGeomSubset, value::TYPE_ID_GEOM_GEOMSUBSET);
DEFINE_PRIM_TYPE(LuxSphereLight, kLuxSphereLight, value::TYPE_ID_LUX_SPHERE);
DEFINE_PRIM_TYPE(LuxDomeLight, kLuxDomeLight, value::TYPE_ID_LUX_DOME);
DEFINE_PRIM_TYPE(LuxDiskLight, kLuxDiskLight, value::TYPE_ID_LUX_DISK);
DEFINE_PRIM_TYPE(LuxDistantLight, kLuxDistantLight, value::TYPE_ID_LUX_DISTANT);
DEFINE_PRIM_TYPE(LuxCylinderLight, kLuxCylinderLight, value::TYPE_ID_LUX_CYLINDER);
DEFINE_PRIM_TYPE(SphereLight, kSphereLight, value::TYPE_ID_LUX_SPHERE);
DEFINE_PRIM_TYPE(DomeLight, kDomeLight, value::TYPE_ID_LUX_DOME);
DEFINE_PRIM_TYPE(DiskLight, kDiskLight, value::TYPE_ID_LUX_DISK);
DEFINE_PRIM_TYPE(DistantLight, kDistantLight, value::TYPE_ID_LUX_DISTANT);
DEFINE_PRIM_TYPE(CylinderLight, kCylinderLight, value::TYPE_ID_LUX_CYLINDER);
DEFINE_PRIM_TYPE(Material, kMaterial, value::TYPE_ID_MATERIAL);
DEFINE_PRIM_TYPE(Shader, kShader, value::TYPE_ID_SHADER);
DEFINE_PRIM_TYPE(SkelRoot, kSkelRoot, value::TYPE_ID_SKEL_ROOT);
@@ -1071,7 +1071,7 @@ void ReconstructNodeRec(const size_t idx,
ReconstructNodeRec(cidx, prim_nodes, prim);
}
parent.children.emplace_back(std::move(prim));
parent.children().emplace_back(std::move(prim));
}
} // namespace
@@ -1100,12 +1100,16 @@ bool USDAReader::Impl::ReconstructStage() {
#endif
}
DCOUT("prim[" << idx << "].num_children = " << prim.children.size());
// root's elementPath is empty"/"
prim.element_path() = Path("", "");
DCOUT("root prim[" << idx << "].elementPath = " << dump_path(prim.element_path()));
DCOUT("root prim[" << idx << "].num_children = " << prim.children().size());
size_t sz = _stage.GetRootPrims().size();
_stage.GetRootPrims().emplace_back(std::move(prim));
DCOUT("num_children = " << _stage.GetRootPrims()[sz].children.size());
DCOUT("num_children = " << _stage.GetRootPrims()[sz].children().size());
}
return true;
@@ -1180,7 +1184,7 @@ bool USDAReader::Impl::RegisterReconstructCallback<GeomSubset>() {
//const prim::ReferenceList &references,
const ascii::AsciiParser::PrimMetaMap &in_meta)
-> nonstd::expected<bool, std::string> {
const Path &parent = full_path.GetParentPrim();
const Path &parent = full_path.GetParentPrimPath();
if (!parent.IsValid()) {
return nonstd::make_unexpected("Invalid Prim path.");
}
@@ -1509,11 +1513,11 @@ bool USDAReader::Impl::Read(ascii::LoadState state) {
RegisterReconstructCallback<Scope>();
RegisterReconstructCallback<LuxSphereLight>();
RegisterReconstructCallback<LuxDomeLight>();
RegisterReconstructCallback<LuxDiskLight>();
RegisterReconstructCallback<LuxDistantLight>();
RegisterReconstructCallback<LuxCylinderLight>();
RegisterReconstructCallback<SphereLight>();
RegisterReconstructCallback<DomeLight>();
RegisterReconstructCallback<DiskLight>();
RegisterReconstructCallback<DistantLight>();
RegisterReconstructCallback<CylinderLight>();
RegisterReconstructCallback<SkelRoot>();
RegisterReconstructCallback<Skeleton>();

View File

@@ -83,11 +83,11 @@ RECONSTRUCT_PRIM_DECL(GeomCylinder);
RECONSTRUCT_PRIM_DECL(GeomSphere);
RECONSTRUCT_PRIM_DECL(GeomBasisCurves);
RECONSTRUCT_PRIM_DECL(GeomCamera);
RECONSTRUCT_PRIM_DECL(LuxSphereLight);
RECONSTRUCT_PRIM_DECL(LuxDomeLight);
RECONSTRUCT_PRIM_DECL(LuxDiskLight);
RECONSTRUCT_PRIM_DECL(LuxDistantLight);
RECONSTRUCT_PRIM_DECL(LuxCylinderLight);
RECONSTRUCT_PRIM_DECL(SphereLight);
RECONSTRUCT_PRIM_DECL(DomeLight);
RECONSTRUCT_PRIM_DECL(DiskLight);
RECONSTRUCT_PRIM_DECL(DistantLight);
RECONSTRUCT_PRIM_DECL(CylinderLight);
RECONSTRUCT_PRIM_DECL(SkelRoot);
RECONSTRUCT_PRIM_DECL(SkelAnimation);
RECONSTRUCT_PRIM_DECL(Skeleton);
@@ -705,6 +705,10 @@ bool USDCReader::Impl::BuildPropertyMap(const std::vector<size_t> &pathIndices,
{
std::string prop_name = path.value().GetPropPart();
if (prop_name.empty()) {
// ???
PUSH_ERROR_AND_RETURN_TAG(kTag, "Property Prop.PropPart is empty");
}
Property prop;
if (!ParseProperty(spec.spec_type, child_fvs, &prop)) {
@@ -1497,11 +1501,11 @@ nonstd::optional<Prim> USDCReader::Impl::ReconstructPrimFromTypeName(
RECONSTRUCT_PRIM(GeomBasisCurves, typeName, prim_name, spec)
RECONSTRUCT_PRIM(GeomCamera, typeName, prim_name, spec)
// RECONSTRUCT_PRIM(GeomSubset, typeName, prim_name, spec)
RECONSTRUCT_PRIM(LuxSphereLight, typeName, prim_name, spec)
RECONSTRUCT_PRIM(LuxDomeLight, typeName, prim_name, spec)
RECONSTRUCT_PRIM(LuxCylinderLight, typeName, prim_name, spec)
RECONSTRUCT_PRIM(LuxDiskLight, typeName, prim_name, spec)
RECONSTRUCT_PRIM(LuxDistantLight, typeName, prim_name, spec)
RECONSTRUCT_PRIM(SphereLight, typeName, prim_name, spec)
RECONSTRUCT_PRIM(DomeLight, typeName, prim_name, spec)
RECONSTRUCT_PRIM(CylinderLight, typeName, prim_name, spec)
RECONSTRUCT_PRIM(DiskLight, typeName, prim_name, spec)
RECONSTRUCT_PRIM(DistantLight, typeName, prim_name, spec)
RECONSTRUCT_PRIM(SkelRoot, typeName, prim_name, spec)
RECONSTRUCT_PRIM(Skeleton, typeName, prim_name, spec)
RECONSTRUCT_PRIM(SkelAnimation, typeName, prim_name, spec)
@@ -1941,8 +1945,6 @@ bool USDCReader::Impl::ReconstructPrimNode(int parent, int current, int level,
<< fv.first << "(type = " << fv.second.type_name() << ")");
}
Path elemPath;
// StageMeta = root only attributes.
// TODO: Unify reconstrction code with USDAReder?
if (current == 0) {
@@ -1991,9 +1993,11 @@ bool USDCReader::Impl::ReconstructPrimNode(int parent, int current, int level,
DCOUT("<== PrimFields end ===");
Path elemPath;
if (const auto &pv = GetElemPath(crate::Index(uint32_t(current)))) {
DCOUT(fmt::format("Element path: {}", pv.value().full_path_name()));
elemPath = pv.value();
DCOUT(fmt::format("Element path: {}", elemPath.full_path_name()));
} else {
PUSH_ERROR_AND_RETURN_TAG(kTag,
"(Internal errror) Element path not found.");
@@ -2037,7 +2041,7 @@ bool USDCReader::Impl::ReconstructPrimNode(int parent, int current, int level,
if (prim) {
// Prim name
prim.value().elementPath = elemPath;
prim.value().element_path() = elemPath;
}
if (primOut) {
@@ -2067,6 +2071,8 @@ bool USDCReader::Impl::ReconstructPrimNode(int parent, int current, int level,
fmt::format("[{}] is a Variantset node(parent = {}). prim_idx? = {}",
current, parent, _prim_table.count(current)));
Path elemPath;
if (const auto &pv = GetElemPath(crate::Index(uint32_t(current)))) {
elemPath = pv.value();
@@ -2096,6 +2102,7 @@ bool USDCReader::Impl::ReconstructPrimNode(int parent, int current, int level,
DCOUT("<== VariantSetFields endn === ");
// Add variantChildren to prim node.
// TODO: elemPath
if (!AddVariantChildrenToPrimNode(parent, variantChildren)) {
return false;
}
@@ -2125,6 +2132,7 @@ bool USDCReader::Impl::ReconstructPrimNode(int parent, int current, int level,
DCOUT("<== VariantFields end === ");
Path elemPath;
if (const auto &pv = GetElemPath(crate::Index(uint32_t(current)))) {
elemPath = pv.value();
DCOUT(fmt::format("Element path: {}", elemPath.full_path_name()));
@@ -2182,10 +2190,10 @@ bool USDCReader::Impl::ReconstructPrimNode(int parent, int current, int level,
if (variantPrim) {
// Prim name
variantPrim.value().elementPath = elemPath; // FIXME: Use variantPrimName?
variantPrim.value().element_path() = elemPath; // FIXME: Use variantPrimName?
// Prim Specifier
variantPrim.value().specifier = specifier.value();
variantPrim.value().specifier() = specifier.value();
// Store variantPrim to temporary buffer.
DCOUT("add prim idx as variant: " << current);
@@ -2322,7 +2330,7 @@ bool USDCReader::Impl::ReconstructPrimRecursively(
} else {
// Add to root prim.
if (prim && rootPrim) {
rootPrim->children.emplace_back(std::move(prim.value()));
rootPrim->children().emplace_back(std::move(prim.value()));
}
}

View File

@@ -15,7 +15,7 @@
// For fast int/float to ascii
// Disabled for a while(need to write a test).
//#include "external/jeaiii_to_text.h"
//#include "external/jeaiii_to_text.h"
#include "external/dtoa_milo.h"
@@ -539,11 +539,11 @@ namespace value {
__FUNC(GeomCone) \
__FUNC(GeomBasisCurves) \
__FUNC(GeomCamera) \
__FUNC(LuxSphereLight) \
__FUNC(LuxDomeLight) \
__FUNC(LuxDiskLight) \
__FUNC(LuxDistantLight) \
__FUNC(LuxCylinderLight) \
__FUNC(SphereLight) \
__FUNC(DomeLight) \
__FUNC(DiskLight) \
__FUNC(DistantLight) \
__FUNC(CylinderLight) \
__FUNC(SkelRoot) \
__FUNC(Skeleton) \
__FUNC(SkelAnimation) \

View File

@@ -17,6 +17,9 @@ tinyusdz_sources=[
'../../src/usdObj.cc',
'../../src/primvar.cc',
'../../src/ascii-parser.cc',
'../../src/ascii-parser-basetype.cc',
'../../src/ascii-parser-timesamples.cc',
'../../src/ascii-parser-timesamples-array.cc',
'../../src/usda-reader.cc',
'../../src/usda-writer.cc',
'../../src/usdc-reader.cc',